allocation.go 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
  1. package costmodel
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/kubecost/cost-model/pkg/cloud"
  9. "github.com/kubecost/cost-model/pkg/env"
  10. "github.com/kubecost/cost-model/pkg/kubecost"
  11. "github.com/kubecost/cost-model/pkg/log"
  12. "github.com/kubecost/cost-model/pkg/prom"
  13. "github.com/kubecost/cost-model/pkg/util"
  14. "k8s.io/apimachinery/pkg/labels"
  15. )
  16. const (
  17. queryFmtPods = `avg(kube_pod_container_status_running{}) by (pod, namespace, cluster_id)[%s:%s]%s`
  18. queryFmtRAMBytesAllocated = `avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id, provider_id)`
  19. queryFmtRAMRequests = `avg(avg_over_time(kube_pod_container_resource_requests_memory_bytes{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  20. queryFmtRAMUsageAvg = `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)`
  21. queryFmtRAMUsageMax = `max(max_over_time(container_memory_working_set_bytes{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`
  22. queryFmtCPUCoresAllocated = `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  23. queryFmtCPURequests = `avg(avg_over_time(kube_pod_container_resource_requests_cpu_cores{container!="", container!="POD", node!=""}[%s]%s)) by (container, pod, namespace, node, cluster_id)`
  24. queryFmtCPUUsageAvg = `avg(rate(container_cpu_usage_seconds_total{container_name!="", container_name!="POD", instance!=""}[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`
  25. // This query could be written without the recording rule
  26. // "kubecost_savings_container_cpu_usage_seconds", but we should
  27. // only do that when we're ready to incur the performance tradeoffs
  28. // with subqueries which would probably be in the world of hourly
  29. // ETL.
  30. //
  31. // See PromQL subquery documentation for a rate example:
  32. // https://prometheus.io/blog/2019/01/28/subquery-support/#examples
  33. queryFmtCPUUsageMax = `max(max_over_time(kubecost_savings_container_cpu_usage_seconds[%s]%s)) by (container_name, pod_name, namespace, instance, cluster_id)`
  34. queryFmtGPUsRequested = `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)`
  35. queryFmtNodeCostPerCPUHr = `avg(avg_over_time(node_cpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type, provider_id)`
  36. queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost[%s]%s)) by (node, cluster_id, instance_type, provider_id)`
  37. queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type, provider_id)`
  38. queryFmtNodeIsSpot = `avg_over_time(kubecost_node_is_spot[%s]%s)`
  39. queryFmtPVCInfo = `avg(kube_persistentvolumeclaim_info{volumename != ""}) by (persistentvolumeclaim, storageclass, volumename, namespace, cluster_id)[%s:%s]%s`
  40. queryFmtPVBytes = `avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s]%s)) by (persistentvolume, cluster_id)`
  41. queryFmtPodPVCAllocation = `avg(avg_over_time(pod_pvc_allocation[%s]%s)) by (persistentvolume, persistentvolumeclaim, pod, namespace, cluster_id)`
  42. queryFmtPVCBytesRequested = `avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{}[%s]%s)) by (persistentvolumeclaim, namespace, cluster_id)`
  43. queryFmtPVCostPerGiBHour = `avg(avg_over_time(pv_hourly_cost[%s]%s)) by (volumename, cluster_id)`
  44. queryFmtNetZoneGiB = `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`
  45. queryFmtNetZoneCostPerGiB = `avg(avg_over_time(kubecost_network_zone_egress_cost{}[%s]%s)) by (cluster_id)`
  46. queryFmtNetRegionGiB = `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`
  47. queryFmtNetRegionCostPerGiB = `avg(avg_over_time(kubecost_network_region_egress_cost{}[%s]%s)) by (cluster_id)`
  48. queryFmtNetInternetGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s]%s)) by (pod_name, namespace, cluster_id) / 1024 / 1024 / 1024`
  49. queryFmtNetInternetCostPerGiB = `avg(avg_over_time(kubecost_network_internet_egress_cost{}[%s]%s)) by (cluster_id)`
  50. queryFmtNamespaceLabels = `avg_over_time(kube_namespace_labels[%s]%s)`
  51. queryFmtNamespaceAnnotations = `avg_over_time(kube_namespace_annotations[%s]%s)`
  52. queryFmtPodLabels = `avg_over_time(kube_pod_labels[%s]%s)`
  53. queryFmtPodAnnotations = `avg_over_time(kube_pod_annotations[%s]%s)`
  54. queryFmtServiceLabels = `avg_over_time(service_selector_labels[%s]%s)`
  55. queryFmtDeploymentLabels = `avg_over_time(deployment_match_labels[%s]%s)`
  56. queryFmtStatefulSetLabels = `avg_over_time(statefulSet_match_labels[%s]%s)`
  57. queryFmtDaemonSetLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet"}[%s]%s)) by (pod, owner_name, namespace, cluster_id)`
  58. queryFmtJobLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="Job"}[%s]%s)) by (pod, owner_name, namespace ,cluster_id)`
  59. queryFmtLBCostPerHr = `avg(avg_over_time(kubecost_load_balancer_cost[%s]%s)) by (namespace, service_name, cluster_id)`
  60. queryFmtLBActiveMins = `count(kubecost_load_balancer_cost) by (namespace, service_name, cluster_id)[%s:%s]%s`
  61. )
  62. // ComputeAllocation uses the CostModel instance to compute an AllocationSet
  63. // for the window defined by the given start and end times. The Allocations
  64. // returned are unaggregated (i.e. down to the container level).
  65. func (cm *CostModel) ComputeAllocation(start, end time.Time, resolution time.Duration) (*kubecost.AllocationSet, error) {
  66. // 1. Build out Pod map from resolution-tuned, batched Pod start/end query
  67. // 2. Run and apply the results of the remaining queries to
  68. // 3. Build out AllocationSet from completed Pod map
  69. // Create a window spanning the requested query
  70. window := kubecost.NewWindow(&start, &end)
  71. // Create an empty AllocationSet. For safety, in the case of an error, we
  72. // should prefer to return this empty set with the error. (In the case of
  73. // no error, of course we populate the set and return it.)
  74. allocSet := kubecost.NewAllocationSet(start, end)
  75. // (1) Build out Pod map
  76. // Build out a map of Allocations as a mapping from pod-to-container-to-
  77. // underlying-Allocation instance, starting with (start, end) so that we
  78. // begin with minutes, from which we compute resource allocation and cost
  79. // totals from measured rate data.
  80. podMap := map[podKey]*Pod{}
  81. // clusterStarts and clusterEnds record the earliest start and latest end
  82. // times, respectively, on a cluster-basis. These are used for unmounted
  83. // PVs and other "virtual" Allocations so that minutes are maximally
  84. // accurate during start-up or spin-down of a cluster
  85. clusterStart := map[string]time.Time{}
  86. clusterEnd := map[string]time.Time{}
  87. cm.buildPodMap(window, resolution, env.GetETLMaxBatchDuration(), podMap, clusterStart, clusterEnd)
  88. // (2) Run and apply remaining queries
  89. // Convert window (start, end) to (duration, offset) for querying Prometheus,
  90. // including handling Thanos offset
  91. durStr, offStr, err := window.DurationOffsetForPrometheus()
  92. if err != nil {
  93. // Negative duration, so return empty set
  94. return allocSet, nil
  95. }
  96. // Convert resolution duration to a query-ready string
  97. resStr := util.DurationString(resolution)
  98. ctx := prom.NewContext(cm.PrometheusClient)
  99. queryRAMBytesAllocated := fmt.Sprintf(queryFmtRAMBytesAllocated, durStr, offStr)
  100. resChRAMBytesAllocated := ctx.Query(queryRAMBytesAllocated)
  101. queryRAMRequests := fmt.Sprintf(queryFmtRAMRequests, durStr, offStr)
  102. resChRAMRequests := ctx.Query(queryRAMRequests)
  103. queryRAMUsageAvg := fmt.Sprintf(queryFmtRAMUsageAvg, durStr, offStr)
  104. resChRAMUsageAvg := ctx.Query(queryRAMUsageAvg)
  105. queryRAMUsageMax := fmt.Sprintf(queryFmtRAMUsageMax, durStr, offStr)
  106. resChRAMUsageMax := ctx.Query(queryRAMUsageMax)
  107. queryCPUCoresAllocated := fmt.Sprintf(queryFmtCPUCoresAllocated, durStr, offStr)
  108. resChCPUCoresAllocated := ctx.Query(queryCPUCoresAllocated)
  109. queryCPURequests := fmt.Sprintf(queryFmtCPURequests, durStr, offStr)
  110. resChCPURequests := ctx.Query(queryCPURequests)
  111. queryCPUUsageAvg := fmt.Sprintf(queryFmtCPUUsageAvg, durStr, offStr)
  112. resChCPUUsageAvg := ctx.Query(queryCPUUsageAvg)
  113. queryCPUUsageMax := fmt.Sprintf(queryFmtCPUUsageMax, durStr, offStr)
  114. resChCPUUsageMax := ctx.Query(queryCPUUsageMax)
  115. queryGPUsRequested := fmt.Sprintf(queryFmtGPUsRequested, durStr, offStr)
  116. resChGPUsRequested := ctx.Query(queryGPUsRequested)
  117. queryNodeCostPerCPUHr := fmt.Sprintf(queryFmtNodeCostPerCPUHr, durStr, offStr)
  118. resChNodeCostPerCPUHr := ctx.Query(queryNodeCostPerCPUHr)
  119. queryNodeCostPerRAMGiBHr := fmt.Sprintf(queryFmtNodeCostPerRAMGiBHr, durStr, offStr)
  120. resChNodeCostPerRAMGiBHr := ctx.Query(queryNodeCostPerRAMGiBHr)
  121. queryNodeCostPerGPUHr := fmt.Sprintf(queryFmtNodeCostPerGPUHr, durStr, offStr)
  122. resChNodeCostPerGPUHr := ctx.Query(queryNodeCostPerGPUHr)
  123. queryNodeIsSpot := fmt.Sprintf(queryFmtNodeIsSpot, durStr, offStr)
  124. resChNodeIsSpot := ctx.Query(queryNodeIsSpot)
  125. queryPVCInfo := fmt.Sprintf(queryFmtPVCInfo, durStr, resStr, offStr)
  126. resChPVCInfo := ctx.Query(queryPVCInfo)
  127. queryPVBytes := fmt.Sprintf(queryFmtPVBytes, durStr, offStr)
  128. resChPVBytes := ctx.Query(queryPVBytes)
  129. queryPodPVCAllocation := fmt.Sprintf(queryFmtPodPVCAllocation, durStr, offStr)
  130. resChPodPVCAllocation := ctx.Query(queryPodPVCAllocation)
  131. queryPVCBytesRequested := fmt.Sprintf(queryFmtPVCBytesRequested, durStr, offStr)
  132. resChPVCBytesRequested := ctx.Query(queryPVCBytesRequested)
  133. queryPVCostPerGiBHour := fmt.Sprintf(queryFmtPVCostPerGiBHour, durStr, offStr)
  134. resChPVCostPerGiBHour := ctx.Query(queryPVCostPerGiBHour)
  135. queryNetZoneGiB := fmt.Sprintf(queryFmtNetZoneGiB, durStr, offStr)
  136. resChNetZoneGiB := ctx.Query(queryNetZoneGiB)
  137. queryNetZoneCostPerGiB := fmt.Sprintf(queryFmtNetZoneCostPerGiB, durStr, offStr)
  138. resChNetZoneCostPerGiB := ctx.Query(queryNetZoneCostPerGiB)
  139. queryNetRegionGiB := fmt.Sprintf(queryFmtNetRegionGiB, durStr, offStr)
  140. resChNetRegionGiB := ctx.Query(queryNetRegionGiB)
  141. queryNetRegionCostPerGiB := fmt.Sprintf(queryFmtNetRegionCostPerGiB, durStr, offStr)
  142. resChNetRegionCostPerGiB := ctx.Query(queryNetRegionCostPerGiB)
  143. queryNetInternetGiB := fmt.Sprintf(queryFmtNetInternetGiB, durStr, offStr)
  144. resChNetInternetGiB := ctx.Query(queryNetInternetGiB)
  145. queryNetInternetCostPerGiB := fmt.Sprintf(queryFmtNetInternetCostPerGiB, durStr, offStr)
  146. resChNetInternetCostPerGiB := ctx.Query(queryNetInternetCostPerGiB)
  147. queryNamespaceLabels := fmt.Sprintf(queryFmtNamespaceLabels, durStr, offStr)
  148. resChNamespaceLabels := ctx.Query(queryNamespaceLabels)
  149. queryNamespaceAnnotations := fmt.Sprintf(queryFmtNamespaceAnnotations, durStr, offStr)
  150. resChNamespaceAnnotations := ctx.Query(queryNamespaceAnnotations)
  151. queryPodLabels := fmt.Sprintf(queryFmtPodLabels, durStr, offStr)
  152. resChPodLabels := ctx.Query(queryPodLabels)
  153. queryPodAnnotations := fmt.Sprintf(queryFmtPodAnnotations, durStr, offStr)
  154. resChPodAnnotations := ctx.Query(queryPodAnnotations)
  155. queryServiceLabels := fmt.Sprintf(queryFmtServiceLabels, durStr, offStr)
  156. resChServiceLabels := ctx.Query(queryServiceLabels)
  157. queryDeploymentLabels := fmt.Sprintf(queryFmtDeploymentLabels, durStr, offStr)
  158. resChDeploymentLabels := ctx.Query(queryDeploymentLabels)
  159. queryStatefulSetLabels := fmt.Sprintf(queryFmtStatefulSetLabels, durStr, offStr)
  160. resChStatefulSetLabels := ctx.Query(queryStatefulSetLabels)
  161. queryDaemonSetLabels := fmt.Sprintf(queryFmtDaemonSetLabels, durStr, offStr)
  162. resChDaemonSetLabels := ctx.Query(queryDaemonSetLabels)
  163. queryJobLabels := fmt.Sprintf(queryFmtJobLabels, durStr, offStr)
  164. resChJobLabels := ctx.Query(queryJobLabels)
  165. queryLBCostPerHr := fmt.Sprintf(queryFmtLBCostPerHr, durStr, offStr)
  166. resChLBCostPerHr := ctx.Query(queryLBCostPerHr)
  167. queryLBActiveMins := fmt.Sprintf(queryFmtLBActiveMins, durStr, resStr, offStr)
  168. resChLBActiveMins := ctx.Query(queryLBActiveMins)
  169. resCPUCoresAllocated, _ := resChCPUCoresAllocated.Await()
  170. resCPURequests, _ := resChCPURequests.Await()
  171. resCPUUsageAvg, _ := resChCPUUsageAvg.Await()
  172. resCPUUsageMax, _ := resChCPUUsageMax.Await()
  173. resRAMBytesAllocated, _ := resChRAMBytesAllocated.Await()
  174. resRAMRequests, _ := resChRAMRequests.Await()
  175. resRAMUsageAvg, _ := resChRAMUsageAvg.Await()
  176. resRAMUsageMax, _ := resChRAMUsageMax.Await()
  177. resGPUsRequested, _ := resChGPUsRequested.Await()
  178. resNodeCostPerCPUHr, _ := resChNodeCostPerCPUHr.Await()
  179. resNodeCostPerRAMGiBHr, _ := resChNodeCostPerRAMGiBHr.Await()
  180. resNodeCostPerGPUHr, _ := resChNodeCostPerGPUHr.Await()
  181. resNodeIsSpot, _ := resChNodeIsSpot.Await()
  182. resPVBytes, _ := resChPVBytes.Await()
  183. resPVCostPerGiBHour, _ := resChPVCostPerGiBHour.Await()
  184. resPVCInfo, _ := resChPVCInfo.Await()
  185. resPVCBytesRequested, _ := resChPVCBytesRequested.Await()
  186. resPodPVCAllocation, _ := resChPodPVCAllocation.Await()
  187. resNetZoneGiB, _ := resChNetZoneGiB.Await()
  188. resNetZoneCostPerGiB, _ := resChNetZoneCostPerGiB.Await()
  189. resNetRegionGiB, _ := resChNetRegionGiB.Await()
  190. resNetRegionCostPerGiB, _ := resChNetRegionCostPerGiB.Await()
  191. resNetInternetGiB, _ := resChNetInternetGiB.Await()
  192. resNetInternetCostPerGiB, _ := resChNetInternetCostPerGiB.Await()
  193. resNamespaceLabels, _ := resChNamespaceLabels.Await()
  194. resNamespaceAnnotations, _ := resChNamespaceAnnotations.Await()
  195. resPodLabels, _ := resChPodLabels.Await()
  196. resPodAnnotations, _ := resChPodAnnotations.Await()
  197. resServiceLabels, _ := resChServiceLabels.Await()
  198. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  199. resStatefulSetLabels, _ := resChStatefulSetLabels.Await()
  200. resDaemonSetLabels, _ := resChDaemonSetLabels.Await()
  201. resJobLabels, _ := resChJobLabels.Await()
  202. resLBCostPerHr, _ := resChLBCostPerHr.Await()
  203. resLBActiveMins, _ := resChLBActiveMins.Await()
  204. if ctx.HasErrors() {
  205. for _, err := range ctx.Errors() {
  206. log.Errorf("CostModel.ComputeAllocation: %s", err)
  207. }
  208. return allocSet, ctx.ErrorCollection()
  209. }
  210. // We choose to apply allocation before requests in the cases of RAM and
  211. // CPU so that we can assert that allocation should always be greater than
  212. // or equal to request.
  213. applyCPUCoresAllocated(podMap, resCPUCoresAllocated)
  214. applyCPUCoresRequested(podMap, resCPURequests)
  215. applyCPUCoresUsedAvg(podMap, resCPUUsageAvg)
  216. applyCPUCoresUsedMax(podMap, resCPUUsageMax)
  217. applyRAMBytesAllocated(podMap, resRAMBytesAllocated)
  218. applyRAMBytesRequested(podMap, resRAMRequests)
  219. applyRAMBytesUsedAvg(podMap, resRAMUsageAvg)
  220. applyRAMBytesUsedMax(podMap, resRAMUsageMax)
  221. applyGPUsRequested(podMap, resGPUsRequested)
  222. applyNetworkAllocation(podMap, resNetZoneGiB, resNetZoneCostPerGiB)
  223. applyNetworkAllocation(podMap, resNetRegionGiB, resNetRegionCostPerGiB)
  224. applyNetworkAllocation(podMap, resNetInternetGiB, resNetInternetCostPerGiB)
  225. namespaceLabels := resToNamespaceLabels(resNamespaceLabels)
  226. podLabels := resToPodLabels(resPodLabels)
  227. namespaceAnnotations := resToNamespaceAnnotations(resNamespaceAnnotations)
  228. podAnnotations := resToPodAnnotations(resPodAnnotations)
  229. applyLabels(podMap, namespaceLabels, podLabels)
  230. applyAnnotations(podMap, namespaceAnnotations, podAnnotations)
  231. serviceLabels := getServiceLabels(resServiceLabels)
  232. allocsByService := map[serviceKey][]*kubecost.Allocation{}
  233. applyServicesToPods(podMap, podLabels, allocsByService, serviceLabels)
  234. podDeploymentMap := labelsToPodControllerMap(podLabels, resToDeploymentLabels(resDeploymentLabels))
  235. podStatefulSetMap := labelsToPodControllerMap(podLabels, resToStatefulSetLabels(resStatefulSetLabels))
  236. podDaemonSetMap := resToPodDaemonSetMap(resDaemonSetLabels)
  237. podJobMap := resToPodJobMap(resJobLabels)
  238. applyControllersToPods(podMap, podDeploymentMap)
  239. applyControllersToPods(podMap, podStatefulSetMap)
  240. applyControllersToPods(podMap, podDaemonSetMap)
  241. applyControllersToPods(podMap, podJobMap)
  242. // TODO breakdown network costs?
  243. // Build out a map of Nodes with resource costs, discounts, and node types
  244. // for converting resource allocation data to cumulative costs.
  245. nodeMap := map[nodeKey]*NodePricing{}
  246. applyNodeCostPerCPUHr(nodeMap, resNodeCostPerCPUHr, cm.Provider.ParseID)
  247. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr, cm.Provider.ParseID)
  248. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr, cm.Provider.ParseID)
  249. applyNodeSpot(nodeMap, resNodeIsSpot)
  250. applyNodeDiscount(nodeMap, cm)
  251. // Build out the map of all PVs with class, size and cost-per-hour.
  252. // Note: this does not record time running, which we may want to
  253. // include later for increased PV precision. (As long as the PV has
  254. // a PVC, we get time running there, so this is only inaccurate
  255. // for short-lived, unmounted PVs.)
  256. pvMap := map[pvKey]*PV{}
  257. buildPVMap(pvMap, resPVCostPerGiBHour)
  258. applyPVBytes(pvMap, resPVBytes)
  259. // Build out the map of all PVCs with time running, bytes requested,
  260. // and connect to the correct PV from pvMap. (If no PV exists, that
  261. // is noted, but does not result in any allocation/cost.)
  262. pvcMap := map[pvcKey]*PVC{}
  263. buildPVCMap(window, pvcMap, pvMap, resPVCInfo)
  264. applyPVCBytesRequested(pvcMap, resPVCBytesRequested)
  265. // Build out the relationships of pods to their PVCs. This step
  266. // populates the PVC.Count field so that PVC allocation can be
  267. // split appropriately among each pod's container allocation.
  268. podPVCMap := map[podKey][]*PVC{}
  269. buildPodPVCMap(podPVCMap, pvMap, pvcMap, podMap, resPodPVCAllocation)
  270. // Identify unmounted PVs (PVs without PVCs) and add one Allocation per
  271. // cluster representing each cluster's unmounted PVs (if necessary).
  272. applyUnmountedPVs(window, podMap, pvMap, pvcMap)
  273. lbMap := getLoadBalancerCosts(resLBCostPerHr, resLBActiveMins, resolution)
  274. applyLoadBalancersToPods(lbMap, allocsByService)
  275. // (3) Build out AllocationSet from Pod map
  276. for _, pod := range podMap {
  277. for _, alloc := range pod.Allocations {
  278. cluster := alloc.Properties.Cluster
  279. nodeName := alloc.Properties.Node
  280. namespace := alloc.Properties.Namespace
  281. pod := alloc.Properties.Pod
  282. container := alloc.Properties.Container
  283. podKey := newPodKey(cluster, namespace, pod)
  284. nodeKey := newNodeKey(cluster, nodeName)
  285. node := cm.getNodePricing(nodeMap, nodeKey)
  286. alloc.Properties.ProviderID = node.ProviderID
  287. alloc.CPUCost = alloc.CPUCoreHours * node.CostPerCPUHr
  288. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * node.CostPerRAMGiBHr
  289. alloc.GPUCost = alloc.GPUHours * node.CostPerGPUHr
  290. if pvcs, ok := podPVCMap[podKey]; ok {
  291. for _, pvc := range pvcs {
  292. // Determine the (start, end) of the relationship between the
  293. // given PVC and the associated Allocation so that a precise
  294. // number of hours can be used to compute cumulative cost.
  295. s, e := alloc.Start, alloc.End
  296. if pvc.Start.After(alloc.Start) {
  297. s = pvc.Start
  298. }
  299. if pvc.End.Before(alloc.End) {
  300. e = pvc.End
  301. }
  302. minutes := e.Sub(s).Minutes()
  303. hrs := minutes / 60.0
  304. count := float64(pvc.Count)
  305. if pvc.Count < 1 {
  306. count = 1
  307. }
  308. gib := pvc.Bytes / 1024 / 1024 / 1024
  309. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  310. // Apply the size and cost of the PV to the allocation, each
  311. // weighted by count (i.e. the number of containers in the pod)
  312. alloc.PVByteHours += pvc.Bytes * hrs / count
  313. alloc.PVCost += cost / count
  314. }
  315. }
  316. // Make sure that the name is correct (node may not be present at this
  317. // point due to it missing from queryMinutes) then insert.
  318. alloc.Name = fmt.Sprintf("%s/%s/%s/%s/%s", cluster, nodeName, namespace, pod, container)
  319. allocSet.Set(alloc)
  320. }
  321. }
  322. return allocSet, nil
  323. }
  324. func (cm *CostModel) buildPodMap(window kubecost.Window, resolution, maxBatchSize time.Duration, podMap map[podKey]*Pod, clusterStart, clusterEnd map[string]time.Time) error {
  325. // Assumes that window is positive and closed
  326. start, end := *window.Start(), *window.End()
  327. // Convert resolution duration to a query-ready string
  328. resStr := util.DurationString(resolution)
  329. ctx := prom.NewContext(cm.PrometheusClient)
  330. // Query for (start, end) by (pod, namespace, cluster) over the given
  331. // window, using the given resolution, and if necessary in batches no
  332. // larger than the given maximum batch size. If working in batches, track
  333. // overall progress by starting with (window.start, window.start) and
  334. // querying in batches no larger than maxBatchSize from start-to-end,
  335. // folding each result set into podMap as the results come back.
  336. coverage := kubecost.NewWindow(&start, &start)
  337. numQuery := 1
  338. for coverage.End().Before(end) {
  339. // Determine the (start, end) of the current batch
  340. batchStart := *coverage.End()
  341. batchEnd := coverage.End().Add(maxBatchSize)
  342. if batchEnd.After(end) {
  343. batchEnd = end
  344. }
  345. batchWindow := kubecost.NewWindow(&batchStart, &batchEnd)
  346. var resPods []*prom.QueryResult
  347. var err error
  348. maxTries := 3
  349. numTries := 0
  350. for resPods == nil && numTries < maxTries {
  351. numTries++
  352. // Convert window (start, end) to (duration, offset) for querying Prometheus,
  353. // including handling Thanos offset
  354. durStr, offStr, err := batchWindow.DurationOffsetForPrometheus()
  355. if err != nil || durStr == "" {
  356. // Negative duration, so set empty results and don't query
  357. resPods = []*prom.QueryResult{}
  358. err = nil
  359. break
  360. }
  361. // Submit and profile query
  362. queryPods := fmt.Sprintf(queryFmtPods, durStr, resStr, offStr)
  363. queryProfile := time.Now()
  364. resPods, err = ctx.Query(queryPods).Await()
  365. if err != nil {
  366. log.Profile(queryProfile, fmt.Sprintf("CostModel.ComputeAllocation: pod query %d try %d failed: %s", numQuery, numTries, queryPods))
  367. resPods = nil
  368. }
  369. }
  370. if err != nil {
  371. return err
  372. }
  373. applyPodResults(window, resolution, podMap, clusterStart, clusterEnd, resPods)
  374. coverage = coverage.ExpandEnd(batchEnd)
  375. numQuery++
  376. }
  377. return nil
  378. }
  379. func applyPodResults(window kubecost.Window, resolution time.Duration, podMap map[podKey]*Pod, clusterStart, clusterEnd map[string]time.Time, resPods []*prom.QueryResult) {
  380. for _, res := range resPods {
  381. if len(res.Values) == 0 {
  382. log.Warningf("CostModel.ComputeAllocation: empty minutes result")
  383. continue
  384. }
  385. cluster, err := res.GetString("cluster_id")
  386. if err != nil {
  387. cluster = env.GetClusterID()
  388. }
  389. labels, err := res.GetStrings("namespace", "pod")
  390. if err != nil {
  391. log.Warningf("CostModel.ComputeAllocation: minutes query result missing field: %s", err)
  392. continue
  393. }
  394. namespace := labels["namespace"]
  395. pod := labels["pod"]
  396. key := newPodKey(cluster, namespace, pod)
  397. // allocStart and allocEnd are the timestamps of the first and last
  398. // minutes the pod was running, respectively. We subtract one resolution
  399. // from allocStart because this point will actually represent the end
  400. // of the first minute. We don't subtract from allocEnd because it
  401. // already represents the end of the last minute.
  402. var allocStart, allocEnd time.Time
  403. startAdjustmentCoeff, endAdjustmentCoeff := 1.0, 1.0
  404. for _, datum := range res.Values {
  405. t := time.Unix(int64(datum.Timestamp), 0)
  406. if allocStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  407. // Set the start timestamp to the earliest non-zero timestamp
  408. allocStart = t
  409. // Record adjustment coefficient, i.e. the portion of the start
  410. // timestamp to "ignore". That is, sometimes the value will be
  411. // 0.5, meaning that we should discount the time running by
  412. // half of the resolution the timestamp stands for.
  413. startAdjustmentCoeff = (1.0 - datum.Value)
  414. }
  415. if datum.Value > 0 && window.Contains(t) {
  416. // Set the end timestamp to the latest non-zero timestamp
  417. allocEnd = t
  418. // Record adjustment coefficient, i.e. the portion of the end
  419. // timestamp to "ignore". (See explanation above for start.)
  420. endAdjustmentCoeff = (1.0 - datum.Value)
  421. }
  422. }
  423. if allocStart.IsZero() || allocEnd.IsZero() {
  424. continue
  425. }
  426. // Adjust timestamps according to the resolution and the adjustment
  427. // coefficients, as described above. That is, count the start timestamp
  428. // from the beginning of the resolution, not the end. Then "reduce" the
  429. // start and end by the correct amount, in the case that the "running"
  430. // value of the first or last timestamp was not a full 1.0.
  431. allocStart = allocStart.Add(-resolution)
  432. // Note: the *100 and /100 are necessary because Duration is an int, so
  433. // 0.5, for instance, will be truncated, resulting in no adjustment.
  434. allocStart = allocStart.Add(time.Duration(startAdjustmentCoeff*100) * resolution / time.Duration(100))
  435. allocEnd = allocEnd.Add(-time.Duration(endAdjustmentCoeff*100) * resolution / time.Duration(100))
  436. // If there is only one point with a value <= 0.5 that the start and
  437. // end timestamps both share, then we will enter this case because at
  438. // least half of a resolution will be subtracted from both the start
  439. // and the end. If that is the case, then add back half of each side
  440. // so that the pod is said to run for half a resolution total.
  441. // e.g. For resolution 1m and a value of 0.5 at one timestamp, we'll
  442. // end up with allocEnd == allocStart and each coeff == 0.5. In
  443. // that case, add 0.25m to each side, resulting in 0.5m duration.
  444. if !allocEnd.After(allocStart) {
  445. allocStart = allocStart.Add(-time.Duration(50*startAdjustmentCoeff) * resolution / time.Duration(100))
  446. allocEnd = allocEnd.Add(time.Duration(50*endAdjustmentCoeff) * resolution / time.Duration(100))
  447. }
  448. // Set start if unset or this datum's start time is earlier than the
  449. // current earliest time.
  450. if _, ok := clusterStart[cluster]; !ok || allocStart.Before(clusterStart[cluster]) {
  451. clusterStart[cluster] = allocStart
  452. }
  453. // Set end if unset or this datum's end time is later than the
  454. // current latest time.
  455. if _, ok := clusterEnd[cluster]; !ok || allocEnd.After(clusterEnd[cluster]) {
  456. clusterEnd[cluster] = allocEnd
  457. }
  458. if pod, ok := podMap[key]; ok {
  459. // Pod has already been recorded, so update it accordingly
  460. if allocStart.Before(pod.Start) {
  461. pod.Start = allocStart
  462. }
  463. if allocEnd.After(pod.End) {
  464. pod.End = allocEnd
  465. }
  466. } else {
  467. // Pod has not been recorded yet, so insert it
  468. podMap[key] = &Pod{
  469. Window: window.Clone(),
  470. Start: allocStart,
  471. End: allocEnd,
  472. Key: key,
  473. Allocations: map[string]*kubecost.Allocation{},
  474. }
  475. }
  476. }
  477. }
  478. func applyCPUCoresAllocated(podMap map[podKey]*Pod, resCPUCoresAllocated []*prom.QueryResult) {
  479. for _, res := range resCPUCoresAllocated {
  480. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  481. if err != nil {
  482. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation result missing field: %s", err)
  483. continue
  484. }
  485. pod, ok := podMap[key]
  486. if !ok {
  487. continue
  488. }
  489. container, err := res.GetString("container")
  490. if err != nil {
  491. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation query result missing 'container': %s", key)
  492. continue
  493. }
  494. if _, ok := pod.Allocations[container]; !ok {
  495. pod.AppendContainer(container)
  496. }
  497. cpuCores := res.Values[0].Value
  498. hours := pod.Allocations[container].Minutes() / 60.0
  499. pod.Allocations[container].CPUCoreHours = cpuCores * hours
  500. node, err := res.GetString("node")
  501. if err != nil {
  502. log.Warningf("CostModel.ComputeAllocation: CPU allocation query result missing 'node': %s", key)
  503. continue
  504. }
  505. pod.Allocations[container].Properties.Node = node
  506. }
  507. }
  508. func applyCPUCoresRequested(podMap map[podKey]*Pod, resCPUCoresRequested []*prom.QueryResult) {
  509. for _, res := range resCPUCoresRequested {
  510. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  511. if err != nil {
  512. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request result missing field: %s", err)
  513. continue
  514. }
  515. pod, ok := podMap[key]
  516. if !ok {
  517. continue
  518. }
  519. container, err := res.GetString("container")
  520. if err != nil {
  521. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request query result missing 'container': %s", key)
  522. continue
  523. }
  524. if _, ok := pod.Allocations[container]; !ok {
  525. pod.AppendContainer(container)
  526. }
  527. pod.Allocations[container].CPUCoreRequestAverage = res.Values[0].Value
  528. // If CPU allocation is less than requests, set CPUCoreHours to
  529. // request level.
  530. if pod.Allocations[container].CPUCores() < res.Values[0].Value {
  531. pod.Allocations[container].CPUCoreHours = res.Values[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  532. }
  533. node, err := res.GetString("node")
  534. if err != nil {
  535. log.Warningf("CostModel.ComputeAllocation: CPU request query result missing 'node': %s", key)
  536. continue
  537. }
  538. pod.Allocations[container].Properties.Node = node
  539. }
  540. }
  541. func applyCPUCoresUsedAvg(podMap map[podKey]*Pod, resCPUCoresUsedAvg []*prom.QueryResult) {
  542. for _, res := range resCPUCoresUsedAvg {
  543. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  544. if err != nil {
  545. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg result missing field: %s", err)
  546. continue
  547. }
  548. pod, ok := podMap[key]
  549. if !ok {
  550. continue
  551. }
  552. container, err := res.GetString("container_name")
  553. if err != nil {
  554. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg query result missing 'container': %s", key)
  555. continue
  556. }
  557. if _, ok := pod.Allocations[container]; !ok {
  558. pod.AppendContainer(container)
  559. }
  560. pod.Allocations[container].CPUCoreUsageAverage = res.Values[0].Value
  561. }
  562. }
  563. func applyCPUCoresUsedMax(podMap map[podKey]*Pod, resCPUCoresUsedMax []*prom.QueryResult) {
  564. for _, res := range resCPUCoresUsedMax {
  565. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  566. if err != nil {
  567. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max result missing field: %s", err)
  568. continue
  569. }
  570. pod, ok := podMap[key]
  571. if !ok {
  572. continue
  573. }
  574. container, err := res.GetString("container_name")
  575. if err != nil {
  576. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max query result missing 'container': %s", key)
  577. continue
  578. }
  579. if _, ok := pod.Allocations[container]; !ok {
  580. pod.AppendContainer(container)
  581. }
  582. if pod.Allocations[container].RawAllocationOnly == nil {
  583. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  584. CPUCoreUsageMax: res.Values[0].Value,
  585. }
  586. } else {
  587. pod.Allocations[container].RawAllocationOnly.CPUCoreUsageMax = res.Values[0].Value
  588. }
  589. }
  590. }
  591. func applyRAMBytesAllocated(podMap map[podKey]*Pod, resRAMBytesAllocated []*prom.QueryResult) {
  592. for _, res := range resRAMBytesAllocated {
  593. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  594. if err != nil {
  595. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation result missing field: %s", err)
  596. continue
  597. }
  598. pod, ok := podMap[key]
  599. if !ok {
  600. continue
  601. }
  602. container, err := res.GetString("container")
  603. if err != nil {
  604. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation query result missing 'container': %s", key)
  605. continue
  606. }
  607. if _, ok := pod.Allocations[container]; !ok {
  608. pod.AppendContainer(container)
  609. }
  610. ramBytes := res.Values[0].Value
  611. hours := pod.Allocations[container].Minutes() / 60.0
  612. pod.Allocations[container].RAMByteHours = ramBytes * hours
  613. node, err := res.GetString("node")
  614. if err != nil {
  615. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing 'node': %s", key)
  616. continue
  617. }
  618. pod.Allocations[container].Properties.Node = node
  619. }
  620. }
  621. func applyRAMBytesRequested(podMap map[podKey]*Pod, resRAMBytesRequested []*prom.QueryResult) {
  622. for _, res := range resRAMBytesRequested {
  623. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  624. if err != nil {
  625. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request result missing field: %s", err)
  626. continue
  627. }
  628. pod, ok := podMap[key]
  629. if !ok {
  630. continue
  631. }
  632. container, err := res.GetString("container")
  633. if err != nil {
  634. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request query result missing 'container': %s", key)
  635. continue
  636. }
  637. if _, ok := pod.Allocations[container]; !ok {
  638. pod.AppendContainer(container)
  639. }
  640. pod.Allocations[container].RAMBytesRequestAverage = res.Values[0].Value
  641. // If RAM allocation is less than requests, set RAMByteHours to
  642. // request level.
  643. if pod.Allocations[container].RAMBytes() < res.Values[0].Value {
  644. pod.Allocations[container].RAMByteHours = res.Values[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  645. }
  646. node, err := res.GetString("node")
  647. if err != nil {
  648. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing 'node': %s", key)
  649. continue
  650. }
  651. pod.Allocations[container].Properties.Node = node
  652. }
  653. }
  654. func applyRAMBytesUsedAvg(podMap map[podKey]*Pod, resRAMBytesUsedAvg []*prom.QueryResult) {
  655. for _, res := range resRAMBytesUsedAvg {
  656. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  657. if err != nil {
  658. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM avg usage result missing field: %s", err)
  659. continue
  660. }
  661. pod, ok := podMap[key]
  662. if !ok {
  663. continue
  664. }
  665. container, err := res.GetString("container_name")
  666. if err != nil {
  667. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage avg query result missing 'container': %s", key)
  668. continue
  669. }
  670. if _, ok := pod.Allocations[container]; !ok {
  671. pod.AppendContainer(container)
  672. }
  673. pod.Allocations[container].RAMBytesUsageAverage = res.Values[0].Value
  674. }
  675. }
  676. func applyRAMBytesUsedMax(podMap map[podKey]*Pod, resRAMBytesUsedMax []*prom.QueryResult) {
  677. for _, res := range resRAMBytesUsedMax {
  678. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  679. if err != nil {
  680. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max result missing field: %s", err)
  681. continue
  682. }
  683. pod, ok := podMap[key]
  684. if !ok {
  685. continue
  686. }
  687. container, err := res.GetString("container_name")
  688. if err != nil {
  689. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max query result missing 'container': %s", key)
  690. continue
  691. }
  692. if _, ok := pod.Allocations[container]; !ok {
  693. pod.AppendContainer(container)
  694. }
  695. if pod.Allocations[container].RawAllocationOnly == nil {
  696. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  697. RAMBytesUsageMax: res.Values[0].Value,
  698. }
  699. } else {
  700. pod.Allocations[container].RawAllocationOnly.RAMBytesUsageMax = res.Values[0].Value
  701. }
  702. }
  703. }
  704. func applyGPUsRequested(podMap map[podKey]*Pod, resGPUsRequested []*prom.QueryResult) {
  705. for _, res := range resGPUsRequested {
  706. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  707. if err != nil {
  708. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request result missing field: %s", err)
  709. continue
  710. }
  711. pod, ok := podMap[key]
  712. if !ok {
  713. continue
  714. }
  715. container, err := res.GetString("container")
  716. if err != nil {
  717. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request query result missing 'container': %s", key)
  718. continue
  719. }
  720. if _, ok := pod.Allocations[container]; !ok {
  721. pod.AppendContainer(container)
  722. }
  723. hrs := pod.Allocations[container].Minutes() / 60.0
  724. pod.Allocations[container].GPUHours = res.Values[0].Value * hrs
  725. }
  726. }
  727. func applyNetworkAllocation(podMap map[podKey]*Pod, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult) {
  728. costPerGiBByCluster := map[string]float64{}
  729. for _, res := range resNetworkCostPerGiB {
  730. cluster, err := res.GetString("cluster_id")
  731. if err != nil {
  732. cluster = env.GetClusterID()
  733. }
  734. costPerGiBByCluster[cluster] = res.Values[0].Value
  735. }
  736. for _, res := range resNetworkGiB {
  737. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  738. if err != nil {
  739. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  740. continue
  741. }
  742. pod, ok := podMap[podKey]
  743. if !ok {
  744. continue
  745. }
  746. for _, alloc := range pod.Allocations {
  747. gib := res.Values[0].Value / float64(len(pod.Allocations))
  748. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  749. alloc.NetworkCost = gib * costPerGiB
  750. }
  751. }
  752. }
  753. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[namespaceKey]map[string]string {
  754. namespaceLabels := map[namespaceKey]map[string]string{}
  755. for _, res := range resNamespaceLabels {
  756. nsKey, err := resultNamespaceKey(res, "cluster_id", "namespace")
  757. if err != nil {
  758. continue
  759. }
  760. if _, ok := namespaceLabels[nsKey]; !ok {
  761. namespaceLabels[nsKey] = map[string]string{}
  762. }
  763. for k, l := range res.GetLabels() {
  764. namespaceLabels[nsKey][k] = l
  765. }
  766. }
  767. return namespaceLabels
  768. }
  769. func resToPodLabels(resPodLabels []*prom.QueryResult) map[podKey]map[string]string {
  770. podLabels := map[podKey]map[string]string{}
  771. for _, res := range resPodLabels {
  772. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  773. if err != nil {
  774. continue
  775. }
  776. if _, ok := podLabels[podKey]; !ok {
  777. podLabels[podKey] = map[string]string{}
  778. }
  779. for k, l := range res.GetLabels() {
  780. podLabels[podKey][k] = l
  781. }
  782. }
  783. return podLabels
  784. }
  785. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  786. namespaceAnnotations := map[string]map[string]string{}
  787. for _, res := range resNamespaceAnnotations {
  788. namespace, err := res.GetString("namespace")
  789. if err != nil {
  790. continue
  791. }
  792. if _, ok := namespaceAnnotations[namespace]; !ok {
  793. namespaceAnnotations[namespace] = map[string]string{}
  794. }
  795. for k, l := range res.GetAnnotations() {
  796. namespaceAnnotations[namespace][k] = l
  797. }
  798. }
  799. return namespaceAnnotations
  800. }
  801. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult) map[podKey]map[string]string {
  802. podAnnotations := map[podKey]map[string]string{}
  803. for _, res := range resPodAnnotations {
  804. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  805. if err != nil {
  806. continue
  807. }
  808. if _, ok := podAnnotations[podKey]; !ok {
  809. podAnnotations[podKey] = map[string]string{}
  810. }
  811. for k, l := range res.GetAnnotations() {
  812. podAnnotations[podKey][k] = l
  813. }
  814. }
  815. return podAnnotations
  816. }
  817. func applyLabels(podMap map[podKey]*Pod, namespaceLabels map[namespaceKey]map[string]string, podLabels map[podKey]map[string]string) {
  818. for podKey, pod := range podMap {
  819. for _, alloc := range pod.Allocations {
  820. allocLabels := alloc.Properties.Labels
  821. if allocLabels == nil {
  822. allocLabels = make(map[string]string)
  823. }
  824. // Apply namespace labels first, then pod labels so that pod labels
  825. // overwrite namespace labels.
  826. nsKey := newNamespaceKey(podKey.Cluster, podKey.Namespace)
  827. if labels, ok := namespaceLabels[nsKey]; ok {
  828. for k, v := range labels {
  829. allocLabels[k] = v
  830. }
  831. }
  832. if labels, ok := podLabels[podKey]; ok {
  833. for k, v := range labels {
  834. allocLabels[k] = v
  835. }
  836. }
  837. alloc.Properties.Labels = allocLabels
  838. }
  839. }
  840. }
  841. func applyAnnotations(podMap map[podKey]*Pod, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  842. for key, pod := range podMap {
  843. for _, alloc := range pod.Allocations {
  844. allocAnnotations := alloc.Properties.Annotations
  845. if allocAnnotations == nil {
  846. allocAnnotations = make(map[string]string)
  847. }
  848. // Apply namespace annotations first, then pod annotations so that
  849. // pod labels overwrite namespace labels.
  850. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  851. for k, v := range labels {
  852. allocAnnotations[k] = v
  853. }
  854. }
  855. if labels, ok := podAnnotations[key]; ok {
  856. for k, v := range labels {
  857. allocAnnotations[k] = v
  858. }
  859. }
  860. alloc.Properties.Annotations = allocAnnotations
  861. }
  862. }
  863. }
  864. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  865. serviceLabels := map[serviceKey]map[string]string{}
  866. for _, res := range resServiceLabels {
  867. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service")
  868. if err != nil {
  869. continue
  870. }
  871. if _, ok := serviceLabels[serviceKey]; !ok {
  872. serviceLabels[serviceKey] = map[string]string{}
  873. }
  874. for k, l := range res.GetLabels() {
  875. serviceLabels[serviceKey][k] = l
  876. }
  877. }
  878. // Prune duplicate services. That is, if the same service exists with
  879. // hyphens instead of underscores, keep the one that uses hyphens.
  880. for key := range serviceLabels {
  881. if strings.Contains(key.Service, "_") {
  882. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  883. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  884. if _, ok := serviceLabels[duplicateKey]; ok {
  885. delete(serviceLabels, key)
  886. }
  887. }
  888. }
  889. return serviceLabels
  890. }
  891. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  892. deploymentLabels := map[controllerKey]map[string]string{}
  893. for _, res := range resDeploymentLabels {
  894. controllerKey, err := resultDeploymentKey(res, "cluster_id", "namespace", "deployment")
  895. if err != nil {
  896. continue
  897. }
  898. if _, ok := deploymentLabels[controllerKey]; !ok {
  899. deploymentLabels[controllerKey] = map[string]string{}
  900. }
  901. for k, l := range res.GetLabels() {
  902. deploymentLabels[controllerKey][k] = l
  903. }
  904. }
  905. // Prune duplicate deployments. That is, if the same deployment exists with
  906. // hyphens instead of underscores, keep the one that uses hyphens.
  907. for key := range deploymentLabels {
  908. if strings.Contains(key.Controller, "_") {
  909. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  910. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  911. if _, ok := deploymentLabels[duplicateKey]; ok {
  912. delete(deploymentLabels, key)
  913. }
  914. }
  915. }
  916. return deploymentLabels
  917. }
  918. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  919. statefulSetLabels := map[controllerKey]map[string]string{}
  920. for _, res := range resStatefulSetLabels {
  921. controllerKey, err := resultStatefulSetKey(res, "cluster_id", "namespace", "statefulSet")
  922. if err != nil {
  923. continue
  924. }
  925. if _, ok := statefulSetLabels[controllerKey]; !ok {
  926. statefulSetLabels[controllerKey] = map[string]string{}
  927. }
  928. for k, l := range res.GetLabels() {
  929. statefulSetLabels[controllerKey][k] = l
  930. }
  931. }
  932. // Prune duplicate stateful sets. That is, if the same stateful set exists
  933. // with hyphens instead of underscores, keep the one that uses hyphens.
  934. for key := range statefulSetLabels {
  935. if strings.Contains(key.Controller, "_") {
  936. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  937. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  938. if _, ok := statefulSetLabels[duplicateKey]; ok {
  939. delete(statefulSetLabels, key)
  940. }
  941. }
  942. }
  943. return statefulSetLabels
  944. }
  945. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  946. podControllerMap := map[podKey]controllerKey{}
  947. // For each controller, turn the labels into a selector and attempt to
  948. // match it with each set of pod labels. A match indicates that the pod
  949. // belongs to the controller.
  950. for cKey, cLabels := range controllerLabels {
  951. selector := labels.Set(cLabels).AsSelectorPreValidated()
  952. for pKey, pLabels := range podLabels {
  953. // If the pod is in a different cluster or namespace, there is
  954. // no need to compare the labels.
  955. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  956. continue
  957. }
  958. podLabelSet := labels.Set(pLabels)
  959. if selector.Matches(podLabelSet) {
  960. if _, ok := podControllerMap[pKey]; ok {
  961. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  962. }
  963. podControllerMap[pKey] = cKey
  964. }
  965. }
  966. }
  967. return podControllerMap
  968. }
  969. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult) map[podKey]controllerKey {
  970. daemonSetLabels := map[podKey]controllerKey{}
  971. for _, res := range resDaemonSetLabels {
  972. controllerKey, err := resultDaemonSetKey(res, "cluster_id", "namespace", "owner_name")
  973. if err != nil {
  974. continue
  975. }
  976. pod, err := res.GetString("pod")
  977. if err != nil {
  978. log.Warningf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  979. }
  980. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  981. daemonSetLabels[podKey] = controllerKey
  982. }
  983. return daemonSetLabels
  984. }
  985. func resToPodJobMap(resJobLabels []*prom.QueryResult) map[podKey]controllerKey {
  986. jobLabels := map[podKey]controllerKey{}
  987. for _, res := range resJobLabels {
  988. controllerKey, err := resultJobKey(res, "cluster_id", "namespace", "owner_name")
  989. if err != nil {
  990. continue
  991. }
  992. // Convert the name of Jobs generated by CronJobs to the name of the
  993. // CronJob by stripping the timestamp off the end.
  994. match := isCron.FindStringSubmatch(controllerKey.Controller)
  995. if match != nil {
  996. controllerKey.Controller = match[1]
  997. }
  998. pod, err := res.GetString("pod")
  999. if err != nil {
  1000. log.Warningf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  1001. }
  1002. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1003. jobLabels[podKey] = controllerKey
  1004. }
  1005. return jobLabels
  1006. }
  1007. func applyServicesToPods(podMap map[podKey]*Pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*kubecost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1008. podServicesMap := map[podKey][]serviceKey{}
  1009. // For each service, turn the labels into a selector and attempt to
  1010. // match it with each set of pod labels. A match indicates that the pod
  1011. // belongs to the service.
  1012. for sKey, sLabels := range serviceLabels {
  1013. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1014. for pKey, pLabels := range podLabels {
  1015. // If the pod is in a different cluster or namespace, there is
  1016. // no need to compare the labels.
  1017. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1018. continue
  1019. }
  1020. podLabelSet := labels.Set(pLabels)
  1021. if selector.Matches(podLabelSet) {
  1022. if _, ok := podServicesMap[pKey]; !ok {
  1023. podServicesMap[pKey] = []serviceKey{}
  1024. }
  1025. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1026. }
  1027. }
  1028. }
  1029. // For each allocation in each pod, attempt to find and apply the list of
  1030. // services associated with the allocation's pod.
  1031. for key, pod := range podMap {
  1032. for _, alloc := range pod.Allocations {
  1033. if sKeys, ok := podServicesMap[key]; ok {
  1034. services := []string{}
  1035. for _, sKey := range sKeys {
  1036. services = append(services, sKey.Service)
  1037. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1038. }
  1039. alloc.Properties.Services = services
  1040. }
  1041. }
  1042. }
  1043. }
  1044. func applyControllersToPods(podMap map[podKey]*Pod, podControllerMap map[podKey]controllerKey) {
  1045. for key, pod := range podMap {
  1046. for _, alloc := range pod.Allocations {
  1047. if controllerKey, ok := podControllerMap[key]; ok {
  1048. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1049. alloc.Properties.Controller = controllerKey.Controller
  1050. }
  1051. }
  1052. }
  1053. }
  1054. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerCPUHr []*prom.QueryResult,
  1055. providerIDParser func(string) string) {
  1056. for _, res := range resNodeCostPerCPUHr {
  1057. cluster, err := res.GetString("cluster_id")
  1058. if err != nil {
  1059. cluster = env.GetClusterID()
  1060. }
  1061. node, err := res.GetString("node")
  1062. if err != nil {
  1063. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1064. continue
  1065. }
  1066. instanceType, err := res.GetString("instance_type")
  1067. if err != nil {
  1068. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1069. continue
  1070. }
  1071. providerID, err := res.GetString("provider_id")
  1072. if err != nil {
  1073. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1074. continue
  1075. }
  1076. key := newNodeKey(cluster, node)
  1077. if _, ok := nodeMap[key]; !ok {
  1078. nodeMap[key] = &NodePricing{
  1079. Name: node,
  1080. NodeType: instanceType,
  1081. ProviderID: providerIDParser(providerID),
  1082. }
  1083. }
  1084. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1085. }
  1086. }
  1087. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult,
  1088. providerIDParser func(string) string) {
  1089. for _, res := range resNodeCostPerRAMGiBHr {
  1090. cluster, err := res.GetString("cluster_id")
  1091. if err != nil {
  1092. cluster = env.GetClusterID()
  1093. }
  1094. node, err := res.GetString("node")
  1095. if err != nil {
  1096. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1097. continue
  1098. }
  1099. instanceType, err := res.GetString("instance_type")
  1100. if err != nil {
  1101. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1102. continue
  1103. }
  1104. providerID, err := res.GetString("provider_id")
  1105. if err != nil {
  1106. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1107. continue
  1108. }
  1109. key := newNodeKey(cluster, node)
  1110. if _, ok := nodeMap[key]; !ok {
  1111. nodeMap[key] = &NodePricing{
  1112. Name: node,
  1113. NodeType: instanceType,
  1114. ProviderID: providerIDParser(providerID),
  1115. }
  1116. }
  1117. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1118. }
  1119. }
  1120. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerGPUHr []*prom.QueryResult,
  1121. providerIDParser func(string) string) {
  1122. for _, res := range resNodeCostPerGPUHr {
  1123. cluster, err := res.GetString("cluster_id")
  1124. if err != nil {
  1125. cluster = env.GetClusterID()
  1126. }
  1127. node, err := res.GetString("node")
  1128. if err != nil {
  1129. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1130. continue
  1131. }
  1132. instanceType, err := res.GetString("instance_type")
  1133. if err != nil {
  1134. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1135. continue
  1136. }
  1137. providerID, err := res.GetString("provider_id")
  1138. if err != nil {
  1139. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1140. continue
  1141. }
  1142. key := newNodeKey(cluster, node)
  1143. if _, ok := nodeMap[key]; !ok {
  1144. nodeMap[key] = &NodePricing{
  1145. Name: node,
  1146. NodeType: instanceType,
  1147. ProviderID: providerIDParser(providerID),
  1148. }
  1149. }
  1150. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1151. }
  1152. }
  1153. func applyNodeSpot(nodeMap map[nodeKey]*NodePricing, resNodeIsSpot []*prom.QueryResult) {
  1154. for _, res := range resNodeIsSpot {
  1155. cluster, err := res.GetString("cluster_id")
  1156. if err != nil {
  1157. cluster = env.GetClusterID()
  1158. }
  1159. node, err := res.GetString("node")
  1160. if err != nil {
  1161. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1162. continue
  1163. }
  1164. key := newNodeKey(cluster, node)
  1165. if _, ok := nodeMap[key]; !ok {
  1166. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1167. continue
  1168. }
  1169. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1170. }
  1171. }
  1172. func applyNodeDiscount(nodeMap map[nodeKey]*NodePricing, cm *CostModel) {
  1173. if cm == nil {
  1174. return
  1175. }
  1176. c, err := cm.Provider.GetConfig()
  1177. if err != nil {
  1178. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1179. return
  1180. }
  1181. discount, err := ParsePercentString(c.Discount)
  1182. if err != nil {
  1183. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1184. return
  1185. }
  1186. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1187. if err != nil {
  1188. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1189. return
  1190. }
  1191. for _, node := range nodeMap {
  1192. // TODO GKE Reserved Instances into account
  1193. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1194. node.CostPerCPUHr *= (1.0 - node.Discount)
  1195. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1196. }
  1197. }
  1198. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  1199. for _, res := range resPVCostPerGiBHour {
  1200. cluster, err := res.GetString("cluster_id")
  1201. if err != nil {
  1202. cluster = env.GetClusterID()
  1203. }
  1204. name, err := res.GetString("volumename")
  1205. if err != nil {
  1206. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  1207. continue
  1208. }
  1209. key := newPVKey(cluster, name)
  1210. pvMap[key] = &PV{
  1211. Cluster: cluster,
  1212. Name: name,
  1213. CostPerGiBHour: res.Values[0].Value,
  1214. }
  1215. }
  1216. }
  1217. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  1218. for _, res := range resPVBytes {
  1219. key, err := resultPVKey(res, "cluster_id", "persistentvolume")
  1220. if err != nil {
  1221. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  1222. continue
  1223. }
  1224. if _, ok := pvMap[key]; !ok {
  1225. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  1226. continue
  1227. }
  1228. pvMap[key].Bytes = res.Values[0].Value
  1229. }
  1230. }
  1231. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  1232. for _, res := range resPVCInfo {
  1233. cluster, err := res.GetString("cluster_id")
  1234. if err != nil {
  1235. cluster = env.GetClusterID()
  1236. }
  1237. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1238. if err != nil {
  1239. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  1240. continue
  1241. }
  1242. namespace := values["namespace"]
  1243. name := values["persistentvolumeclaim"]
  1244. volume := values["volumename"]
  1245. storageClass := values["storageclass"]
  1246. pvKey := newPVKey(cluster, volume)
  1247. pvcKey := newPVCKey(cluster, namespace, name)
  1248. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  1249. // the PVC was running, respectively. We subtract 1m from pvcStart
  1250. // because this point will actually represent the end of the first
  1251. // minute. We don't subtract from pvcEnd because it already represents
  1252. // the end of the last minute.
  1253. var pvcStart, pvcEnd time.Time
  1254. for _, datum := range res.Values {
  1255. t := time.Unix(int64(datum.Timestamp), 0)
  1256. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1257. pvcStart = t
  1258. }
  1259. if datum.Value > 0 && window.Contains(t) {
  1260. pvcEnd = t
  1261. }
  1262. }
  1263. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1264. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1265. }
  1266. pvcStart = pvcStart.Add(-time.Minute)
  1267. if _, ok := pvMap[pvKey]; !ok {
  1268. continue
  1269. }
  1270. pvMap[pvKey].StorageClass = storageClass
  1271. if _, ok := pvcMap[pvcKey]; !ok {
  1272. pvcMap[pvcKey] = &PVC{}
  1273. }
  1274. pvcMap[pvcKey].Name = name
  1275. pvcMap[pvcKey].Namespace = namespace
  1276. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1277. pvcMap[pvcKey].Start = pvcStart
  1278. pvcMap[pvcKey].End = pvcEnd
  1279. }
  1280. }
  1281. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1282. for _, res := range resPVCBytesRequested {
  1283. key, err := resultPVCKey(res, "cluster_id", "namespace", "persistentvolumeclaim")
  1284. if err != nil {
  1285. continue
  1286. }
  1287. if _, ok := pvcMap[key]; !ok {
  1288. continue
  1289. }
  1290. pvcMap[key].Bytes = res.Values[0].Value
  1291. }
  1292. }
  1293. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podMap map[podKey]*Pod, resPodPVCAllocation []*prom.QueryResult) {
  1294. for _, res := range resPodPVCAllocation {
  1295. cluster, err := res.GetString("cluster_id")
  1296. if err != nil {
  1297. cluster = env.GetClusterID()
  1298. }
  1299. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1300. if err != nil {
  1301. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1302. continue
  1303. }
  1304. namespace := values["namespace"]
  1305. pod := values["pod"]
  1306. name := values["persistentvolumeclaim"]
  1307. volume := values["persistentvolume"]
  1308. podKey := newPodKey(cluster, namespace, pod)
  1309. pvKey := newPVKey(cluster, volume)
  1310. pvcKey := newPVCKey(cluster, namespace, name)
  1311. if _, ok := pvMap[pvKey]; !ok {
  1312. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1313. continue
  1314. }
  1315. if _, ok := podPVCMap[podKey]; !ok {
  1316. podPVCMap[podKey] = []*PVC{}
  1317. }
  1318. pvc, ok := pvcMap[pvcKey]
  1319. if !ok {
  1320. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1321. continue
  1322. }
  1323. count := 1
  1324. if pod, ok := podMap[podKey]; ok && len(pod.Allocations) > 0 {
  1325. count = len(pod.Allocations)
  1326. } else {
  1327. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC %s for missing pod %s", pvcKey, podKey)
  1328. }
  1329. pvc.Count = count
  1330. pvc.Mounted = true
  1331. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1332. }
  1333. }
  1334. func applyUnmountedPVs(window kubecost.Window, podMap map[podKey]*Pod, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1335. unmountedPVBytes := map[string]float64{}
  1336. unmountedPVCost := map[string]float64{}
  1337. for _, pv := range pvMap {
  1338. mounted := false
  1339. for _, pvc := range pvcMap {
  1340. if pvc.Volume == nil {
  1341. continue
  1342. }
  1343. if pvc.Volume == pv {
  1344. mounted = true
  1345. break
  1346. }
  1347. }
  1348. if !mounted {
  1349. gib := pv.Bytes / 1024 / 1024 / 1024
  1350. hrs := window.Minutes() / 60.0 // TODO improve with PV hours, not window hours
  1351. cost := pv.CostPerGiBHour * gib * hrs
  1352. unmountedPVCost[pv.Cluster] += cost
  1353. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1354. }
  1355. }
  1356. for cluster, amount := range unmountedPVCost {
  1357. container := kubecost.UnmountedSuffix
  1358. pod := kubecost.UnmountedSuffix
  1359. namespace := kubecost.UnmountedSuffix
  1360. node := ""
  1361. key := newPodKey(cluster, namespace, pod)
  1362. podMap[key] = &Pod{
  1363. Window: window.Clone(),
  1364. Start: *window.Start(),
  1365. End: *window.End(),
  1366. Key: key,
  1367. Allocations: map[string]*kubecost.Allocation{},
  1368. }
  1369. podMap[key].AppendContainer(container)
  1370. podMap[key].Allocations[container].Properties.Cluster = cluster
  1371. podMap[key].Allocations[container].Properties.Node = node
  1372. podMap[key].Allocations[container].Properties.Namespace = namespace
  1373. podMap[key].Allocations[container].Properties.Pod = pod
  1374. podMap[key].Allocations[container].Properties.Container = container
  1375. podMap[key].Allocations[container].PVByteHours = unmountedPVBytes[cluster] * window.Minutes() / 60.0
  1376. podMap[key].Allocations[container].PVCost = amount
  1377. }
  1378. }
  1379. func applyUnmountedPVCs(window kubecost.Window, podMap map[podKey]*Pod, pvcMap map[pvcKey]*PVC) {
  1380. unmountedPVCBytes := map[namespaceKey]float64{}
  1381. unmountedPVCCost := map[namespaceKey]float64{}
  1382. for _, pvc := range pvcMap {
  1383. if !pvc.Mounted && pvc.Volume != nil {
  1384. key := newNamespaceKey(pvc.Cluster, pvc.Namespace)
  1385. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1386. hrs := pvc.Minutes() / 60.0
  1387. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1388. unmountedPVCCost[key] += cost
  1389. unmountedPVCBytes[key] += pvc.Volume.Bytes
  1390. }
  1391. }
  1392. for key, amount := range unmountedPVCCost {
  1393. container := kubecost.UnmountedSuffix
  1394. pod := kubecost.UnmountedSuffix
  1395. namespace := key.Namespace
  1396. node := ""
  1397. cluster := key.Cluster
  1398. podKey := newPodKey(cluster, namespace, pod)
  1399. podMap[podKey] = &Pod{
  1400. Window: window.Clone(),
  1401. Start: *window.Start(),
  1402. End: *window.End(),
  1403. Key: podKey,
  1404. Allocations: map[string]*kubecost.Allocation{},
  1405. }
  1406. podMap[podKey].AppendContainer(container)
  1407. podMap[podKey].Allocations[container].Properties.Cluster = cluster
  1408. podMap[podKey].Allocations[container].Properties.Node = node
  1409. podMap[podKey].Allocations[container].Properties.Namespace = namespace
  1410. podMap[podKey].Allocations[container].Properties.Pod = pod
  1411. podMap[podKey].Allocations[container].Properties.Container = container
  1412. podMap[podKey].Allocations[container].PVByteHours = unmountedPVCBytes[key] * window.Minutes() / 60.0
  1413. podMap[podKey].Allocations[container].PVCost = amount
  1414. }
  1415. }
  1416. // LB describes the start and end time of a Load Balancer along with cost
  1417. type LB struct {
  1418. TotalCost float64
  1419. Start time.Time
  1420. End time.Time
  1421. }
  1422. func getLoadBalancerCosts(resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration) map[serviceKey]*LB {
  1423. lbMap := make(map[serviceKey]*LB)
  1424. lbHourlyCosts := make(map[serviceKey]float64)
  1425. for _, res := range resLBCost {
  1426. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service_name")
  1427. if err != nil {
  1428. continue
  1429. }
  1430. lbHourlyCosts[serviceKey] = res.Values[0].Value
  1431. }
  1432. for _, res := range resLBActiveMins {
  1433. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service_name")
  1434. if err != nil || len(res.Values) == 0 {
  1435. continue
  1436. }
  1437. if _, ok := lbHourlyCosts[serviceKey]; !ok {
  1438. log.Warningf("CostModel: failed to find hourly cost for Load Balancer: %v", serviceKey)
  1439. continue
  1440. }
  1441. s := time.Unix(int64(res.Values[0].Timestamp), 0)
  1442. // subtract resolution from start time to cover full time period
  1443. s = s.Add(-resolution)
  1444. e := time.Unix(int64(res.Values[len(res.Values)-1].Timestamp), 0)
  1445. hours := e.Sub(s).Hours()
  1446. lbMap[serviceKey] = &LB{
  1447. TotalCost: lbHourlyCosts[serviceKey] * hours,
  1448. Start: s,
  1449. End: e,
  1450. }
  1451. }
  1452. return lbMap
  1453. }
  1454. func applyLoadBalancersToPods(lbMap map[serviceKey]*LB, allocsByService map[serviceKey][]*kubecost.Allocation) {
  1455. for sKey, lb := range lbMap {
  1456. totalHours := 0.0
  1457. allocHours := make(map[*kubecost.Allocation]float64)
  1458. // Add portion of load balancing cost to each allocation
  1459. // proportional to the total number of hours allocations used the load balancer
  1460. for _, alloc := range allocsByService[sKey] {
  1461. // Determine the (start, end) of the relationship between the
  1462. // given LB and the associated Allocation so that a precise
  1463. // number of hours can be used to compute cumulative cost.
  1464. s, e := alloc.Start, alloc.End
  1465. if lb.Start.After(alloc.Start) {
  1466. s = lb.Start
  1467. }
  1468. if lb.End.Before(alloc.End) {
  1469. e = lb.End
  1470. }
  1471. hours := e.Sub(s).Hours()
  1472. // A negative number of hours signifies no overlap between the windows
  1473. if hours > 0 {
  1474. totalHours += hours
  1475. allocHours[alloc] = hours
  1476. }
  1477. }
  1478. // Distribute cost of service once total hours is calculated
  1479. for alloc, hours := range allocHours {
  1480. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1481. }
  1482. }
  1483. }
  1484. // getNodePricing determines node pricing, given a key and a mapping from keys
  1485. // to their NodePricing instances, as well as the custom pricing configuration
  1486. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1487. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1488. // back on custom pricing as a default.
  1489. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*NodePricing, nodeKey nodeKey) *NodePricing {
  1490. // Find the relevant NodePricing, if it exists. If not, substitute the
  1491. // custom NodePricing as a default.
  1492. node, ok := nodeMap[nodeKey]
  1493. if !ok || node == nil {
  1494. if nodeKey.Node != "" {
  1495. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1496. }
  1497. return cm.getCustomNodePricing(false)
  1498. }
  1499. // If custom pricing is enabled and can be retrieved, override detected
  1500. // node pricing with the custom values.
  1501. customPricingConfig, err := cm.Provider.GetConfig()
  1502. if err != nil {
  1503. log.Warningf("CostModel: failed to load custom pricing: %s", err)
  1504. }
  1505. if cloud.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1506. return cm.getCustomNodePricing(node.Preemptible)
  1507. }
  1508. node.Source = "prometheus"
  1509. // If any of the values are NaN or zero, replace them with the custom
  1510. // values as default.
  1511. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1512. // them as strings like this?
  1513. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1514. log.Warningf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1515. cpuCostStr := customPricingConfig.CPU
  1516. if node.Preemptible {
  1517. cpuCostStr = customPricingConfig.SpotCPU
  1518. }
  1519. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1520. if err != nil {
  1521. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1522. }
  1523. node.CostPerCPUHr = costPerCPUHr
  1524. node.Source += "/customCPU"
  1525. }
  1526. if math.IsNaN(node.CostPerGPUHr) {
  1527. log.Warningf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1528. gpuCostStr := customPricingConfig.GPU
  1529. if node.Preemptible {
  1530. gpuCostStr = customPricingConfig.SpotGPU
  1531. }
  1532. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1533. if err != nil {
  1534. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1535. }
  1536. node.CostPerGPUHr = costPerGPUHr
  1537. node.Source += "/customGPU"
  1538. }
  1539. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1540. log.Warningf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1541. ramCostStr := customPricingConfig.RAM
  1542. if node.Preemptible {
  1543. ramCostStr = customPricingConfig.SpotRAM
  1544. }
  1545. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1546. if err != nil {
  1547. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1548. }
  1549. node.CostPerRAMGiBHr = costPerRAMHr
  1550. node.Source += "/customRAM"
  1551. }
  1552. return node
  1553. }
  1554. // getCustomNodePricing converts the CostModel's configured custom pricing
  1555. // values into a NodePricing instance.
  1556. func (cm *CostModel) getCustomNodePricing(spot bool) *NodePricing {
  1557. customPricingConfig, err := cm.Provider.GetConfig()
  1558. if err != nil {
  1559. return nil
  1560. }
  1561. cpuCostStr := customPricingConfig.CPU
  1562. gpuCostStr := customPricingConfig.GPU
  1563. ramCostStr := customPricingConfig.RAM
  1564. if spot {
  1565. cpuCostStr = customPricingConfig.SpotCPU
  1566. gpuCostStr = customPricingConfig.SpotGPU
  1567. ramCostStr = customPricingConfig.SpotRAM
  1568. }
  1569. node := &NodePricing{Source: "custom"}
  1570. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1571. if err != nil {
  1572. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1573. }
  1574. node.CostPerCPUHr = costPerCPUHr
  1575. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1576. if err != nil {
  1577. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1578. }
  1579. node.CostPerGPUHr = costPerGPUHr
  1580. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1581. if err != nil {
  1582. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1583. }
  1584. node.CostPerRAMGiBHr = costPerRAMHr
  1585. return node
  1586. }
  1587. // NodePricing describes the resource costs associated with a given node, as
  1588. // well as the source of the information (e.g. prometheus, custom)
  1589. type NodePricing struct {
  1590. Name string
  1591. NodeType string
  1592. ProviderID string
  1593. Preemptible bool
  1594. CostPerCPUHr float64
  1595. CostPerRAMGiBHr float64
  1596. CostPerGPUHr float64
  1597. Discount float64
  1598. Source string
  1599. }
  1600. // Pod describes a running pod's start and end time within a Window and
  1601. // all the Allocations (i.e. containers) contained within it.
  1602. type Pod struct {
  1603. Window kubecost.Window
  1604. Start time.Time
  1605. End time.Time
  1606. Key podKey
  1607. Allocations map[string]*kubecost.Allocation
  1608. }
  1609. // AppendContainer adds an entry for the given container name to the Pod.
  1610. func (p Pod) AppendContainer(container string) {
  1611. name := fmt.Sprintf("%s/%s/%s/%s", p.Key.Cluster, p.Key.Namespace, p.Key.Pod, container)
  1612. alloc := &kubecost.Allocation{
  1613. Name: name,
  1614. Properties: &kubecost.AllocationProperties{},
  1615. Window: p.Window.Clone(),
  1616. Start: p.Start,
  1617. End: p.End,
  1618. }
  1619. alloc.Properties.Container = container
  1620. alloc.Properties.Pod = p.Key.Pod
  1621. alloc.Properties.Namespace = p.Key.Namespace
  1622. alloc.Properties.Cluster = p.Key.Cluster
  1623. p.Allocations[container] = alloc
  1624. }
  1625. // PVC describes a PersistentVolumeClaim
  1626. // TODO:CLEANUP move to pkg/kubecost?
  1627. // TODO:CLEANUP add PersistentVolumeClaims field to type Allocation?
  1628. type PVC struct {
  1629. Bytes float64 `json:"bytes"`
  1630. Count int `json:"count"`
  1631. Name string `json:"name"`
  1632. Cluster string `json:"cluster"`
  1633. Namespace string `json:"namespace"`
  1634. Volume *PV `json:"persistentVolume"`
  1635. Mounted bool `json:"mounted"`
  1636. Start time.Time `json:"start"`
  1637. End time.Time `json:"end"`
  1638. }
  1639. // Cost computes the cumulative cost of the PVC
  1640. func (pvc *PVC) Cost() float64 {
  1641. if pvc == nil || pvc.Volume == nil {
  1642. return 0.0
  1643. }
  1644. gib := pvc.Bytes / 1024 / 1024 / 1024
  1645. hrs := pvc.Minutes() / 60.0
  1646. return pvc.Volume.CostPerGiBHour * gib * hrs
  1647. }
  1648. // Minutes computes the number of minutes over which the PVC is defined
  1649. func (pvc *PVC) Minutes() float64 {
  1650. if pvc == nil {
  1651. return 0.0
  1652. }
  1653. return pvc.End.Sub(pvc.Start).Minutes()
  1654. }
  1655. // String returns a string representation of the PVC
  1656. func (pvc *PVC) String() string {
  1657. if pvc == nil {
  1658. return "<nil>"
  1659. }
  1660. 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))
  1661. }
  1662. // PV describes a PersistentVolume
  1663. // TODO:CLEANUP move to pkg/kubecost?
  1664. type PV struct {
  1665. Bytes float64 `json:"bytes"`
  1666. CostPerGiBHour float64 `json:"costPerGiBHour"`
  1667. Cluster string `json:"cluster"`
  1668. Name string `json:"name"`
  1669. StorageClass string `json:"storageClass"`
  1670. }
  1671. // String returns a string representation of the PV
  1672. func (pv *PV) String() string {
  1673. if pv == nil {
  1674. return "<nil>"
  1675. }
  1676. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  1677. }