allocation.go 72 KB

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