allocation.go 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  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)`
  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)`
  36. queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`
  37. queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost[%s]%s)) by (node, cluster_id, instance_type)`
  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)
  247. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr)
  248. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr)
  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.CPUCost = alloc.CPUCoreHours * node.CostPerCPUHr
  287. alloc.RAMCost = (alloc.RAMByteHours / 1024 / 1024 / 1024) * node.CostPerRAMGiBHr
  288. alloc.GPUCost = alloc.GPUHours * node.CostPerGPUHr
  289. if pvcs, ok := podPVCMap[podKey]; ok {
  290. for _, pvc := range pvcs {
  291. // Determine the (start, end) of the relationship between the
  292. // given PVC and the associated Allocation so that a precise
  293. // number of hours can be used to compute cumulative cost.
  294. s, e := alloc.Start, alloc.End
  295. if pvc.Start.After(alloc.Start) {
  296. s = pvc.Start
  297. }
  298. if pvc.End.Before(alloc.End) {
  299. e = pvc.End
  300. }
  301. minutes := e.Sub(s).Minutes()
  302. hrs := minutes / 60.0
  303. count := float64(pvc.Count)
  304. if pvc.Count < 1 {
  305. count = 1
  306. }
  307. gib := pvc.Bytes / 1024 / 1024 / 1024
  308. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  309. // Apply the size and cost of the PV to the allocation, each
  310. // weighted by count (i.e. the number of containers in the pod)
  311. alloc.PVByteHours += pvc.Bytes * hrs / count
  312. alloc.PVCost += cost / count
  313. }
  314. }
  315. // Make sure that the name is correct (node may not be present at this
  316. // point due to it missing from queryMinutes) then insert.
  317. alloc.Name = fmt.Sprintf("%s/%s/%s/%s/%s", cluster, nodeName, namespace, pod, container)
  318. allocSet.Set(alloc)
  319. }
  320. }
  321. return allocSet, nil
  322. }
  323. func (cm *CostModel) buildPodMap(window kubecost.Window, resolution, maxBatchSize time.Duration, podMap map[podKey]*Pod, clusterStart, clusterEnd map[string]time.Time) error {
  324. // Assumes that window is positive and closed
  325. start, end := *window.Start(), *window.End()
  326. // Convert resolution duration to a query-ready string
  327. resStr := util.DurationString(resolution)
  328. ctx := prom.NewContext(cm.PrometheusClient)
  329. // Query for (start, end) by (pod, namespace, cluster) over the given
  330. // window, using the given resolution, and if necessary in batches no
  331. // larger than the given maximum batch size. If working in batches, track
  332. // overall progress by starting with (window.start, window.start) and
  333. // querying in batches no larger than maxBatchSize from start-to-end,
  334. // folding each result set into podMap as the results come back.
  335. coverage := kubecost.NewWindow(&start, &start)
  336. numQuery := 1
  337. for coverage.End().Before(end) {
  338. // Determine the (start, end) of the current batch
  339. batchStart := *coverage.End()
  340. batchEnd := coverage.End().Add(maxBatchSize)
  341. if batchEnd.After(end) {
  342. batchEnd = end
  343. }
  344. batchWindow := kubecost.NewWindow(&batchStart, &batchEnd)
  345. var resPods []*prom.QueryResult
  346. var err error
  347. maxTries := 3
  348. numTries := 0
  349. for resPods == nil && numTries < maxTries {
  350. numTries++
  351. // Convert window (start, end) to (duration, offset) for querying Prometheus,
  352. // including handling Thanos offset
  353. durStr, offStr, err := batchWindow.DurationOffsetForPrometheus()
  354. if err != nil || durStr == "" {
  355. // Negative duration, so set empty results and don't query
  356. resPods = []*prom.QueryResult{}
  357. err = nil
  358. break
  359. }
  360. // Submit and profile query
  361. queryPods := fmt.Sprintf(queryFmtPods, durStr, resStr, offStr)
  362. queryProfile := time.Now()
  363. resPods, err = ctx.Query(queryPods).Await()
  364. if err != nil {
  365. log.Profile(queryProfile, fmt.Sprintf("CostModel.ComputeAllocation: pod query %d try %d failed: %s", numQuery, numTries, queryPods))
  366. resPods = nil
  367. }
  368. }
  369. if err != nil {
  370. return err
  371. }
  372. applyPodResults(window, resolution, podMap, clusterStart, clusterEnd, resPods)
  373. coverage = coverage.ExpandEnd(batchEnd)
  374. numQuery++
  375. }
  376. return nil
  377. }
  378. func applyPodResults(window kubecost.Window, resolution time.Duration, podMap map[podKey]*Pod, clusterStart, clusterEnd map[string]time.Time, resPods []*prom.QueryResult) {
  379. for _, res := range resPods {
  380. if len(res.Values) == 0 {
  381. log.Warningf("CostModel.ComputeAllocation: empty minutes result")
  382. continue
  383. }
  384. cluster, err := res.GetString("cluster_id")
  385. if err != nil {
  386. cluster = env.GetClusterID()
  387. }
  388. labels, err := res.GetStrings("namespace", "pod")
  389. if err != nil {
  390. log.Warningf("CostModel.ComputeAllocation: minutes query result missing field: %s", err)
  391. continue
  392. }
  393. namespace := labels["namespace"]
  394. pod := labels["pod"]
  395. key := newPodKey(cluster, namespace, pod)
  396. // allocStart and allocEnd are the timestamps of the first and last
  397. // minutes the pod was running, respectively. We subtract one resolution
  398. // from allocStart because this point will actually represent the end
  399. // of the first minute. We don't subtract from allocEnd because it
  400. // already represents the end of the last minute.
  401. var allocStart, allocEnd time.Time
  402. startAdjustmentCoeff, endAdjustmentCoeff := 1.0, 1.0
  403. for _, datum := range res.Values {
  404. t := time.Unix(int64(datum.Timestamp), 0)
  405. if allocStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  406. // Set the start timestamp to the earliest non-zero timestamp
  407. allocStart = t
  408. // Record adjustment coefficient, i.e. the portion of the start
  409. // timestamp to "ignore". That is, sometimes the value will be
  410. // 0.5, meaning that we should discount the time running by
  411. // half of the resolution the timestamp stands for.
  412. startAdjustmentCoeff = (1.0 - datum.Value)
  413. }
  414. if datum.Value > 0 && window.Contains(t) {
  415. // Set the end timestamp to the latest non-zero timestamp
  416. allocEnd = t
  417. // Record adjustment coefficient, i.e. the portion of the end
  418. // timestamp to "ignore". (See explanation above for start.)
  419. endAdjustmentCoeff = (1.0 - datum.Value)
  420. }
  421. }
  422. if allocStart.IsZero() || allocEnd.IsZero() {
  423. continue
  424. }
  425. // Adjust timestamps according to the resolution and the adjustment
  426. // coefficients, as described above. That is, count the start timestamp
  427. // from the beginning of the resolution, not the end. Then "reduce" the
  428. // start and end by the correct amount, in the case that the "running"
  429. // value of the first or last timestamp was not a full 1.0.
  430. allocStart = allocStart.Add(-resolution)
  431. // Note: the *100 and /100 are necessary because Duration is an int, so
  432. // 0.5, for instance, will be truncated, resulting in no adjustment.
  433. allocStart = allocStart.Add(time.Duration(startAdjustmentCoeff*100) * resolution / time.Duration(100))
  434. allocEnd = allocEnd.Add(-time.Duration(endAdjustmentCoeff*100) * resolution / time.Duration(100))
  435. // If there is only one point with a value <= 0.5 that the start and
  436. // end timestamps both share, then we will enter this case because at
  437. // least half of a resolution will be subtracted from both the start
  438. // and the end. If that is the case, then add back half of each side
  439. // so that the pod is said to run for half a resolution total.
  440. // e.g. For resolution 1m and a value of 0.5 at one timestamp, we'll
  441. // end up with allocEnd == allocStart and each coeff == 0.5. In
  442. // that case, add 0.25m to each side, resulting in 0.5m duration.
  443. if !allocEnd.After(allocStart) {
  444. allocStart = allocStart.Add(-time.Duration(50*startAdjustmentCoeff) * resolution / time.Duration(100))
  445. allocEnd = allocEnd.Add(time.Duration(50*endAdjustmentCoeff) * resolution / time.Duration(100))
  446. }
  447. // Set start if unset or this datum's start time is earlier than the
  448. // current earliest time.
  449. if _, ok := clusterStart[cluster]; !ok || allocStart.Before(clusterStart[cluster]) {
  450. clusterStart[cluster] = allocStart
  451. }
  452. // Set end if unset or this datum's end time is later than the
  453. // current latest time.
  454. if _, ok := clusterEnd[cluster]; !ok || allocEnd.After(clusterEnd[cluster]) {
  455. clusterEnd[cluster] = allocEnd
  456. }
  457. if pod, ok := podMap[key]; ok {
  458. // Pod has already been recorded, so update it accordingly
  459. if allocStart.Before(pod.Start) {
  460. pod.Start = allocStart
  461. }
  462. if allocEnd.After(pod.End) {
  463. pod.End = allocEnd
  464. }
  465. } else {
  466. // Pod has not been recorded yet, so insert it
  467. podMap[key] = &Pod{
  468. Window: window.Clone(),
  469. Start: allocStart,
  470. End: allocEnd,
  471. Key: key,
  472. Allocations: map[string]*kubecost.Allocation{},
  473. }
  474. }
  475. }
  476. }
  477. func applyCPUCoresAllocated(podMap map[podKey]*Pod, resCPUCoresAllocated []*prom.QueryResult) {
  478. for _, res := range resCPUCoresAllocated {
  479. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  480. if err != nil {
  481. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation result missing field: %s", err)
  482. continue
  483. }
  484. pod, ok := podMap[key]
  485. if !ok {
  486. continue
  487. }
  488. container, err := res.GetString("container")
  489. if err != nil {
  490. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU allocation query result missing 'container': %s", key)
  491. continue
  492. }
  493. if _, ok := pod.Allocations[container]; !ok {
  494. pod.AppendContainer(container)
  495. }
  496. cpuCores := res.Values[0].Value
  497. hours := pod.Allocations[container].Minutes() / 60.0
  498. pod.Allocations[container].CPUCoreHours = cpuCores * hours
  499. node, err := res.GetString("node")
  500. if err != nil {
  501. log.Warningf("CostModel.ComputeAllocation: CPU allocation query result missing 'node': %s", key)
  502. continue
  503. }
  504. pod.Allocations[container].Properties.Node = node
  505. }
  506. }
  507. func applyCPUCoresRequested(podMap map[podKey]*Pod, resCPUCoresRequested []*prom.QueryResult) {
  508. for _, res := range resCPUCoresRequested {
  509. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  510. if err != nil {
  511. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request result missing field: %s", err)
  512. continue
  513. }
  514. pod, ok := podMap[key]
  515. if !ok {
  516. continue
  517. }
  518. container, err := res.GetString("container")
  519. if err != nil {
  520. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU request query result missing 'container': %s", key)
  521. continue
  522. }
  523. if _, ok := pod.Allocations[container]; !ok {
  524. pod.AppendContainer(container)
  525. }
  526. pod.Allocations[container].CPUCoreRequestAverage = res.Values[0].Value
  527. // If CPU allocation is less than requests, set CPUCoreHours to
  528. // request level.
  529. if pod.Allocations[container].CPUCores() < res.Values[0].Value {
  530. pod.Allocations[container].CPUCoreHours = res.Values[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  531. }
  532. node, err := res.GetString("node")
  533. if err != nil {
  534. log.Warningf("CostModel.ComputeAllocation: CPU request query result missing 'node': %s", key)
  535. continue
  536. }
  537. pod.Allocations[container].Properties.Node = node
  538. }
  539. }
  540. func applyCPUCoresUsedAvg(podMap map[podKey]*Pod, resCPUCoresUsedAvg []*prom.QueryResult) {
  541. for _, res := range resCPUCoresUsedAvg {
  542. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  543. if err != nil {
  544. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg result missing field: %s", err)
  545. continue
  546. }
  547. pod, ok := podMap[key]
  548. if !ok {
  549. continue
  550. }
  551. container, err := res.GetString("container_name")
  552. if err != nil {
  553. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg query result missing 'container': %s", key)
  554. continue
  555. }
  556. if _, ok := pod.Allocations[container]; !ok {
  557. pod.AppendContainer(container)
  558. }
  559. pod.Allocations[container].CPUCoreUsageAverage = res.Values[0].Value
  560. }
  561. }
  562. func applyCPUCoresUsedMax(podMap map[podKey]*Pod, resCPUCoresUsedMax []*prom.QueryResult) {
  563. for _, res := range resCPUCoresUsedMax {
  564. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  565. if err != nil {
  566. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max result missing field: %s", err)
  567. continue
  568. }
  569. pod, ok := podMap[key]
  570. if !ok {
  571. continue
  572. }
  573. container, err := res.GetString("container_name")
  574. if err != nil {
  575. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max query result missing 'container': %s", key)
  576. continue
  577. }
  578. if _, ok := pod.Allocations[container]; !ok {
  579. pod.AppendContainer(container)
  580. }
  581. if pod.Allocations[container].RawAllocationOnly == nil {
  582. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  583. CPUCoreUsageMax: res.Values[0].Value,
  584. }
  585. } else {
  586. pod.Allocations[container].RawAllocationOnly.CPUCoreUsageMax = res.Values[0].Value
  587. }
  588. }
  589. }
  590. func applyRAMBytesAllocated(podMap map[podKey]*Pod, resRAMBytesAllocated []*prom.QueryResult) {
  591. for _, res := range resRAMBytesAllocated {
  592. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  593. if err != nil {
  594. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation result missing field: %s", err)
  595. continue
  596. }
  597. pod, ok := podMap[key]
  598. if !ok {
  599. continue
  600. }
  601. container, err := res.GetString("container")
  602. if err != nil {
  603. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation query result missing 'container': %s", key)
  604. continue
  605. }
  606. if _, ok := pod.Allocations[container]; !ok {
  607. pod.AppendContainer(container)
  608. }
  609. ramBytes := res.Values[0].Value
  610. hours := pod.Allocations[container].Minutes() / 60.0
  611. pod.Allocations[container].RAMByteHours = ramBytes * hours
  612. node, err := res.GetString("node")
  613. if err != nil {
  614. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing 'node': %s", key)
  615. continue
  616. }
  617. pod.Allocations[container].Properties.Node = node
  618. }
  619. }
  620. func applyRAMBytesRequested(podMap map[podKey]*Pod, resRAMBytesRequested []*prom.QueryResult) {
  621. for _, res := range resRAMBytesRequested {
  622. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  623. if err != nil {
  624. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request result missing field: %s", err)
  625. continue
  626. }
  627. pod, ok := podMap[key]
  628. if !ok {
  629. continue
  630. }
  631. container, err := res.GetString("container")
  632. if err != nil {
  633. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request query result missing 'container': %s", key)
  634. continue
  635. }
  636. if _, ok := pod.Allocations[container]; !ok {
  637. pod.AppendContainer(container)
  638. }
  639. pod.Allocations[container].RAMBytesRequestAverage = res.Values[0].Value
  640. // If RAM allocation is less than requests, set RAMByteHours to
  641. // request level.
  642. if pod.Allocations[container].RAMBytes() < res.Values[0].Value {
  643. pod.Allocations[container].RAMByteHours = res.Values[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  644. }
  645. node, err := res.GetString("node")
  646. if err != nil {
  647. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing 'node': %s", key)
  648. continue
  649. }
  650. pod.Allocations[container].Properties.Node = node
  651. }
  652. }
  653. func applyRAMBytesUsedAvg(podMap map[podKey]*Pod, resRAMBytesUsedAvg []*prom.QueryResult) {
  654. for _, res := range resRAMBytesUsedAvg {
  655. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  656. if err != nil {
  657. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM avg usage result missing field: %s", err)
  658. continue
  659. }
  660. pod, ok := podMap[key]
  661. if !ok {
  662. continue
  663. }
  664. container, err := res.GetString("container_name")
  665. if err != nil {
  666. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage avg query result missing 'container': %s", key)
  667. continue
  668. }
  669. if _, ok := pod.Allocations[container]; !ok {
  670. pod.AppendContainer(container)
  671. }
  672. pod.Allocations[container].RAMBytesUsageAverage = res.Values[0].Value
  673. }
  674. }
  675. func applyRAMBytesUsedMax(podMap map[podKey]*Pod, resRAMBytesUsedMax []*prom.QueryResult) {
  676. for _, res := range resRAMBytesUsedMax {
  677. key, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  678. if err != nil {
  679. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max result missing field: %s", err)
  680. continue
  681. }
  682. pod, ok := podMap[key]
  683. if !ok {
  684. continue
  685. }
  686. container, err := res.GetString("container_name")
  687. if err != nil {
  688. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max query result missing 'container': %s", key)
  689. continue
  690. }
  691. if _, ok := pod.Allocations[container]; !ok {
  692. pod.AppendContainer(container)
  693. }
  694. if pod.Allocations[container].RawAllocationOnly == nil {
  695. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  696. RAMBytesUsageMax: res.Values[0].Value,
  697. }
  698. } else {
  699. pod.Allocations[container].RawAllocationOnly.RAMBytesUsageMax = res.Values[0].Value
  700. }
  701. }
  702. }
  703. func applyGPUsRequested(podMap map[podKey]*Pod, resGPUsRequested []*prom.QueryResult) {
  704. for _, res := range resGPUsRequested {
  705. key, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  706. if err != nil {
  707. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request result missing field: %s", err)
  708. continue
  709. }
  710. pod, ok := podMap[key]
  711. if !ok {
  712. continue
  713. }
  714. container, err := res.GetString("container")
  715. if err != nil {
  716. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request query result missing 'container': %s", key)
  717. continue
  718. }
  719. if _, ok := pod.Allocations[container]; !ok {
  720. pod.AppendContainer(container)
  721. }
  722. hrs := pod.Allocations[container].Minutes() / 60.0
  723. pod.Allocations[container].GPUHours = res.Values[0].Value * hrs
  724. }
  725. }
  726. func applyNetworkAllocation(podMap map[podKey]*Pod, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult) {
  727. costPerGiBByCluster := map[string]float64{}
  728. for _, res := range resNetworkCostPerGiB {
  729. cluster, err := res.GetString("cluster_id")
  730. if err != nil {
  731. cluster = env.GetClusterID()
  732. }
  733. costPerGiBByCluster[cluster] = res.Values[0].Value
  734. }
  735. for _, res := range resNetworkGiB {
  736. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod_name")
  737. if err != nil {
  738. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  739. continue
  740. }
  741. pod, ok := podMap[podKey]
  742. if !ok {
  743. continue
  744. }
  745. for _, alloc := range pod.Allocations {
  746. gib := res.Values[0].Value / float64(len(pod.Allocations))
  747. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  748. alloc.NetworkCost = gib * costPerGiB
  749. }
  750. }
  751. }
  752. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[namespaceKey]map[string]string {
  753. namespaceLabels := map[namespaceKey]map[string]string{}
  754. for _, res := range resNamespaceLabels {
  755. nsKey, err := resultNamespaceKey(res, "cluster_id", "namespace")
  756. if err != nil {
  757. continue
  758. }
  759. if _, ok := namespaceLabels[nsKey]; !ok {
  760. namespaceLabels[nsKey] = map[string]string{}
  761. }
  762. for k, l := range res.GetLabels() {
  763. namespaceLabels[nsKey][k] = l
  764. }
  765. }
  766. return namespaceLabels
  767. }
  768. func resToPodLabels(resPodLabels []*prom.QueryResult) map[podKey]map[string]string {
  769. podLabels := map[podKey]map[string]string{}
  770. for _, res := range resPodLabels {
  771. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  772. if err != nil {
  773. continue
  774. }
  775. if _, ok := podLabels[podKey]; !ok {
  776. podLabels[podKey] = map[string]string{}
  777. }
  778. for k, l := range res.GetLabels() {
  779. podLabels[podKey][k] = l
  780. }
  781. }
  782. return podLabels
  783. }
  784. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  785. namespaceAnnotations := map[string]map[string]string{}
  786. for _, res := range resNamespaceAnnotations {
  787. namespace, err := res.GetString("namespace")
  788. if err != nil {
  789. continue
  790. }
  791. if _, ok := namespaceAnnotations[namespace]; !ok {
  792. namespaceAnnotations[namespace] = map[string]string{}
  793. }
  794. for k, l := range res.GetAnnotations() {
  795. namespaceAnnotations[namespace][k] = l
  796. }
  797. }
  798. return namespaceAnnotations
  799. }
  800. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult) map[podKey]map[string]string {
  801. podAnnotations := map[podKey]map[string]string{}
  802. for _, res := range resPodAnnotations {
  803. podKey, err := resultPodKey(res, "cluster_id", "namespace", "pod")
  804. if err != nil {
  805. continue
  806. }
  807. if _, ok := podAnnotations[podKey]; !ok {
  808. podAnnotations[podKey] = map[string]string{}
  809. }
  810. for k, l := range res.GetAnnotations() {
  811. podAnnotations[podKey][k] = l
  812. }
  813. }
  814. return podAnnotations
  815. }
  816. func applyLabels(podMap map[podKey]*Pod, namespaceLabels map[namespaceKey]map[string]string, podLabels map[podKey]map[string]string) {
  817. for podKey, pod := range podMap {
  818. for _, alloc := range pod.Allocations {
  819. allocLabels := alloc.Properties.Labels
  820. if allocLabels == nil {
  821. allocLabels = make(map[string]string)
  822. }
  823. // Apply namespace labels first, then pod labels so that pod labels
  824. // overwrite namespace labels.
  825. nsKey := newNamespaceKey(podKey.Cluster, podKey.Namespace)
  826. if labels, ok := namespaceLabels[nsKey]; ok {
  827. for k, v := range labels {
  828. allocLabels[k] = v
  829. }
  830. }
  831. if labels, ok := podLabels[podKey]; ok {
  832. for k, v := range labels {
  833. allocLabels[k] = v
  834. }
  835. }
  836. alloc.Properties.Labels = allocLabels
  837. }
  838. }
  839. }
  840. func applyAnnotations(podMap map[podKey]*Pod, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  841. for key, pod := range podMap {
  842. for _, alloc := range pod.Allocations {
  843. allocAnnotations := alloc.Properties.Annotations
  844. if allocAnnotations == nil {
  845. allocAnnotations = make(map[string]string)
  846. }
  847. // Apply namespace annotations first, then pod annotations so that
  848. // pod labels overwrite namespace labels.
  849. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  850. for k, v := range labels {
  851. allocAnnotations[k] = v
  852. }
  853. }
  854. if labels, ok := podAnnotations[key]; ok {
  855. for k, v := range labels {
  856. allocAnnotations[k] = v
  857. }
  858. }
  859. alloc.Properties.Annotations = allocAnnotations
  860. }
  861. }
  862. }
  863. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  864. serviceLabels := map[serviceKey]map[string]string{}
  865. for _, res := range resServiceLabels {
  866. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service")
  867. if err != nil {
  868. continue
  869. }
  870. if _, ok := serviceLabels[serviceKey]; !ok {
  871. serviceLabels[serviceKey] = map[string]string{}
  872. }
  873. for k, l := range res.GetLabels() {
  874. serviceLabels[serviceKey][k] = l
  875. }
  876. }
  877. // Prune duplicate services. That is, if the same service exists with
  878. // hyphens instead of underscores, keep the one that uses hyphens.
  879. for key := range serviceLabels {
  880. if strings.Contains(key.Service, "_") {
  881. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  882. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  883. if _, ok := serviceLabels[duplicateKey]; ok {
  884. delete(serviceLabels, key)
  885. }
  886. }
  887. }
  888. return serviceLabels
  889. }
  890. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  891. deploymentLabels := map[controllerKey]map[string]string{}
  892. for _, res := range resDeploymentLabels {
  893. controllerKey, err := resultDeploymentKey(res, "cluster_id", "namespace", "deployment")
  894. if err != nil {
  895. continue
  896. }
  897. if _, ok := deploymentLabels[controllerKey]; !ok {
  898. deploymentLabels[controllerKey] = map[string]string{}
  899. }
  900. for k, l := range res.GetLabels() {
  901. deploymentLabels[controllerKey][k] = l
  902. }
  903. }
  904. // Prune duplicate deployments. That is, if the same deployment exists with
  905. // hyphens instead of underscores, keep the one that uses hyphens.
  906. for key := range deploymentLabels {
  907. if strings.Contains(key.Controller, "_") {
  908. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  909. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  910. if _, ok := deploymentLabels[duplicateKey]; ok {
  911. delete(deploymentLabels, key)
  912. }
  913. }
  914. }
  915. return deploymentLabels
  916. }
  917. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  918. statefulSetLabels := map[controllerKey]map[string]string{}
  919. for _, res := range resStatefulSetLabels {
  920. controllerKey, err := resultStatefulSetKey(res, "cluster_id", "namespace", "statefulSet")
  921. if err != nil {
  922. continue
  923. }
  924. if _, ok := statefulSetLabels[controllerKey]; !ok {
  925. statefulSetLabels[controllerKey] = map[string]string{}
  926. }
  927. for k, l := range res.GetLabels() {
  928. statefulSetLabels[controllerKey][k] = l
  929. }
  930. }
  931. // Prune duplicate stateful sets. That is, if the same stateful set exists
  932. // with hyphens instead of underscores, keep the one that uses hyphens.
  933. for key := range statefulSetLabels {
  934. if strings.Contains(key.Controller, "_") {
  935. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  936. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  937. if _, ok := statefulSetLabels[duplicateKey]; ok {
  938. delete(statefulSetLabels, key)
  939. }
  940. }
  941. }
  942. return statefulSetLabels
  943. }
  944. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  945. podControllerMap := map[podKey]controllerKey{}
  946. // For each controller, turn the labels into a selector and attempt to
  947. // match it with each set of pod labels. A match indicates that the pod
  948. // belongs to the controller.
  949. for cKey, cLabels := range controllerLabels {
  950. selector := labels.Set(cLabels).AsSelectorPreValidated()
  951. for pKey, pLabels := range podLabels {
  952. // If the pod is in a different cluster or namespace, there is
  953. // no need to compare the labels.
  954. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  955. continue
  956. }
  957. podLabelSet := labels.Set(pLabels)
  958. if selector.Matches(podLabelSet) {
  959. if _, ok := podControllerMap[pKey]; ok {
  960. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  961. }
  962. podControllerMap[pKey] = cKey
  963. }
  964. }
  965. }
  966. return podControllerMap
  967. }
  968. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult) map[podKey]controllerKey {
  969. daemonSetLabels := map[podKey]controllerKey{}
  970. for _, res := range resDaemonSetLabels {
  971. controllerKey, err := resultDaemonSetKey(res, "cluster_id", "namespace", "owner_name")
  972. if err != nil {
  973. continue
  974. }
  975. pod, err := res.GetString("pod")
  976. if err != nil {
  977. log.Warningf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  978. }
  979. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  980. daemonSetLabels[podKey] = controllerKey
  981. }
  982. return daemonSetLabels
  983. }
  984. func resToPodJobMap(resJobLabels []*prom.QueryResult) map[podKey]controllerKey {
  985. jobLabels := map[podKey]controllerKey{}
  986. for _, res := range resJobLabels {
  987. controllerKey, err := resultJobKey(res, "cluster_id", "namespace", "owner_name")
  988. if err != nil {
  989. continue
  990. }
  991. // Convert the name of Jobs generated by CronJobs to the name of the
  992. // CronJob by stripping the timestamp off the end.
  993. match := isCron.FindStringSubmatch(controllerKey.Controller)
  994. if match != nil {
  995. controllerKey.Controller = match[1]
  996. }
  997. pod, err := res.GetString("pod")
  998. if err != nil {
  999. log.Warningf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  1000. }
  1001. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1002. jobLabels[podKey] = controllerKey
  1003. }
  1004. return jobLabels
  1005. }
  1006. func applyServicesToPods(podMap map[podKey]*Pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*kubecost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1007. podServicesMap := map[podKey][]serviceKey{}
  1008. // For each service, turn the labels into a selector and attempt to
  1009. // match it with each set of pod labels. A match indicates that the pod
  1010. // belongs to the service.
  1011. for sKey, sLabels := range serviceLabels {
  1012. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1013. for pKey, pLabels := range podLabels {
  1014. // If the pod is in a different cluster or namespace, there is
  1015. // no need to compare the labels.
  1016. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1017. continue
  1018. }
  1019. podLabelSet := labels.Set(pLabels)
  1020. if selector.Matches(podLabelSet) {
  1021. if _, ok := podServicesMap[pKey]; !ok {
  1022. podServicesMap[pKey] = []serviceKey{}
  1023. }
  1024. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1025. }
  1026. }
  1027. }
  1028. // For each allocation in each pod, attempt to find and apply the list of
  1029. // services associated with the allocation's pod.
  1030. for key, pod := range podMap {
  1031. for _, alloc := range pod.Allocations {
  1032. if sKeys, ok := podServicesMap[key]; ok {
  1033. services := []string{}
  1034. for _, sKey := range sKeys {
  1035. services = append(services, sKey.Service)
  1036. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1037. }
  1038. alloc.Properties.Services = services
  1039. }
  1040. }
  1041. }
  1042. }
  1043. func applyControllersToPods(podMap map[podKey]*Pod, podControllerMap map[podKey]controllerKey) {
  1044. for key, pod := range podMap {
  1045. for _, alloc := range pod.Allocations {
  1046. if controllerKey, ok := podControllerMap[key]; ok {
  1047. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1048. alloc.Properties.Controller = controllerKey.Controller
  1049. }
  1050. }
  1051. }
  1052. }
  1053. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerCPUHr []*prom.QueryResult) {
  1054. for _, res := range resNodeCostPerCPUHr {
  1055. cluster, err := res.GetString("cluster_id")
  1056. if err != nil {
  1057. cluster = env.GetClusterID()
  1058. }
  1059. node, err := res.GetString("node")
  1060. if err != nil {
  1061. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1062. continue
  1063. }
  1064. instanceType, err := res.GetString("instance_type")
  1065. if err != nil {
  1066. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1067. continue
  1068. }
  1069. key := newNodeKey(cluster, node)
  1070. if _, ok := nodeMap[key]; !ok {
  1071. nodeMap[key] = &NodePricing{
  1072. Name: node,
  1073. NodeType: instanceType,
  1074. }
  1075. }
  1076. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1077. }
  1078. }
  1079. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  1080. for _, res := range resNodeCostPerRAMGiBHr {
  1081. cluster, err := res.GetString("cluster_id")
  1082. if err != nil {
  1083. cluster = env.GetClusterID()
  1084. }
  1085. node, err := res.GetString("node")
  1086. if err != nil {
  1087. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1088. continue
  1089. }
  1090. instanceType, err := res.GetString("instance_type")
  1091. if err != nil {
  1092. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1093. continue
  1094. }
  1095. key := newNodeKey(cluster, node)
  1096. if _, ok := nodeMap[key]; !ok {
  1097. nodeMap[key] = &NodePricing{
  1098. Name: node,
  1099. NodeType: instanceType,
  1100. }
  1101. }
  1102. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1103. }
  1104. }
  1105. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerGPUHr []*prom.QueryResult) {
  1106. for _, res := range resNodeCostPerGPUHr {
  1107. cluster, err := res.GetString("cluster_id")
  1108. if err != nil {
  1109. cluster = env.GetClusterID()
  1110. }
  1111. node, err := res.GetString("node")
  1112. if err != nil {
  1113. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1114. continue
  1115. }
  1116. instanceType, err := res.GetString("instance_type")
  1117. if err != nil {
  1118. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1119. continue
  1120. }
  1121. key := newNodeKey(cluster, node)
  1122. if _, ok := nodeMap[key]; !ok {
  1123. nodeMap[key] = &NodePricing{
  1124. Name: node,
  1125. NodeType: instanceType,
  1126. }
  1127. }
  1128. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1129. }
  1130. }
  1131. func applyNodeSpot(nodeMap map[nodeKey]*NodePricing, resNodeIsSpot []*prom.QueryResult) {
  1132. for _, res := range resNodeIsSpot {
  1133. cluster, err := res.GetString("cluster_id")
  1134. if err != nil {
  1135. cluster = env.GetClusterID()
  1136. }
  1137. node, err := res.GetString("node")
  1138. if err != nil {
  1139. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1140. continue
  1141. }
  1142. key := newNodeKey(cluster, node)
  1143. if _, ok := nodeMap[key]; !ok {
  1144. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1145. continue
  1146. }
  1147. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1148. }
  1149. }
  1150. func applyNodeDiscount(nodeMap map[nodeKey]*NodePricing, cm *CostModel) {
  1151. if cm == nil {
  1152. return
  1153. }
  1154. c, err := cm.Provider.GetConfig()
  1155. if err != nil {
  1156. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1157. return
  1158. }
  1159. discount, err := ParsePercentString(c.Discount)
  1160. if err != nil {
  1161. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1162. return
  1163. }
  1164. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1165. if err != nil {
  1166. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1167. return
  1168. }
  1169. for _, node := range nodeMap {
  1170. // TODO GKE Reserved Instances into account
  1171. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1172. node.CostPerCPUHr *= (1.0 - node.Discount)
  1173. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1174. }
  1175. }
  1176. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  1177. for _, res := range resPVCostPerGiBHour {
  1178. cluster, err := res.GetString("cluster_id")
  1179. if err != nil {
  1180. cluster = env.GetClusterID()
  1181. }
  1182. name, err := res.GetString("volumename")
  1183. if err != nil {
  1184. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  1185. continue
  1186. }
  1187. key := newPVKey(cluster, name)
  1188. pvMap[key] = &PV{
  1189. Cluster: cluster,
  1190. Name: name,
  1191. CostPerGiBHour: res.Values[0].Value,
  1192. }
  1193. }
  1194. }
  1195. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  1196. for _, res := range resPVBytes {
  1197. key, err := resultPVKey(res, "cluster_id", "persistentvolume")
  1198. if err != nil {
  1199. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  1200. continue
  1201. }
  1202. if _, ok := pvMap[key]; !ok {
  1203. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  1204. continue
  1205. }
  1206. pvMap[key].Bytes = res.Values[0].Value
  1207. }
  1208. }
  1209. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  1210. for _, res := range resPVCInfo {
  1211. cluster, err := res.GetString("cluster_id")
  1212. if err != nil {
  1213. cluster = env.GetClusterID()
  1214. }
  1215. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1216. if err != nil {
  1217. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  1218. continue
  1219. }
  1220. namespace := values["namespace"]
  1221. name := values["persistentvolumeclaim"]
  1222. volume := values["volumename"]
  1223. storageClass := values["storageclass"]
  1224. pvKey := newPVKey(cluster, volume)
  1225. pvcKey := newPVCKey(cluster, namespace, name)
  1226. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  1227. // the PVC was running, respectively. We subtract 1m from pvcStart
  1228. // because this point will actually represent the end of the first
  1229. // minute. We don't subtract from pvcEnd because it already represents
  1230. // the end of the last minute.
  1231. var pvcStart, pvcEnd time.Time
  1232. for _, datum := range res.Values {
  1233. t := time.Unix(int64(datum.Timestamp), 0)
  1234. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1235. pvcStart = t
  1236. }
  1237. if datum.Value > 0 && window.Contains(t) {
  1238. pvcEnd = t
  1239. }
  1240. }
  1241. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1242. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1243. }
  1244. pvcStart = pvcStart.Add(-time.Minute)
  1245. if _, ok := pvMap[pvKey]; !ok {
  1246. continue
  1247. }
  1248. pvMap[pvKey].StorageClass = storageClass
  1249. if _, ok := pvcMap[pvcKey]; !ok {
  1250. pvcMap[pvcKey] = &PVC{}
  1251. }
  1252. pvcMap[pvcKey].Name = name
  1253. pvcMap[pvcKey].Namespace = namespace
  1254. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1255. pvcMap[pvcKey].Start = pvcStart
  1256. pvcMap[pvcKey].End = pvcEnd
  1257. }
  1258. }
  1259. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1260. for _, res := range resPVCBytesRequested {
  1261. key, err := resultPVCKey(res, "cluster_id", "namespace", "persistentvolumeclaim")
  1262. if err != nil {
  1263. continue
  1264. }
  1265. if _, ok := pvcMap[key]; !ok {
  1266. continue
  1267. }
  1268. pvcMap[key].Bytes = res.Values[0].Value
  1269. }
  1270. }
  1271. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podMap map[podKey]*Pod, resPodPVCAllocation []*prom.QueryResult) {
  1272. for _, res := range resPodPVCAllocation {
  1273. cluster, err := res.GetString("cluster_id")
  1274. if err != nil {
  1275. cluster = env.GetClusterID()
  1276. }
  1277. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1278. if err != nil {
  1279. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1280. continue
  1281. }
  1282. namespace := values["namespace"]
  1283. pod := values["pod"]
  1284. name := values["persistentvolumeclaim"]
  1285. volume := values["persistentvolume"]
  1286. podKey := newPodKey(cluster, namespace, pod)
  1287. pvKey := newPVKey(cluster, volume)
  1288. pvcKey := newPVCKey(cluster, namespace, name)
  1289. if _, ok := pvMap[pvKey]; !ok {
  1290. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1291. continue
  1292. }
  1293. if _, ok := podPVCMap[podKey]; !ok {
  1294. podPVCMap[podKey] = []*PVC{}
  1295. }
  1296. pvc, ok := pvcMap[pvcKey]
  1297. if !ok {
  1298. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1299. continue
  1300. }
  1301. count := 1
  1302. if pod, ok := podMap[podKey]; ok && len(pod.Allocations) > 0 {
  1303. count = len(pod.Allocations)
  1304. } else {
  1305. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC %s for missing pod %s", pvcKey, podKey)
  1306. }
  1307. pvc.Count = count
  1308. pvc.Mounted = true
  1309. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1310. }
  1311. }
  1312. func applyUnmountedPVs(window kubecost.Window, podMap map[podKey]*Pod, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1313. unmountedPVBytes := map[string]float64{}
  1314. unmountedPVCost := map[string]float64{}
  1315. for _, pv := range pvMap {
  1316. mounted := false
  1317. for _, pvc := range pvcMap {
  1318. if pvc.Volume == nil {
  1319. continue
  1320. }
  1321. if pvc.Volume == pv {
  1322. mounted = true
  1323. break
  1324. }
  1325. }
  1326. if !mounted {
  1327. gib := pv.Bytes / 1024 / 1024 / 1024
  1328. hrs := window.Minutes() / 60.0 // TODO improve with PV hours, not window hours
  1329. cost := pv.CostPerGiBHour * gib * hrs
  1330. unmountedPVCost[pv.Cluster] += cost
  1331. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1332. }
  1333. }
  1334. for cluster, amount := range unmountedPVCost {
  1335. container := kubecost.UnmountedSuffix
  1336. pod := kubecost.UnmountedSuffix
  1337. namespace := kubecost.UnmountedSuffix
  1338. node := ""
  1339. key := newPodKey(cluster, namespace, pod)
  1340. podMap[key] = &Pod{
  1341. Window: window.Clone(),
  1342. Start: *window.Start(),
  1343. End: *window.End(),
  1344. Key: key,
  1345. Allocations: map[string]*kubecost.Allocation{},
  1346. }
  1347. podMap[key].AppendContainer(container)
  1348. podMap[key].Allocations[container].Properties.Cluster = cluster
  1349. podMap[key].Allocations[container].Properties.Node = node
  1350. podMap[key].Allocations[container].Properties.Namespace = namespace
  1351. podMap[key].Allocations[container].Properties.Pod = pod
  1352. podMap[key].Allocations[container].Properties.Container = container
  1353. podMap[key].Allocations[container].PVByteHours = unmountedPVBytes[cluster] * window.Minutes() / 60.0
  1354. podMap[key].Allocations[container].PVCost = amount
  1355. }
  1356. }
  1357. func applyUnmountedPVCs(window kubecost.Window, podMap map[podKey]*Pod, pvcMap map[pvcKey]*PVC) {
  1358. unmountedPVCBytes := map[namespaceKey]float64{}
  1359. unmountedPVCCost := map[namespaceKey]float64{}
  1360. for _, pvc := range pvcMap {
  1361. if !pvc.Mounted && pvc.Volume != nil {
  1362. key := newNamespaceKey(pvc.Cluster, pvc.Namespace)
  1363. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1364. hrs := pvc.Minutes() / 60.0
  1365. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1366. unmountedPVCCost[key] += cost
  1367. unmountedPVCBytes[key] += pvc.Volume.Bytes
  1368. }
  1369. }
  1370. for key, amount := range unmountedPVCCost {
  1371. container := kubecost.UnmountedSuffix
  1372. pod := kubecost.UnmountedSuffix
  1373. namespace := key.Namespace
  1374. node := ""
  1375. cluster := key.Cluster
  1376. podKey := newPodKey(cluster, namespace, pod)
  1377. podMap[podKey] = &Pod{
  1378. Window: window.Clone(),
  1379. Start: *window.Start(),
  1380. End: *window.End(),
  1381. Key: podKey,
  1382. Allocations: map[string]*kubecost.Allocation{},
  1383. }
  1384. podMap[podKey].AppendContainer(container)
  1385. podMap[podKey].Allocations[container].Properties.Cluster = cluster
  1386. podMap[podKey].Allocations[container].Properties.Node = node
  1387. podMap[podKey].Allocations[container].Properties.Namespace = namespace
  1388. podMap[podKey].Allocations[container].Properties.Pod = pod
  1389. podMap[podKey].Allocations[container].Properties.Container = container
  1390. podMap[podKey].Allocations[container].PVByteHours = unmountedPVCBytes[key] * window.Minutes() / 60.0
  1391. podMap[podKey].Allocations[container].PVCost = amount
  1392. }
  1393. }
  1394. // LB describes the start and end time of a Load Balancer along with cost
  1395. type LB struct {
  1396. TotalCost float64
  1397. Start time.Time
  1398. End time.Time
  1399. }
  1400. func getLoadBalancerCosts(resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration) map[serviceKey]*LB {
  1401. lbMap := make(map[serviceKey]*LB)
  1402. lbHourlyCosts := make(map[serviceKey]float64)
  1403. for _, res := range resLBCost {
  1404. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service_name")
  1405. if err != nil {
  1406. continue
  1407. }
  1408. lbHourlyCosts[serviceKey] = res.Values[0].Value
  1409. }
  1410. for _, res := range resLBActiveMins {
  1411. serviceKey, err := resultServiceKey(res, "cluster_id", "namespace", "service_name")
  1412. if err != nil || len(res.Values) == 0 {
  1413. continue
  1414. }
  1415. if _, ok := lbHourlyCosts[serviceKey]; !ok {
  1416. log.Warningf("CostModel: failed to find hourly cost for Load Balancer: %v", serviceKey)
  1417. continue
  1418. }
  1419. s := time.Unix(int64(res.Values[0].Timestamp), 0)
  1420. // subtract resolution from start time to cover full time period
  1421. s = s.Add(-resolution)
  1422. e := time.Unix(int64(res.Values[len(res.Values)-1].Timestamp), 0)
  1423. hours := e.Sub(s).Hours()
  1424. lbMap[serviceKey] = &LB{
  1425. TotalCost: lbHourlyCosts[serviceKey] * hours,
  1426. Start: s,
  1427. End: e,
  1428. }
  1429. }
  1430. return lbMap
  1431. }
  1432. func applyLoadBalancersToPods(lbMap map[serviceKey]*LB, allocsByService map[serviceKey][]*kubecost.Allocation) {
  1433. for sKey, lb := range lbMap {
  1434. totalHours := 0.0
  1435. allocHours := make(map[*kubecost.Allocation]float64)
  1436. // Add portion of load balancing cost to each allocation
  1437. // proportional to the total number of hours allocations used the load balancer
  1438. for _, alloc := range allocsByService[sKey] {
  1439. // Determine the (start, end) of the relationship between the
  1440. // given LB and the associated Allocation so that a precise
  1441. // number of hours can be used to compute cumulative cost.
  1442. s, e := alloc.Start, alloc.End
  1443. if lb.Start.After(alloc.Start) {
  1444. s = lb.Start
  1445. }
  1446. if lb.End.Before(alloc.End) {
  1447. e = lb.End
  1448. }
  1449. hours := e.Sub(s).Hours()
  1450. // A negative number of hours signifies no overlap between the windows
  1451. if hours > 0 {
  1452. totalHours += hours
  1453. allocHours[alloc] = hours
  1454. }
  1455. }
  1456. // Distribute cost of service once total hours is calculated
  1457. for alloc, hours := range allocHours {
  1458. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1459. }
  1460. }
  1461. }
  1462. // getNodePricing determines node pricing, given a key and a mapping from keys
  1463. // to their NodePricing instances, as well as the custom pricing configuration
  1464. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1465. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1466. // back on custom pricing as a default.
  1467. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*NodePricing, nodeKey nodeKey) *NodePricing {
  1468. // Find the relevant NodePricing, if it exists. If not, substitute the
  1469. // custom NodePricing as a default.
  1470. node, ok := nodeMap[nodeKey]
  1471. if !ok || node == nil {
  1472. if nodeKey.Node != "" {
  1473. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1474. }
  1475. return cm.getCustomNodePricing(false)
  1476. }
  1477. // If custom pricing is enabled and can be retrieved, override detected
  1478. // node pricing with the custom values.
  1479. customPricingConfig, err := cm.Provider.GetConfig()
  1480. if err != nil {
  1481. log.Warningf("CostModel: failed to load custom pricing: %s", err)
  1482. }
  1483. if cloud.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1484. return cm.getCustomNodePricing(node.Preemptible)
  1485. }
  1486. node.Source = "prometheus"
  1487. // If any of the values are NaN or zero, replace them with the custom
  1488. // values as default.
  1489. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1490. // them as strings like this?
  1491. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1492. log.Warningf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1493. cpuCostStr := customPricingConfig.CPU
  1494. if node.Preemptible {
  1495. cpuCostStr = customPricingConfig.SpotCPU
  1496. }
  1497. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1498. if err != nil {
  1499. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1500. }
  1501. node.CostPerCPUHr = costPerCPUHr
  1502. node.Source += "/customCPU"
  1503. }
  1504. if math.IsNaN(node.CostPerGPUHr) {
  1505. log.Warningf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1506. gpuCostStr := customPricingConfig.GPU
  1507. if node.Preemptible {
  1508. gpuCostStr = customPricingConfig.SpotGPU
  1509. }
  1510. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1511. if err != nil {
  1512. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1513. }
  1514. node.CostPerGPUHr = costPerGPUHr
  1515. node.Source += "/customGPU"
  1516. }
  1517. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1518. log.Warningf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1519. ramCostStr := customPricingConfig.RAM
  1520. if node.Preemptible {
  1521. ramCostStr = customPricingConfig.SpotRAM
  1522. }
  1523. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1524. if err != nil {
  1525. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1526. }
  1527. node.CostPerRAMGiBHr = costPerRAMHr
  1528. node.Source += "/customRAM"
  1529. }
  1530. return node
  1531. }
  1532. // getCustomNodePricing converts the CostModel's configured custom pricing
  1533. // values into a NodePricing instance.
  1534. func (cm *CostModel) getCustomNodePricing(spot bool) *NodePricing {
  1535. customPricingConfig, err := cm.Provider.GetConfig()
  1536. if err != nil {
  1537. return nil
  1538. }
  1539. cpuCostStr := customPricingConfig.CPU
  1540. gpuCostStr := customPricingConfig.GPU
  1541. ramCostStr := customPricingConfig.RAM
  1542. if spot {
  1543. cpuCostStr = customPricingConfig.SpotCPU
  1544. gpuCostStr = customPricingConfig.SpotGPU
  1545. ramCostStr = customPricingConfig.SpotRAM
  1546. }
  1547. node := &NodePricing{Source: "custom"}
  1548. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1549. if err != nil {
  1550. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1551. }
  1552. node.CostPerCPUHr = costPerCPUHr
  1553. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1554. if err != nil {
  1555. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1556. }
  1557. node.CostPerGPUHr = costPerGPUHr
  1558. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1559. if err != nil {
  1560. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1561. }
  1562. node.CostPerRAMGiBHr = costPerRAMHr
  1563. return node
  1564. }
  1565. // NodePricing describes the resource costs associated with a given node, as
  1566. // well as the source of the information (e.g. prometheus, custom)
  1567. type NodePricing struct {
  1568. Name string
  1569. NodeType string
  1570. Preemptible bool
  1571. CostPerCPUHr float64
  1572. CostPerRAMGiBHr float64
  1573. CostPerGPUHr float64
  1574. Discount float64
  1575. Source string
  1576. }
  1577. // Pod describes a running pod's start and end time within a Window and
  1578. // all the Allocations (i.e. containers) contained within it.
  1579. type Pod struct {
  1580. Window kubecost.Window
  1581. Start time.Time
  1582. End time.Time
  1583. Key podKey
  1584. Allocations map[string]*kubecost.Allocation
  1585. }
  1586. // AppendContainer adds an entry for the given container name to the Pod.
  1587. func (p Pod) AppendContainer(container string) {
  1588. name := fmt.Sprintf("%s/%s/%s/%s", p.Key.Cluster, p.Key.Namespace, p.Key.Pod, container)
  1589. alloc := &kubecost.Allocation{
  1590. Name: name,
  1591. Properties: &kubecost.AllocationProperties{},
  1592. Window: p.Window.Clone(),
  1593. Start: p.Start,
  1594. End: p.End,
  1595. }
  1596. alloc.Properties.Container = container
  1597. alloc.Properties.Pod = p.Key.Pod
  1598. alloc.Properties.Namespace = p.Key.Namespace
  1599. alloc.Properties.Cluster = p.Key.Cluster
  1600. p.Allocations[container] = alloc
  1601. }
  1602. // PVC describes a PersistentVolumeClaim
  1603. // TODO:CLEANUP move to pkg/kubecost?
  1604. // TODO:CLEANUP add PersistentVolumeClaims field to type Allocation?
  1605. type PVC struct {
  1606. Bytes float64 `json:"bytes"`
  1607. Count int `json:"count"`
  1608. Name string `json:"name"`
  1609. Cluster string `json:"cluster"`
  1610. Namespace string `json:"namespace"`
  1611. Volume *PV `json:"persistentVolume"`
  1612. Mounted bool `json:"mounted"`
  1613. Start time.Time `json:"start"`
  1614. End time.Time `json:"end"`
  1615. }
  1616. // Cost computes the cumulative cost of the PVC
  1617. func (pvc *PVC) Cost() float64 {
  1618. if pvc == nil || pvc.Volume == nil {
  1619. return 0.0
  1620. }
  1621. gib := pvc.Bytes / 1024 / 1024 / 1024
  1622. hrs := pvc.Minutes() / 60.0
  1623. return pvc.Volume.CostPerGiBHour * gib * hrs
  1624. }
  1625. // Minutes computes the number of minutes over which the PVC is defined
  1626. func (pvc *PVC) Minutes() float64 {
  1627. if pvc == nil {
  1628. return 0.0
  1629. }
  1630. return pvc.End.Sub(pvc.Start).Minutes()
  1631. }
  1632. // String returns a string representation of the PVC
  1633. func (pvc *PVC) String() string {
  1634. if pvc == nil {
  1635. return "<nil>"
  1636. }
  1637. 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))
  1638. }
  1639. // PV describes a PersistentVolume
  1640. // TODO:CLEANUP move to pkg/kubecost?
  1641. type PV struct {
  1642. Bytes float64 `json:"bytes"`
  1643. CostPerGiBHour float64 `json:"costPerGiBHour"`
  1644. Cluster string `json:"cluster"`
  1645. Name string `json:"name"`
  1646. StorageClass string `json:"storageClass"`
  1647. }
  1648. // String returns a string representation of the PV
  1649. func (pv *PV) String() string {
  1650. if pv == nil {
  1651. return "<nil>"
  1652. }
  1653. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  1654. }