clustercache.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. package scrape
  2. import (
  3. "fmt"
  4. "slices"
  5. "strconv"
  6. "strings"
  7. "github.com/kubecost/events"
  8. "github.com/opencost/opencost/core/pkg/clustercache"
  9. "github.com/opencost/opencost/core/pkg/external"
  10. "github.com/opencost/opencost/core/pkg/log"
  11. "github.com/opencost/opencost/core/pkg/source"
  12. coreutil "github.com/opencost/opencost/core/pkg/util"
  13. "github.com/opencost/opencost/core/pkg/util/promutil"
  14. "github.com/opencost/opencost/modules/collector-source/pkg/event"
  15. "github.com/opencost/opencost/modules/collector-source/pkg/metric"
  16. "github.com/opencost/opencost/modules/collector-source/pkg/util"
  17. "golang.org/x/exp/maps"
  18. v1 "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/api/resource"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/apimachinery/pkg/util/validation"
  22. )
  23. const unmountedPVsContainer = "unmounted-pvs"
  24. type ClusterCacheScraper struct {
  25. clusterCache clustercache.ClusterCache
  26. externalLabelProvider external.LabelProvider
  27. nodeIndex *persistedIndex[string]
  28. namespaceIndex *persistedIndex[string]
  29. pvcIndex *persistedIndex[pvcKey]
  30. pvIndex *persistedIndex[string]
  31. }
  32. func newClusterCacheScraper(clusterCache clustercache.ClusterCache, externalLabelProvider external.LabelProvider) Scraper {
  33. return &ClusterCacheScraper{
  34. clusterCache: clusterCache,
  35. externalLabelProvider: externalLabelProvider,
  36. nodeIndex: newPersistedIndex[string]("node"),
  37. namespaceIndex: newPersistedIndex[string]("namespace"),
  38. pvcIndex: newPersistedIndex[pvcKey]("pvc"),
  39. pvIndex: newPersistedIndex[string]("pv"),
  40. }
  41. }
  42. func (ccs *ClusterCacheScraper) Scrape() []metric.Update {
  43. // retrieve objects for scrape
  44. nodes := ccs.clusterCache.GetAllNodes()
  45. deployments := ccs.clusterCache.GetAllDeployments()
  46. namespaces := ccs.clusterCache.GetAllNamespaces()
  47. pods := ccs.clusterCache.GetAllPods()
  48. pvcs := ccs.clusterCache.GetAllPersistentVolumeClaims()
  49. pvs := ccs.clusterCache.GetAllPersistentVolumes()
  50. services := ccs.clusterCache.GetAllServices()
  51. statefulSets := ccs.clusterCache.GetAllStatefulSets()
  52. daemonSets := ccs.clusterCache.GetAllDaemonSets()
  53. jobs := ccs.clusterCache.GetAllJobs()
  54. cronJobs := ccs.clusterCache.GetAllCronJobs()
  55. replicaSets := ccs.clusterCache.GetAllReplicaSets()
  56. resourceQuotas := ccs.clusterCache.GetAllResourceQuotas()
  57. // create scrape indexes. While the pairs being mapped here don't have a 1 to 1 relationship in the general case,
  58. // we are assuming that in the context of a single snapshot of the cluster they are 1 to 1. Entries are retained
  59. // across scrapes so that objects which outlive their referent in the cluster cache still resolve a UID.
  60. nodeNameToUID := ccs.nodeIndex.update(buildNodeIndex(nodes))
  61. namespaceNameToUID := ccs.namespaceIndex.update(buildNamespaceIndex(namespaces))
  62. pvcNameToUID := ccs.pvcIndex.update(buildPVCIndex(pvcs))
  63. pvNameToUID := ccs.pvIndex.update(buildPVIndex(pvs))
  64. scrapeFuncs := []ScrapeFunc{
  65. ccs.GetScrapeNodes(nodes),
  66. ccs.GetScrapeDeployments(deployments, namespaceNameToUID),
  67. ccs.GetScrapeNamespaces(namespaces),
  68. ccs.GetScrapePods(pods, pvcs, nodeNameToUID, namespaceNameToUID, pvcNameToUID),
  69. ccs.GetScrapePVCs(pvcs, namespaceNameToUID, pvNameToUID),
  70. ccs.GetScrapePVs(pvs),
  71. ccs.GetScrapeServices(services, namespaceNameToUID),
  72. ccs.GetScrapeStatefulSets(statefulSets, namespaceNameToUID),
  73. ccs.GetScrapeDaemonSets(daemonSets, namespaceNameToUID),
  74. ccs.GetScrapeJobs(jobs, namespaceNameToUID),
  75. ccs.GetScrapeCronJobs(cronJobs, namespaceNameToUID),
  76. ccs.GetScrapeReplicaSets(replicaSets, namespaceNameToUID),
  77. ccs.GetScrapeResourceQuotas(resourceQuotas, namespaceNameToUID),
  78. }
  79. return concurrentScrape(scrapeFuncs...)
  80. }
  81. func (ccs *ClusterCacheScraper) GetScrapeNodes(nodes []*clustercache.Node) ScrapeFunc {
  82. return func() []metric.Update {
  83. return ccs.scrapeNodes(nodes)
  84. }
  85. }
  86. func (ccs *ClusterCacheScraper) scrapeNodes(nodes []*clustercache.Node) []metric.Update {
  87. var scrapeResults []metric.Update
  88. // get external labels
  89. var externalLabels map[string]string
  90. var err error
  91. if ccs.externalLabelProvider != nil {
  92. externalLabels, err = ccs.externalLabelProvider.Labels()
  93. if err != nil {
  94. log.Errorf("failed to get external labels to nodes: %s", err)
  95. }
  96. }
  97. for _, node := range nodes {
  98. nodeInfo := map[string]string{
  99. source.NodeLabel: node.Name,
  100. source.ProviderIDLabel: node.SpecProviderID,
  101. source.UIDLabel: string(node.UID),
  102. }
  103. if instanceType, ok := coreutil.GetInstanceType(node.Labels); ok {
  104. nodeInfo[source.InstanceTypeLabel] = instanceType
  105. }
  106. scrapeResults = append(scrapeResults, metric.Update{
  107. Name: metric.NodeInfo,
  108. Labels: nodeInfo,
  109. AdditionalInfo: nodeInfo,
  110. })
  111. // Node Capacity
  112. scrapeResults = scrapeResourceList(
  113. metric.NodeResourceCapacities,
  114. node.Status.Capacity,
  115. nodeInfo,
  116. scrapeResults)
  117. // This block and metric can be removed, when we stop exporting assets and allocations
  118. if node.Status.Capacity != nil {
  119. if quantity, ok := node.Status.Capacity[v1.ResourceCPU]; ok {
  120. _, _, value := toResourceUnitValue(v1.ResourceCPU, quantity)
  121. scrapeResults = append(scrapeResults, metric.Update{
  122. Name: metric.KubeNodeStatusCapacityCPUCores,
  123. Labels: nodeInfo,
  124. Value: value,
  125. })
  126. }
  127. if quantity, ok := node.Status.Capacity[v1.ResourceMemory]; ok {
  128. _, _, value := toResourceUnitValue(v1.ResourceMemory, quantity)
  129. scrapeResults = append(scrapeResults, metric.Update{
  130. Name: metric.KubeNodeStatusCapacityMemoryBytes,
  131. Labels: nodeInfo,
  132. Value: value,
  133. })
  134. }
  135. }
  136. // Node Allocatable Resources
  137. scrapeResults = scrapeResourceList(
  138. metric.NodeResourcesAllocatable,
  139. node.Status.Allocatable,
  140. nodeInfo,
  141. scrapeResults)
  142. // This block and metric can be removed, when we stop exporting assets and allocations
  143. if node.Status.Allocatable != nil {
  144. if quantity, ok := node.Status.Allocatable[v1.ResourceCPU]; ok {
  145. _, _, value := toResourceUnitValue(v1.ResourceCPU, quantity)
  146. scrapeResults = append(scrapeResults, metric.Update{
  147. Name: metric.KubeNodeStatusAllocatableCPUCores,
  148. Labels: nodeInfo,
  149. Value: value,
  150. })
  151. }
  152. if quantity, ok := node.Status.Allocatable[v1.ResourceMemory]; ok {
  153. _, _, value := toResourceUnitValue(v1.ResourceMemory, quantity)
  154. scrapeResults = append(scrapeResults, metric.Update{
  155. Name: metric.KubeNodeStatusAllocatableMemoryBytes,
  156. Labels: nodeInfo,
  157. Value: value,
  158. })
  159. }
  160. }
  161. var nodeLabels map[string]string
  162. // Merge external labels into node labels; node labels win on conflict.\
  163. if len(externalLabels) > 0 {
  164. nodeLabels = promutil.KubeLabelsToLabelsMerge(node.Labels, externalLabels)
  165. } else {
  166. nodeLabels = promutil.KubeLabelsToLabelsMap(node.Labels)
  167. }
  168. scrapeResults = append(scrapeResults, metric.Update{
  169. Name: metric.KubeNodeLabels,
  170. Labels: nodeInfo,
  171. Value: 0,
  172. AdditionalInfo: nodeLabels,
  173. })
  174. }
  175. events.Dispatch(event.ScrapeEvent{
  176. ScraperName: event.KubernetesClusterScraperName,
  177. ScrapeType: event.NodeScraperType,
  178. Targets: len(nodes),
  179. Errors: nil,
  180. })
  181. return scrapeResults
  182. }
  183. func (ccs *ClusterCacheScraper) GetScrapeDeployments(deployments []*clustercache.Deployment, namespaceIndex map[string]types.UID) ScrapeFunc {
  184. return func() []metric.Update {
  185. return ccs.scrapeDeployments(deployments, namespaceIndex)
  186. }
  187. }
  188. func (ccs *ClusterCacheScraper) scrapeDeployments(deployments []*clustercache.Deployment, namespaceIndex map[string]types.UID) []metric.Update {
  189. var scrapeResults []metric.Update
  190. for _, deployment := range deployments {
  191. nsUID, ok := namespaceIndex[deployment.Namespace]
  192. if !ok {
  193. log.Debugf("deployment namespaceUID missing from index for namespace name '%s'", deployment.Namespace)
  194. }
  195. deploymentInfo := map[string]string{
  196. source.UIDLabel: string(deployment.UID),
  197. source.NamespaceUIDLabel: string(nsUID),
  198. source.NamespaceLabel: deployment.Namespace,
  199. source.DeploymentLabel: deployment.Name,
  200. }
  201. scrapeResults = append(scrapeResults, metric.Update{
  202. Name: metric.DeploymentInfo,
  203. Labels: deploymentInfo,
  204. Value: 0,
  205. AdditionalInfo: deploymentInfo,
  206. })
  207. // deployment labels
  208. labelNames, labelValues := promutil.KubeLabelsToLabels(deployment.Labels)
  209. deploymentLabels := util.ToMap(labelNames, labelValues)
  210. scrapeResults = append(scrapeResults, metric.Update{
  211. Name: metric.DeploymentLabels,
  212. Labels: deploymentInfo,
  213. Value: 0,
  214. AdditionalInfo: deploymentLabels,
  215. })
  216. // deployment annotations
  217. annoationNames, annotationValues := promutil.KubeAnnotationsToLabels(deployment.Annotations)
  218. deploymentAnnotations := util.ToMap(annoationNames, annotationValues)
  219. scrapeResults = append(scrapeResults, metric.Update{
  220. Name: metric.DeploymentAnnotations,
  221. Labels: deploymentInfo,
  222. Value: 0,
  223. AdditionalInfo: deploymentAnnotations,
  224. })
  225. // deployment match labels
  226. matchLabelNames, matchLabelValues := promutil.KubeLabelsToLabels(deployment.MatchLabels)
  227. deploymentMatchLabels := util.ToMap(matchLabelNames, matchLabelValues)
  228. scrapeResults = append(scrapeResults, metric.Update{
  229. Name: metric.DeploymentMatchLabels,
  230. Labels: deploymentInfo,
  231. Value: 0,
  232. AdditionalInfo: deploymentMatchLabels,
  233. })
  234. }
  235. events.Dispatch(event.ScrapeEvent{
  236. ScraperName: event.KubernetesClusterScraperName,
  237. ScrapeType: event.DeploymentScraperType,
  238. Targets: len(deployments),
  239. Errors: nil,
  240. })
  241. return scrapeResults
  242. }
  243. func (ccs *ClusterCacheScraper) GetScrapeNamespaces(namespaces []*clustercache.Namespace) ScrapeFunc {
  244. return func() []metric.Update {
  245. return ccs.scrapeNamespaces(namespaces)
  246. }
  247. }
  248. func (ccs *ClusterCacheScraper) scrapeNamespaces(namespaces []*clustercache.Namespace) []metric.Update {
  249. var scrapeResults []metric.Update
  250. for _, namespace := range namespaces {
  251. namespaceInfo := map[string]string{
  252. source.NamespaceLabel: namespace.Name,
  253. source.UIDLabel: string(namespace.UID),
  254. }
  255. scrapeResults = append(scrapeResults, metric.Update{
  256. Name: metric.NamespaceInfo,
  257. Labels: namespaceInfo,
  258. AdditionalInfo: namespaceInfo,
  259. Value: 0,
  260. })
  261. // namespace labels
  262. labelNames, labelValues := promutil.KubeLabelsToLabels(namespace.Labels)
  263. namespaceLabels := util.ToMap(labelNames, labelValues)
  264. scrapeResults = append(scrapeResults, metric.Update{
  265. Name: metric.KubeNamespaceLabels,
  266. Labels: namespaceInfo,
  267. Value: 0,
  268. AdditionalInfo: namespaceLabels,
  269. })
  270. // namespace annotations
  271. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(namespace.Annotations)
  272. namespaceAnnotations := util.ToMap(annotationNames, annotationValues)
  273. scrapeResults = append(scrapeResults, metric.Update{
  274. Name: metric.KubeNamespaceAnnotations,
  275. Labels: namespaceInfo,
  276. Value: 0,
  277. AdditionalInfo: namespaceAnnotations,
  278. })
  279. }
  280. events.Dispatch(event.ScrapeEvent{
  281. ScraperName: event.KubernetesClusterScraperName,
  282. ScrapeType: event.NamespaceScraperType,
  283. Targets: len(namespaces),
  284. Errors: nil,
  285. })
  286. return scrapeResults
  287. }
  288. func (ccs *ClusterCacheScraper) GetScrapePods(
  289. pods []*clustercache.Pod,
  290. pvcs []*clustercache.PersistentVolumeClaim,
  291. nodeIndex map[string]types.UID,
  292. namespaceIndex map[string]types.UID,
  293. pvcIndex map[pvcKey]types.UID,
  294. ) ScrapeFunc {
  295. return func() []metric.Update {
  296. return ccs.scrapePods(pods, pvcs, nodeIndex, namespaceIndex, pvcIndex)
  297. }
  298. }
  299. func (ccs *ClusterCacheScraper) scrapePods(
  300. pods []*clustercache.Pod,
  301. pvcs []*clustercache.PersistentVolumeClaim,
  302. nodeIndex map[string]types.UID,
  303. namespaceIndex map[string]types.UID,
  304. pvcIndex map[pvcKey]types.UID,
  305. ) []metric.Update {
  306. // this is only populated if we find gpu resources being requested
  307. var nodesGpuInfo map[string]*NodeGpuInfo
  308. // pv allocation and unmounted pvs
  309. pvcInfo := getPvcsInfo(pvcs)
  310. // pod info by uid
  311. podInfoByUid := make(map[string]map[string]string)
  312. var scrapeResults []metric.Update
  313. for _, pod := range pods {
  314. // pods without a set node name are not running
  315. if pod.Spec.NodeName == "" {
  316. continue
  317. }
  318. nodeUID, ok := nodeIndex[pod.Spec.NodeName]
  319. if !ok {
  320. log.Debugf("pod nodeUID missing from index for node name '%s'", pod.Spec.NodeName)
  321. }
  322. nsUID, ok := namespaceIndex[pod.Namespace]
  323. if !ok {
  324. log.Debugf("pod namespaceUID missing from index for namespace name '%s'", pod.Namespace)
  325. }
  326. podInfo := map[string]string{
  327. source.UIDLabel: string(pod.UID),
  328. source.PodLabel: pod.Name,
  329. source.NamespaceUIDLabel: string(nsUID),
  330. source.NodeUIDLabel: string(nodeUID),
  331. }
  332. scrapeResults = append(scrapeResults, metric.Update{
  333. Name: metric.PodInfo,
  334. Labels: podInfo,
  335. Value: 0,
  336. AdditionalInfo: podInfo,
  337. })
  338. podInfo[source.NamespaceLabel] = pod.Namespace
  339. podInfo[source.NodeLabel] = pod.Spec.NodeName
  340. podInfo[source.InstanceLabel] = pod.Spec.NodeName
  341. podInfoByUid[string(pod.UID)] = podInfo
  342. // pod labels
  343. labelNames, labelValues := promutil.KubeLabelsToLabels(pod.Labels)
  344. podLabels := util.ToMap(labelNames, labelValues)
  345. scrapeResults = append(scrapeResults, metric.Update{
  346. Name: metric.KubePodLabels,
  347. Labels: podInfo,
  348. Value: 0,
  349. AdditionalInfo: podLabels,
  350. })
  351. // pod annotations
  352. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(pod.Annotations)
  353. podAnnotations := util.ToMap(annotationNames, annotationValues)
  354. scrapeResults = append(scrapeResults, metric.Update{
  355. Name: metric.KubePodAnnotations,
  356. Labels: podInfo,
  357. Value: 0,
  358. AdditionalInfo: podAnnotations,
  359. })
  360. // Determine PVC use data for Pod
  361. claimed := make(map[string]struct{})
  362. for _, volume := range pod.Spec.Volumes {
  363. if volume.PersistentVolumeClaim != nil {
  364. name := volume.PersistentVolumeClaim.ClaimName
  365. key := pod.Namespace + "," + name
  366. if _, seen := claimed[key]; seen {
  367. continue
  368. }
  369. if pvc, ok := pvcInfo[key]; ok {
  370. pvc.PodsClaimed = append(pvc.PodsClaimed, string(pod.UID))
  371. claimed[key] = struct{}{}
  372. }
  373. }
  374. }
  375. // Pod owner metric
  376. for _, owner := range pod.OwnerReferences {
  377. controller := "false"
  378. if owner.Controller != nil && *owner.Controller {
  379. controller = "true"
  380. }
  381. ownerInfo := maps.Clone(podInfo)
  382. ownerInfo[source.OwnerKindLabel] = owner.Kind
  383. ownerInfo[source.OwnerNameLabel] = owner.Name
  384. ownerInfo[source.OwnerUIDLabel] = string(owner.UID)
  385. ownerInfo[source.ControllerLabel] = controller
  386. scrapeResults = append(scrapeResults, metric.Update{
  387. Name: metric.KubePodOwner,
  388. Labels: ownerInfo,
  389. Value: 0,
  390. AdditionalInfo: ownerInfo,
  391. })
  392. }
  393. // Container Status
  394. for _, status := range pod.Status.ContainerStatuses {
  395. if status.State.Running != nil {
  396. containerInfo := maps.Clone(podInfo)
  397. containerInfo[source.ContainerLabel] = status.Name
  398. scrapeResults = append(scrapeResults, metric.Update{
  399. Name: metric.KubePodContainerStatusRunning,
  400. Labels: containerInfo,
  401. AdditionalInfo: containerInfo,
  402. Value: 0,
  403. })
  404. }
  405. }
  406. for _, volume := range pod.Spec.Volumes {
  407. if volume.PersistentVolumeClaim != nil {
  408. pvcUID, ok := pvcIndex[pvcKey{
  409. name: volume.PersistentVolumeClaim.ClaimName,
  410. namespace: pod.Namespace,
  411. }]
  412. if !ok {
  413. continue
  414. }
  415. podPVCVolumeInfo := map[string]string{
  416. source.UIDLabel: string(pod.UID),
  417. source.PVCUIDLabel: string(pvcUID),
  418. source.PodVolumeNameLabel: volume.Name,
  419. }
  420. scrapeResults = append(scrapeResults, metric.Update{
  421. Name: metric.PodPVCVolume,
  422. Labels: podPVCVolumeInfo,
  423. Value: 0,
  424. })
  425. }
  426. }
  427. for _, container := range pod.Spec.Containers {
  428. containerInfo := maps.Clone(podInfo)
  429. containerInfo[source.ContainerLabel] = container.Name
  430. // Requests
  431. scrapeResults = scrapeResourceList(
  432. metric.KubePodContainerResourceRequests,
  433. container.Resources.Requests,
  434. containerInfo,
  435. scrapeResults)
  436. // Limits
  437. scrapeResults = scrapeResourceList(
  438. metric.KubePodContainerResourceLimits,
  439. container.Resources.Limits,
  440. containerInfo,
  441. scrapeResults)
  442. // Todo remove when asset/allocation pipeline are removed
  443. // gpu "requests" is either the request or limit if it exists
  444. var gpuRequest *float64
  445. for resourceName, quantity := range container.Resources.Requests {
  446. if isGpuResourceName(resourceName) {
  447. // set gpu request if it exists
  448. _, _, value := toResourceUnitValue(resourceName, quantity)
  449. gpuRequestValue := value
  450. gpuRequest = &gpuRequestValue
  451. break
  452. }
  453. }
  454. // Limits
  455. if gpuRequest == nil {
  456. for resourceName, quantity := range container.Resources.Limits {
  457. if isGpuResourceName(resourceName) {
  458. // set gpu request if it exists
  459. _, _, value := toResourceUnitValue(resourceName, quantity)
  460. gpuRequestValue := value
  461. gpuRequest = &gpuRequestValue
  462. break
  463. }
  464. }
  465. }
  466. // handle the GPU allocation metric here IFF there exists a request/limit for GPUs
  467. // we only load the node gpu data map if we run into a container with gpu requests/limits
  468. if gpuRequest != nil {
  469. if nodesGpuInfo == nil {
  470. nodesGpuInfo = ccs.getNodesGpuInfo()
  471. }
  472. gpuAlloc := *gpuRequest
  473. if nodeGpuInfo, ok := nodesGpuInfo[pod.Spec.NodeName]; ok {
  474. if nodeGpuInfo != nil && nodeGpuInfo.VGPU != 0 {
  475. gpuAlloc = gpuAlloc * (nodeGpuInfo.GPU / nodeGpuInfo.VGPU)
  476. }
  477. }
  478. scrapeResults = append(scrapeResults, metric.Update{
  479. Name: metric.ContainerGPUAllocation,
  480. Labels: maps.Clone(containerInfo),
  481. Value: gpuAlloc,
  482. })
  483. }
  484. }
  485. }
  486. // Iterate through PVC Info after the pods have been tallied and export
  487. // allocation metrics based on the number of other pods claiming the volume
  488. for _, pvc := range pvcInfo {
  489. // unmounted pvs get full allocation
  490. if len(pvc.PodsClaimed) == 0 {
  491. labels := map[string]string{
  492. source.PodLabel: unmountedPVsContainer,
  493. source.NamespaceLabel: pvc.Namespace,
  494. source.PVCLabel: pvc.Claim,
  495. source.PVLabel: pvc.VolumeName,
  496. }
  497. scrapeResults = append(scrapeResults, metric.Update{
  498. Name: metric.PodPVCAllocation,
  499. Labels: labels,
  500. Value: pvc.Requests,
  501. })
  502. continue
  503. }
  504. // pods get a proportion of pv allocation
  505. value := pvc.Requests / float64(len(pvc.PodsClaimed))
  506. for _, podUid := range pvc.PodsClaimed {
  507. podInfo, ok := podInfoByUid[podUid]
  508. if !ok {
  509. continue
  510. }
  511. pvcLabels := maps.Clone(podInfo)
  512. pvcLabels[source.PVCLabel] = pvc.Claim
  513. pvcLabels[source.PVLabel] = pvc.VolumeName
  514. scrapeResults = append(scrapeResults, metric.Update{
  515. Name: metric.PodPVCAllocation,
  516. Labels: pvcLabels,
  517. Value: value,
  518. })
  519. }
  520. }
  521. events.Dispatch(event.ScrapeEvent{
  522. ScraperName: event.KubernetesClusterScraperName,
  523. ScrapeType: event.PodScraperType,
  524. Targets: len(pods),
  525. Errors: nil,
  526. })
  527. return scrapeResults
  528. }
  529. func scrapeResourceList(metricName string, resourceList v1.ResourceList, baseLabels map[string]string, scrapeResults []metric.Update) []metric.Update {
  530. if resourceList != nil {
  531. // sorting keys here for testing purposes
  532. keys := maps.Keys(resourceList)
  533. slices.Sort(keys)
  534. for _, resourceName := range keys {
  535. quantity := resourceList[resourceName]
  536. resource, unit, value := toResourceUnitValue(resourceName, quantity)
  537. // failed to parse the resource type
  538. if resource == "" {
  539. log.DedupedWarningf(5, "Failed to parse resource units and quantity for resource: %s", resourceName)
  540. continue
  541. }
  542. resourceRequestInfo := maps.Clone(baseLabels)
  543. resourceRequestInfo[source.ResourceLabel] = resource
  544. resourceRequestInfo[source.UnitLabel] = unit
  545. scrapeResults = append(scrapeResults, metric.Update{
  546. Name: metricName,
  547. Labels: resourceRequestInfo,
  548. Value: value,
  549. })
  550. }
  551. }
  552. return scrapeResults
  553. }
  554. func (ccs *ClusterCacheScraper) GetScrapePVCs(
  555. pvcs []*clustercache.PersistentVolumeClaim,
  556. namespaceIndex map[string]types.UID,
  557. pvIndex map[string]types.UID,
  558. ) ScrapeFunc {
  559. return func() []metric.Update {
  560. return ccs.scrapePVCs(pvcs, namespaceIndex, pvIndex)
  561. }
  562. }
  563. func (ccs *ClusterCacheScraper) scrapePVCs(
  564. pvcs []*clustercache.PersistentVolumeClaim,
  565. namespaceIndex map[string]types.UID,
  566. pvIndex map[string]types.UID,
  567. ) []metric.Update {
  568. var scrapeResults []metric.Update
  569. for _, pvc := range pvcs {
  570. nsUID, ok := namespaceIndex[pvc.Namespace]
  571. if !ok {
  572. log.Debugf("pvc namespaceUID missing from index for namespace name '%s'", pvc.Namespace)
  573. }
  574. pvUID, ok := pvIndex[pvc.Spec.VolumeName]
  575. if !ok && pvc.Spec.VolumeName != "" {
  576. log.Debugf("pvc volume name missing from index for pv name '%s'", pvc.Spec.VolumeName)
  577. }
  578. pvcInfo := map[string]string{
  579. source.UIDLabel: string(pvc.UID),
  580. source.PVCLabel: pvc.Name,
  581. source.NamespaceUIDLabel: string(nsUID),
  582. source.NamespaceLabel: pvc.Namespace,
  583. source.VolumeNameLabel: pvc.Spec.VolumeName,
  584. source.PVUIDLabel: string(pvUID),
  585. source.StorageClassLabel: getPersistentVolumeClaimClass(pvc),
  586. }
  587. scrapeResults = append(scrapeResults, metric.Update{
  588. Name: metric.KubePersistentVolumeClaimInfo,
  589. Labels: pvcInfo,
  590. AdditionalInfo: pvcInfo,
  591. Value: 0,
  592. })
  593. if storage, ok := pvc.Spec.Resources.Requests[v1.ResourceStorage]; ok {
  594. scrapeResults = append(scrapeResults, metric.Update{
  595. Name: metric.KubePersistentVolumeClaimResourceRequestsStorageBytes,
  596. Labels: pvcInfo,
  597. Value: float64(storage.Value()),
  598. })
  599. }
  600. }
  601. events.Dispatch(event.ScrapeEvent{
  602. ScraperName: event.KubernetesClusterScraperName,
  603. ScrapeType: event.PvcScraperType,
  604. Targets: len(pvcs),
  605. Errors: nil,
  606. })
  607. return scrapeResults
  608. }
  609. func (ccs *ClusterCacheScraper) GetScrapePVs(pvs []*clustercache.PersistentVolume) ScrapeFunc {
  610. return func() []metric.Update {
  611. return ccs.scrapePVs(pvs)
  612. }
  613. }
  614. func (ccs *ClusterCacheScraper) scrapePVs(pvs []*clustercache.PersistentVolume) []metric.Update {
  615. var scrapeResults []metric.Update
  616. for _, pv := range pvs {
  617. providerID := clustercache.GetPVProviderID(pv)
  618. pvInfo := map[string]string{
  619. source.UIDLabel: string(pv.UID),
  620. source.PVLabel: pv.Name,
  621. source.StorageClassLabel: pv.Spec.StorageClassName,
  622. source.ProviderIDLabel: providerID,
  623. }
  624. if pv.Spec.CSI != nil && pv.Spec.CSI.VolumeHandle != "" {
  625. pvInfo[source.CSIVolumeHandleLabel] = pv.Spec.CSI.VolumeHandle
  626. }
  627. scrapeResults = append(scrapeResults, metric.Update{
  628. Name: metric.KubecostPVInfo,
  629. Labels: pvInfo,
  630. AdditionalInfo: pvInfo,
  631. Value: 0,
  632. })
  633. if storage, ok := pv.Spec.Capacity[v1.ResourceStorage]; ok {
  634. scrapeResults = append(scrapeResults, metric.Update{
  635. Name: metric.KubePersistentVolumeCapacityBytes,
  636. Labels: pvInfo,
  637. Value: float64(storage.Value()),
  638. })
  639. }
  640. }
  641. events.Dispatch(event.ScrapeEvent{
  642. ScraperName: event.KubernetesClusterScraperName,
  643. ScrapeType: event.PvScraperType,
  644. Targets: len(pvs),
  645. Errors: nil,
  646. })
  647. return scrapeResults
  648. }
  649. func (ccs *ClusterCacheScraper) GetScrapeServices(
  650. services []*clustercache.Service,
  651. namespaceIndex map[string]types.UID,
  652. ) ScrapeFunc {
  653. return func() []metric.Update {
  654. return ccs.scrapeServices(services, namespaceIndex)
  655. }
  656. }
  657. func (ccs *ClusterCacheScraper) scrapeServices(
  658. services []*clustercache.Service,
  659. namespaceIndex map[string]types.UID,
  660. ) []metric.Update {
  661. var scrapeResults []metric.Update
  662. for _, service := range services {
  663. namespaceUID := namespaceIndex[service.Namespace]
  664. // Assuming one address for now
  665. var lbIngressAddress string
  666. lbIngressAddresses := clustercache.GetLoadBalancerIngressAddress(service)
  667. if len(lbIngressAddresses) > 0 {
  668. lbIngressAddress = lbIngressAddresses[0]
  669. }
  670. serviceInfo := map[string]string{
  671. source.UIDLabel: string(service.UID),
  672. source.ServiceLabel: service.Name,
  673. source.NamespaceLabel: service.Namespace,
  674. source.NamespaceUIDLabel: string(namespaceUID),
  675. source.ServiceTypeLabel: string(service.Type),
  676. source.LBIngressAddress: lbIngressAddress,
  677. }
  678. scrapeResults = append(scrapeResults, metric.Update{
  679. Name: metric.ServiceInfo,
  680. Labels: serviceInfo,
  681. Value: 0,
  682. AdditionalInfo: serviceInfo,
  683. })
  684. // service selector labels
  685. selectorNames, selectorValues := promutil.KubeLabelsToLabels(service.SpecSelector)
  686. serviceLabels := util.ToMap(selectorNames, selectorValues)
  687. scrapeResults = append(scrapeResults, metric.Update{
  688. Name: metric.ServiceSelectorLabels,
  689. Labels: serviceInfo,
  690. Value: 0,
  691. AdditionalInfo: serviceLabels,
  692. })
  693. }
  694. events.Dispatch(event.ScrapeEvent{
  695. ScraperName: event.KubernetesClusterScraperName,
  696. ScrapeType: event.ServiceScraperType,
  697. Targets: len(services),
  698. Errors: nil,
  699. })
  700. return scrapeResults
  701. }
  702. func (ccs *ClusterCacheScraper) GetScrapeStatefulSets(statefulSets []*clustercache.StatefulSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  703. return func() []metric.Update {
  704. return ccs.scrapeStatefulSets(statefulSets, namespaceIndex)
  705. }
  706. }
  707. func (ccs *ClusterCacheScraper) scrapeStatefulSets(statefulSets []*clustercache.StatefulSet, namespaceIndex map[string]types.UID) []metric.Update {
  708. var scrapeResults []metric.Update
  709. for _, statefulSet := range statefulSets {
  710. nsUID, ok := namespaceIndex[statefulSet.Namespace]
  711. if !ok {
  712. log.Debugf("statefulSet namespaceUID missing from index for namespace name '%s'", statefulSet.Namespace)
  713. }
  714. statefulSetInfo := map[string]string{
  715. source.UIDLabel: string(statefulSet.UID),
  716. source.NamespaceUIDLabel: string(nsUID),
  717. source.StatefulSetLabel: statefulSet.Name,
  718. }
  719. // statefulSet info
  720. scrapeResults = append(scrapeResults, metric.Update{
  721. Name: metric.StatefulSetInfo,
  722. Labels: statefulSetInfo,
  723. Value: 0,
  724. AdditionalInfo: statefulSetInfo,
  725. })
  726. // statefulSet labels
  727. labelNames, labelValues := promutil.KubeLabelsToLabels(statefulSet.Labels)
  728. statefulSetLabels := util.ToMap(labelNames, labelValues)
  729. scrapeResults = append(scrapeResults, metric.Update{
  730. Name: metric.StatefulSetLabels,
  731. Labels: statefulSetInfo,
  732. Value: 0,
  733. AdditionalInfo: statefulSetLabels,
  734. })
  735. // statefulSet annotations
  736. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(statefulSet.Annotations)
  737. statefulSetAnnotations := util.ToMap(annotationNames, annotationValues)
  738. scrapeResults = append(scrapeResults, metric.Update{
  739. Name: metric.StatefulSetAnnotations,
  740. Labels: statefulSetInfo,
  741. Value: 0,
  742. AdditionalInfo: statefulSetAnnotations,
  743. })
  744. // statefulSet match labels
  745. statefulSetInfo[source.NamespaceLabel] = statefulSet.Namespace
  746. matchLabelNames, matchLabelValues := promutil.KubeLabelsToLabels(statefulSet.SpecSelector.MatchLabels)
  747. statefulSetMatchLabels := util.ToMap(matchLabelNames, matchLabelValues)
  748. scrapeResults = append(scrapeResults, metric.Update{
  749. Name: metric.StatefulSetMatchLabels,
  750. Labels: statefulSetInfo,
  751. Value: 0,
  752. AdditionalInfo: statefulSetMatchLabels,
  753. })
  754. }
  755. events.Dispatch(event.ScrapeEvent{
  756. ScraperName: event.KubernetesClusterScraperName,
  757. ScrapeType: event.StatefulSetScraperType,
  758. Targets: len(statefulSets),
  759. Errors: nil,
  760. })
  761. return scrapeResults
  762. }
  763. func (ccs *ClusterCacheScraper) GetScrapeDaemonSets(daemonSets []*clustercache.DaemonSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  764. return func() []metric.Update {
  765. return ccs.scrapeDaemonSets(daemonSets, namespaceIndex)
  766. }
  767. }
  768. func (ccs *ClusterCacheScraper) scrapeDaemonSets(daemonSets []*clustercache.DaemonSet, namespaceIndex map[string]types.UID) []metric.Update {
  769. var scrapeResults []metric.Update
  770. for _, daemonSet := range daemonSets {
  771. nsUID, ok := namespaceIndex[daemonSet.Namespace]
  772. if !ok {
  773. log.Debugf("daemonSet namespaceUID missing from index for namespace name '%s'", daemonSet.Namespace)
  774. }
  775. daemonSetInfo := map[string]string{
  776. source.UIDLabel: string(daemonSet.UID),
  777. source.NamespaceUIDLabel: string(nsUID),
  778. source.DaemonSetLabel: daemonSet.Name,
  779. }
  780. // daemonSet info
  781. scrapeResults = append(scrapeResults, metric.Update{
  782. Name: metric.DaemonSetInfo,
  783. Labels: daemonSetInfo,
  784. Value: 0,
  785. AdditionalInfo: daemonSetInfo,
  786. })
  787. // daemonSet labels
  788. labelNames, labelValues := promutil.KubeLabelsToLabels(daemonSet.Labels)
  789. daemonSetLabels := util.ToMap(labelNames, labelValues)
  790. scrapeResults = append(scrapeResults, metric.Update{
  791. Name: metric.DaemonSetLabels,
  792. Labels: daemonSetInfo,
  793. Value: 0,
  794. AdditionalInfo: daemonSetLabels,
  795. })
  796. // daemonSet annotations
  797. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(daemonSet.Annotations)
  798. daemonSetAnnotations := util.ToMap(annotationNames, annotationValues)
  799. scrapeResults = append(scrapeResults, metric.Update{
  800. Name: metric.DaemonSetAnnotations,
  801. Labels: daemonSetInfo,
  802. Value: 0,
  803. AdditionalInfo: daemonSetAnnotations,
  804. })
  805. // daemonSet arguments
  806. daemonSetArguments := coreutil.ParseContainerArgs(daemonSet.SpecContainers)
  807. argKeys := maps.Keys(daemonSetArguments)
  808. slices.Sort(argKeys)
  809. for _, arg := range argKeys {
  810. value := daemonSetArguments[arg]
  811. argLabels := map[string]string{
  812. source.UIDLabel: string(daemonSet.UID),
  813. source.NamespaceUIDLabel: string(nsUID),
  814. source.DaemonSetLabel: daemonSet.Name,
  815. source.ArgLabel: arg,
  816. source.ValueLabel: value,
  817. }
  818. scrapeResults = append(scrapeResults, metric.Update{
  819. Name: metric.DaemonSetArguments,
  820. Labels: argLabels,
  821. Value: 0,
  822. AdditionalInfo: argLabels,
  823. })
  824. }
  825. }
  826. events.Dispatch(event.ScrapeEvent{
  827. ScraperName: event.KubernetesClusterScraperName,
  828. ScrapeType: event.DaemonSetScraperType,
  829. Targets: len(daemonSets),
  830. Errors: nil,
  831. })
  832. return scrapeResults
  833. }
  834. func (ccs *ClusterCacheScraper) GetScrapeJobs(jobs []*clustercache.Job, namespaceIndex map[string]types.UID) ScrapeFunc {
  835. return func() []metric.Update {
  836. return ccs.scrapeJobs(jobs, namespaceIndex)
  837. }
  838. }
  839. func (ccs *ClusterCacheScraper) scrapeJobs(jobs []*clustercache.Job, namespaceIndex map[string]types.UID) []metric.Update {
  840. var scrapeResults []metric.Update
  841. for _, job := range jobs {
  842. nsUID, ok := namespaceIndex[job.Namespace]
  843. if !ok {
  844. log.Debugf("job namespaceUID missing from index for namespace name '%s'", job.Namespace)
  845. }
  846. jobInfo := map[string]string{
  847. source.UIDLabel: string(job.UID),
  848. source.NamespaceUIDLabel: string(nsUID),
  849. source.JobLabel: job.Name,
  850. }
  851. // job info
  852. scrapeResults = append(scrapeResults, metric.Update{
  853. Name: metric.JobInfo,
  854. Labels: jobInfo,
  855. Value: 0,
  856. AdditionalInfo: jobInfo,
  857. })
  858. // job labels
  859. labelNames, labelValues := promutil.KubeLabelsToLabels(job.Labels)
  860. jobLabels := util.ToMap(labelNames, labelValues)
  861. scrapeResults = append(scrapeResults, metric.Update{
  862. Name: metric.JobLabels,
  863. Labels: jobInfo,
  864. Value: 0,
  865. AdditionalInfo: jobLabels,
  866. })
  867. // job annotations
  868. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(job.Annotations)
  869. jobAnnotations := util.ToMap(annotationNames, annotationValues)
  870. scrapeResults = append(scrapeResults, metric.Update{
  871. Name: metric.JobAnnotations,
  872. Labels: jobInfo,
  873. Value: 0,
  874. AdditionalInfo: jobAnnotations,
  875. })
  876. }
  877. events.Dispatch(event.ScrapeEvent{
  878. ScraperName: event.KubernetesClusterScraperName,
  879. ScrapeType: event.JobScraperType,
  880. Targets: len(jobs),
  881. Errors: nil,
  882. })
  883. return scrapeResults
  884. }
  885. func (ccs *ClusterCacheScraper) GetScrapeCronJobs(cronJobs []*clustercache.CronJob, namespaceIndex map[string]types.UID) ScrapeFunc {
  886. return func() []metric.Update {
  887. return ccs.scrapeCronJobs(cronJobs, namespaceIndex)
  888. }
  889. }
  890. func (ccs *ClusterCacheScraper) scrapeCronJobs(cronJobs []*clustercache.CronJob, namespaceIndex map[string]types.UID) []metric.Update {
  891. var scrapeResults []metric.Update
  892. for _, cronJob := range cronJobs {
  893. nsUID, ok := namespaceIndex[cronJob.Namespace]
  894. if !ok {
  895. log.Debugf("cronjob namespaceUID missing from index for namespace name '%s'", cronJob.Namespace)
  896. }
  897. cronJobInfo := map[string]string{
  898. source.UIDLabel: string(cronJob.UID),
  899. source.NamespaceUIDLabel: string(nsUID),
  900. source.CronJobLabel: cronJob.Name,
  901. }
  902. // cronjob info
  903. scrapeResults = append(scrapeResults, metric.Update{
  904. Name: metric.CronJobInfo,
  905. Labels: cronJobInfo,
  906. Value: 0,
  907. AdditionalInfo: cronJobInfo,
  908. })
  909. // cronjob labels
  910. labelNames, labelValues := promutil.KubeLabelsToLabels(cronJob.Labels)
  911. cronJobLabels := util.ToMap(labelNames, labelValues)
  912. scrapeResults = append(scrapeResults, metric.Update{
  913. Name: metric.CronJobLabels,
  914. Labels: cronJobInfo,
  915. Value: 0,
  916. AdditionalInfo: cronJobLabels,
  917. })
  918. // cronjob annotations
  919. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(cronJob.Annotations)
  920. cronJobAnnotations := util.ToMap(annotationNames, annotationValues)
  921. scrapeResults = append(scrapeResults, metric.Update{
  922. Name: metric.CronJobAnnotations,
  923. Labels: cronJobInfo,
  924. Value: 0,
  925. AdditionalInfo: cronJobAnnotations,
  926. })
  927. }
  928. events.Dispatch(event.ScrapeEvent{
  929. ScraperName: event.KubernetesClusterScraperName,
  930. ScrapeType: event.CronJobScraperType,
  931. Targets: len(cronJobs),
  932. Errors: nil,
  933. })
  934. return scrapeResults
  935. }
  936. func (ccs *ClusterCacheScraper) GetScrapeReplicaSets(replicaSets []*clustercache.ReplicaSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  937. return func() []metric.Update {
  938. return ccs.scrapeReplicaSets(replicaSets, namespaceIndex)
  939. }
  940. }
  941. func (ccs *ClusterCacheScraper) scrapeReplicaSets(replicaSets []*clustercache.ReplicaSet, namespaceIndex map[string]types.UID) []metric.Update {
  942. var scrapeResults []metric.Update
  943. for _, replicaSet := range replicaSets {
  944. nsUID, ok := namespaceIndex[replicaSet.Namespace]
  945. if !ok {
  946. log.Debugf("replicaset namespaceUID missing from index for namespace name '%s'", replicaSet.Namespace)
  947. }
  948. replicaSetInfo := map[string]string{
  949. source.UIDLabel: string(replicaSet.UID),
  950. source.NamespaceUIDLabel: string(nsUID),
  951. source.ReplicaSetLabel: replicaSet.Name,
  952. }
  953. // replicaset info
  954. scrapeResults = append(scrapeResults, metric.Update{
  955. Name: metric.ReplicaSetInfo,
  956. Labels: replicaSetInfo,
  957. Value: 0,
  958. AdditionalInfo: replicaSetInfo,
  959. })
  960. // replicaset labels
  961. labelNames, labelValues := promutil.KubeLabelsToLabels(replicaSet.Labels)
  962. replicaSetLabels := util.ToMap(labelNames, labelValues)
  963. scrapeResults = append(scrapeResults, metric.Update{
  964. Name: metric.ReplicaSetLabels,
  965. Labels: replicaSetInfo,
  966. Value: 0,
  967. AdditionalInfo: replicaSetLabels,
  968. })
  969. // replicaset annotations
  970. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(replicaSet.Annotations)
  971. replicaSetAnnotations := util.ToMap(annotationNames, annotationValues)
  972. scrapeResults = append(scrapeResults, metric.Update{
  973. Name: metric.ReplicaSetAnnotations,
  974. Labels: replicaSetInfo,
  975. Value: 0,
  976. AdditionalInfo: replicaSetAnnotations,
  977. })
  978. // owner references for backward compatibility
  979. replicaSetOwnerInfo := map[string]string{
  980. source.ReplicaSetLabel: replicaSet.Name,
  981. source.NamespaceLabel: replicaSet.Namespace,
  982. source.UIDLabel: string(replicaSet.UID),
  983. }
  984. // this specific metric exports a special <none> value for name and kind
  985. // if there are no owners
  986. if len(replicaSet.OwnerReferences) == 0 {
  987. ownerInfo := maps.Clone(replicaSetOwnerInfo)
  988. ownerInfo[source.OwnerKindLabel] = source.NoneLabelValue
  989. ownerInfo[source.OwnerNameLabel] = source.NoneLabelValue
  990. ownerInfo[source.ControllerLabel] = "false"
  991. scrapeResults = append(scrapeResults, metric.Update{
  992. Name: metric.KubeReplicasetOwner,
  993. Labels: ownerInfo,
  994. Value: 0,
  995. AdditionalInfo: ownerInfo,
  996. })
  997. } else {
  998. for _, owner := range replicaSet.OwnerReferences {
  999. controller := "false"
  1000. if owner.Controller != nil && *owner.Controller {
  1001. controller = "true"
  1002. }
  1003. ownerInfo := maps.Clone(replicaSetOwnerInfo)
  1004. ownerInfo[source.OwnerKindLabel] = owner.Kind
  1005. ownerInfo[source.OwnerNameLabel] = owner.Name
  1006. ownerInfo[source.OwnerUIDLabel] = string(owner.UID)
  1007. ownerInfo[source.ControllerLabel] = controller
  1008. scrapeResults = append(scrapeResults, metric.Update{
  1009. Name: metric.KubeReplicasetOwner,
  1010. Labels: ownerInfo,
  1011. Value: 0,
  1012. AdditionalInfo: ownerInfo,
  1013. })
  1014. }
  1015. }
  1016. }
  1017. events.Dispatch(event.ScrapeEvent{
  1018. ScraperName: event.KubernetesClusterScraperName,
  1019. ScrapeType: event.ReplicaSetScraperType,
  1020. Targets: len(replicaSets),
  1021. Errors: nil,
  1022. })
  1023. return scrapeResults
  1024. }
  1025. func (ccs *ClusterCacheScraper) GetScrapeResourceQuotas(resourceQuotas []*clustercache.ResourceQuota, namespaceIndex map[string]types.UID) ScrapeFunc {
  1026. return func() []metric.Update {
  1027. return ccs.scrapeResourceQuotas(resourceQuotas, namespaceIndex)
  1028. }
  1029. }
  1030. func (ccs *ClusterCacheScraper) scrapeResourceQuotas(resourceQuotas []*clustercache.ResourceQuota, namespaceIndex map[string]types.UID) []metric.Update {
  1031. var scrapeResults []metric.Update
  1032. processResource := func(baseLabels map[string]string, name v1.ResourceName, quantity resource.Quantity, metricName string) metric.Update {
  1033. resource, unit, value := toResourceUnitValue(name, quantity)
  1034. labels := maps.Clone(baseLabels)
  1035. labels[source.ResourceLabel] = resource
  1036. labels[source.UnitLabel] = unit
  1037. return metric.Update{
  1038. Name: metricName,
  1039. Labels: labels,
  1040. Value: value,
  1041. }
  1042. }
  1043. for _, resourceQuota := range resourceQuotas {
  1044. nsUID, _ := namespaceIndex[resourceQuota.Namespace]
  1045. resourceQuotaInfo := map[string]string{
  1046. source.UIDLabel: string(resourceQuota.UID),
  1047. source.NamespaceUIDLabel: string(nsUID),
  1048. source.ResourceQuotaLabel: resourceQuota.Name,
  1049. }
  1050. scrapeResults = append(scrapeResults, metric.Update{
  1051. Name: metric.ResourceQuotaInfo,
  1052. Labels: resourceQuotaInfo,
  1053. AdditionalInfo: resourceQuotaInfo,
  1054. Value: 0,
  1055. })
  1056. if resourceQuota.Spec.Hard != nil {
  1057. // CPU/memory requests can also be aliased as "cpu" and "memory". For now, however, only scrape the complete names
  1058. // https://kubernetes.io/docs/concepts/policy/resource-quotas/#compute-resource-quota
  1059. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceRequestsCPU]; ok {
  1060. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaSpecResourceRequests))
  1061. }
  1062. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceRequestsMemory]; ok {
  1063. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaSpecResourceRequests))
  1064. }
  1065. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceLimitsCPU]; ok {
  1066. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaSpecResourceLimits))
  1067. }
  1068. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceLimitsMemory]; ok {
  1069. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaSpecResourceLimits))
  1070. }
  1071. }
  1072. if resourceQuota.Status.Used != nil {
  1073. if quantity, ok := resourceQuota.Status.Used[v1.ResourceRequestsCPU]; ok {
  1074. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaStatusUsedResourceRequests))
  1075. }
  1076. if quantity, ok := resourceQuota.Status.Used[v1.ResourceRequestsMemory]; ok {
  1077. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaStatusUsedResourceRequests))
  1078. }
  1079. if quantity, ok := resourceQuota.Status.Used[v1.ResourceLimitsCPU]; ok {
  1080. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaStatusUsedResourceLimits))
  1081. }
  1082. if quantity, ok := resourceQuota.Status.Used[v1.ResourceLimitsMemory]; ok {
  1083. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaStatusUsedResourceLimits))
  1084. }
  1085. }
  1086. }
  1087. events.Dispatch(event.ScrapeEvent{
  1088. ScraperName: event.KubernetesClusterScraperName,
  1089. ScrapeType: event.ResourceQuotaScraperType,
  1090. Targets: len(resourceQuotas),
  1091. Errors: nil,
  1092. })
  1093. return scrapeResults
  1094. }
  1095. // PvcInfo is used to store information about a pvc for tracking volume usage.
  1096. type PvcInfo struct {
  1097. Class string
  1098. Claim string
  1099. Namespace string
  1100. VolumeName string
  1101. Requests float64
  1102. PodsClaimed []string
  1103. }
  1104. func getPvcsInfo(pvcs []*clustercache.PersistentVolumeClaim) map[string]*PvcInfo {
  1105. toReturn := make(map[string]*PvcInfo)
  1106. for _, pvc := range pvcs {
  1107. ns := pvc.Namespace
  1108. pvcName := pvc.Name
  1109. volumeName := pvc.Spec.VolumeName
  1110. pvClass := getPersistentVolumeClaimClass(pvc)
  1111. requests := float64(pvc.Spec.Resources.Requests.Storage().Value())
  1112. key := ns + "," + pvcName
  1113. toReturn[key] = &PvcInfo{
  1114. Class: pvClass,
  1115. Claim: pvcName,
  1116. Namespace: ns,
  1117. VolumeName: volumeName,
  1118. Requests: requests,
  1119. }
  1120. }
  1121. return toReturn
  1122. }
  1123. // NodeGpuInfo contains the gpu count and vgpu counts for nodes
  1124. type NodeGpuInfo struct {
  1125. GPU float64
  1126. VGPU float64
  1127. }
  1128. func (ccs *ClusterCacheScraper) getNodesGpuInfo() map[string]*NodeGpuInfo {
  1129. // use a closure to cache allocatableVGPU result instead of calculating
  1130. // it every time we need it
  1131. var allocatableVGPUs *float64
  1132. allocVGPUs := func() (float64, error) {
  1133. if allocatableVGPUs != nil {
  1134. return *allocatableVGPUs, nil
  1135. }
  1136. vgpu, err := getAllocatableVGPUs(ccs.clusterCache.GetAllDaemonSets())
  1137. if err != nil {
  1138. return vgpu, err
  1139. }
  1140. allocatableVGPUs = &vgpu
  1141. return *allocatableVGPUs, nil
  1142. }
  1143. var nodeGpuMap map[string]*NodeGpuInfo = make(map[string]*NodeGpuInfo)
  1144. for _, node := range ccs.clusterCache.GetAllNodes() {
  1145. info, err := gpuInfoFor(node, allocVGPUs)
  1146. if err != nil {
  1147. log.Warnf("Failed to retrieve GPU Info for Node: %s - %s", node.Name, err)
  1148. continue
  1149. }
  1150. nodeGpuMap[node.Name] = info
  1151. }
  1152. return nodeGpuMap
  1153. }
  1154. // getPersistentVolumeClaimClass returns StorageClassName. If no storage class was
  1155. // requested, it returns "".
  1156. func getPersistentVolumeClaimClass(claim *clustercache.PersistentVolumeClaim) string {
  1157. // Use beta annotation first
  1158. if class, found := claim.Annotations[v1.BetaStorageClassAnnotation]; found {
  1159. return class
  1160. }
  1161. if claim.Spec.StorageClassName != nil {
  1162. return *claim.Spec.StorageClassName
  1163. }
  1164. // Special non-empty string to indicate absence of storage class.
  1165. return ""
  1166. }
  1167. // toResourceUnitValue accepts a resource name and quantity and returns the sanitized resource, the unit, and the value in the units.
  1168. // Returns an empty string for resource and unit if there was a failure.
  1169. func toResourceUnitValue(resourceName v1.ResourceName, quantity resource.Quantity) (resource string, unit string, value float64) {
  1170. resource = resourceName.String()
  1171. switch resourceName {
  1172. case v1.ResourceCPU:
  1173. unit = "core"
  1174. value = float64(quantity.MilliValue()) / 1000
  1175. return
  1176. case v1.ResourceStorage:
  1177. fallthrough
  1178. case v1.ResourceEphemeralStorage:
  1179. fallthrough
  1180. case v1.ResourceMemory:
  1181. unit = "byte"
  1182. value = float64(quantity.Value())
  1183. return
  1184. case v1.ResourcePods:
  1185. unit = "integer"
  1186. value = float64(quantity.Value())
  1187. return
  1188. default:
  1189. if isHugePageResourceName(resourceName) || isAttachableVolumeResourceName(resourceName) {
  1190. unit = "byte"
  1191. value = float64(quantity.Value())
  1192. return
  1193. }
  1194. if isExtendedResourceName(resourceName) {
  1195. unit = "integer"
  1196. value = float64(quantity.Value())
  1197. return
  1198. }
  1199. }
  1200. resource = ""
  1201. unit = ""
  1202. value = 0.0
  1203. return
  1204. }
  1205. func isGpuResourceName(name v1.ResourceName) bool {
  1206. return name == "nvidia.com/gpu" || name == "k8s.amazonaws.com/vgpu"
  1207. }
  1208. // isHugePageResourceName checks for a huge page container resource name
  1209. func isHugePageResourceName(name v1.ResourceName) bool {
  1210. return strings.HasPrefix(string(name), v1.ResourceHugePagesPrefix)
  1211. }
  1212. // isAttachableVolumeResourceName checks for attached volume container resource name
  1213. func isAttachableVolumeResourceName(name v1.ResourceName) bool {
  1214. return strings.HasPrefix(string(name), v1.ResourceAttachableVolumesPrefix)
  1215. }
  1216. // isExtendedResourceName checks for extended container resource name
  1217. func isExtendedResourceName(name v1.ResourceName) bool {
  1218. if isNativeResource(name) || strings.HasPrefix(string(name), v1.DefaultResourceRequestsPrefix) {
  1219. return false
  1220. }
  1221. // Ensure it satisfies the rules in IsQualifiedName() after converted into quota resource name
  1222. nameForQuota := fmt.Sprintf("%s%s", v1.DefaultResourceRequestsPrefix, string(name))
  1223. if errs := validation.IsQualifiedName(nameForQuota); len(errs) != 0 {
  1224. return false
  1225. }
  1226. return true
  1227. }
  1228. // isNativeResource checks for a kubernetes.io/ prefixed resource name
  1229. func isNativeResource(name v1.ResourceName) bool {
  1230. return !strings.Contains(string(name), "/") || isPrefixedNativeResource(name)
  1231. }
  1232. func isPrefixedNativeResource(name v1.ResourceName) bool {
  1233. return strings.Contains(string(name), v1.ResourceDefaultNamespacePrefix)
  1234. }
  1235. // gets the Node GPUs and VGPUs using the node data from k8s. Returns nil if GPUs could not be located for the node.
  1236. func gpuInfoFor(
  1237. n *clustercache.Node,
  1238. allocatedVGPUs func() (float64, error),
  1239. ) (*NodeGpuInfo, error) {
  1240. g, hasGpu := n.Status.Capacity["nvidia.com/gpu"]
  1241. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  1242. // Case 1: Standard NVIDIA GPU
  1243. if hasGpu && g.Value() != 0 && !hasReplicas {
  1244. return &NodeGpuInfo{
  1245. GPU: float64(g.Value()),
  1246. VGPU: float64(g.Value()),
  1247. }, nil
  1248. }
  1249. // Case 2: NVIDIA GPU with GPU Feature Discovery (GFD) Pod enabled.
  1250. // Ref: https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html#verifying-the-gpu-time-slicing-configuration
  1251. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L44-L45
  1252. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L103-L118
  1253. if hasReplicas {
  1254. resultGPU := 0.0
  1255. resultVGPU := 0.0
  1256. if c, ok := n.Labels["nvidia.com/gpu.count"]; ok {
  1257. var err error
  1258. resultGPU, err = strconv.ParseFloat(c, 64)
  1259. if err != nil {
  1260. return nil, fmt.Errorf("could not parse label \"nvidia.com/gpu.count\": %v", err)
  1261. }
  1262. }
  1263. if s, ok := n.Status.Capacity["nvidia.com/gpu.shared"]; ok { // GFD configured `renameByDefault=true`
  1264. resultVGPU = float64(s.Value())
  1265. } else if g, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // GFD configured `renameByDefault=false`
  1266. resultVGPU = float64(g.Value())
  1267. } else {
  1268. resultVGPU = resultGPU
  1269. }
  1270. return &NodeGpuInfo{
  1271. GPU: resultGPU,
  1272. VGPU: resultVGPU,
  1273. }, nil
  1274. }
  1275. // Case 3: AWS vGPU
  1276. if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  1277. vgpuCount, err := allocatedVGPUs()
  1278. if err != nil {
  1279. return nil, err
  1280. }
  1281. vgpuCoeff := 10.0
  1282. if vgpuCount > 0.0 {
  1283. vgpuCoeff = vgpuCount
  1284. }
  1285. if vgpu.Value() != 0 {
  1286. resultGPU := float64(vgpu.Value()) / vgpuCoeff
  1287. resultVGPU := float64(vgpu.Value())
  1288. return &NodeGpuInfo{
  1289. GPU: resultGPU,
  1290. VGPU: resultVGPU,
  1291. }, nil
  1292. }
  1293. }
  1294. // No GPU found
  1295. return nil, nil
  1296. }
  1297. func getAllocatableVGPUs(daemonsets []*clustercache.DaemonSet) (float64, error) {
  1298. vgpuCount := 0.0
  1299. for _, ds := range daemonsets {
  1300. dsContainerList := &ds.SpecContainers
  1301. for _, ctnr := range *dsContainerList {
  1302. if ctnr.Args != nil {
  1303. for _, arg := range ctnr.Args {
  1304. if strings.Contains(arg, "--vgpu=") {
  1305. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  1306. if err != nil {
  1307. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  1308. continue
  1309. }
  1310. vgpuCount = vgpus
  1311. return vgpuCount, nil
  1312. }
  1313. }
  1314. }
  1315. }
  1316. }
  1317. return vgpuCount, nil
  1318. }