clustercache.go 47 KB

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