clustercache.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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. // daemonSet arguments
  801. for arg, value := range coreutil.ParseContainerArgs(daemonSet.SpecContainers) {
  802. argLabels := map[string]string{
  803. source.UIDLabel: string(daemonSet.UID),
  804. source.NamespaceUIDLabel: string(nsUID),
  805. source.DaemonSetLabel: daemonSet.Name,
  806. source.ArgLabel: arg,
  807. source.ValueLabel: value,
  808. }
  809. scrapeResults = append(scrapeResults, metric.Update{
  810. Name: metric.DaemonSetArguments,
  811. Labels: argLabels,
  812. Value: 0,
  813. AdditionalInfo: argLabels,
  814. })
  815. }
  816. }
  817. events.Dispatch(event.ScrapeEvent{
  818. ScraperName: event.KubernetesClusterScraperName,
  819. ScrapeType: event.DaemonSetScraperType,
  820. Targets: len(daemonSets),
  821. Errors: nil,
  822. })
  823. return scrapeResults
  824. }
  825. func (ccs *ClusterCacheScraper) GetScrapeJobs(jobs []*clustercache.Job, namespaceIndex map[string]types.UID) ScrapeFunc {
  826. return func() []metric.Update {
  827. return ccs.scrapeJobs(jobs, namespaceIndex)
  828. }
  829. }
  830. func (ccs *ClusterCacheScraper) scrapeJobs(jobs []*clustercache.Job, namespaceIndex map[string]types.UID) []metric.Update {
  831. var scrapeResults []metric.Update
  832. for _, job := range jobs {
  833. nsUID, ok := namespaceIndex[job.Namespace]
  834. if !ok {
  835. log.Debugf("job namespaceUID missing from index for namespace name '%s'", job.Namespace)
  836. }
  837. jobInfo := map[string]string{
  838. source.UIDLabel: string(job.UID),
  839. source.NamespaceUIDLabel: string(nsUID),
  840. source.JobLabel: job.Name,
  841. }
  842. // job info
  843. scrapeResults = append(scrapeResults, metric.Update{
  844. Name: metric.JobInfo,
  845. Labels: jobInfo,
  846. Value: 0,
  847. AdditionalInfo: jobInfo,
  848. })
  849. // job labels
  850. labelNames, labelValues := promutil.KubeLabelsToLabels(job.Labels)
  851. jobLabels := util.ToMap(labelNames, labelValues)
  852. scrapeResults = append(scrapeResults, metric.Update{
  853. Name: metric.JobLabels,
  854. Labels: jobInfo,
  855. Value: 0,
  856. AdditionalInfo: jobLabels,
  857. })
  858. // job annotations
  859. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(job.Annotations)
  860. jobAnnotations := util.ToMap(annotationNames, annotationValues)
  861. scrapeResults = append(scrapeResults, metric.Update{
  862. Name: metric.JobAnnotations,
  863. Labels: jobInfo,
  864. Value: 0,
  865. AdditionalInfo: jobAnnotations,
  866. })
  867. }
  868. events.Dispatch(event.ScrapeEvent{
  869. ScraperName: event.KubernetesClusterScraperName,
  870. ScrapeType: event.JobScraperType,
  871. Targets: len(jobs),
  872. Errors: nil,
  873. })
  874. return scrapeResults
  875. }
  876. func (ccs *ClusterCacheScraper) GetScrapeCronJobs(cronJobs []*clustercache.CronJob, namespaceIndex map[string]types.UID) ScrapeFunc {
  877. return func() []metric.Update {
  878. return ccs.scrapeCronJobs(cronJobs, namespaceIndex)
  879. }
  880. }
  881. func (ccs *ClusterCacheScraper) scrapeCronJobs(cronJobs []*clustercache.CronJob, namespaceIndex map[string]types.UID) []metric.Update {
  882. var scrapeResults []metric.Update
  883. for _, cronJob := range cronJobs {
  884. nsUID, ok := namespaceIndex[cronJob.Namespace]
  885. if !ok {
  886. log.Debugf("cronjob namespaceUID missing from index for namespace name '%s'", cronJob.Namespace)
  887. }
  888. cronJobInfo := map[string]string{
  889. source.UIDLabel: string(cronJob.UID),
  890. source.NamespaceUIDLabel: string(nsUID),
  891. source.CronJobLabel: cronJob.Name,
  892. }
  893. // cronjob info
  894. scrapeResults = append(scrapeResults, metric.Update{
  895. Name: metric.CronJobInfo,
  896. Labels: cronJobInfo,
  897. Value: 0,
  898. AdditionalInfo: cronJobInfo,
  899. })
  900. // cronjob labels
  901. labelNames, labelValues := promutil.KubeLabelsToLabels(cronJob.Labels)
  902. cronJobLabels := util.ToMap(labelNames, labelValues)
  903. scrapeResults = append(scrapeResults, metric.Update{
  904. Name: metric.CronJobLabels,
  905. Labels: cronJobInfo,
  906. Value: 0,
  907. AdditionalInfo: cronJobLabels,
  908. })
  909. // cronjob annotations
  910. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(cronJob.Annotations)
  911. cronJobAnnotations := util.ToMap(annotationNames, annotationValues)
  912. scrapeResults = append(scrapeResults, metric.Update{
  913. Name: metric.CronJobAnnotations,
  914. Labels: cronJobInfo,
  915. Value: 0,
  916. AdditionalInfo: cronJobAnnotations,
  917. })
  918. }
  919. events.Dispatch(event.ScrapeEvent{
  920. ScraperName: event.KubernetesClusterScraperName,
  921. ScrapeType: event.CronJobScraperType,
  922. Targets: len(cronJobs),
  923. Errors: nil,
  924. })
  925. return scrapeResults
  926. }
  927. func (ccs *ClusterCacheScraper) GetScrapeReplicaSets(replicaSets []*clustercache.ReplicaSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  928. return func() []metric.Update {
  929. return ccs.scrapeReplicaSets(replicaSets, namespaceIndex)
  930. }
  931. }
  932. func (ccs *ClusterCacheScraper) scrapeReplicaSets(replicaSets []*clustercache.ReplicaSet, namespaceIndex map[string]types.UID) []metric.Update {
  933. var scrapeResults []metric.Update
  934. for _, replicaSet := range replicaSets {
  935. nsUID, ok := namespaceIndex[replicaSet.Namespace]
  936. if !ok {
  937. log.Debugf("replicaset namespaceUID missing from index for namespace name '%s'", replicaSet.Namespace)
  938. }
  939. replicaSetInfo := map[string]string{
  940. source.UIDLabel: string(replicaSet.UID),
  941. source.NamespaceUIDLabel: string(nsUID),
  942. source.ReplicaSetLabel: replicaSet.Name,
  943. }
  944. // replicaset info
  945. scrapeResults = append(scrapeResults, metric.Update{
  946. Name: metric.ReplicaSetInfo,
  947. Labels: replicaSetInfo,
  948. Value: 0,
  949. AdditionalInfo: replicaSetInfo,
  950. })
  951. // replicaset labels
  952. labelNames, labelValues := promutil.KubeLabelsToLabels(replicaSet.Labels)
  953. replicaSetLabels := util.ToMap(labelNames, labelValues)
  954. scrapeResults = append(scrapeResults, metric.Update{
  955. Name: metric.ReplicaSetLabels,
  956. Labels: replicaSetInfo,
  957. Value: 0,
  958. AdditionalInfo: replicaSetLabels,
  959. })
  960. // replicaset annotations
  961. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(replicaSet.Annotations)
  962. replicaSetAnnotations := util.ToMap(annotationNames, annotationValues)
  963. scrapeResults = append(scrapeResults, metric.Update{
  964. Name: metric.ReplicaSetAnnotations,
  965. Labels: replicaSetInfo,
  966. Value: 0,
  967. AdditionalInfo: replicaSetAnnotations,
  968. })
  969. // owner references for backward compatibility
  970. replicaSetOwnerInfo := map[string]string{
  971. source.ReplicaSetLabel: replicaSet.Name,
  972. source.NamespaceLabel: replicaSet.Namespace,
  973. source.UIDLabel: string(replicaSet.UID),
  974. }
  975. // this specific metric exports a special <none> value for name and kind
  976. // if there are no owners
  977. if len(replicaSet.OwnerReferences) == 0 {
  978. ownerInfo := maps.Clone(replicaSetOwnerInfo)
  979. ownerInfo[source.OwnerKindLabel] = source.NoneLabelValue
  980. ownerInfo[source.OwnerNameLabel] = source.NoneLabelValue
  981. ownerInfo[source.ControllerLabel] = "false"
  982. scrapeResults = append(scrapeResults, metric.Update{
  983. Name: metric.KubeReplicasetOwner,
  984. Labels: ownerInfo,
  985. Value: 0,
  986. AdditionalInfo: ownerInfo,
  987. })
  988. } else {
  989. for _, owner := range replicaSet.OwnerReferences {
  990. controller := "false"
  991. if owner.Controller != nil && *owner.Controller {
  992. controller = "true"
  993. }
  994. ownerInfo := maps.Clone(replicaSetOwnerInfo)
  995. ownerInfo[source.OwnerKindLabel] = owner.Kind
  996. ownerInfo[source.OwnerNameLabel] = owner.Name
  997. ownerInfo[source.OwnerUIDLabel] = string(owner.UID)
  998. ownerInfo[source.ControllerLabel] = controller
  999. scrapeResults = append(scrapeResults, metric.Update{
  1000. Name: metric.KubeReplicasetOwner,
  1001. Labels: ownerInfo,
  1002. Value: 0,
  1003. AdditionalInfo: ownerInfo,
  1004. })
  1005. }
  1006. }
  1007. }
  1008. events.Dispatch(event.ScrapeEvent{
  1009. ScraperName: event.KubernetesClusterScraperName,
  1010. ScrapeType: event.ReplicaSetScraperType,
  1011. Targets: len(replicaSets),
  1012. Errors: nil,
  1013. })
  1014. return scrapeResults
  1015. }
  1016. func (ccs *ClusterCacheScraper) GetScrapeResourceQuotas(resourceQuotas []*clustercache.ResourceQuota, namespaceIndex map[string]types.UID) ScrapeFunc {
  1017. return func() []metric.Update {
  1018. return ccs.scrapeResourceQuotas(resourceQuotas, namespaceIndex)
  1019. }
  1020. }
  1021. func (ccs *ClusterCacheScraper) scrapeResourceQuotas(resourceQuotas []*clustercache.ResourceQuota, namespaceIndex map[string]types.UID) []metric.Update {
  1022. var scrapeResults []metric.Update
  1023. processResource := func(baseLabels map[string]string, name v1.ResourceName, quantity resource.Quantity, metricName string) metric.Update {
  1024. resource, unit, value := toResourceUnitValue(name, quantity)
  1025. labels := maps.Clone(baseLabels)
  1026. labels[source.ResourceLabel] = resource
  1027. labels[source.UnitLabel] = unit
  1028. return metric.Update{
  1029. Name: metricName,
  1030. Labels: labels,
  1031. Value: value,
  1032. }
  1033. }
  1034. for _, resourceQuota := range resourceQuotas {
  1035. nsUID, _ := namespaceIndex[resourceQuota.Namespace]
  1036. resourceQuotaInfo := map[string]string{
  1037. source.UIDLabel: string(resourceQuota.UID),
  1038. source.NamespaceUIDLabel: string(nsUID),
  1039. source.ResourceQuotaLabel: resourceQuota.Name,
  1040. }
  1041. scrapeResults = append(scrapeResults, metric.Update{
  1042. Name: metric.ResourceQuotaInfo,
  1043. Labels: resourceQuotaInfo,
  1044. AdditionalInfo: resourceQuotaInfo,
  1045. Value: 0,
  1046. })
  1047. if resourceQuota.Spec.Hard != nil {
  1048. // CPU/memory requests can also be aliased as "cpu" and "memory". For now, however, only scrape the complete names
  1049. // https://kubernetes.io/docs/concepts/policy/resource-quotas/#compute-resource-quota
  1050. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceRequestsCPU]; ok {
  1051. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaSpecResourceRequests))
  1052. }
  1053. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceRequestsMemory]; ok {
  1054. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaSpecResourceRequests))
  1055. }
  1056. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceLimitsCPU]; ok {
  1057. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaSpecResourceLimits))
  1058. }
  1059. if quantity, ok := resourceQuota.Spec.Hard[v1.ResourceLimitsMemory]; ok {
  1060. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaSpecResourceLimits))
  1061. }
  1062. }
  1063. if resourceQuota.Status.Used != nil {
  1064. if quantity, ok := resourceQuota.Status.Used[v1.ResourceRequestsCPU]; ok {
  1065. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaStatusUsedResourceRequests))
  1066. }
  1067. if quantity, ok := resourceQuota.Status.Used[v1.ResourceRequestsMemory]; ok {
  1068. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaStatusUsedResourceRequests))
  1069. }
  1070. if quantity, ok := resourceQuota.Status.Used[v1.ResourceLimitsCPU]; ok {
  1071. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceCPU, quantity, metric.KubeResourceQuotaStatusUsedResourceLimits))
  1072. }
  1073. if quantity, ok := resourceQuota.Status.Used[v1.ResourceLimitsMemory]; ok {
  1074. scrapeResults = append(scrapeResults, processResource(resourceQuotaInfo, v1.ResourceMemory, quantity, metric.KubeResourceQuotaStatusUsedResourceLimits))
  1075. }
  1076. }
  1077. }
  1078. events.Dispatch(event.ScrapeEvent{
  1079. ScraperName: event.KubernetesClusterScraperName,
  1080. ScrapeType: event.ResourceQuotaScraperType,
  1081. Targets: len(resourceQuotas),
  1082. Errors: nil,
  1083. })
  1084. return scrapeResults
  1085. }
  1086. // PvcInfo is used to store information about a pvc for tracking volume usage.
  1087. type PvcInfo struct {
  1088. Class string
  1089. Claim string
  1090. Namespace string
  1091. VolumeName string
  1092. Requests float64
  1093. PodsClaimed []string
  1094. }
  1095. func getPvcsInfo(pvcs []*clustercache.PersistentVolumeClaim) map[string]*PvcInfo {
  1096. toReturn := make(map[string]*PvcInfo)
  1097. for _, pvc := range pvcs {
  1098. ns := pvc.Namespace
  1099. pvcName := pvc.Name
  1100. volumeName := pvc.Spec.VolumeName
  1101. pvClass := getPersistentVolumeClaimClass(pvc)
  1102. requests := float64(pvc.Spec.Resources.Requests.Storage().Value())
  1103. key := ns + "," + pvcName
  1104. toReturn[key] = &PvcInfo{
  1105. Class: pvClass,
  1106. Claim: pvcName,
  1107. Namespace: ns,
  1108. VolumeName: volumeName,
  1109. Requests: requests,
  1110. }
  1111. }
  1112. return toReturn
  1113. }
  1114. // NodeGpuInfo contains the gpu count and vgpu counts for nodes
  1115. type NodeGpuInfo struct {
  1116. GPU float64
  1117. VGPU float64
  1118. }
  1119. func (ccs *ClusterCacheScraper) getNodesGpuInfo() map[string]*NodeGpuInfo {
  1120. // use a closure to cache allocatableVGPU result instead of calculating
  1121. // it every time we need it
  1122. var allocatableVGPUs *float64
  1123. allocVGPUs := func() (float64, error) {
  1124. if allocatableVGPUs != nil {
  1125. return *allocatableVGPUs, nil
  1126. }
  1127. vgpu, err := getAllocatableVGPUs(ccs.clusterCache.GetAllDaemonSets())
  1128. if err != nil {
  1129. return vgpu, err
  1130. }
  1131. allocatableVGPUs = &vgpu
  1132. return *allocatableVGPUs, nil
  1133. }
  1134. var nodeGpuMap map[string]*NodeGpuInfo = make(map[string]*NodeGpuInfo)
  1135. for _, node := range ccs.clusterCache.GetAllNodes() {
  1136. info, err := gpuInfoFor(node, allocVGPUs)
  1137. if err != nil {
  1138. log.Warnf("Failed to retrieve GPU Info for Node: %s - %s", node.Name, err)
  1139. continue
  1140. }
  1141. nodeGpuMap[node.Name] = info
  1142. }
  1143. return nodeGpuMap
  1144. }
  1145. // getPersistentVolumeClaimClass returns StorageClassName. If no storage class was
  1146. // requested, it returns "".
  1147. func getPersistentVolumeClaimClass(claim *clustercache.PersistentVolumeClaim) string {
  1148. // Use beta annotation first
  1149. if class, found := claim.Annotations[v1.BetaStorageClassAnnotation]; found {
  1150. return class
  1151. }
  1152. if claim.Spec.StorageClassName != nil {
  1153. return *claim.Spec.StorageClassName
  1154. }
  1155. // Special non-empty string to indicate absence of storage class.
  1156. return ""
  1157. }
  1158. // toResourceUnitValue accepts a resource name and quantity and returns the sanitized resource, the unit, and the value in the units.
  1159. // Returns an empty string for resource and unit if there was a failure.
  1160. func toResourceUnitValue(resourceName v1.ResourceName, quantity resource.Quantity) (resource string, unit string, value float64) {
  1161. resource = promutil.SanitizeLabelName(string(resourceName))
  1162. switch resourceName {
  1163. case v1.ResourceCPU:
  1164. unit = "core"
  1165. value = float64(quantity.MilliValue()) / 1000
  1166. return
  1167. case v1.ResourceStorage:
  1168. fallthrough
  1169. case v1.ResourceEphemeralStorage:
  1170. fallthrough
  1171. case v1.ResourceMemory:
  1172. unit = "byte"
  1173. value = float64(quantity.Value())
  1174. return
  1175. case v1.ResourcePods:
  1176. unit = "integer"
  1177. value = float64(quantity.Value())
  1178. return
  1179. default:
  1180. if isHugePageResourceName(resourceName) || isAttachableVolumeResourceName(resourceName) {
  1181. unit = "byte"
  1182. value = float64(quantity.Value())
  1183. return
  1184. }
  1185. if isExtendedResourceName(resourceName) {
  1186. unit = "integer"
  1187. value = float64(quantity.Value())
  1188. return
  1189. }
  1190. }
  1191. resource = ""
  1192. unit = ""
  1193. value = 0.0
  1194. return
  1195. }
  1196. func isGpuResourceName(name v1.ResourceName) bool {
  1197. return name == "nvidia.com/gpu" || name == "k8s.amazonaws.com/vgpu"
  1198. }
  1199. // isHugePageResourceName checks for a huge page container resource name
  1200. func isHugePageResourceName(name v1.ResourceName) bool {
  1201. return strings.HasPrefix(string(name), v1.ResourceHugePagesPrefix)
  1202. }
  1203. // isAttachableVolumeResourceName checks for attached volume container resource name
  1204. func isAttachableVolumeResourceName(name v1.ResourceName) bool {
  1205. return strings.HasPrefix(string(name), v1.ResourceAttachableVolumesPrefix)
  1206. }
  1207. // isExtendedResourceName checks for extended container resource name
  1208. func isExtendedResourceName(name v1.ResourceName) bool {
  1209. if isNativeResource(name) || strings.HasPrefix(string(name), v1.DefaultResourceRequestsPrefix) {
  1210. return false
  1211. }
  1212. // Ensure it satisfies the rules in IsQualifiedName() after converted into quota resource name
  1213. nameForQuota := fmt.Sprintf("%s%s", v1.DefaultResourceRequestsPrefix, string(name))
  1214. if errs := validation.IsQualifiedName(nameForQuota); len(errs) != 0 {
  1215. return false
  1216. }
  1217. return true
  1218. }
  1219. // isNativeResource checks for a kubernetes.io/ prefixed resource name
  1220. func isNativeResource(name v1.ResourceName) bool {
  1221. return !strings.Contains(string(name), "/") || isPrefixedNativeResource(name)
  1222. }
  1223. func isPrefixedNativeResource(name v1.ResourceName) bool {
  1224. return strings.Contains(string(name), v1.ResourceDefaultNamespacePrefix)
  1225. }
  1226. // gets the Node GPUs and VGPUs using the node data from k8s. Returns nil if GPUs could not be located for the node.
  1227. func gpuInfoFor(
  1228. n *clustercache.Node,
  1229. allocatedVGPUs func() (float64, error),
  1230. ) (*NodeGpuInfo, error) {
  1231. g, hasGpu := n.Status.Capacity["nvidia.com/gpu"]
  1232. _, hasReplicas := n.Labels["nvidia.com/gpu.replicas"]
  1233. // Case 1: Standard NVIDIA GPU
  1234. if hasGpu && g.Value() != 0 && !hasReplicas {
  1235. return &NodeGpuInfo{
  1236. GPU: float64(g.Value()),
  1237. VGPU: float64(g.Value()),
  1238. }, nil
  1239. }
  1240. // Case 2: NVIDIA GPU with GPU Feature Discovery (GFD) Pod enabled.
  1241. // Ref: https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/gpu-sharing.html#verifying-the-gpu-time-slicing-configuration
  1242. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L44-L45
  1243. // Ref: https://github.com/NVIDIA/k8s-device-plugin/blob/d899752a424818428f744a946d32b132ea2c0cf1/internal/lm/resource_test.go#L103-L118
  1244. if hasReplicas {
  1245. resultGPU := 0.0
  1246. resultVGPU := 0.0
  1247. if c, ok := n.Labels["nvidia.com/gpu.count"]; ok {
  1248. var err error
  1249. resultGPU, err = strconv.ParseFloat(c, 64)
  1250. if err != nil {
  1251. return nil, fmt.Errorf("could not parse label \"nvidia.com/gpu.count\": %v", err)
  1252. }
  1253. }
  1254. if s, ok := n.Status.Capacity["nvidia.com/gpu.shared"]; ok { // GFD configured `renameByDefault=true`
  1255. resultVGPU = float64(s.Value())
  1256. } else if g, ok := n.Status.Capacity["nvidia.com/gpu"]; ok { // GFD configured `renameByDefault=false`
  1257. resultVGPU = float64(g.Value())
  1258. } else {
  1259. resultVGPU = resultGPU
  1260. }
  1261. return &NodeGpuInfo{
  1262. GPU: resultGPU,
  1263. VGPU: resultVGPU,
  1264. }, nil
  1265. }
  1266. // Case 3: AWS vGPU
  1267. if vgpu, ok := n.Status.Capacity["k8s.amazonaws.com/vgpu"]; ok {
  1268. vgpuCount, err := allocatedVGPUs()
  1269. if err != nil {
  1270. return nil, err
  1271. }
  1272. vgpuCoeff := 10.0
  1273. if vgpuCount > 0.0 {
  1274. vgpuCoeff = vgpuCount
  1275. }
  1276. if vgpu.Value() != 0 {
  1277. resultGPU := float64(vgpu.Value()) / vgpuCoeff
  1278. resultVGPU := float64(vgpu.Value())
  1279. return &NodeGpuInfo{
  1280. GPU: resultGPU,
  1281. VGPU: resultVGPU,
  1282. }, nil
  1283. }
  1284. }
  1285. // No GPU found
  1286. return nil, nil
  1287. }
  1288. func getAllocatableVGPUs(daemonsets []*clustercache.DaemonSet) (float64, error) {
  1289. vgpuCount := 0.0
  1290. for _, ds := range daemonsets {
  1291. dsContainerList := &ds.SpecContainers
  1292. for _, ctnr := range *dsContainerList {
  1293. if ctnr.Args != nil {
  1294. for _, arg := range ctnr.Args {
  1295. if strings.Contains(arg, "--vgpu=") {
  1296. vgpus, err := strconv.ParseFloat(arg[strings.IndexByte(arg, '=')+1:], 64)
  1297. if err != nil {
  1298. log.Errorf("failed to parse vgpu allocation string %s: %v", arg, err)
  1299. continue
  1300. }
  1301. vgpuCount = vgpus
  1302. return vgpuCount, nil
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. return vgpuCount, nil
  1309. }