allocation.go 73 KB

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