clustercache.go 48 KB

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