allocation.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/kubecost/cost-model/pkg/env"
  6. "github.com/kubecost/cost-model/pkg/kubecost"
  7. "github.com/kubecost/cost-model/pkg/log"
  8. "github.com/kubecost/cost-model/pkg/prom"
  9. "github.com/kubecost/cost-model/pkg/thanos"
  10. "k8s.io/apimachinery/pkg/labels"
  11. )
  12. // TODO niko/cdmr move to pkg/kubecost
  13. // TODO niko/cdmr add PersistenVolumeClaims to type Allocation?
  14. type PVC struct {
  15. Bytes float64 `json:"bytes"`
  16. Count int `json:"count"`
  17. Name string `json:"name"`
  18. Cluster string `json:"cluster"`
  19. Namespace string `json:"namespace"`
  20. Volume *PV `json:"persistentVolume"`
  21. Start time.Time `json:"start"`
  22. End time.Time `json:"end"`
  23. }
  24. func (pvc *PVC) Cost() float64 {
  25. if pvc == nil || pvc.Volume == nil {
  26. return 0.0
  27. }
  28. gib := pvc.Bytes / 1024 / 1024 / 1024
  29. hrs := pvc.Minutes() / 60.0
  30. return pvc.Volume.CostPerGiBHour * gib * hrs
  31. }
  32. func (pvc *PVC) Minutes() float64 {
  33. if pvc == nil {
  34. return 0.0
  35. }
  36. return pvc.End.Sub(pvc.Start).Minutes()
  37. }
  38. func (pvc *PVC) String() string {
  39. if pvc == nil {
  40. return "<nil>"
  41. }
  42. return fmt.Sprintf("%s/%s/%s{Bytes:%.2f, Cost:%.6f, Start,End:%s}", pvc.Cluster, pvc.Namespace, pvc.Name, pvc.Bytes, pvc.Cost(), kubecost.NewWindow(&pvc.Start, &pvc.End))
  43. }
  44. // TODO niko/cdmr move to pkg/kubecost
  45. type PV struct {
  46. Bytes float64 `json:"bytes"`
  47. CostPerGiBHour float64 `json:"costPerGiBHour"` // TODO niko/cdmr GiB or GB?
  48. Cluster string `json:"cluster"`
  49. Name string `json:"name"`
  50. StorageClass string `json:"storageClass"`
  51. }
  52. func (pv *PV) String() string {
  53. if pv == nil {
  54. return "<nil>"
  55. }
  56. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  57. }
  58. // ComputeAllocation uses the CostModel instance to compute an AllocationSet
  59. // for the window defined by the given start and end times. The Allocations
  60. // returned are unaggregated (i.e. down to the container level).
  61. func (cm *CostModel) ComputeAllocation(start, end time.Time) (*kubecost.AllocationSet, error) {
  62. // Create a window spanning the requested query
  63. s, e := start, end
  64. window := kubecost.NewWindow(&s, &e)
  65. // Create an empty AllocationSet. For safety, in the case of an error, we
  66. // should prefer to return this empty set with the error. (In the case of
  67. // no error, of course we populate the set and return it.)
  68. allocSet := kubecost.NewAllocationSet(start, end)
  69. // Convert window (start, end) to (duration, offset) for querying Prometheus
  70. timesToDurations := func(s, e time.Time) (dur, off time.Duration) {
  71. now := time.Now()
  72. off = now.Sub(e)
  73. dur = e.Sub(s)
  74. return dur, off
  75. }
  76. duration, offset := timesToDurations(start, end)
  77. // If using Thanos, increase offset to 3 hours, reducing the duration by
  78. // equal measure to maintain the same starting point.
  79. thanosDur := thanos.OffsetDuration()
  80. // TODO niko/cdmr confirm that this flag works interchangeably with ThanosClient != nil
  81. if offset < thanosDur && env.IsThanosEnabled() {
  82. diff := thanosDur - offset
  83. offset += diff
  84. duration -= diff
  85. }
  86. // If duration < 0, return an empty set
  87. if duration < 0 {
  88. return allocSet, nil
  89. }
  90. // Negative offset means that the end time is in the future. Prometheus
  91. // fails for non-positive offset values, so shrink the duration and
  92. // remove the offset altogether.
  93. if offset < 0 {
  94. duration = duration + offset
  95. offset = 0
  96. }
  97. durStr := fmt.Sprintf("%dm", int64(duration.Minutes()))
  98. offStr := fmt.Sprintf(" offset %dm", int64(offset.Minutes()))
  99. if offset < time.Minute {
  100. offStr = ""
  101. }
  102. // TODO niko/cdmr dynamic resolution? add to ComputeAllocation() in allocation.Source?
  103. resStr := "1m"
  104. // resPerHr := 60
  105. // TODO niko/cdmr remove after testing
  106. startQuerying := time.Now()
  107. ctx := prom.NewContext(cm.PrometheusClient)
  108. // TODO niko/cdmr retries? (That should probably go into the Store.)
  109. // TODO niko/cmdr check: will multiple Prometheus jobs multiply the totals?
  110. // TODO niko/cdmr should we try doing this without resolution? Could yield
  111. // more accurate results, but might also be more challenging in some
  112. // respects; e.g. "correcting" the start point by what amount?
  113. queryMinutes := fmt.Sprintf(`avg(kube_pod_container_status_running{}) by (container, pod, namespace, kubernetes_node, cluster_id)[%s:%s]%s`, durStr, resStr, offStr)
  114. resChMinutes := ctx.Query(queryMinutes)
  115. queryRAMBytesAllocated := fmt.Sprintf(`avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`, durStr, offStr)
  116. resChRAMBytesAllocated := ctx.Query(queryRAMBytesAllocated)
  117. queryRAMRequests := fmt.Sprintf(`avg(avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`, durStr, offStr)
  118. resChRAMRequests := ctx.Query(queryRAMRequests)
  119. queryRAMUsage := fmt.Sprintf(`avg(avg_over_time(container_memory_working_set_bytes{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`, durStr, offStr)
  120. resChRAMUsage := ctx.Query(queryRAMUsage)
  121. queryCPUCoresAllocated := fmt.Sprintf(`avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`, durStr, offStr)
  122. resChCPUCoresAllocated := ctx.Query(queryCPUCoresAllocated)
  123. queryCPURequests := fmt.Sprintf(`avg(avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`, durStr, offStr)
  124. resChCPURequests := ctx.Query(queryCPURequests)
  125. queryCPUUsage := fmt.Sprintf(`avg(rate(container_cpu_usage_seconds_total{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`, durStr, offStr)
  126. resChCPUUsage := ctx.Query(queryCPUUsage)
  127. // TODO niko/cdmr find an env with GPUs to test this (generate one?)
  128. queryGPUsRequested := fmt.Sprintf(`avg(avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`, durStr, offStr)
  129. resChGPUsRequested := ctx.Query(queryGPUsRequested)
  130. queryNodeCostPerCPUHr := fmt.Sprintf(`avg(avg_over_time(node_cpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`, durStr, offStr)
  131. resChNodeCostPerCPUHr := ctx.Query(queryNodeCostPerCPUHr)
  132. queryNodeCostPerRAMGiBHr := fmt.Sprintf(`avg(avg_over_time(node_ram_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`, durStr, offStr)
  133. resChNodeCostPerRAMGiBHr := ctx.Query(queryNodeCostPerRAMGiBHr)
  134. queryNodeCostPerGPUHr := fmt.Sprintf(`avg(avg_over_time(node_gpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`, durStr, offStr)
  135. resChNodeCostPerGPUHr := ctx.Query(queryNodeCostPerGPUHr)
  136. queryNodeIsSpot := fmt.Sprintf(`avg_over_time(kubecost_node_is_spot[%s]%s)`, durStr, offStr)
  137. resChNodeIsSpot := ctx.Query(queryNodeIsSpot)
  138. queryPVCInfo := fmt.Sprintf(`avg(kube_persistentvolumeclaim_info{volumename != ""}) by (persistentvolumeclaim, storageclass, volumename, namespace, cluster_id)[%s:%s]%s`, durStr, resStr, offStr)
  139. resChPVCInfo := ctx.Query(queryPVCInfo)
  140. queryPVBytes := fmt.Sprintf(`avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s]%s)) by (persistentvolume, cluster_id)`, durStr, offStr)
  141. resChPVBytes := ctx.Query(queryPVBytes)
  142. queryPodPVCAllocation := fmt.Sprintf(`avg(avg_over_time(pod_pvc_allocation[%s]%s)) by (persistentvolume, persistentvolumeclaim, pod, namespace, cluster_id)`, durStr, offStr)
  143. resChPodPVCAllocation := ctx.Query(queryPodPVCAllocation)
  144. queryPVCBytesRequested := fmt.Sprintf(`avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{}[%s]%s)) by (persistentvolumeclaim, namespace, cluster_id)`, durStr, offStr)
  145. resChPVCBytesRequested := ctx.Query(queryPVCBytesRequested)
  146. queryPVCostPerGiBHour := fmt.Sprintf(`avg(avg_over_time(pv_hourly_cost[%s]%s)) by (volumename, cluster_id)`, durStr, offStr)
  147. resChPVCostPerGiBHour := ctx.Query(queryPVCostPerGiBHour)
  148. queryNetZoneGiB := fmt.Sprintf(`sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`, durStr, offStr)
  149. resChNetZoneGiB := ctx.Query(queryNetZoneGiB)
  150. queryNetZoneCostPerGiB := fmt.Sprintf(`avg(avg_over_time(kubecost_network_zone_egress_cost{}[%s]%s)) by (cluster_id)`, durStr, offStr)
  151. resChNetZoneCostPerGiB := ctx.Query(queryNetZoneCostPerGiB)
  152. queryNetRegionGiB := fmt.Sprintf(`sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`, durStr, offStr)
  153. resChNetRegionGiB := ctx.Query(queryNetRegionGiB)
  154. queryNetRegionCostPerGiB := fmt.Sprintf(`avg(avg_over_time(kubecost_network_region_egress_cost{}[%s]%s)) by (cluster_id)`, durStr, offStr)
  155. resChNetRegionCostPerGiB := ctx.Query(queryNetRegionCostPerGiB)
  156. queryNetInternetGiB := fmt.Sprintf(`sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`, durStr, offStr)
  157. resChNetInternetGiB := ctx.Query(queryNetInternetGiB)
  158. queryNetInternetCostPerGiB := fmt.Sprintf(`avg(avg_over_time(kubecost_network_internet_egress_cost{}[%s]%s)) by (cluster_id)`, durStr, offStr)
  159. resChNetInternetCostPerGiB := ctx.Query(queryNetInternetCostPerGiB)
  160. queryNamespaceLabels := fmt.Sprintf(`avg_over_time(kube_namespace_labels[%s]%s)`, durStr, offStr)
  161. resChNamespaceLabels := ctx.Query(queryNamespaceLabels)
  162. queryNamespaceAnnotations := fmt.Sprintf(`avg_over_time(kube_namespace_annotations[%s]%s)`, durStr, offStr)
  163. resChNamespaceAnnotations := ctx.Query(queryNamespaceAnnotations)
  164. queryPodLabels := fmt.Sprintf(`avg_over_time(kube_pod_labels[%s]%s)`, durStr, offStr)
  165. resChPodLabels := ctx.Query(queryPodLabels)
  166. queryPodAnnotations := fmt.Sprintf(`avg_over_time(kube_pod_annotations[%s]%s)`, durStr, offStr)
  167. resChPodAnnotations := ctx.Query(queryPodAnnotations)
  168. queryServiceLabels := fmt.Sprintf(`avg_over_time(service_selector_labels[%s]%s)`, durStr, offStr)
  169. resChServiceLabels := ctx.Query(queryServiceLabels)
  170. queryDeploymentLabels := fmt.Sprintf(`avg_over_time(deployment_match_labels[%s]%s)`, durStr, offStr)
  171. resChDeploymentLabels := ctx.Query(queryDeploymentLabels)
  172. queryStatefulSetLabels := fmt.Sprintf(`avg_over_time(statefulSet_match_labels[%s]%s)`, durStr, offStr)
  173. resChStatefulSetLabels := ctx.Query(queryStatefulSetLabels)
  174. queryDaemonSetLabels := fmt.Sprintf(`sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet"}[%s]%s)) by (pod, owner_name, namespace, cluster_id)`, durStr, offStr)
  175. resChDaemonSetLabels := ctx.Query(queryDaemonSetLabels)
  176. queryJobLabels := fmt.Sprintf(`sum(avg_over_time(kube_pod_owner{owner_kind="Job"}[%s]%s)) by (pod, owner_name, namespace ,cluster_id)`, durStr, offStr)
  177. resChJobLabels := ctx.Query(queryJobLabels)
  178. resMinutes, _ := resChMinutes.Await()
  179. resCPUCoresAllocated, _ := resChCPUCoresAllocated.Await()
  180. resCPURequests, _ := resChCPURequests.Await()
  181. resCPUUsage, _ := resChCPUUsage.Await()
  182. resRAMBytesAllocated, _ := resChRAMBytesAllocated.Await()
  183. resRAMRequests, _ := resChRAMRequests.Await()
  184. resRAMUsage, _ := resChRAMUsage.Await()
  185. resGPUsRequested, _ := resChGPUsRequested.Await()
  186. resNodeCostPerCPUHr, _ := resChNodeCostPerCPUHr.Await()
  187. resNodeCostPerRAMGiBHr, _ := resChNodeCostPerRAMGiBHr.Await()
  188. resNodeCostPerGPUHr, _ := resChNodeCostPerGPUHr.Await()
  189. resNodeIsSpot, _ := resChNodeIsSpot.Await()
  190. resPVBytes, _ := resChPVBytes.Await()
  191. resPVCostPerGiBHour, _ := resChPVCostPerGiBHour.Await()
  192. resPVCInfo, _ := resChPVCInfo.Await()
  193. resPVCBytesRequested, _ := resChPVCBytesRequested.Await()
  194. resPodPVCAllocation, _ := resChPodPVCAllocation.Await()
  195. resNetZoneGiB, _ := resChNetZoneGiB.Await()
  196. resNetZoneCostPerGiB, _ := resChNetZoneCostPerGiB.Await()
  197. resNetRegionGiB, _ := resChNetRegionGiB.Await()
  198. resNetRegionCostPerGiB, _ := resChNetRegionCostPerGiB.Await()
  199. resNetInternetGiB, _ := resChNetInternetGiB.Await()
  200. resNetInternetCostPerGiB, _ := resChNetInternetCostPerGiB.Await()
  201. resNamespaceLabels, _ := resChNamespaceLabels.Await()
  202. resNamespaceAnnotations, _ := resChNamespaceAnnotations.Await()
  203. resPodLabels, _ := resChPodLabels.Await()
  204. resPodAnnotations, _ := resChPodAnnotations.Await()
  205. resServiceLabels, _ := resChServiceLabels.Await()
  206. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  207. resStatefulSetLabels, _ := resChStatefulSetLabels.Await()
  208. resDaemonSetLabels, _ := resChDaemonSetLabels.Await()
  209. resJobLabels, _ := resChJobLabels.Await()
  210. // ----------------------------------------------------------------------//
  211. // TODO niko/cdmr remove all logs after testing
  212. // log.Infof("CostModel.ComputeAllocation: minutes : %s", queryMinutes)
  213. // log.Infof("CostModel.ComputeAllocation: CPU cores: %s", queryCPUCoresAllocated)
  214. // log.Infof("CostModel.ComputeAllocation: CPU req : %s", queryCPURequests)
  215. // log.Infof("CostModel.ComputeAllocation: CPU use : %s", queryCPUUsage)
  216. // log.Infof("CostModel.ComputeAllocation: $/CPU*Hr : %s", queryNodeCostPerCPUHr)
  217. // log.Infof("CostModel.ComputeAllocation: RAM bytes: %s", queryRAMBytesAllocated)
  218. // log.Infof("CostModel.ComputeAllocation: RAM req : %s", queryRAMRequests)
  219. // log.Infof("CostModel.ComputeAllocation: RAM use : %s", queryRAMUsage)
  220. // log.Infof("CostModel.ComputeAllocation: $/GiB*Hr : %s", queryNodeCostPerRAMGiBHr)
  221. // log.Infof("CostModel.ComputeAllocation: PV $/gbhr: %s", queryPVCostPerGiBHour)
  222. // log.Infof("CostModel.ComputeAllocation: PV bytes : %s", queryPVBytes)
  223. // log.Infof("CostModel.ComputeAllocation: PVC alloc: %s", queryPodPVCAllocation)
  224. // log.Infof("CostModel.ComputeAllocation: PVC bytes: %s", queryPVCBytesRequested)
  225. // log.Infof("CostModel.ComputeAllocation: PVC info : %s", queryPVCInfo)
  226. // log.Infof("CostModel.ComputeAllocation: Net Z GiB: %s", queryNetZoneGiB)
  227. // log.Infof("CostModel.ComputeAllocation: Net Z $ : %s", queryNetZoneCostPerGiB)
  228. // log.Infof("CostModel.ComputeAllocation: Net R GiB: %s", queryNetRegionGiB)
  229. // log.Infof("CostModel.ComputeAllocation: Net R $ : %s", queryNetRegionCostPerGiB)
  230. // log.Infof("CostModel.ComputeAllocation: Net I GiB: %s", queryNetInternetGiB)
  231. // log.Infof("CostModel.ComputeAllocation: Net I $ : %s", queryNetInternetCostPerGiB)
  232. // log.Infof("CostModel.ComputeAllocation: NamespaceLabels: %s", queryNamespaceLabels)
  233. // log.Infof("CostModel.ComputeAllocation: NamespaceAnnotations: %s", queryNamespaceAnnotations)
  234. // log.Infof("CostModel.ComputeAllocation: PodLabels: %s", queryPodLabels)
  235. // log.Infof("CostModel.ComputeAllocation: PodAnnotations: %s", queryPodAnnotations)
  236. // log.Infof("CostModel.ComputeAllocation: ServiceLabels: %s", queryServiceLabels)
  237. // log.Infof("CostModel.ComputeAllocation: DeploymentLabels: %s", queryDeploymentLabels)
  238. // log.Infof("CostModel.ComputeAllocation: StatefulSetLabels: %s", queryStatefulSetLabels)
  239. // log.Infof("CostModel.ComputeAllocation: DaemonSetLabels: %s", queryDaemonSetLabels)
  240. // log.Infof("CostModel.ComputeAllocation: JobLabels: %s", queryJobLabels)
  241. log.Profile(startQuerying, "CostModel.ComputeAllocation: queries complete")
  242. defer log.Profile(time.Now(), "CostModel.ComputeAllocation: processing complete")
  243. // ----------------------------------------------------------------------//
  244. // Build out a map of Allocations, starting with (start, end) so that we
  245. // begin with minutes, from which we compute resource allocation and cost
  246. // totals from measured rate data.
  247. // TODO niko/cdmr can we start with a reasonable guess at map size?
  248. allocationMap := map[containerKey]*kubecost.Allocation{}
  249. // Keep track of the allocations per pod, for the sake of splitting PVC and
  250. // Network allocation into per-Allocation from per-Pod.
  251. podAllocation := map[podKey][]*kubecost.Allocation{}
  252. // clusterStarts and clusterEnds record the earliest start and latest end
  253. // times, respectively, on a cluster-basis. These are used for unmounted
  254. // PVs and other "virtual" Allocations so that minutes are maximally
  255. // accurate during start-up or spin-down of a cluster
  256. clusterStart := map[string]time.Time{}
  257. clusterEnd := map[string]time.Time{}
  258. buildAllocationMap(window, allocationMap, podAllocation, clusterStart, clusterEnd, resMinutes)
  259. applyCPUCoresAllocated(allocationMap, resCPUCoresAllocated)
  260. applyCPUCoresRequested(allocationMap, resCPURequests)
  261. applyCPUCoresUsed(allocationMap, resCPUUsage)
  262. applyRAMBytesAllocated(allocationMap, resRAMBytesAllocated)
  263. applyRAMBytesRequested(allocationMap, resRAMRequests)
  264. applyRAMBytesUsed(allocationMap, resRAMUsage)
  265. applyGPUsRequested(allocationMap, resGPUsRequested)
  266. applyNetworkAllocation(allocationMap, podAllocation, resNetZoneGiB, resNetZoneCostPerGiB)
  267. applyNetworkAllocation(allocationMap, podAllocation, resNetRegionGiB, resNetRegionCostPerGiB)
  268. applyNetworkAllocation(allocationMap, podAllocation, resNetInternetGiB, resNetInternetCostPerGiB)
  269. // TODO niko/cdmr pruneDuplicateData? (see costmodel.go)
  270. namespaceLabels := resToNamespaceLabels(resNamespaceLabels)
  271. podLabels := resToPodLabels(resPodLabels)
  272. namespaceAnnotations := resToNamespaceAnnotations(resNamespaceAnnotations)
  273. podAnnotations := resToPodAnnotations(resPodAnnotations)
  274. applyLabels(allocationMap, namespaceLabels, podLabels)
  275. applyAnnotations(allocationMap, namespaceAnnotations, podAnnotations)
  276. serviceLabels := getServiceLabels(resServiceLabels)
  277. applyServicesToPods(allocationMap, podLabels, serviceLabels)
  278. podDeploymentMap := labelsToPodControllerMap(podLabels, resToDeploymentLabels(resDeploymentLabels))
  279. podStatefulSetMap := labelsToPodControllerMap(podLabels, resToStatefulSetLabels(resStatefulSetLabels))
  280. podDaemonSetMap := resToPodDaemonSetMap(resDaemonSetLabels)
  281. podJobMap := resToPodJobMap(resJobLabels)
  282. applyControllersToPods(allocationMap, podDeploymentMap)
  283. applyControllersToPods(allocationMap, podStatefulSetMap)
  284. applyControllersToPods(allocationMap, podDaemonSetMap)
  285. applyControllersToPods(allocationMap, podJobMap)
  286. // TODO niko/cdmr breakdown network costs?
  287. // Build out a map of Nodes with resource costs, discounts, and node types
  288. // for converting resource allocation data to cumulative costs.
  289. nodeMap := map[nodeKey]*Node{}
  290. applyNodeCostPerCPUHr(nodeMap, resNodeCostPerCPUHr)
  291. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr)
  292. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr)
  293. applyNodeSpot(nodeMap, resNodeIsSpot)
  294. applyNodeDiscount(nodeMap, cm)
  295. // TODO niko/cdmr comment
  296. pvMap := map[pvKey]*PV{}
  297. buildPVMap(pvMap, resPVCostPerGiBHour)
  298. applyPVBytes(pvMap, resPVBytes)
  299. // TODO niko/cdmr apply PV bytes?
  300. // TODO niko/cdmr comment
  301. pvcMap := map[pvcKey]*PVC{}
  302. buildPVCMap(window, pvcMap, pvMap, resPVCInfo)
  303. applyPVCBytesRequested(pvcMap, resPVCBytesRequested)
  304. // TODO niko/cdmr comment
  305. podPVCMap := map[podKey][]*PVC{}
  306. buildPodPVCMap(podPVCMap, pvMap, pvcMap, podAllocation, resPodPVCAllocation)
  307. // Identify unmounted PVs (PVs without PVCs) and add one Allocation per
  308. // cluster representing each cluster's unmounted PVs (if necessary).
  309. applyUnmountedPVs(window, allocationMap, pvMap, pvcMap)
  310. for _, alloc := range allocationMap {
  311. cluster, _ := alloc.Properties.GetCluster()
  312. node, _ := alloc.Properties.GetNode()
  313. namespace, _ := alloc.Properties.GetNamespace()
  314. pod, _ := alloc.Properties.GetPod()
  315. podKey := newPodKey(cluster, namespace, pod)
  316. nodeKey := newNodeKey(cluster, node)
  317. if n, ok := nodeMap[nodeKey]; !ok {
  318. if pod != "unmounted-pvs" {
  319. log.Warningf("CostModel.ComputeAllocation: failed to find node %s for %s", nodeKey, alloc.Name)
  320. }
  321. } else {
  322. alloc.CPUCost = alloc.CPUCoreHours * n.CostPerCPUHr
  323. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * n.CostPerRAMGiBHr
  324. alloc.GPUCost = alloc.GPUHours * n.CostPerGPUHr
  325. }
  326. if pvcs, ok := podPVCMap[podKey]; ok {
  327. for _, pvc := range pvcs {
  328. // Determine the (start, end) of the relationship between the
  329. // given PVC and the associated Allocation so that a precise
  330. // number of hours can be used to compute cumulative cost.
  331. s, e := alloc.Start, alloc.End
  332. if pvc.Start.After(alloc.Start) {
  333. s = pvc.Start
  334. }
  335. if pvc.End.Before(alloc.End) {
  336. e = pvc.End
  337. }
  338. minutes := e.Sub(s).Minutes()
  339. hrs := minutes / 60.0
  340. gib := pvc.Bytes / 1024 / 1024 / 1024
  341. alloc.PVByteHours += pvc.Bytes * hrs
  342. alloc.PVCost += pvc.Volume.CostPerGiBHour * gib * hrs / float64(pvc.Count)
  343. }
  344. }
  345. alloc.TotalCost = 0.0
  346. alloc.TotalCost += alloc.CPUCost
  347. alloc.TotalCost += alloc.RAMCost
  348. alloc.TotalCost += alloc.GPUCost
  349. alloc.TotalCost += alloc.PVCost
  350. alloc.TotalCost += alloc.NetworkCost
  351. alloc.TotalCost += alloc.SharedCost
  352. alloc.TotalCost += alloc.ExternalCost
  353. allocSet.Set(alloc)
  354. }
  355. return allocSet, nil
  356. }
  357. func buildAllocationMap(window kubecost.Window, allocationMap map[containerKey]*kubecost.Allocation, podAllocation map[podKey][]*kubecost.Allocation, clusterStart, clusterEnd map[string]time.Time, resMinutes []*prom.QueryResult) {
  358. for _, res := range resMinutes {
  359. if len(res.Values) == 0 {
  360. log.Warningf("CostModel.ComputeAllocation: empty minutes result")
  361. continue
  362. }
  363. cluster, err := res.GetString("cluster_id")
  364. if err != nil {
  365. cluster = env.GetClusterID()
  366. }
  367. labels, err := res.GetStrings("kubernetes_node", "namespace", "pod", "container")
  368. if err != nil {
  369. log.Warningf("CostModel.ComputeAllocation: minutes query result missing field: %s", err)
  370. continue
  371. }
  372. node := labels["kubernetes_node"]
  373. namespace := labels["namespace"]
  374. pod := labels["pod"]
  375. container := labels["container"]
  376. containerKey := newContainerKey(cluster, namespace, pod, container)
  377. podKey := newPodKey(cluster, namespace, pod)
  378. // allocStart and allocEnd are the timestamps of the first and last
  379. // minutes the allocation was running, respectively. We subtract 1m
  380. // from allocStart because this point will actually represent the end
  381. // of the first minute. We don't subtract from allocEnd because it
  382. // already represents the end of the last minute.
  383. var allocStart, allocEnd time.Time
  384. for _, datum := range res.Values {
  385. t := time.Unix(int64(datum.Timestamp), 0)
  386. if allocStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  387. allocStart = t
  388. }
  389. if datum.Value > 0 && window.Contains(t) {
  390. allocEnd = t
  391. }
  392. }
  393. if allocStart.IsZero() || allocEnd.IsZero() {
  394. // TODO niko/cdmr remove log?
  395. // log.Warningf("CostModel.ComputeAllocation: allocation %s has no running time, skipping", containerKey)
  396. continue
  397. }
  398. allocStart = allocStart.Add(-time.Minute)
  399. // Set start if unset or this datum's start time is earlier than the
  400. // current earliest time.
  401. if _, ok := clusterStart[cluster]; !ok || allocStart.Before(clusterStart[cluster]) {
  402. clusterStart[cluster] = allocStart
  403. }
  404. // Set end if unset or this datum's end time is later than the
  405. // current latest time.
  406. if _, ok := clusterEnd[cluster]; !ok || allocEnd.After(clusterEnd[cluster]) {
  407. clusterEnd[cluster] = allocEnd
  408. }
  409. name := fmt.Sprintf("%s/%s/%s/%s", cluster, namespace, pod, container)
  410. alloc := &kubecost.Allocation{
  411. Name: name,
  412. Properties: kubecost.Properties{},
  413. Window: window.Clone(),
  414. Start: allocStart,
  415. End: allocEnd,
  416. }
  417. alloc.Properties.SetContainer(container)
  418. alloc.Properties.SetPod(pod)
  419. alloc.Properties.SetNamespace(namespace)
  420. alloc.Properties.SetNode(node)
  421. alloc.Properties.SetCluster(cluster)
  422. allocationMap[containerKey] = alloc
  423. if _, ok := podAllocation[podKey]; !ok {
  424. podAllocation[podKey] = []*kubecost.Allocation{}
  425. }
  426. podAllocation[podKey] = append(podAllocation[podKey], alloc)
  427. }
  428. }
  429. func applyCPUCoresAllocated(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresAllocated []*prom.QueryResult) {
  430. for _, res := range resCPUCoresAllocated {
  431. // TODO niko/cdmr do we need node here?
  432. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  433. if err != nil {
  434. log.Warningf("CostModel.ComputeAllocation: CPU allocation query result missing field: %s", err)
  435. continue
  436. }
  437. _, ok := allocationMap[key]
  438. if !ok {
  439. log.Warningf("CostModel.ComputeAllocation: unidentified CPU allocation query result: %s", key)
  440. continue
  441. }
  442. cpuCores := res.Values[0].Value
  443. hours := allocationMap[key].Minutes() / 60.0
  444. allocationMap[key].CPUCoreHours = cpuCores * hours
  445. }
  446. }
  447. func applyCPUCoresRequested(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresRequested []*prom.QueryResult) {
  448. for _, res := range resCPUCoresRequested {
  449. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  450. if err != nil {
  451. log.Warningf("CostModel.ComputeAllocation: CPU request query result missing field: %s", err)
  452. continue
  453. }
  454. _, ok := allocationMap[key]
  455. if !ok {
  456. // TODO niko/cdmr remove log?
  457. // log.Warningf("CostModel.ComputeAllocation: unidentified CPU request query result: %s", key)
  458. continue
  459. }
  460. allocationMap[key].CPUCoreRequestAverage = res.Values[0].Value
  461. // CPU allocation is less than requests, so set CPUCoreHours to
  462. // request level.
  463. // TODO niko/cdmr why is this happening?
  464. if allocationMap[key].CPUCores() < res.Values[0].Value {
  465. allocationMap[key].CPUCoreHours = res.Values[0].Value * (allocationMap[key].Minutes() / 60.0)
  466. }
  467. }
  468. }
  469. func applyCPUCoresUsed(allocationMap map[containerKey]*kubecost.Allocation, resCPUCoresUsed []*prom.QueryResult) {
  470. for _, res := range resCPUCoresUsed {
  471. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod_name", "container_name")
  472. if err != nil {
  473. log.Warningf("CostModel.ComputeAllocation: CPU usage query result missing field: %s", err)
  474. continue
  475. }
  476. _, ok := allocationMap[key]
  477. if !ok {
  478. log.Warningf("CostModel.ComputeAllocation: unidentified CPU usage query result: %s", key)
  479. continue
  480. }
  481. allocationMap[key].CPUCoreUsageAverage = res.Values[0].Value
  482. }
  483. }
  484. func applyRAMBytesRequested(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesRequested []*prom.QueryResult) {
  485. for _, res := range resRAMBytesRequested {
  486. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  487. if err != nil {
  488. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing field: %s", err)
  489. continue
  490. }
  491. _, ok := allocationMap[key]
  492. if !ok {
  493. // TODO niko/cdmr remove log?
  494. // log.Warningf("CostModel.ComputeAllocation: unidentified RAM request query result: %s", key)
  495. continue
  496. }
  497. allocationMap[key].RAMBytesRequestAverage = res.Values[0].Value
  498. // RAM allocation is less than requests, so set RAMByteHours to
  499. // request level.
  500. // TODO niko/cdmr why is this happening?
  501. if allocationMap[key].RAMBytes() < res.Values[0].Value {
  502. allocationMap[key].RAMByteHours = res.Values[0].Value * (allocationMap[key].Minutes() / 60.0)
  503. }
  504. }
  505. }
  506. func applyRAMBytesUsed(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesUsed []*prom.QueryResult) {
  507. for _, res := range resRAMBytesUsed {
  508. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod_name", "container_name")
  509. if err != nil {
  510. log.Warningf("CostModel.ComputeAllocation: RAM usage query result missing field: %s", err)
  511. continue
  512. }
  513. _, ok := allocationMap[key]
  514. if !ok {
  515. log.Warningf("CostModel.ComputeAllocation: unidentified RAM usage query result: %s", key)
  516. continue
  517. }
  518. allocationMap[key].RAMBytesUsageAverage = res.Values[0].Value
  519. }
  520. }
  521. func applyRAMBytesAllocated(allocationMap map[containerKey]*kubecost.Allocation, resRAMBytesAllocated []*prom.QueryResult) {
  522. for _, res := range resRAMBytesAllocated {
  523. // TODO niko/cdmr do we need node here?
  524. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  525. if err != nil {
  526. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing field: %s", err)
  527. continue
  528. }
  529. _, ok := allocationMap[key]
  530. if !ok {
  531. log.Warningf("CostModel.ComputeAllocation: unidentified RAM allocation query result: %s", key)
  532. continue
  533. }
  534. ramBytes := res.Values[0].Value
  535. hours := allocationMap[key].Minutes() / 60.0
  536. allocationMap[key].RAMByteHours = ramBytes * hours
  537. }
  538. }
  539. func applyGPUsRequested(allocationMap map[containerKey]*kubecost.Allocation, resGPUsRequested []*prom.QueryResult) {
  540. for _, res := range resGPUsRequested {
  541. // TODO niko/cdmr do we need node here?
  542. key, err := resultContainerKey(res, "cluster_id", "namespace", "pod", "container")
  543. if err != nil {
  544. log.Warningf("CostModel.ComputeAllocation: GPU allocation query result missing field: %s", err)
  545. continue
  546. }
  547. _, ok := allocationMap[key]
  548. if !ok {
  549. log.Warningf("CostModel.ComputeAllocation: unidentified GPU allocation query result: %s", key)
  550. continue
  551. }
  552. // TODO niko/cdmr complete
  553. log.Infof("CostModel.ComputeAllocation: GPU results: %s=%f", key, res.Values[0].Value)
  554. }
  555. }
  556. func applyNetworkAllocation(allocationMap map[containerKey]*kubecost.Allocation, podAllocation map[podKey][]*kubecost.Allocation, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult) {
  557. costPerGiBByCluster := map[string]float64{}
  558. for _, res := range resNetworkCostPerGiB {
  559. cluster, err := res.GetString("cluster_id")
  560. if err != nil {
  561. cluster = env.GetClusterID()
  562. }
  563. costPerGiBByCluster[cluster] = res.Values[0].Value
  564. }
  565. for _, res := range resNetworkGiB {
  566. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  567. if err != nil {
  568. log.Warningf("CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  569. continue
  570. }
  571. allocs, ok := podAllocation[podKey]
  572. if !ok {
  573. log.Warningf("CostModel.ComputeAllocation: Network allocation query result for unidentified pod allocations: %s", podKey)
  574. continue
  575. }
  576. for _, alloc := range allocs {
  577. gib := res.Values[0].Value
  578. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  579. alloc.NetworkCost = gib * costPerGiB
  580. }
  581. }
  582. }
  583. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[string]map[string]string {
  584. namespaceLabels := map[string]map[string]string{}
  585. for _, res := range resNamespaceLabels {
  586. namespace, err := res.GetString("namespace")
  587. if err != nil {
  588. continue
  589. }
  590. if _, ok := namespaceLabels[namespace]; !ok {
  591. namespaceLabels[namespace] = map[string]string{}
  592. }
  593. for k, l := range res.GetLabels() {
  594. namespaceLabels[namespace][k] = l
  595. }
  596. }
  597. return namespaceLabels
  598. }
  599. func resToPodLabels(resPodLabels []*prom.QueryResult) map[podKey]map[string]string {
  600. podLabels := map[podKey]map[string]string{}
  601. for _, res := range resPodLabels {
  602. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  603. if err != nil {
  604. continue
  605. }
  606. if _, ok := podLabels[podKey]; !ok {
  607. podLabels[podKey] = map[string]string{}
  608. }
  609. for k, l := range res.GetLabels() {
  610. podLabels[podKey][k] = l
  611. }
  612. }
  613. return podLabels
  614. }
  615. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  616. namespaceAnnotations := map[string]map[string]string{}
  617. for _, res := range resNamespaceAnnotations {
  618. namespace, err := res.GetString("namespace")
  619. if err != nil {
  620. continue
  621. }
  622. if _, ok := namespaceAnnotations[namespace]; !ok {
  623. namespaceAnnotations[namespace] = map[string]string{}
  624. }
  625. for k, l := range res.GetAnnotations() {
  626. namespaceAnnotations[namespace][k] = l
  627. }
  628. }
  629. return namespaceAnnotations
  630. }
  631. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult) map[podKey]map[string]string {
  632. podAnnotations := map[podKey]map[string]string{}
  633. for _, res := range resPodAnnotations {
  634. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  635. if err != nil {
  636. continue
  637. }
  638. if _, ok := podAnnotations[podKey]; !ok {
  639. podAnnotations[podKey] = map[string]string{}
  640. }
  641. for k, l := range res.GetAnnotations() {
  642. podAnnotations[podKey][k] = l
  643. }
  644. }
  645. return podAnnotations
  646. }
  647. func applyLabels(allocationMap map[containerKey]*kubecost.Allocation, namespaceLabels map[string]map[string]string, podLabels map[podKey]map[string]string) {
  648. for key, alloc := range allocationMap {
  649. allocLabels, err := alloc.Properties.GetLabels()
  650. if err != nil {
  651. allocLabels = map[string]string{}
  652. }
  653. // Apply namespace labels first, then pod labels so that pod labels
  654. // overwrite namespace labels.
  655. if labels, ok := namespaceLabels[key.Namespace]; ok {
  656. for k, v := range labels {
  657. allocLabels[k] = v
  658. }
  659. }
  660. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  661. if labels, ok := podLabels[podKey]; ok {
  662. for k, v := range labels {
  663. allocLabels[k] = v
  664. }
  665. }
  666. alloc.Properties.SetLabels(allocLabels)
  667. }
  668. }
  669. func applyAnnotations(allocationMap map[containerKey]*kubecost.Allocation, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  670. for key, alloc := range allocationMap {
  671. allocAnnotations, err := alloc.Properties.GetAnnotations()
  672. if err != nil {
  673. allocAnnotations = map[string]string{}
  674. }
  675. // Apply namespace annotations first, then pod annotations so that
  676. // pod labels overwrite namespace labels.
  677. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  678. for k, v := range labels {
  679. allocAnnotations[k] = v
  680. }
  681. }
  682. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  683. if labels, ok := podAnnotations[podKey]; ok {
  684. for k, v := range labels {
  685. allocAnnotations[k] = v
  686. }
  687. }
  688. alloc.Properties.SetAnnotations(allocAnnotations)
  689. }
  690. }
  691. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  692. serviceLabels := map[serviceKey]map[string]string{}
  693. for _, res := range resServiceLabels {
  694. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service")
  695. if err != nil {
  696. continue
  697. }
  698. if _, ok := serviceLabels[serviceKey]; !ok {
  699. serviceLabels[serviceKey] = map[string]string{}
  700. }
  701. for k, l := range res.GetLabels() {
  702. serviceLabels[serviceKey][k] = l
  703. }
  704. }
  705. return serviceLabels
  706. }
  707. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  708. deploymentLabels := map[controllerKey]map[string]string{}
  709. for _, res := range resDeploymentLabels {
  710. controllerKey, err := resultDeploymentKey(res, "cluster_id", "namespace", "deployment")
  711. if err != nil {
  712. continue
  713. }
  714. if _, ok := deploymentLabels[controllerKey]; !ok {
  715. deploymentLabels[controllerKey] = map[string]string{}
  716. }
  717. for k, l := range res.GetLabels() {
  718. deploymentLabels[controllerKey][k] = l
  719. }
  720. }
  721. return deploymentLabels
  722. }
  723. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  724. statefulSetLabels := map[controllerKey]map[string]string{}
  725. for _, res := range resStatefulSetLabels {
  726. controllerKey, err := resultStatefulSetKey(res, "cluster_id", "namespace", "statefulSet")
  727. if err != nil {
  728. continue
  729. }
  730. if _, ok := statefulSetLabels[controllerKey]; !ok {
  731. statefulSetLabels[controllerKey] = map[string]string{}
  732. }
  733. for k, l := range res.GetLabels() {
  734. statefulSetLabels[controllerKey][k] = l
  735. }
  736. }
  737. return statefulSetLabels
  738. }
  739. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  740. podControllerMap := map[podKey]controllerKey{}
  741. // For each controller, turn the labels into a selector and attempt to
  742. // match it with each set of pod labels. A match indicates that the pod
  743. // belongs to the controller.
  744. for cKey, cLabels := range controllerLabels {
  745. selector := labels.Set(cLabels).AsSelectorPreValidated()
  746. for pKey, pLabels := range podLabels {
  747. // If the pod is in a different cluster or namespace, there is
  748. // no need to compare the labels.
  749. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  750. continue
  751. }
  752. podLabelSet := labels.Set(pLabels)
  753. if selector.Matches(podLabelSet) {
  754. // TODO niko/cdmr does this need to be one-to-many? In that case, we'd
  755. // need a different Allocation schema
  756. if _, ok := podControllerMap[pKey]; ok {
  757. // TODO niko/cdmr remove log
  758. log.Warningf("CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  759. }
  760. podControllerMap[pKey] = cKey
  761. }
  762. }
  763. }
  764. return podControllerMap
  765. }
  766. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult) map[podKey]controllerKey {
  767. daemonSetLabels := map[podKey]controllerKey{}
  768. for _, res := range resDaemonSetLabels {
  769. controllerKey, err := resultDaemonSetKey(res, "cluster_id", "namespace", "owner_name")
  770. if err != nil {
  771. continue
  772. }
  773. pod, err := res.GetString("pod")
  774. if err != nil {
  775. log.Warningf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  776. }
  777. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  778. daemonSetLabels[podKey] = controllerKey
  779. }
  780. return daemonSetLabels
  781. }
  782. func resToPodJobMap(resJobLabels []*prom.QueryResult) map[podKey]controllerKey {
  783. jobLabels := map[podKey]controllerKey{}
  784. for _, res := range resJobLabels {
  785. controllerKey, err := resultJobKey(res, "cluster_id", "namespace", "owner_name")
  786. if err != nil {
  787. continue
  788. }
  789. pod, err := res.GetString("pod")
  790. if err != nil {
  791. log.Warningf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  792. }
  793. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  794. jobLabels[podKey] = controllerKey
  795. }
  796. return jobLabels
  797. }
  798. func applyServicesToPods(allocationMap map[containerKey]*kubecost.Allocation, podLabels map[podKey]map[string]string, serviceLabels map[serviceKey]map[string]string) {
  799. podServicesMap := map[podKey][]serviceKey{}
  800. // For each service, turn the labels into a selector and attempt to
  801. // match it with each set of pod labels. A match indicates that the pod
  802. // belongs to the service.
  803. for sKey, sLabels := range serviceLabels {
  804. selector := labels.Set(sLabels).AsSelectorPreValidated()
  805. for pKey, pLabels := range podLabels {
  806. // If the pod is in a different cluster or namespace, there is
  807. // no need to compare the labels.
  808. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  809. continue
  810. }
  811. podLabelSet := labels.Set(pLabels)
  812. if selector.Matches(podLabelSet) {
  813. if _, ok := podServicesMap[pKey]; !ok {
  814. podServicesMap[pKey] = []serviceKey{}
  815. }
  816. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  817. }
  818. }
  819. }
  820. // For each allocation, attempt to find and apply the list of services
  821. // associated with the allocation's pod.
  822. for key, alloc := range allocationMap {
  823. pKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  824. if sKeys, ok := podServicesMap[pKey]; ok {
  825. services := []string{}
  826. for _, sKey := range sKeys {
  827. services = append(services, sKey.Service)
  828. }
  829. alloc.Properties.SetServices(services)
  830. }
  831. }
  832. }
  833. func applyControllersToPods(allocationMap map[containerKey]*kubecost.Allocation, podControllerMap map[podKey]controllerKey) {
  834. for key, alloc := range allocationMap {
  835. podKey := newPodKey(key.Cluster, key.Namespace, key.Pod)
  836. if controllerKey, ok := podControllerMap[podKey]; ok {
  837. alloc.Properties.SetControllerKind(controllerKey.ControllerKind)
  838. alloc.Properties.SetController(controllerKey.Controller)
  839. }
  840. }
  841. }
  842. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*Node, resNodeCostPerCPUHr []*prom.QueryResult) {
  843. for _, res := range resNodeCostPerCPUHr {
  844. cluster, err := res.GetString("cluster_id")
  845. if err != nil {
  846. cluster = env.GetClusterID()
  847. }
  848. node, err := res.GetString("node")
  849. if err != nil {
  850. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  851. continue
  852. }
  853. instanceType, err := res.GetString("instance_type")
  854. if err != nil {
  855. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  856. continue
  857. }
  858. key := newNodeKey(cluster, node)
  859. if _, ok := nodeMap[key]; !ok {
  860. nodeMap[key] = &Node{
  861. Name: node,
  862. NodeType: instanceType,
  863. }
  864. }
  865. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  866. }
  867. }
  868. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*Node, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  869. for _, res := range resNodeCostPerRAMGiBHr {
  870. cluster, err := res.GetString("cluster_id")
  871. if err != nil {
  872. cluster = env.GetClusterID()
  873. }
  874. node, err := res.GetString("node")
  875. if err != nil {
  876. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  877. continue
  878. }
  879. instanceType, err := res.GetString("instance_type")
  880. if err != nil {
  881. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  882. continue
  883. }
  884. key := newNodeKey(cluster, node)
  885. if _, ok := nodeMap[key]; !ok {
  886. nodeMap[key] = &Node{
  887. Name: node,
  888. NodeType: instanceType,
  889. }
  890. }
  891. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  892. }
  893. }
  894. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*Node, resNodeCostPerGPUHr []*prom.QueryResult) {
  895. for _, res := range resNodeCostPerGPUHr {
  896. cluster, err := res.GetString("cluster_id")
  897. if err != nil {
  898. cluster = env.GetClusterID()
  899. }
  900. node, err := res.GetString("node")
  901. if err != nil {
  902. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  903. continue
  904. }
  905. instanceType, err := res.GetString("instance_type")
  906. if err != nil {
  907. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  908. continue
  909. }
  910. key := newNodeKey(cluster, node)
  911. if _, ok := nodeMap[key]; !ok {
  912. nodeMap[key] = &Node{
  913. Name: node,
  914. NodeType: instanceType,
  915. }
  916. }
  917. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  918. }
  919. }
  920. func applyNodeSpot(nodeMap map[nodeKey]*Node, resNodeIsSpot []*prom.QueryResult) {
  921. for _, res := range resNodeIsSpot {
  922. cluster, err := res.GetString("cluster_id")
  923. if err != nil {
  924. cluster = env.GetClusterID()
  925. }
  926. node, err := res.GetString("node")
  927. if err != nil {
  928. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  929. continue
  930. }
  931. key := newNodeKey(cluster, node)
  932. if _, ok := nodeMap[key]; !ok {
  933. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  934. continue
  935. }
  936. nodeMap[key].Preemptible = res.Values[0].Value > 0
  937. }
  938. }
  939. func applyNodeDiscount(nodeMap map[nodeKey]*Node, cm *CostModel) {
  940. if cm == nil {
  941. return
  942. }
  943. c, err := cm.Provider.GetConfig()
  944. if err != nil {
  945. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  946. return
  947. }
  948. discount, err := ParsePercentString(c.Discount)
  949. if err != nil {
  950. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  951. return
  952. }
  953. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  954. if err != nil {
  955. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  956. return
  957. }
  958. for _, node := range nodeMap {
  959. // TODO niko/cdmr take RI into account?
  960. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  961. node.CostPerCPUHr *= (1.0 - node.Discount)
  962. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  963. }
  964. }
  965. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  966. for _, res := range resPVCostPerGiBHour {
  967. cluster, err := res.GetString("cluster_id")
  968. if err != nil {
  969. cluster = env.GetClusterID()
  970. }
  971. name, err := res.GetString("volumename")
  972. if err != nil {
  973. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  974. continue
  975. }
  976. key := newPVKey(cluster, name)
  977. pvMap[key] = &PV{
  978. Cluster: cluster,
  979. Name: name,
  980. CostPerGiBHour: res.Values[0].Value,
  981. }
  982. }
  983. }
  984. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  985. for _, res := range resPVBytes {
  986. key, err := resultPVKey(res, "cluster_id", "persistentvolume")
  987. if err != nil {
  988. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  989. continue
  990. }
  991. if _, ok := pvMap[key]; !ok {
  992. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  993. continue
  994. }
  995. pvMap[key].Bytes = res.Values[0].Value
  996. }
  997. }
  998. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  999. for _, res := range resPVCInfo {
  1000. cluster, err := res.GetString("cluster_id")
  1001. if err != nil {
  1002. cluster = env.GetClusterID()
  1003. }
  1004. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1005. if err != nil {
  1006. log.Warningf("CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  1007. continue
  1008. }
  1009. // TODO niko/cdmr ?
  1010. namespace := values["namespace"]
  1011. name := values["persistentvolumeclaim"]
  1012. volume := values["volumename"]
  1013. storageClass := values["storageclass"]
  1014. pvKey := newPVKey(cluster, volume)
  1015. pvcKey := newPVCKey(cluster, namespace, name)
  1016. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  1017. // the PVC was running, respectively. We subtract 1m from pvcStart
  1018. // because this point will actually represent the end of the first
  1019. // minute. We don't subtract from pvcEnd because it already represents
  1020. // the end of the last minute.
  1021. var pvcStart, pvcEnd time.Time
  1022. for _, datum := range res.Values {
  1023. t := time.Unix(int64(datum.Timestamp), 0)
  1024. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1025. pvcStart = t
  1026. }
  1027. if datum.Value > 0 && window.Contains(t) {
  1028. pvcEnd = t
  1029. }
  1030. }
  1031. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1032. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1033. }
  1034. pvcStart = pvcStart.Add(-time.Minute)
  1035. if _, ok := pvMap[pvKey]; !ok {
  1036. log.Warningf("CostModel.ComputeAllocation: PV missing for PVC info query result: %s", pvKey)
  1037. continue
  1038. }
  1039. pvMap[pvKey].StorageClass = storageClass
  1040. if _, ok := pvcMap[pvcKey]; !ok {
  1041. pvcMap[pvcKey] = &PVC{}
  1042. }
  1043. pvcMap[pvcKey].Name = name
  1044. pvcMap[pvcKey].Namespace = namespace
  1045. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1046. pvcMap[pvcKey].Start = pvcStart
  1047. pvcMap[pvcKey].End = pvcEnd
  1048. }
  1049. }
  1050. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1051. for _, res := range resPVCBytesRequested {
  1052. key, err := resultPVCKey(res, "cluster_id", "namespace", "persistentvolumeclaim")
  1053. if err != nil {
  1054. log.Warningf("CostModel.ComputeAllocation: PVC bytes requested query result missing field: %s", err)
  1055. continue
  1056. }
  1057. if _, ok := pvcMap[key]; !ok {
  1058. log.Warningf("CostModel.ComputeAllocation: PVC bytes requested result for missing PVC: %s", err)
  1059. continue
  1060. }
  1061. pvcMap[key].Bytes = res.Values[0].Value
  1062. }
  1063. }
  1064. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podAllocation map[podKey][]*kubecost.Allocation, resPodPVCAllocation []*prom.QueryResult) {
  1065. for _, res := range resPodPVCAllocation {
  1066. cluster, err := res.GetString("cluster_id")
  1067. if err != nil {
  1068. cluster = env.GetClusterID()
  1069. }
  1070. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1071. if err != nil {
  1072. log.Warningf("CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1073. continue
  1074. }
  1075. namespace := values["namespace"]
  1076. pod := values["pod"]
  1077. name := values["persistentvolumeclaim"]
  1078. volume := values["persistentvolume"]
  1079. podKey := newPodKey(cluster, namespace, pod)
  1080. pvKey := newPVKey(cluster, volume)
  1081. pvcKey := newPVCKey(cluster, namespace, name)
  1082. if _, ok := pvMap[pvKey]; !ok {
  1083. log.Warningf("CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1084. continue
  1085. }
  1086. if _, ok := podPVCMap[podKey]; !ok {
  1087. podPVCMap[podKey] = []*PVC{}
  1088. }
  1089. pvc, ok := pvcMap[pvcKey]
  1090. if !ok {
  1091. log.Warningf("CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1092. continue
  1093. }
  1094. pvc.Count = len(podAllocation[podKey])
  1095. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1096. }
  1097. }
  1098. func applyUnmountedPVs(window kubecost.Window, allocationMap map[containerKey]*kubecost.Allocation, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1099. unmountedPVBytes := map[string]float64{}
  1100. unmountedPVCost := map[string]float64{}
  1101. for _, pv := range pvMap {
  1102. mounted := false
  1103. for _, pvc := range pvcMap {
  1104. if pvc.Volume == nil {
  1105. continue
  1106. }
  1107. if pvc.Volume == pv {
  1108. mounted = true
  1109. break
  1110. }
  1111. }
  1112. log.Infof("CostModel.ComputeAllocation: PV %s is mounted? %t", pv.Name, mounted)
  1113. if !mounted {
  1114. gib := pv.Bytes / 1024 / 1024 / 1024
  1115. hrs := window.Minutes() / 60.0
  1116. cost := pv.CostPerGiBHour * gib * hrs
  1117. unmountedPVCost[pv.Cluster] += cost
  1118. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1119. }
  1120. }
  1121. for cluster, amount := range unmountedPVCost {
  1122. container := "unmounted-pvs"
  1123. pod := "unmounted-pvs"
  1124. namespace := "" // TODO niko/cdmr what about this?
  1125. containerKey := newContainerKey(cluster, namespace, pod, container)
  1126. allocationMap[containerKey] = &kubecost.Allocation{
  1127. Name: fmt.Sprintf("%s/%s/%s/%s", cluster, namespace, pod, container),
  1128. Properties: kubecost.Properties{
  1129. kubecost.ClusterProp: cluster,
  1130. kubecost.NamespaceProp: namespace,
  1131. kubecost.PodProp: pod,
  1132. kubecost.ContainerProp: container,
  1133. },
  1134. Window: window.Clone(),
  1135. Start: *window.Start(),
  1136. End: *window.End(),
  1137. PVByteHours: unmountedPVBytes[cluster] * window.Minutes() / 60.0,
  1138. PVCost: amount,
  1139. TotalCost: amount,
  1140. }
  1141. }
  1142. }
  1143. type containerKey struct {
  1144. Cluster string
  1145. Namespace string
  1146. Pod string
  1147. Container string
  1148. }
  1149. func (k containerKey) String() string {
  1150. return fmt.Sprintf("%s/%s/%s/%s", k.Cluster, k.Namespace, k.Pod, k.Container)
  1151. }
  1152. func newContainerKey(cluster, namespace, pod, container string) containerKey {
  1153. return containerKey{
  1154. Cluster: cluster,
  1155. Namespace: namespace,
  1156. Pod: pod,
  1157. Container: container,
  1158. }
  1159. }
  1160. func resultContainerKey(res *prom.QueryResult, clusterLabel, namespaceLabel, podLabel, containerLabel string) (containerKey, error) {
  1161. key := containerKey{}
  1162. cluster, err := res.GetString(clusterLabel)
  1163. if err != nil {
  1164. cluster = env.GetClusterID()
  1165. }
  1166. key.Cluster = cluster
  1167. namespace, err := res.GetString(namespaceLabel)
  1168. if err != nil {
  1169. return key, err
  1170. }
  1171. key.Namespace = namespace
  1172. pod, err := res.GetString(podLabel)
  1173. if err != nil {
  1174. return key, err
  1175. }
  1176. key.Pod = pod
  1177. container, err := res.GetString(containerLabel)
  1178. if err != nil {
  1179. return key, err
  1180. }
  1181. key.Container = container
  1182. return key, nil
  1183. }
  1184. type podKey struct {
  1185. Cluster string
  1186. Namespace string
  1187. Pod string
  1188. }
  1189. func (k podKey) String() string {
  1190. return fmt.Sprintf("%s/%s/%s", k.Cluster, k.Namespace, k.Pod)
  1191. }
  1192. func newPodKey(cluster, namespace, pod string) podKey {
  1193. return podKey{
  1194. Cluster: cluster,
  1195. Namespace: namespace,
  1196. Pod: pod,
  1197. }
  1198. }
  1199. func resultPodKey(res *prom.QueryResult, clusterLabel, namespaceLabel, podLabel string) (podKey, error) {
  1200. key := podKey{}
  1201. cluster, err := res.GetString(clusterLabel)
  1202. if err != nil {
  1203. cluster = env.GetClusterID()
  1204. }
  1205. key.Cluster = cluster
  1206. namespace, err := res.GetString(namespaceLabel)
  1207. if err != nil {
  1208. return key, err
  1209. }
  1210. key.Namespace = namespace
  1211. pod, err := res.GetString(podLabel)
  1212. if err != nil {
  1213. return key, err
  1214. }
  1215. key.Pod = pod
  1216. return key, nil
  1217. }
  1218. type controllerKey struct {
  1219. Cluster string
  1220. Namespace string
  1221. ControllerKind string
  1222. Controller string
  1223. }
  1224. func (k controllerKey) String() string {
  1225. return fmt.Sprintf("%s/%s/%s/%s", k.Cluster, k.Namespace, k.ControllerKind, k.Controller)
  1226. }
  1227. func newControllerKey(cluster, namespace, controllerKind, controller string) controllerKey {
  1228. return controllerKey{
  1229. Cluster: cluster,
  1230. Namespace: namespace,
  1231. ControllerKind: controllerKind,
  1232. Controller: controller,
  1233. }
  1234. }
  1235. func resultControllerKey(controllerKind string, res *prom.QueryResult, clusterLabel, namespaceLabel, controllerLabel string) (controllerKey, error) {
  1236. key := controllerKey{}
  1237. cluster, err := res.GetString(clusterLabel)
  1238. if err != nil {
  1239. cluster = env.GetClusterID()
  1240. }
  1241. key.Cluster = cluster
  1242. namespace, err := res.GetString(namespaceLabel)
  1243. if err != nil {
  1244. return key, err
  1245. }
  1246. key.Namespace = namespace
  1247. controller, err := res.GetString(controllerLabel)
  1248. if err != nil {
  1249. return key, err
  1250. }
  1251. key.Controller = controller
  1252. key.ControllerKind = controllerKind
  1253. return key, nil
  1254. }
  1255. func resultDeploymentKey(res *prom.QueryResult, clusterLabel, namespaceLabel, controllerLabel string) (controllerKey, error) {
  1256. return resultControllerKey("deployment", res, clusterLabel, namespaceLabel, controllerLabel)
  1257. }
  1258. func resultStatefulSetKey(res *prom.QueryResult, clusterLabel, namespaceLabel, controllerLabel string) (controllerKey, error) {
  1259. return resultControllerKey("statefulset", res, clusterLabel, namespaceLabel, controllerLabel)
  1260. }
  1261. func resultDaemonSetKey(res *prom.QueryResult, clusterLabel, namespaceLabel, controllerLabel string) (controllerKey, error) {
  1262. return resultControllerKey("daemonset", res, clusterLabel, namespaceLabel, controllerLabel)
  1263. }
  1264. func resultJobKey(res *prom.QueryResult, clusterLabel, namespaceLabel, controllerLabel string) (controllerKey, error) {
  1265. return resultControllerKey("job", res, clusterLabel, namespaceLabel, controllerLabel)
  1266. }
  1267. type serviceKey struct {
  1268. Cluster string
  1269. Namespace string
  1270. Service string
  1271. }
  1272. func (k serviceKey) String() string {
  1273. return fmt.Sprintf("%s/%s/%s", k.Cluster, k.Namespace, k.Service)
  1274. }
  1275. func newServiceKey(cluster, namespace, service string) serviceKey {
  1276. return serviceKey{
  1277. Cluster: cluster,
  1278. Namespace: namespace,
  1279. Service: service,
  1280. }
  1281. }
  1282. func resultServiceKey(res *prom.QueryResult, clusterLabel, namespaceLabel, serviceLabel string) (serviceKey, error) {
  1283. key := serviceKey{}
  1284. cluster, err := res.GetString(clusterLabel)
  1285. if err != nil {
  1286. cluster = env.GetClusterID()
  1287. }
  1288. key.Cluster = cluster
  1289. namespace, err := res.GetString(namespaceLabel)
  1290. if err != nil {
  1291. return key, err
  1292. }
  1293. key.Namespace = namespace
  1294. service, err := res.GetString(serviceLabel)
  1295. if err != nil {
  1296. return key, err
  1297. }
  1298. key.Service = service
  1299. return key, nil
  1300. }
  1301. type nodeKey struct {
  1302. Cluster string
  1303. Node string
  1304. }
  1305. func (k nodeKey) String() string {
  1306. return fmt.Sprintf("%s/%s", k.Cluster, k.Node)
  1307. }
  1308. func newNodeKey(cluster, node string) nodeKey {
  1309. return nodeKey{
  1310. Cluster: cluster,
  1311. Node: node,
  1312. }
  1313. }
  1314. func resultNodeKey(res *prom.QueryResult, clusterLabel, nodeLabel string) (nodeKey, error) {
  1315. key := nodeKey{}
  1316. cluster, err := res.GetString(clusterLabel)
  1317. if err != nil {
  1318. cluster = env.GetClusterID()
  1319. }
  1320. key.Cluster = cluster
  1321. node, err := res.GetString(nodeLabel)
  1322. if err != nil {
  1323. return key, err
  1324. }
  1325. key.Node = node
  1326. return key, nil
  1327. }
  1328. type pvcKey struct {
  1329. Cluster string
  1330. Namespace string
  1331. PersistentVolumeClaim string
  1332. }
  1333. func (k pvcKey) String() string {
  1334. return fmt.Sprintf("%s/%s/%s", k.Cluster, k.Namespace, k.PersistentVolumeClaim)
  1335. }
  1336. func newPVCKey(cluster, namespace, persistentVolumeClaim string) pvcKey {
  1337. return pvcKey{
  1338. Cluster: cluster,
  1339. Namespace: namespace,
  1340. PersistentVolumeClaim: persistentVolumeClaim,
  1341. }
  1342. }
  1343. func resultPVCKey(res *prom.QueryResult, clusterLabel, namespaceLabel, pvcLabel string) (pvcKey, error) {
  1344. key := pvcKey{}
  1345. cluster, err := res.GetString(clusterLabel)
  1346. if err != nil {
  1347. cluster = env.GetClusterID()
  1348. }
  1349. key.Cluster = cluster
  1350. namespace, err := res.GetString(namespaceLabel)
  1351. if err != nil {
  1352. return key, err
  1353. }
  1354. key.Namespace = namespace
  1355. pvc, err := res.GetString(pvcLabel)
  1356. if err != nil {
  1357. return key, err
  1358. }
  1359. key.PersistentVolumeClaim = pvc
  1360. return key, nil
  1361. }
  1362. type pvKey struct {
  1363. Cluster string
  1364. PersistentVolume string
  1365. }
  1366. func (k pvKey) String() string {
  1367. return fmt.Sprintf("%s/%s", k.Cluster, k.PersistentVolume)
  1368. }
  1369. func newPVKey(cluster, persistentVolume string) pvKey {
  1370. return pvKey{
  1371. Cluster: cluster,
  1372. PersistentVolume: persistentVolume,
  1373. }
  1374. }
  1375. func resultPVKey(res *prom.QueryResult, clusterLabel, persistentVolumeLabel string) (pvKey, error) {
  1376. key := pvKey{}
  1377. cluster, err := res.GetString(clusterLabel)
  1378. if err != nil {
  1379. cluster = env.GetClusterID()
  1380. }
  1381. key.Cluster = cluster
  1382. persistentVolume, err := res.GetString(persistentVolumeLabel)
  1383. if err != nil {
  1384. return key, err
  1385. }
  1386. key.PersistentVolume = persistentVolume
  1387. return key, nil
  1388. }