allocation.go 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. package costmodel
  2. import (
  3. "fmt"
  4. "github.com/kubecost/cost-model/pkg/util/timeutil"
  5. "math"
  6. "strconv"
  7. "strings"
  8. "time"
  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. 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_name")
  584. if err != nil {
  585. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage avg query result missing 'container': %s", key)
  586. continue
  587. }
  588. if _, ok := pod.Allocations[container]; !ok {
  589. pod.AppendContainer(container)
  590. }
  591. pod.Allocations[container].CPUCoreUsageAverage = res.Values[0].Value
  592. }
  593. }
  594. func applyCPUCoresUsedMax(podMap map[podKey]*Pod, resCPUCoresUsedMax []*prom.QueryResult) {
  595. for _, res := range resCPUCoresUsedMax {
  596. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  597. if err != nil {
  598. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max result missing field: %s", err)
  599. continue
  600. }
  601. pod, ok := podMap[key]
  602. if !ok {
  603. continue
  604. }
  605. container, err := res.GetString("container_name")
  606. if err != nil {
  607. log.DedupedWarningf(10, "CostModel.ComputeAllocation: CPU usage max query result missing 'container': %s", key)
  608. continue
  609. }
  610. if _, ok := pod.Allocations[container]; !ok {
  611. pod.AppendContainer(container)
  612. }
  613. if pod.Allocations[container].RawAllocationOnly == nil {
  614. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  615. CPUCoreUsageMax: res.Values[0].Value,
  616. }
  617. } else {
  618. pod.Allocations[container].RawAllocationOnly.CPUCoreUsageMax = res.Values[0].Value
  619. }
  620. }
  621. }
  622. func applyRAMBytesAllocated(podMap map[podKey]*Pod, resRAMBytesAllocated []*prom.QueryResult) {
  623. for _, res := range resRAMBytesAllocated {
  624. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod")
  625. if err != nil {
  626. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation result missing field: %s", err)
  627. continue
  628. }
  629. pod, ok := podMap[key]
  630. if !ok {
  631. continue
  632. }
  633. container, err := res.GetString("container")
  634. if err != nil {
  635. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM allocation query result missing 'container': %s", key)
  636. continue
  637. }
  638. if _, ok := pod.Allocations[container]; !ok {
  639. pod.AppendContainer(container)
  640. }
  641. ramBytes := res.Values[0].Value
  642. hours := pod.Allocations[container].Minutes() / 60.0
  643. pod.Allocations[container].RAMByteHours = ramBytes * hours
  644. node, err := res.GetString("node")
  645. if err != nil {
  646. log.Warningf("CostModel.ComputeAllocation: RAM allocation query result missing 'node': %s", key)
  647. continue
  648. }
  649. pod.Allocations[container].Properties.Node = node
  650. }
  651. }
  652. func applyRAMBytesRequested(podMap map[podKey]*Pod, resRAMBytesRequested []*prom.QueryResult) {
  653. for _, res := range resRAMBytesRequested {
  654. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod")
  655. if err != nil {
  656. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request result missing field: %s", err)
  657. continue
  658. }
  659. pod, ok := podMap[key]
  660. if !ok {
  661. continue
  662. }
  663. container, err := res.GetString("container")
  664. if err != nil {
  665. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM request query result missing 'container': %s", key)
  666. continue
  667. }
  668. if _, ok := pod.Allocations[container]; !ok {
  669. pod.AppendContainer(container)
  670. }
  671. pod.Allocations[container].RAMBytesRequestAverage = res.Values[0].Value
  672. // If RAM allocation is less than requests, set RAMByteHours to
  673. // request level.
  674. if pod.Allocations[container].RAMBytes() < res.Values[0].Value {
  675. pod.Allocations[container].RAMByteHours = res.Values[0].Value * (pod.Allocations[container].Minutes() / 60.0)
  676. }
  677. node, err := res.GetString("node")
  678. if err != nil {
  679. log.Warningf("CostModel.ComputeAllocation: RAM request query result missing 'node': %s", key)
  680. continue
  681. }
  682. pod.Allocations[container].Properties.Node = node
  683. }
  684. }
  685. func applyRAMBytesUsedAvg(podMap map[podKey]*Pod, resRAMBytesUsedAvg []*prom.QueryResult) {
  686. for _, res := range resRAMBytesUsedAvg {
  687. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  688. if err != nil {
  689. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM avg usage result missing field: %s", err)
  690. continue
  691. }
  692. pod, ok := podMap[key]
  693. if !ok {
  694. continue
  695. }
  696. container, err := res.GetString("container_name")
  697. if err != nil {
  698. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage avg query result missing 'container': %s", key)
  699. continue
  700. }
  701. if _, ok := pod.Allocations[container]; !ok {
  702. pod.AppendContainer(container)
  703. }
  704. pod.Allocations[container].RAMBytesUsageAverage = res.Values[0].Value
  705. }
  706. }
  707. func applyRAMBytesUsedMax(podMap map[podKey]*Pod, resRAMBytesUsedMax []*prom.QueryResult) {
  708. for _, res := range resRAMBytesUsedMax {
  709. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  710. if err != nil {
  711. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max result missing field: %s", err)
  712. continue
  713. }
  714. pod, ok := podMap[key]
  715. if !ok {
  716. continue
  717. }
  718. container, err := res.GetString("container_name")
  719. if err != nil {
  720. log.DedupedWarningf(10, "CostModel.ComputeAllocation: RAM usage max query result missing 'container': %s", key)
  721. continue
  722. }
  723. if _, ok := pod.Allocations[container]; !ok {
  724. pod.AppendContainer(container)
  725. }
  726. if pod.Allocations[container].RawAllocationOnly == nil {
  727. pod.Allocations[container].RawAllocationOnly = &kubecost.RawAllocationOnlyData{
  728. RAMBytesUsageMax: res.Values[0].Value,
  729. }
  730. } else {
  731. pod.Allocations[container].RawAllocationOnly.RAMBytesUsageMax = res.Values[0].Value
  732. }
  733. }
  734. }
  735. func applyGPUsRequested(podMap map[podKey]*Pod, resGPUsRequested []*prom.QueryResult) {
  736. for _, res := range resGPUsRequested {
  737. key, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod")
  738. if err != nil {
  739. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request result missing field: %s", err)
  740. continue
  741. }
  742. pod, ok := podMap[key]
  743. if !ok {
  744. continue
  745. }
  746. container, err := res.GetString("container")
  747. if err != nil {
  748. log.DedupedWarningf(10, "CostModel.ComputeAllocation: GPU request query result missing 'container': %s", key)
  749. continue
  750. }
  751. if _, ok := pod.Allocations[container]; !ok {
  752. pod.AppendContainer(container)
  753. }
  754. hrs := pod.Allocations[container].Minutes() / 60.0
  755. pod.Allocations[container].GPUHours = res.Values[0].Value * hrs
  756. }
  757. }
  758. func applyNetworkTotals(podMap map[podKey]*Pod, resNetworkTransferBytes []*prom.QueryResult, resNetworkReceiveBytes []*prom.QueryResult) {
  759. for _, res := range resNetworkTransferBytes {
  760. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  761. if err != nil {
  762. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Transfer Bytes query result missing field: %s", err)
  763. continue
  764. }
  765. pod, ok := podMap[podKey]
  766. if !ok {
  767. continue
  768. }
  769. for _, alloc := range pod.Allocations {
  770. alloc.NetworkTransferBytes = res.Values[0].Value / float64(len(pod.Allocations))
  771. }
  772. }
  773. for _, res := range resNetworkReceiveBytes {
  774. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  775. if err != nil {
  776. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network Receive Bytes query result missing field: %s", err)
  777. continue
  778. }
  779. pod, ok := podMap[podKey]
  780. if !ok {
  781. continue
  782. }
  783. for _, alloc := range pod.Allocations {
  784. alloc.NetworkReceiveBytes = res.Values[0].Value / float64(len(pod.Allocations))
  785. }
  786. }
  787. }
  788. func applyNetworkAllocation(podMap map[podKey]*Pod, resNetworkGiB []*prom.QueryResult, resNetworkCostPerGiB []*prom.QueryResult) {
  789. costPerGiBByCluster := map[string]float64{}
  790. for _, res := range resNetworkCostPerGiB {
  791. cluster, err := res.GetString(env.GetPromClusterLabel())
  792. if err != nil {
  793. cluster = env.GetClusterID()
  794. }
  795. costPerGiBByCluster[cluster] = res.Values[0].Value
  796. }
  797. for _, res := range resNetworkGiB {
  798. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod_name")
  799. if err != nil {
  800. log.DedupedWarningf(10, "CostModel.ComputeAllocation: Network allocation query result missing field: %s", err)
  801. continue
  802. }
  803. pod, ok := podMap[podKey]
  804. if !ok {
  805. continue
  806. }
  807. for _, alloc := range pod.Allocations {
  808. gib := res.Values[0].Value / float64(len(pod.Allocations))
  809. costPerGiB := costPerGiBByCluster[podKey.Cluster]
  810. alloc.NetworkCost = gib * costPerGiB
  811. }
  812. }
  813. }
  814. func resToNamespaceLabels(resNamespaceLabels []*prom.QueryResult) map[namespaceKey]map[string]string {
  815. namespaceLabels := map[namespaceKey]map[string]string{}
  816. for _, res := range resNamespaceLabels {
  817. nsKey, err := resultNamespaceKey(res, env.GetPromClusterLabel(), "namespace")
  818. if err != nil {
  819. continue
  820. }
  821. if _, ok := namespaceLabels[nsKey]; !ok {
  822. namespaceLabels[nsKey] = map[string]string{}
  823. }
  824. for k, l := range res.GetLabels() {
  825. namespaceLabels[nsKey][k] = l
  826. }
  827. }
  828. return namespaceLabels
  829. }
  830. func resToPodLabels(resPodLabels []*prom.QueryResult) map[podKey]map[string]string {
  831. podLabels := map[podKey]map[string]string{}
  832. for _, res := range resPodLabels {
  833. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod")
  834. if err != nil {
  835. continue
  836. }
  837. if _, ok := podLabels[podKey]; !ok {
  838. podLabels[podKey] = map[string]string{}
  839. }
  840. for k, l := range res.GetLabels() {
  841. podLabels[podKey][k] = l
  842. }
  843. }
  844. return podLabels
  845. }
  846. func resToNamespaceAnnotations(resNamespaceAnnotations []*prom.QueryResult) map[string]map[string]string {
  847. namespaceAnnotations := map[string]map[string]string{}
  848. for _, res := range resNamespaceAnnotations {
  849. namespace, err := res.GetString("namespace")
  850. if err != nil {
  851. continue
  852. }
  853. if _, ok := namespaceAnnotations[namespace]; !ok {
  854. namespaceAnnotations[namespace] = map[string]string{}
  855. }
  856. for k, l := range res.GetAnnotations() {
  857. namespaceAnnotations[namespace][k] = l
  858. }
  859. }
  860. return namespaceAnnotations
  861. }
  862. func resToPodAnnotations(resPodAnnotations []*prom.QueryResult) map[podKey]map[string]string {
  863. podAnnotations := map[podKey]map[string]string{}
  864. for _, res := range resPodAnnotations {
  865. podKey, err := resultPodKey(res, env.GetPromClusterLabel(), "namespace", "pod")
  866. if err != nil {
  867. continue
  868. }
  869. if _, ok := podAnnotations[podKey]; !ok {
  870. podAnnotations[podKey] = map[string]string{}
  871. }
  872. for k, l := range res.GetAnnotations() {
  873. podAnnotations[podKey][k] = l
  874. }
  875. }
  876. return podAnnotations
  877. }
  878. func applyLabels(podMap map[podKey]*Pod, namespaceLabels map[namespaceKey]map[string]string, podLabels map[podKey]map[string]string) {
  879. for podKey, pod := range podMap {
  880. for _, alloc := range pod.Allocations {
  881. allocLabels := alloc.Properties.Labels
  882. if allocLabels == nil {
  883. allocLabels = make(map[string]string)
  884. }
  885. // Apply namespace labels first, then pod labels so that pod labels
  886. // overwrite namespace labels.
  887. nsKey := newNamespaceKey(podKey.Cluster, podKey.Namespace)
  888. if labels, ok := namespaceLabels[nsKey]; ok {
  889. for k, v := range labels {
  890. allocLabels[k] = v
  891. }
  892. }
  893. if labels, ok := podLabels[podKey]; ok {
  894. for k, v := range labels {
  895. allocLabels[k] = v
  896. }
  897. }
  898. alloc.Properties.Labels = allocLabels
  899. }
  900. }
  901. }
  902. func applyAnnotations(podMap map[podKey]*Pod, namespaceAnnotations map[string]map[string]string, podAnnotations map[podKey]map[string]string) {
  903. for key, pod := range podMap {
  904. for _, alloc := range pod.Allocations {
  905. allocAnnotations := alloc.Properties.Annotations
  906. if allocAnnotations == nil {
  907. allocAnnotations = make(map[string]string)
  908. }
  909. // Apply namespace annotations first, then pod annotations so that
  910. // pod labels overwrite namespace labels.
  911. if labels, ok := namespaceAnnotations[key.Namespace]; ok {
  912. for k, v := range labels {
  913. allocAnnotations[k] = v
  914. }
  915. }
  916. if labels, ok := podAnnotations[key]; ok {
  917. for k, v := range labels {
  918. allocAnnotations[k] = v
  919. }
  920. }
  921. alloc.Properties.Annotations = allocAnnotations
  922. }
  923. }
  924. }
  925. func getServiceLabels(resServiceLabels []*prom.QueryResult) map[serviceKey]map[string]string {
  926. serviceLabels := map[serviceKey]map[string]string{}
  927. for _, res := range resServiceLabels {
  928. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service")
  929. if err != nil {
  930. continue
  931. }
  932. if _, ok := serviceLabels[serviceKey]; !ok {
  933. serviceLabels[serviceKey] = map[string]string{}
  934. }
  935. for k, l := range res.GetLabels() {
  936. serviceLabels[serviceKey][k] = l
  937. }
  938. }
  939. // Prune duplicate services. That is, if the same service exists with
  940. // hyphens instead of underscores, keep the one that uses hyphens.
  941. for key := range serviceLabels {
  942. if strings.Contains(key.Service, "_") {
  943. duplicateService := strings.Replace(key.Service, "_", "-", -1)
  944. duplicateKey := newServiceKey(key.Cluster, key.Namespace, duplicateService)
  945. if _, ok := serviceLabels[duplicateKey]; ok {
  946. delete(serviceLabels, key)
  947. }
  948. }
  949. }
  950. return serviceLabels
  951. }
  952. func resToDeploymentLabels(resDeploymentLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  953. deploymentLabels := map[controllerKey]map[string]string{}
  954. for _, res := range resDeploymentLabels {
  955. controllerKey, err := resultDeploymentKey(res, env.GetPromClusterLabel(), "namespace", "deployment")
  956. if err != nil {
  957. continue
  958. }
  959. if _, ok := deploymentLabels[controllerKey]; !ok {
  960. deploymentLabels[controllerKey] = map[string]string{}
  961. }
  962. for k, l := range res.GetLabels() {
  963. deploymentLabels[controllerKey][k] = l
  964. }
  965. }
  966. // Prune duplicate deployments. That is, if the same deployment exists with
  967. // hyphens instead of underscores, keep the one that uses hyphens.
  968. for key := range deploymentLabels {
  969. if strings.Contains(key.Controller, "_") {
  970. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  971. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  972. if _, ok := deploymentLabels[duplicateKey]; ok {
  973. delete(deploymentLabels, key)
  974. }
  975. }
  976. }
  977. return deploymentLabels
  978. }
  979. func resToStatefulSetLabels(resStatefulSetLabels []*prom.QueryResult) map[controllerKey]map[string]string {
  980. statefulSetLabels := map[controllerKey]map[string]string{}
  981. for _, res := range resStatefulSetLabels {
  982. controllerKey, err := resultStatefulSetKey(res, env.GetPromClusterLabel(), "namespace", "statefulSet")
  983. if err != nil {
  984. continue
  985. }
  986. if _, ok := statefulSetLabels[controllerKey]; !ok {
  987. statefulSetLabels[controllerKey] = map[string]string{}
  988. }
  989. for k, l := range res.GetLabels() {
  990. statefulSetLabels[controllerKey][k] = l
  991. }
  992. }
  993. // Prune duplicate stateful sets. That is, if the same stateful set exists
  994. // with hyphens instead of underscores, keep the one that uses hyphens.
  995. for key := range statefulSetLabels {
  996. if strings.Contains(key.Controller, "_") {
  997. duplicateController := strings.Replace(key.Controller, "_", "-", -1)
  998. duplicateKey := newControllerKey(key.Cluster, key.Namespace, key.ControllerKind, duplicateController)
  999. if _, ok := statefulSetLabels[duplicateKey]; ok {
  1000. delete(statefulSetLabels, key)
  1001. }
  1002. }
  1003. }
  1004. return statefulSetLabels
  1005. }
  1006. func labelsToPodControllerMap(podLabels map[podKey]map[string]string, controllerLabels map[controllerKey]map[string]string) map[podKey]controllerKey {
  1007. podControllerMap := map[podKey]controllerKey{}
  1008. // For each controller, turn the labels into a selector and attempt to
  1009. // match it with each set of pod labels. A match indicates that the pod
  1010. // belongs to the controller.
  1011. for cKey, cLabels := range controllerLabels {
  1012. selector := labels.Set(cLabels).AsSelectorPreValidated()
  1013. for pKey, pLabels := range podLabels {
  1014. // If the pod is in a different cluster or namespace, there is
  1015. // no need to compare the labels.
  1016. if cKey.Cluster != pKey.Cluster || cKey.Namespace != pKey.Namespace {
  1017. continue
  1018. }
  1019. podLabelSet := labels.Set(pLabels)
  1020. if selector.Matches(podLabelSet) {
  1021. if _, ok := podControllerMap[pKey]; ok {
  1022. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PodControllerMap match already exists: %s matches %s and %s", pKey, podControllerMap[pKey], cKey)
  1023. }
  1024. podControllerMap[pKey] = cKey
  1025. }
  1026. }
  1027. }
  1028. return podControllerMap
  1029. }
  1030. func resToPodDaemonSetMap(resDaemonSetLabels []*prom.QueryResult) map[podKey]controllerKey {
  1031. daemonSetLabels := map[podKey]controllerKey{}
  1032. for _, res := range resDaemonSetLabels {
  1033. controllerKey, err := resultDaemonSetKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1034. if err != nil {
  1035. continue
  1036. }
  1037. pod, err := res.GetString("pod")
  1038. if err != nil {
  1039. log.Warningf("CostModel.ComputeAllocation: DaemonSetLabel result without pod: %s", controllerKey)
  1040. }
  1041. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1042. daemonSetLabels[podKey] = controllerKey
  1043. }
  1044. return daemonSetLabels
  1045. }
  1046. func resToPodJobMap(resJobLabels []*prom.QueryResult) map[podKey]controllerKey {
  1047. jobLabels := map[podKey]controllerKey{}
  1048. for _, res := range resJobLabels {
  1049. controllerKey, err := resultJobKey(res, env.GetPromClusterLabel(), "namespace", "owner_name")
  1050. if err != nil {
  1051. continue
  1052. }
  1053. // Convert the name of Jobs generated by CronJobs to the name of the
  1054. // CronJob by stripping the timestamp off the end.
  1055. match := isCron.FindStringSubmatch(controllerKey.Controller)
  1056. if match != nil {
  1057. controllerKey.Controller = match[1]
  1058. }
  1059. pod, err := res.GetString("pod")
  1060. if err != nil {
  1061. log.Warningf("CostModel.ComputeAllocation: JobLabel result without pod: %s", controllerKey)
  1062. }
  1063. podKey := newPodKey(controllerKey.Cluster, controllerKey.Namespace, pod)
  1064. jobLabels[podKey] = controllerKey
  1065. }
  1066. return jobLabels
  1067. }
  1068. func applyServicesToPods(podMap map[podKey]*Pod, podLabels map[podKey]map[string]string, allocsByService map[serviceKey][]*kubecost.Allocation, serviceLabels map[serviceKey]map[string]string) {
  1069. podServicesMap := map[podKey][]serviceKey{}
  1070. // For each service, turn the labels into a selector and attempt to
  1071. // match it with each set of pod labels. A match indicates that the pod
  1072. // belongs to the service.
  1073. for sKey, sLabels := range serviceLabels {
  1074. selector := labels.Set(sLabels).AsSelectorPreValidated()
  1075. for pKey, pLabels := range podLabels {
  1076. // If the pod is in a different cluster or namespace, there is
  1077. // no need to compare the labels.
  1078. if sKey.Cluster != pKey.Cluster || sKey.Namespace != pKey.Namespace {
  1079. continue
  1080. }
  1081. podLabelSet := labels.Set(pLabels)
  1082. if selector.Matches(podLabelSet) {
  1083. if _, ok := podServicesMap[pKey]; !ok {
  1084. podServicesMap[pKey] = []serviceKey{}
  1085. }
  1086. podServicesMap[pKey] = append(podServicesMap[pKey], sKey)
  1087. }
  1088. }
  1089. }
  1090. // For each allocation in each pod, attempt to find and apply the list of
  1091. // services associated with the allocation's pod.
  1092. for key, pod := range podMap {
  1093. for _, alloc := range pod.Allocations {
  1094. if sKeys, ok := podServicesMap[key]; ok {
  1095. services := []string{}
  1096. for _, sKey := range sKeys {
  1097. services = append(services, sKey.Service)
  1098. allocsByService[sKey] = append(allocsByService[sKey], alloc)
  1099. }
  1100. alloc.Properties.Services = services
  1101. }
  1102. }
  1103. }
  1104. }
  1105. func applyControllersToPods(podMap map[podKey]*Pod, podControllerMap map[podKey]controllerKey) {
  1106. for key, pod := range podMap {
  1107. for _, alloc := range pod.Allocations {
  1108. if controllerKey, ok := podControllerMap[key]; ok {
  1109. alloc.Properties.ControllerKind = controllerKey.ControllerKind
  1110. alloc.Properties.Controller = controllerKey.Controller
  1111. }
  1112. }
  1113. }
  1114. }
  1115. func applyNodeCostPerCPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerCPUHr []*prom.QueryResult) {
  1116. for _, res := range resNodeCostPerCPUHr {
  1117. cluster, err := res.GetString(env.GetPromClusterLabel())
  1118. if err != nil {
  1119. cluster = env.GetClusterID()
  1120. }
  1121. node, err := res.GetString("node")
  1122. if err != nil {
  1123. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1124. continue
  1125. }
  1126. instanceType, err := res.GetString("instance_type")
  1127. if err != nil {
  1128. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1129. continue
  1130. }
  1131. providerID, err := res.GetString("provider_id")
  1132. if err != nil {
  1133. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1134. continue
  1135. }
  1136. key := newNodeKey(cluster, node)
  1137. if _, ok := nodeMap[key]; !ok {
  1138. nodeMap[key] = &NodePricing{
  1139. Name: node,
  1140. NodeType: instanceType,
  1141. ProviderID: cloud.ParseID(providerID),
  1142. }
  1143. }
  1144. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1145. }
  1146. }
  1147. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult) {
  1148. for _, res := range resNodeCostPerRAMGiBHr {
  1149. cluster, err := res.GetString(env.GetPromClusterLabel())
  1150. if err != nil {
  1151. cluster = env.GetClusterID()
  1152. }
  1153. node, err := res.GetString("node")
  1154. if err != nil {
  1155. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1156. continue
  1157. }
  1158. instanceType, err := res.GetString("instance_type")
  1159. if err != nil {
  1160. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1161. continue
  1162. }
  1163. providerID, err := res.GetString("provider_id")
  1164. if err != nil {
  1165. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1166. continue
  1167. }
  1168. key := newNodeKey(cluster, node)
  1169. if _, ok := nodeMap[key]; !ok {
  1170. nodeMap[key] = &NodePricing{
  1171. Name: node,
  1172. NodeType: instanceType,
  1173. ProviderID: cloud.ParseID(providerID),
  1174. }
  1175. }
  1176. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1177. }
  1178. }
  1179. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerGPUHr []*prom.QueryResult) {
  1180. for _, res := range resNodeCostPerGPUHr {
  1181. cluster, err := res.GetString(env.GetPromClusterLabel())
  1182. if err != nil {
  1183. cluster = env.GetClusterID()
  1184. }
  1185. node, err := res.GetString("node")
  1186. if err != nil {
  1187. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1188. continue
  1189. }
  1190. instanceType, err := res.GetString("instance_type")
  1191. if err != nil {
  1192. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1193. continue
  1194. }
  1195. providerID, err := res.GetString("provider_id")
  1196. if err != nil {
  1197. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1198. continue
  1199. }
  1200. key := newNodeKey(cluster, node)
  1201. if _, ok := nodeMap[key]; !ok {
  1202. nodeMap[key] = &NodePricing{
  1203. Name: node,
  1204. NodeType: instanceType,
  1205. ProviderID: cloud.ParseID(providerID),
  1206. }
  1207. }
  1208. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1209. }
  1210. }
  1211. func applyNodeSpot(nodeMap map[nodeKey]*NodePricing, resNodeIsSpot []*prom.QueryResult) {
  1212. for _, res := range resNodeIsSpot {
  1213. cluster, err := res.GetString(env.GetPromClusterLabel())
  1214. if err != nil {
  1215. cluster = env.GetClusterID()
  1216. }
  1217. node, err := res.GetString("node")
  1218. if err != nil {
  1219. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1220. continue
  1221. }
  1222. key := newNodeKey(cluster, node)
  1223. if _, ok := nodeMap[key]; !ok {
  1224. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1225. continue
  1226. }
  1227. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1228. }
  1229. }
  1230. func applyNodeDiscount(nodeMap map[nodeKey]*NodePricing, cm *CostModel) {
  1231. if cm == nil {
  1232. return
  1233. }
  1234. c, err := cm.Provider.GetConfig()
  1235. if err != nil {
  1236. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1237. return
  1238. }
  1239. discount, err := ParsePercentString(c.Discount)
  1240. if err != nil {
  1241. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1242. return
  1243. }
  1244. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1245. if err != nil {
  1246. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1247. return
  1248. }
  1249. for _, node := range nodeMap {
  1250. // TODO GKE Reserved Instances into account
  1251. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1252. node.CostPerCPUHr *= (1.0 - node.Discount)
  1253. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1254. }
  1255. }
  1256. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  1257. for _, res := range resPVCostPerGiBHour {
  1258. cluster, err := res.GetString(env.GetPromClusterLabel())
  1259. if err != nil {
  1260. cluster = env.GetClusterID()
  1261. }
  1262. name, err := res.GetString("volumename")
  1263. if err != nil {
  1264. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  1265. continue
  1266. }
  1267. key := newPVKey(cluster, name)
  1268. pvMap[key] = &PV{
  1269. Cluster: cluster,
  1270. Name: name,
  1271. CostPerGiBHour: res.Values[0].Value,
  1272. }
  1273. }
  1274. }
  1275. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  1276. for _, res := range resPVBytes {
  1277. key, err := resultPVKey(res, env.GetPromClusterLabel(), "persistentvolume")
  1278. if err != nil {
  1279. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  1280. continue
  1281. }
  1282. if _, ok := pvMap[key]; !ok {
  1283. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  1284. continue
  1285. }
  1286. pvMap[key].Bytes = res.Values[0].Value
  1287. }
  1288. }
  1289. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  1290. for _, res := range resPVCInfo {
  1291. cluster, err := res.GetString(env.GetPromClusterLabel())
  1292. if err != nil {
  1293. cluster = env.GetClusterID()
  1294. }
  1295. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1296. if err != nil {
  1297. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  1298. continue
  1299. }
  1300. namespace := values["namespace"]
  1301. name := values["persistentvolumeclaim"]
  1302. volume := values["volumename"]
  1303. storageClass := values["storageclass"]
  1304. pvKey := newPVKey(cluster, volume)
  1305. pvcKey := newPVCKey(cluster, namespace, name)
  1306. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  1307. // the PVC was running, respectively. We subtract 1m from pvcStart
  1308. // because this point will actually represent the end of the first
  1309. // minute. We don't subtract from pvcEnd because it already represents
  1310. // the end of the last minute.
  1311. var pvcStart, pvcEnd time.Time
  1312. for _, datum := range res.Values {
  1313. t := time.Unix(int64(datum.Timestamp), 0)
  1314. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1315. pvcStart = t
  1316. }
  1317. if datum.Value > 0 && window.Contains(t) {
  1318. pvcEnd = t
  1319. }
  1320. }
  1321. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1322. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1323. }
  1324. pvcStart = pvcStart.Add(-time.Minute)
  1325. if _, ok := pvMap[pvKey]; !ok {
  1326. continue
  1327. }
  1328. pvMap[pvKey].StorageClass = storageClass
  1329. if _, ok := pvcMap[pvcKey]; !ok {
  1330. pvcMap[pvcKey] = &PVC{}
  1331. }
  1332. pvcMap[pvcKey].Name = name
  1333. pvcMap[pvcKey].Namespace = namespace
  1334. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1335. pvcMap[pvcKey].Start = pvcStart
  1336. pvcMap[pvcKey].End = pvcEnd
  1337. }
  1338. }
  1339. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1340. for _, res := range resPVCBytesRequested {
  1341. key, err := resultPVCKey(res, env.GetPromClusterLabel(), "namespace", "persistentvolumeclaim")
  1342. if err != nil {
  1343. continue
  1344. }
  1345. if _, ok := pvcMap[key]; !ok {
  1346. continue
  1347. }
  1348. pvcMap[key].Bytes = res.Values[0].Value
  1349. }
  1350. }
  1351. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podMap map[podKey]*Pod, resPodPVCAllocation []*prom.QueryResult) {
  1352. for _, res := range resPodPVCAllocation {
  1353. cluster, err := res.GetString(env.GetPromClusterLabel())
  1354. if err != nil {
  1355. cluster = env.GetClusterID()
  1356. }
  1357. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1358. if err != nil {
  1359. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1360. continue
  1361. }
  1362. namespace := values["namespace"]
  1363. pod := values["pod"]
  1364. name := values["persistentvolumeclaim"]
  1365. volume := values["persistentvolume"]
  1366. podKey := newPodKey(cluster, namespace, pod)
  1367. pvKey := newPVKey(cluster, volume)
  1368. pvcKey := newPVCKey(cluster, namespace, name)
  1369. if _, ok := pvMap[pvKey]; !ok {
  1370. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1371. continue
  1372. }
  1373. if _, ok := podPVCMap[podKey]; !ok {
  1374. podPVCMap[podKey] = []*PVC{}
  1375. }
  1376. pvc, ok := pvcMap[pvcKey]
  1377. if !ok {
  1378. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1379. continue
  1380. }
  1381. count := 1
  1382. if pod, ok := podMap[podKey]; ok && len(pod.Allocations) > 0 {
  1383. count = len(pod.Allocations)
  1384. } else {
  1385. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC %s for missing pod %s", pvcKey, podKey)
  1386. }
  1387. pvc.Count = count
  1388. pvc.Mounted = true
  1389. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1390. }
  1391. }
  1392. func applyUnmountedPVs(window kubecost.Window, podMap map[podKey]*Pod, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1393. unmountedPVBytes := map[string]float64{}
  1394. unmountedPVCost := map[string]float64{}
  1395. for _, pv := range pvMap {
  1396. mounted := false
  1397. for _, pvc := range pvcMap {
  1398. if pvc.Volume == nil {
  1399. continue
  1400. }
  1401. if pvc.Volume == pv {
  1402. mounted = true
  1403. break
  1404. }
  1405. }
  1406. if !mounted {
  1407. gib := pv.Bytes / 1024 / 1024 / 1024
  1408. hrs := window.Minutes() / 60.0 // TODO improve with PV hours, not window hours
  1409. cost := pv.CostPerGiBHour * gib * hrs
  1410. unmountedPVCost[pv.Cluster] += cost
  1411. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1412. }
  1413. }
  1414. for cluster, amount := range unmountedPVCost {
  1415. container := kubecost.UnmountedSuffix
  1416. pod := kubecost.UnmountedSuffix
  1417. namespace := kubecost.UnmountedSuffix
  1418. node := ""
  1419. key := newPodKey(cluster, namespace, pod)
  1420. podMap[key] = &Pod{
  1421. Window: window.Clone(),
  1422. Start: *window.Start(),
  1423. End: *window.End(),
  1424. Key: key,
  1425. Allocations: map[string]*kubecost.Allocation{},
  1426. }
  1427. podMap[key].AppendContainer(container)
  1428. podMap[key].Allocations[container].Properties.Cluster = cluster
  1429. podMap[key].Allocations[container].Properties.Node = node
  1430. podMap[key].Allocations[container].Properties.Namespace = namespace
  1431. podMap[key].Allocations[container].Properties.Pod = pod
  1432. podMap[key].Allocations[container].Properties.Container = container
  1433. pvKey := kubecost.PVKey{
  1434. Cluster: cluster,
  1435. Name: kubecost.UnmountedSuffix,
  1436. }
  1437. unmountedPVs := kubecost.PVAllocations{
  1438. pvKey: {
  1439. ByteHours: unmountedPVBytes[cluster] * window.Minutes() / 60.0,
  1440. Cost: amount,
  1441. },
  1442. }
  1443. podMap[key].Allocations[container].PVs = podMap[key].Allocations[container].PVs.Add(unmountedPVs)
  1444. }
  1445. }
  1446. func applyUnmountedPVCs(window kubecost.Window, podMap map[podKey]*Pod, pvcMap map[pvcKey]*PVC) {
  1447. unmountedPVCBytes := map[namespaceKey]float64{}
  1448. unmountedPVCCost := map[namespaceKey]float64{}
  1449. for _, pvc := range pvcMap {
  1450. if !pvc.Mounted && pvc.Volume != nil {
  1451. key := newNamespaceKey(pvc.Cluster, pvc.Namespace)
  1452. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1453. hrs := pvc.Minutes() / 60.0
  1454. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1455. unmountedPVCCost[key] += cost
  1456. unmountedPVCBytes[key] += pvc.Volume.Bytes
  1457. }
  1458. }
  1459. for key, amount := range unmountedPVCCost {
  1460. container := kubecost.UnmountedSuffix
  1461. pod := kubecost.UnmountedSuffix
  1462. namespace := key.Namespace
  1463. node := ""
  1464. cluster := key.Cluster
  1465. podKey := newPodKey(cluster, namespace, pod)
  1466. podMap[podKey] = &Pod{
  1467. Window: window.Clone(),
  1468. Start: *window.Start(),
  1469. End: *window.End(),
  1470. Key: podKey,
  1471. Allocations: map[string]*kubecost.Allocation{},
  1472. }
  1473. podMap[podKey].AppendContainer(container)
  1474. podMap[podKey].Allocations[container].Properties.Cluster = cluster
  1475. podMap[podKey].Allocations[container].Properties.Node = node
  1476. podMap[podKey].Allocations[container].Properties.Namespace = namespace
  1477. podMap[podKey].Allocations[container].Properties.Pod = pod
  1478. podMap[podKey].Allocations[container].Properties.Container = container
  1479. pvKey := kubecost.PVKey{
  1480. Cluster: cluster,
  1481. Name: kubecost.UnmountedSuffix,
  1482. }
  1483. unmountedPVs := kubecost.PVAllocations{
  1484. pvKey: {
  1485. ByteHours: unmountedPVCBytes[key] * window.Minutes() / 60.0,
  1486. Cost: amount,
  1487. },
  1488. }
  1489. podMap[podKey].Allocations[container].PVs = podMap[podKey].Allocations[container].PVs.Add(unmountedPVs)
  1490. }
  1491. }
  1492. // LB describes the start and end time of a Load Balancer along with cost
  1493. type LB struct {
  1494. TotalCost float64
  1495. Start time.Time
  1496. End time.Time
  1497. }
  1498. func getLoadBalancerCosts(resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration) map[serviceKey]*LB {
  1499. lbMap := make(map[serviceKey]*LB)
  1500. lbHourlyCosts := make(map[serviceKey]float64)
  1501. for _, res := range resLBCost {
  1502. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1503. if err != nil {
  1504. continue
  1505. }
  1506. lbHourlyCosts[serviceKey] = res.Values[0].Value
  1507. }
  1508. for _, res := range resLBActiveMins {
  1509. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1510. if err != nil || len(res.Values) == 0 {
  1511. continue
  1512. }
  1513. if _, ok := lbHourlyCosts[serviceKey]; !ok {
  1514. log.Warningf("CostModel: failed to find hourly cost for Load Balancer: %v", serviceKey)
  1515. continue
  1516. }
  1517. s := time.Unix(int64(res.Values[0].Timestamp), 0)
  1518. // subtract resolution from start time to cover full time period
  1519. s = s.Add(-resolution)
  1520. e := time.Unix(int64(res.Values[len(res.Values)-1].Timestamp), 0)
  1521. hours := e.Sub(s).Hours()
  1522. lbMap[serviceKey] = &LB{
  1523. TotalCost: lbHourlyCosts[serviceKey] * hours,
  1524. Start: s,
  1525. End: e,
  1526. }
  1527. }
  1528. return lbMap
  1529. }
  1530. func applyLoadBalancersToPods(lbMap map[serviceKey]*LB, allocsByService map[serviceKey][]*kubecost.Allocation) {
  1531. for sKey, lb := range lbMap {
  1532. totalHours := 0.0
  1533. allocHours := make(map[*kubecost.Allocation]float64)
  1534. // Add portion of load balancing cost to each allocation
  1535. // proportional to the total number of hours allocations used the load balancer
  1536. for _, alloc := range allocsByService[sKey] {
  1537. // Determine the (start, end) of the relationship between the
  1538. // given LB and the associated Allocation so that a precise
  1539. // number of hours can be used to compute cumulative cost.
  1540. s, e := alloc.Start, alloc.End
  1541. if lb.Start.After(alloc.Start) {
  1542. s = lb.Start
  1543. }
  1544. if lb.End.Before(alloc.End) {
  1545. e = lb.End
  1546. }
  1547. hours := e.Sub(s).Hours()
  1548. // A negative number of hours signifies no overlap between the windows
  1549. if hours > 0 {
  1550. totalHours += hours
  1551. allocHours[alloc] = hours
  1552. }
  1553. }
  1554. // Distribute cost of service once total hours is calculated
  1555. for alloc, hours := range allocHours {
  1556. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1557. }
  1558. }
  1559. }
  1560. // getNodePricing determines node pricing, given a key and a mapping from keys
  1561. // to their NodePricing instances, as well as the custom pricing configuration
  1562. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1563. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1564. // back on custom pricing as a default.
  1565. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*NodePricing, nodeKey nodeKey) *NodePricing {
  1566. // Find the relevant NodePricing, if it exists. If not, substitute the
  1567. // custom NodePricing as a default.
  1568. node, ok := nodeMap[nodeKey]
  1569. if !ok || node == nil {
  1570. if nodeKey.Node != "" {
  1571. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1572. }
  1573. return cm.getCustomNodePricing(false)
  1574. }
  1575. // If custom pricing is enabled and can be retrieved, override detected
  1576. // node pricing with the custom values.
  1577. customPricingConfig, err := cm.Provider.GetConfig()
  1578. if err != nil {
  1579. log.Warningf("CostModel: failed to load custom pricing: %s", err)
  1580. }
  1581. if cloud.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1582. return cm.getCustomNodePricing(node.Preemptible)
  1583. }
  1584. node.Source = "prometheus"
  1585. // If any of the values are NaN or zero, replace them with the custom
  1586. // values as default.
  1587. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1588. // them as strings like this?
  1589. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1590. log.Warningf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1591. cpuCostStr := customPricingConfig.CPU
  1592. if node.Preemptible {
  1593. cpuCostStr = customPricingConfig.SpotCPU
  1594. }
  1595. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1596. if err != nil {
  1597. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1598. }
  1599. node.CostPerCPUHr = costPerCPUHr
  1600. node.Source += "/customCPU"
  1601. }
  1602. if math.IsNaN(node.CostPerGPUHr) {
  1603. log.Warningf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1604. gpuCostStr := customPricingConfig.GPU
  1605. if node.Preemptible {
  1606. gpuCostStr = customPricingConfig.SpotGPU
  1607. }
  1608. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1609. if err != nil {
  1610. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1611. }
  1612. node.CostPerGPUHr = costPerGPUHr
  1613. node.Source += "/customGPU"
  1614. }
  1615. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1616. log.Warningf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1617. ramCostStr := customPricingConfig.RAM
  1618. if node.Preemptible {
  1619. ramCostStr = customPricingConfig.SpotRAM
  1620. }
  1621. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1622. if err != nil {
  1623. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1624. }
  1625. node.CostPerRAMGiBHr = costPerRAMHr
  1626. node.Source += "/customRAM"
  1627. }
  1628. return node
  1629. }
  1630. // getCustomNodePricing converts the CostModel's configured custom pricing
  1631. // values into a NodePricing instance.
  1632. func (cm *CostModel) getCustomNodePricing(spot bool) *NodePricing {
  1633. customPricingConfig, err := cm.Provider.GetConfig()
  1634. if err != nil {
  1635. return nil
  1636. }
  1637. cpuCostStr := customPricingConfig.CPU
  1638. gpuCostStr := customPricingConfig.GPU
  1639. ramCostStr := customPricingConfig.RAM
  1640. if spot {
  1641. cpuCostStr = customPricingConfig.SpotCPU
  1642. gpuCostStr = customPricingConfig.SpotGPU
  1643. ramCostStr = customPricingConfig.SpotRAM
  1644. }
  1645. node := &NodePricing{Source: "custom"}
  1646. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1647. if err != nil {
  1648. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1649. }
  1650. node.CostPerCPUHr = costPerCPUHr
  1651. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1652. if err != nil {
  1653. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1654. }
  1655. node.CostPerGPUHr = costPerGPUHr
  1656. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1657. if err != nil {
  1658. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1659. }
  1660. node.CostPerRAMGiBHr = costPerRAMHr
  1661. return node
  1662. }
  1663. // NodePricing describes the resource costs associated with a given node, as
  1664. // well as the source of the information (e.g. prometheus, custom)
  1665. type NodePricing struct {
  1666. Name string
  1667. NodeType string
  1668. ProviderID string
  1669. Preemptible bool
  1670. CostPerCPUHr float64
  1671. CostPerRAMGiBHr float64
  1672. CostPerGPUHr float64
  1673. Discount float64
  1674. Source string
  1675. }
  1676. // Pod describes a running pod's start and end time within a Window and
  1677. // all the Allocations (i.e. containers) contained within it.
  1678. type Pod struct {
  1679. Window kubecost.Window
  1680. Start time.Time
  1681. End time.Time
  1682. Key podKey
  1683. Allocations map[string]*kubecost.Allocation
  1684. }
  1685. // AppendContainer adds an entry for the given container name to the Pod.
  1686. func (p Pod) AppendContainer(container string) {
  1687. name := fmt.Sprintf("%s/%s/%s/%s", p.Key.Cluster, p.Key.Namespace, p.Key.Pod, container)
  1688. alloc := &kubecost.Allocation{
  1689. Name: name,
  1690. Properties: &kubecost.AllocationProperties{},
  1691. Window: p.Window.Clone(),
  1692. Start: p.Start,
  1693. End: p.End,
  1694. }
  1695. alloc.Properties.Container = container
  1696. alloc.Properties.Pod = p.Key.Pod
  1697. alloc.Properties.Namespace = p.Key.Namespace
  1698. alloc.Properties.Cluster = p.Key.Cluster
  1699. p.Allocations[container] = alloc
  1700. }
  1701. // PVC describes a PersistentVolumeClaim
  1702. // TODO:CLEANUP move to pkg/kubecost?
  1703. // TODO:CLEANUP add PersistentVolumeClaims field to type Allocation?
  1704. type PVC struct {
  1705. Bytes float64 `json:"bytes"`
  1706. Count int `json:"count"`
  1707. Name string `json:"name"`
  1708. Cluster string `json:"cluster"`
  1709. Namespace string `json:"namespace"`
  1710. Volume *PV `json:"persistentVolume"`
  1711. Mounted bool `json:"mounted"`
  1712. Start time.Time `json:"start"`
  1713. End time.Time `json:"end"`
  1714. }
  1715. // Cost computes the cumulative cost of the PVC
  1716. func (pvc *PVC) Cost() float64 {
  1717. if pvc == nil || pvc.Volume == nil {
  1718. return 0.0
  1719. }
  1720. gib := pvc.Bytes / 1024 / 1024 / 1024
  1721. hrs := pvc.Minutes() / 60.0
  1722. return pvc.Volume.CostPerGiBHour * gib * hrs
  1723. }
  1724. // Minutes computes the number of minutes over which the PVC is defined
  1725. func (pvc *PVC) Minutes() float64 {
  1726. if pvc == nil {
  1727. return 0.0
  1728. }
  1729. return pvc.End.Sub(pvc.Start).Minutes()
  1730. }
  1731. // String returns a string representation of the PVC
  1732. func (pvc *PVC) String() string {
  1733. if pvc == nil {
  1734. return "<nil>"
  1735. }
  1736. 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))
  1737. }
  1738. // PV describes a PersistentVolume
  1739. // TODO:CLEANUP move to pkg/kubecost?
  1740. type PV struct {
  1741. Bytes float64 `json:"bytes"`
  1742. CostPerGiBHour float64 `json:"costPerGiBHour"`
  1743. Cluster string `json:"cluster"`
  1744. Name string `json:"name"`
  1745. StorageClass string `json:"storageClass"`
  1746. }
  1747. // String returns a string representation of the PV
  1748. func (pv *PV) String() string {
  1749. if pv == nil {
  1750. return "<nil>"
  1751. }
  1752. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  1753. }