clustercache.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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 := clustercache.GetPVProviderID(pv)
  609. pvInfo := map[string]string{
  610. source.UIDLabel: string(pv.UID),
  611. source.PVLabel: pv.Name,
  612. source.StorageClassLabel: pv.Spec.StorageClassName,
  613. source.ProviderIDLabel: providerID,
  614. }
  615. if pv.Spec.CSI != nil && pv.Spec.CSI.VolumeHandle != "" {
  616. pvInfo[source.CSIVolumeHandleLabel] = pv.Spec.CSI.VolumeHandle
  617. }
  618. scrapeResults = append(scrapeResults, metric.Update{
  619. Name: metric.KubecostPVInfo,
  620. Labels: pvInfo,
  621. AdditionalInfo: pvInfo,
  622. Value: 0,
  623. })
  624. if storage, ok := pv.Spec.Capacity[v1.ResourceStorage]; ok {
  625. scrapeResults = append(scrapeResults, metric.Update{
  626. Name: metric.KubePersistentVolumeCapacityBytes,
  627. Labels: pvInfo,
  628. Value: float64(storage.Value()),
  629. })
  630. }
  631. }
  632. events.Dispatch(event.ScrapeEvent{
  633. ScraperName: event.KubernetesClusterScraperName,
  634. ScrapeType: event.PvScraperType,
  635. Targets: len(pvs),
  636. Errors: nil,
  637. })
  638. return scrapeResults
  639. }
  640. func (ccs *ClusterCacheScraper) GetScrapeServices(
  641. services []*clustercache.Service,
  642. namespaceIndex map[string]types.UID,
  643. ) ScrapeFunc {
  644. return func() []metric.Update {
  645. return ccs.scrapeServices(services, namespaceIndex)
  646. }
  647. }
  648. func (ccs *ClusterCacheScraper) scrapeServices(
  649. services []*clustercache.Service,
  650. namespaceIndex map[string]types.UID,
  651. ) []metric.Update {
  652. var scrapeResults []metric.Update
  653. for _, service := range services {
  654. namespaceUID := namespaceIndex[service.Namespace]
  655. // Assuming one address for now
  656. var lbIngressAddress string
  657. lbIngressAddresses := clustercache.GetLoadBalancerIngressAddress(service)
  658. if len(lbIngressAddresses) > 0 {
  659. lbIngressAddress = lbIngressAddresses[0]
  660. }
  661. serviceInfo := map[string]string{
  662. source.UIDLabel: string(service.UID),
  663. source.ServiceLabel: service.Name,
  664. source.NamespaceLabel: service.Namespace,
  665. source.NamespaceUIDLabel: string(namespaceUID),
  666. source.ServiceTypeLabel: string(service.Type),
  667. source.LBIngressAddress: lbIngressAddress,
  668. }
  669. scrapeResults = append(scrapeResults, metric.Update{
  670. Name: metric.ServiceInfo,
  671. Labels: serviceInfo,
  672. Value: 0,
  673. AdditionalInfo: serviceInfo,
  674. })
  675. // service selector labels
  676. selectorNames, selectorValues := promutil.KubeLabelsToLabels(service.SpecSelector)
  677. serviceLabels := util.ToMap(selectorNames, selectorValues)
  678. scrapeResults = append(scrapeResults, metric.Update{
  679. Name: metric.ServiceSelectorLabels,
  680. Labels: serviceInfo,
  681. Value: 0,
  682. AdditionalInfo: serviceLabels,
  683. })
  684. }
  685. events.Dispatch(event.ScrapeEvent{
  686. ScraperName: event.KubernetesClusterScraperName,
  687. ScrapeType: event.ServiceScraperType,
  688. Targets: len(services),
  689. Errors: nil,
  690. })
  691. return scrapeResults
  692. }
  693. func (ccs *ClusterCacheScraper) GetScrapeStatefulSets(statefulSets []*clustercache.StatefulSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  694. return func() []metric.Update {
  695. return ccs.scrapeStatefulSets(statefulSets, namespaceIndex)
  696. }
  697. }
  698. func (ccs *ClusterCacheScraper) scrapeStatefulSets(statefulSets []*clustercache.StatefulSet, namespaceIndex map[string]types.UID) []metric.Update {
  699. var scrapeResults []metric.Update
  700. for _, statefulSet := range statefulSets {
  701. nsUID, ok := namespaceIndex[statefulSet.Namespace]
  702. if !ok {
  703. log.Debugf("statefulSet namespaceUID missing from index for namespace name '%s'", statefulSet.Namespace)
  704. }
  705. statefulSetInfo := map[string]string{
  706. source.UIDLabel: string(statefulSet.UID),
  707. source.NamespaceUIDLabel: string(nsUID),
  708. source.StatefulSetLabel: statefulSet.Name,
  709. }
  710. // statefulSet info
  711. scrapeResults = append(scrapeResults, metric.Update{
  712. Name: metric.StatefulSetInfo,
  713. Labels: statefulSetInfo,
  714. Value: 0,
  715. AdditionalInfo: statefulSetInfo,
  716. })
  717. // statefulSet labels
  718. labelNames, labelValues := promutil.KubeLabelsToLabels(statefulSet.Labels)
  719. statefulSetLabels := util.ToMap(labelNames, labelValues)
  720. scrapeResults = append(scrapeResults, metric.Update{
  721. Name: metric.StatefulSetLabels,
  722. Labels: statefulSetInfo,
  723. Value: 0,
  724. AdditionalInfo: statefulSetLabels,
  725. })
  726. // statefulSet annotations
  727. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(statefulSet.Annotations)
  728. statefulSetAnnotations := util.ToMap(annotationNames, annotationValues)
  729. scrapeResults = append(scrapeResults, metric.Update{
  730. Name: metric.StatefulSetAnnotations,
  731. Labels: statefulSetInfo,
  732. Value: 0,
  733. AdditionalInfo: statefulSetAnnotations,
  734. })
  735. // statefulSet match labels
  736. statefulSetInfo[source.NamespaceLabel] = statefulSet.Namespace
  737. matchLabelNames, matchLabelValues := promutil.KubeLabelsToLabels(statefulSet.SpecSelector.MatchLabels)
  738. statefulSetMatchLabels := util.ToMap(matchLabelNames, matchLabelValues)
  739. scrapeResults = append(scrapeResults, metric.Update{
  740. Name: metric.StatefulSetMatchLabels,
  741. Labels: statefulSetInfo,
  742. Value: 0,
  743. AdditionalInfo: statefulSetMatchLabels,
  744. })
  745. }
  746. events.Dispatch(event.ScrapeEvent{
  747. ScraperName: event.KubernetesClusterScraperName,
  748. ScrapeType: event.StatefulSetScraperType,
  749. Targets: len(statefulSets),
  750. Errors: nil,
  751. })
  752. return scrapeResults
  753. }
  754. func (ccs *ClusterCacheScraper) GetScrapeDaemonSets(daemonSets []*clustercache.DaemonSet, namespaceIndex map[string]types.UID) ScrapeFunc {
  755. return func() []metric.Update {
  756. return ccs.scrapeDaemonSets(daemonSets, namespaceIndex)
  757. }
  758. }
  759. func (ccs *ClusterCacheScraper) scrapeDaemonSets(daemonSets []*clustercache.DaemonSet, namespaceIndex map[string]types.UID) []metric.Update {
  760. var scrapeResults []metric.Update
  761. for _, daemonSet := range daemonSets {
  762. nsUID, ok := namespaceIndex[daemonSet.Namespace]
  763. if !ok {
  764. log.Debugf("daemonSet namespaceUID missing from index for namespace name '%s'", daemonSet.Namespace)
  765. }
  766. daemonSetInfo := map[string]string{
  767. source.UIDLabel: string(daemonSet.UID),
  768. source.NamespaceUIDLabel: string(nsUID),
  769. source.DaemonSetLabel: daemonSet.Name,
  770. }
  771. // daemonSet info
  772. scrapeResults = append(scrapeResults, metric.Update{
  773. Name: metric.DaemonSetInfo,
  774. Labels: daemonSetInfo,
  775. Value: 0,
  776. AdditionalInfo: daemonSetInfo,
  777. })
  778. // daemonSet labels
  779. labelNames, labelValues := promutil.KubeLabelsToLabels(daemonSet.Labels)
  780. daemonSetLabels := util.ToMap(labelNames, labelValues)
  781. scrapeResults = append(scrapeResults, metric.Update{
  782. Name: metric.DaemonSetLabels,
  783. Labels: daemonSetInfo,
  784. Value: 0,
  785. AdditionalInfo: daemonSetLabels,
  786. })
  787. // daemonSet annotations
  788. annotationNames, annotationValues := promutil.KubeAnnotationsToLabels(daemonSet.Annotations)
  789. daemonSetAnnotations := util.ToMap(annotationNames, annotationValues)
  790. scrapeResults = append(scrapeResults, metric.Update{
  791. Name: metric.DaemonSetAnnotations,
  792. Labels: daemonSetInfo,
  793. Value: 0,
  794. AdditionalInfo: daemonSetAnnotations,
  795. })
  796. // daemonSet arguments
  797. daemonSetArguments := coreutil.ParseContainerArgs(daemonSet.SpecContainers)
  798. argKeys := maps.Keys(daemonSetArguments)
  799. slices.Sort(argKeys)
  800. for _, arg := range argKeys {
  801. value := daemonSetArguments[arg]
  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 = resourceName.String()
  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. }