allocation.go 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  1. package costmodel
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/kubecost/cost-model/pkg/cloud"
  9. "github.com/kubecost/cost-model/pkg/env"
  10. "github.com/kubecost/cost-model/pkg/kubecost"
  11. "github.com/kubecost/cost-model/pkg/log"
  12. "github.com/kubecost/cost-model/pkg/prom"
  13. "github.com/kubecost/cost-model/pkg/util"
  14. "k8s.io/apimachinery/pkg/labels"
  15. )
  16. const (
  17. queryFmtPods = `avg(kube_pod_container_status_running{}) by (pod, namespace, %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 := util.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, cm.Provider.ParseID)
  268. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr, cm.Provider.ParseID)
  269. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr, cm.Provider.ParseID)
  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 := util.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. providerIDParser func(string) string) {
  1117. for _, res := range resNodeCostPerCPUHr {
  1118. cluster, err := res.GetString(env.GetPromClusterLabel())
  1119. if err != nil {
  1120. cluster = env.GetClusterID()
  1121. }
  1122. node, err := res.GetString("node")
  1123. if err != nil {
  1124. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1125. continue
  1126. }
  1127. instanceType, err := res.GetString("instance_type")
  1128. if err != nil {
  1129. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1130. continue
  1131. }
  1132. providerID, err := res.GetString("provider_id")
  1133. if err != nil {
  1134. log.Warningf("CostModel.ComputeAllocation: Node CPU cost query result missing field: %s", err)
  1135. continue
  1136. }
  1137. key := newNodeKey(cluster, node)
  1138. if _, ok := nodeMap[key]; !ok {
  1139. nodeMap[key] = &NodePricing{
  1140. Name: node,
  1141. NodeType: instanceType,
  1142. ProviderID: providerIDParser(providerID),
  1143. }
  1144. }
  1145. nodeMap[key].CostPerCPUHr = res.Values[0].Value
  1146. }
  1147. }
  1148. func applyNodeCostPerRAMGiBHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerRAMGiBHr []*prom.QueryResult,
  1149. providerIDParser func(string) string) {
  1150. for _, res := range resNodeCostPerRAMGiBHr {
  1151. cluster, err := res.GetString(env.GetPromClusterLabel())
  1152. if err != nil {
  1153. cluster = env.GetClusterID()
  1154. }
  1155. node, err := res.GetString("node")
  1156. if err != nil {
  1157. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1158. continue
  1159. }
  1160. instanceType, err := res.GetString("instance_type")
  1161. if err != nil {
  1162. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1163. continue
  1164. }
  1165. providerID, err := res.GetString("provider_id")
  1166. if err != nil {
  1167. log.Warningf("CostModel.ComputeAllocation: Node RAM cost query result missing field: %s", err)
  1168. continue
  1169. }
  1170. key := newNodeKey(cluster, node)
  1171. if _, ok := nodeMap[key]; !ok {
  1172. nodeMap[key] = &NodePricing{
  1173. Name: node,
  1174. NodeType: instanceType,
  1175. ProviderID: providerIDParser(providerID),
  1176. }
  1177. }
  1178. nodeMap[key].CostPerRAMGiBHr = res.Values[0].Value
  1179. }
  1180. }
  1181. func applyNodeCostPerGPUHr(nodeMap map[nodeKey]*NodePricing, resNodeCostPerGPUHr []*prom.QueryResult,
  1182. providerIDParser func(string) string) {
  1183. for _, res := range resNodeCostPerGPUHr {
  1184. cluster, err := res.GetString(env.GetPromClusterLabel())
  1185. if err != nil {
  1186. cluster = env.GetClusterID()
  1187. }
  1188. node, err := res.GetString("node")
  1189. if err != nil {
  1190. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1191. continue
  1192. }
  1193. instanceType, err := res.GetString("instance_type")
  1194. if err != nil {
  1195. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1196. continue
  1197. }
  1198. providerID, err := res.GetString("provider_id")
  1199. if err != nil {
  1200. log.Warningf("CostModel.ComputeAllocation: Node GPU cost query result missing field: %s", err)
  1201. continue
  1202. }
  1203. key := newNodeKey(cluster, node)
  1204. if _, ok := nodeMap[key]; !ok {
  1205. nodeMap[key] = &NodePricing{
  1206. Name: node,
  1207. NodeType: instanceType,
  1208. ProviderID: providerIDParser(providerID),
  1209. }
  1210. }
  1211. nodeMap[key].CostPerGPUHr = res.Values[0].Value
  1212. }
  1213. }
  1214. func applyNodeSpot(nodeMap map[nodeKey]*NodePricing, resNodeIsSpot []*prom.QueryResult) {
  1215. for _, res := range resNodeIsSpot {
  1216. cluster, err := res.GetString(env.GetPromClusterLabel())
  1217. if err != nil {
  1218. cluster = env.GetClusterID()
  1219. }
  1220. node, err := res.GetString("node")
  1221. if err != nil {
  1222. log.Warningf("CostModel.ComputeAllocation: Node spot query result missing field: %s", err)
  1223. continue
  1224. }
  1225. key := newNodeKey(cluster, node)
  1226. if _, ok := nodeMap[key]; !ok {
  1227. log.Warningf("CostModel.ComputeAllocation: Node spot query result for missing node: %s", key)
  1228. continue
  1229. }
  1230. nodeMap[key].Preemptible = res.Values[0].Value > 0
  1231. }
  1232. }
  1233. func applyNodeDiscount(nodeMap map[nodeKey]*NodePricing, cm *CostModel) {
  1234. if cm == nil {
  1235. return
  1236. }
  1237. c, err := cm.Provider.GetConfig()
  1238. if err != nil {
  1239. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1240. return
  1241. }
  1242. discount, err := ParsePercentString(c.Discount)
  1243. if err != nil {
  1244. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1245. return
  1246. }
  1247. negotiatedDiscount, err := ParsePercentString(c.NegotiatedDiscount)
  1248. if err != nil {
  1249. log.Errorf("CostModel.ComputeAllocation: applyNodeDiscount: %s", err)
  1250. return
  1251. }
  1252. for _, node := range nodeMap {
  1253. // TODO GKE Reserved Instances into account
  1254. node.Discount = cm.Provider.CombinedDiscountForNode(node.NodeType, node.Preemptible, discount, negotiatedDiscount)
  1255. node.CostPerCPUHr *= (1.0 - node.Discount)
  1256. node.CostPerRAMGiBHr *= (1.0 - node.Discount)
  1257. }
  1258. }
  1259. func buildPVMap(pvMap map[pvKey]*PV, resPVCostPerGiBHour []*prom.QueryResult) {
  1260. for _, res := range resPVCostPerGiBHour {
  1261. cluster, err := res.GetString(env.GetPromClusterLabel())
  1262. if err != nil {
  1263. cluster = env.GetClusterID()
  1264. }
  1265. name, err := res.GetString("volumename")
  1266. if err != nil {
  1267. log.Warningf("CostModel.ComputeAllocation: PV cost without volumename")
  1268. continue
  1269. }
  1270. key := newPVKey(cluster, name)
  1271. pvMap[key] = &PV{
  1272. Cluster: cluster,
  1273. Name: name,
  1274. CostPerGiBHour: res.Values[0].Value,
  1275. }
  1276. }
  1277. }
  1278. func applyPVBytes(pvMap map[pvKey]*PV, resPVBytes []*prom.QueryResult) {
  1279. for _, res := range resPVBytes {
  1280. key, err := resultPVKey(res, env.GetPromClusterLabel(), "persistentvolume")
  1281. if err != nil {
  1282. log.Warningf("CostModel.ComputeAllocation: PV bytes query result missing field: %s", err)
  1283. continue
  1284. }
  1285. if _, ok := pvMap[key]; !ok {
  1286. log.Warningf("CostModel.ComputeAllocation: PV bytes result for missing PV: %s", err)
  1287. continue
  1288. }
  1289. pvMap[key].Bytes = res.Values[0].Value
  1290. }
  1291. }
  1292. func buildPVCMap(window kubecost.Window, pvcMap map[pvcKey]*PVC, pvMap map[pvKey]*PV, resPVCInfo []*prom.QueryResult) {
  1293. for _, res := range resPVCInfo {
  1294. cluster, err := res.GetString(env.GetPromClusterLabel())
  1295. if err != nil {
  1296. cluster = env.GetClusterID()
  1297. }
  1298. values, err := res.GetStrings("persistentvolumeclaim", "storageclass", "volumename", "namespace")
  1299. if err != nil {
  1300. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC info query result missing field: %s", err)
  1301. continue
  1302. }
  1303. namespace := values["namespace"]
  1304. name := values["persistentvolumeclaim"]
  1305. volume := values["volumename"]
  1306. storageClass := values["storageclass"]
  1307. pvKey := newPVKey(cluster, volume)
  1308. pvcKey := newPVCKey(cluster, namespace, name)
  1309. // pvcStart and pvcEnd are the timestamps of the first and last minutes
  1310. // the PVC was running, respectively. We subtract 1m from pvcStart
  1311. // because this point will actually represent the end of the first
  1312. // minute. We don't subtract from pvcEnd because it already represents
  1313. // the end of the last minute.
  1314. var pvcStart, pvcEnd time.Time
  1315. for _, datum := range res.Values {
  1316. t := time.Unix(int64(datum.Timestamp), 0)
  1317. if pvcStart.IsZero() && datum.Value > 0 && window.Contains(t) {
  1318. pvcStart = t
  1319. }
  1320. if datum.Value > 0 && window.Contains(t) {
  1321. pvcEnd = t
  1322. }
  1323. }
  1324. if pvcStart.IsZero() || pvcEnd.IsZero() {
  1325. log.Warningf("CostModel.ComputeAllocation: PVC %s has no running time", pvcKey)
  1326. }
  1327. pvcStart = pvcStart.Add(-time.Minute)
  1328. if _, ok := pvMap[pvKey]; !ok {
  1329. continue
  1330. }
  1331. pvMap[pvKey].StorageClass = storageClass
  1332. if _, ok := pvcMap[pvcKey]; !ok {
  1333. pvcMap[pvcKey] = &PVC{}
  1334. }
  1335. pvcMap[pvcKey].Name = name
  1336. pvcMap[pvcKey].Namespace = namespace
  1337. pvcMap[pvcKey].Volume = pvMap[pvKey]
  1338. pvcMap[pvcKey].Start = pvcStart
  1339. pvcMap[pvcKey].End = pvcEnd
  1340. }
  1341. }
  1342. func applyPVCBytesRequested(pvcMap map[pvcKey]*PVC, resPVCBytesRequested []*prom.QueryResult) {
  1343. for _, res := range resPVCBytesRequested {
  1344. key, err := resultPVCKey(res, env.GetPromClusterLabel(), "namespace", "persistentvolumeclaim")
  1345. if err != nil {
  1346. continue
  1347. }
  1348. if _, ok := pvcMap[key]; !ok {
  1349. continue
  1350. }
  1351. pvcMap[key].Bytes = res.Values[0].Value
  1352. }
  1353. }
  1354. func buildPodPVCMap(podPVCMap map[podKey][]*PVC, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC, podMap map[podKey]*Pod, resPodPVCAllocation []*prom.QueryResult) {
  1355. for _, res := range resPodPVCAllocation {
  1356. cluster, err := res.GetString(env.GetPromClusterLabel())
  1357. if err != nil {
  1358. cluster = env.GetClusterID()
  1359. }
  1360. values, err := res.GetStrings("persistentvolume", "persistentvolumeclaim", "pod", "namespace")
  1361. if err != nil {
  1362. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC allocation query result missing field: %s", err)
  1363. continue
  1364. }
  1365. namespace := values["namespace"]
  1366. pod := values["pod"]
  1367. name := values["persistentvolumeclaim"]
  1368. volume := values["persistentvolume"]
  1369. podKey := newPodKey(cluster, namespace, pod)
  1370. pvKey := newPVKey(cluster, volume)
  1371. pvcKey := newPVCKey(cluster, namespace, name)
  1372. if _, ok := pvMap[pvKey]; !ok {
  1373. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PV missing for PVC allocation query result: %s", pvKey)
  1374. continue
  1375. }
  1376. if _, ok := podPVCMap[podKey]; !ok {
  1377. podPVCMap[podKey] = []*PVC{}
  1378. }
  1379. pvc, ok := pvcMap[pvcKey]
  1380. if !ok {
  1381. log.DedupedWarningf(5, "CostModel.ComputeAllocation: PVC missing for PVC allocation query: %s", pvcKey)
  1382. continue
  1383. }
  1384. count := 1
  1385. if pod, ok := podMap[podKey]; ok && len(pod.Allocations) > 0 {
  1386. count = len(pod.Allocations)
  1387. } else {
  1388. log.DedupedWarningf(10, "CostModel.ComputeAllocation: PVC %s for missing pod %s", pvcKey, podKey)
  1389. }
  1390. pvc.Count = count
  1391. pvc.Mounted = true
  1392. podPVCMap[podKey] = append(podPVCMap[podKey], pvc)
  1393. }
  1394. }
  1395. func applyUnmountedPVs(window kubecost.Window, podMap map[podKey]*Pod, pvMap map[pvKey]*PV, pvcMap map[pvcKey]*PVC) {
  1396. unmountedPVBytes := map[string]float64{}
  1397. unmountedPVCost := map[string]float64{}
  1398. for _, pv := range pvMap {
  1399. mounted := false
  1400. for _, pvc := range pvcMap {
  1401. if pvc.Volume == nil {
  1402. continue
  1403. }
  1404. if pvc.Volume == pv {
  1405. mounted = true
  1406. break
  1407. }
  1408. }
  1409. if !mounted {
  1410. gib := pv.Bytes / 1024 / 1024 / 1024
  1411. hrs := window.Minutes() / 60.0 // TODO improve with PV hours, not window hours
  1412. cost := pv.CostPerGiBHour * gib * hrs
  1413. unmountedPVCost[pv.Cluster] += cost
  1414. unmountedPVBytes[pv.Cluster] += pv.Bytes
  1415. }
  1416. }
  1417. for cluster, amount := range unmountedPVCost {
  1418. container := kubecost.UnmountedSuffix
  1419. pod := kubecost.UnmountedSuffix
  1420. namespace := kubecost.UnmountedSuffix
  1421. node := ""
  1422. key := newPodKey(cluster, namespace, pod)
  1423. podMap[key] = &Pod{
  1424. Window: window.Clone(),
  1425. Start: *window.Start(),
  1426. End: *window.End(),
  1427. Key: key,
  1428. Allocations: map[string]*kubecost.Allocation{},
  1429. }
  1430. podMap[key].AppendContainer(container)
  1431. podMap[key].Allocations[container].Properties.Cluster = cluster
  1432. podMap[key].Allocations[container].Properties.Node = node
  1433. podMap[key].Allocations[container].Properties.Namespace = namespace
  1434. podMap[key].Allocations[container].Properties.Pod = pod
  1435. podMap[key].Allocations[container].Properties.Container = container
  1436. pvKey := kubecost.PVKey{
  1437. Cluster: cluster,
  1438. Name: kubecost.UnmountedSuffix,
  1439. }
  1440. unmountedPVs := kubecost.PVAllocations{
  1441. pvKey: {
  1442. ByteHours: unmountedPVBytes[cluster] * window.Minutes() / 60.0,
  1443. Cost: amount,
  1444. },
  1445. }
  1446. podMap[key].Allocations[container].PVs = podMap[key].Allocations[container].PVs.Add(unmountedPVs)
  1447. }
  1448. }
  1449. func applyUnmountedPVCs(window kubecost.Window, podMap map[podKey]*Pod, pvcMap map[pvcKey]*PVC) {
  1450. unmountedPVCBytes := map[namespaceKey]float64{}
  1451. unmountedPVCCost := map[namespaceKey]float64{}
  1452. for _, pvc := range pvcMap {
  1453. if !pvc.Mounted && pvc.Volume != nil {
  1454. key := newNamespaceKey(pvc.Cluster, pvc.Namespace)
  1455. gib := pvc.Volume.Bytes / 1024 / 1024 / 1024
  1456. hrs := pvc.Minutes() / 60.0
  1457. cost := pvc.Volume.CostPerGiBHour * gib * hrs
  1458. unmountedPVCCost[key] += cost
  1459. unmountedPVCBytes[key] += pvc.Volume.Bytes
  1460. }
  1461. }
  1462. for key, amount := range unmountedPVCCost {
  1463. container := kubecost.UnmountedSuffix
  1464. pod := kubecost.UnmountedSuffix
  1465. namespace := key.Namespace
  1466. node := ""
  1467. cluster := key.Cluster
  1468. podKey := newPodKey(cluster, namespace, pod)
  1469. podMap[podKey] = &Pod{
  1470. Window: window.Clone(),
  1471. Start: *window.Start(),
  1472. End: *window.End(),
  1473. Key: podKey,
  1474. Allocations: map[string]*kubecost.Allocation{},
  1475. }
  1476. podMap[podKey].AppendContainer(container)
  1477. podMap[podKey].Allocations[container].Properties.Cluster = cluster
  1478. podMap[podKey].Allocations[container].Properties.Node = node
  1479. podMap[podKey].Allocations[container].Properties.Namespace = namespace
  1480. podMap[podKey].Allocations[container].Properties.Pod = pod
  1481. podMap[podKey].Allocations[container].Properties.Container = container
  1482. pvKey := kubecost.PVKey{
  1483. Cluster: cluster,
  1484. Name: kubecost.UnmountedSuffix,
  1485. }
  1486. unmountedPVs := kubecost.PVAllocations{
  1487. pvKey: {
  1488. ByteHours: unmountedPVCBytes[key] * window.Minutes() / 60.0,
  1489. Cost: amount,
  1490. },
  1491. }
  1492. podMap[podKey].Allocations[container].PVs = podMap[podKey].Allocations[container].PVs.Add(unmountedPVs)
  1493. }
  1494. }
  1495. // LB describes the start and end time of a Load Balancer along with cost
  1496. type LB struct {
  1497. TotalCost float64
  1498. Start time.Time
  1499. End time.Time
  1500. }
  1501. func getLoadBalancerCosts(resLBCost, resLBActiveMins []*prom.QueryResult, resolution time.Duration) map[serviceKey]*LB {
  1502. lbMap := make(map[serviceKey]*LB)
  1503. lbHourlyCosts := make(map[serviceKey]float64)
  1504. for _, res := range resLBCost {
  1505. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1506. if err != nil {
  1507. continue
  1508. }
  1509. lbHourlyCosts[serviceKey] = res.Values[0].Value
  1510. }
  1511. for _, res := range resLBActiveMins {
  1512. serviceKey, err := resultServiceKey(res, env.GetPromClusterLabel(), "namespace", "service_name")
  1513. if err != nil || len(res.Values) == 0 {
  1514. continue
  1515. }
  1516. if _, ok := lbHourlyCosts[serviceKey]; !ok {
  1517. log.Warningf("CostModel: failed to find hourly cost for Load Balancer: %v", serviceKey)
  1518. continue
  1519. }
  1520. s := time.Unix(int64(res.Values[0].Timestamp), 0)
  1521. // subtract resolution from start time to cover full time period
  1522. s = s.Add(-resolution)
  1523. e := time.Unix(int64(res.Values[len(res.Values)-1].Timestamp), 0)
  1524. hours := e.Sub(s).Hours()
  1525. lbMap[serviceKey] = &LB{
  1526. TotalCost: lbHourlyCosts[serviceKey] * hours,
  1527. Start: s,
  1528. End: e,
  1529. }
  1530. }
  1531. return lbMap
  1532. }
  1533. func applyLoadBalancersToPods(lbMap map[serviceKey]*LB, allocsByService map[serviceKey][]*kubecost.Allocation) {
  1534. for sKey, lb := range lbMap {
  1535. totalHours := 0.0
  1536. allocHours := make(map[*kubecost.Allocation]float64)
  1537. // Add portion of load balancing cost to each allocation
  1538. // proportional to the total number of hours allocations used the load balancer
  1539. for _, alloc := range allocsByService[sKey] {
  1540. // Determine the (start, end) of the relationship between the
  1541. // given LB and the associated Allocation so that a precise
  1542. // number of hours can be used to compute cumulative cost.
  1543. s, e := alloc.Start, alloc.End
  1544. if lb.Start.After(alloc.Start) {
  1545. s = lb.Start
  1546. }
  1547. if lb.End.Before(alloc.End) {
  1548. e = lb.End
  1549. }
  1550. hours := e.Sub(s).Hours()
  1551. // A negative number of hours signifies no overlap between the windows
  1552. if hours > 0 {
  1553. totalHours += hours
  1554. allocHours[alloc] = hours
  1555. }
  1556. }
  1557. // Distribute cost of service once total hours is calculated
  1558. for alloc, hours := range allocHours {
  1559. alloc.LoadBalancerCost += lb.TotalCost * hours / totalHours
  1560. }
  1561. }
  1562. }
  1563. // getNodePricing determines node pricing, given a key and a mapping from keys
  1564. // to their NodePricing instances, as well as the custom pricing configuration
  1565. // inherent to the CostModel instance. If custom pricing is set, use that. If
  1566. // not, use the pricing defined by the given key. If that doesn't exist, fall
  1567. // back on custom pricing as a default.
  1568. func (cm *CostModel) getNodePricing(nodeMap map[nodeKey]*NodePricing, nodeKey nodeKey) *NodePricing {
  1569. // Find the relevant NodePricing, if it exists. If not, substitute the
  1570. // custom NodePricing as a default.
  1571. node, ok := nodeMap[nodeKey]
  1572. if !ok || node == nil {
  1573. if nodeKey.Node != "" {
  1574. log.DedupedWarningf(5, "CostModel: failed to find node for %s", nodeKey)
  1575. }
  1576. return cm.getCustomNodePricing(false)
  1577. }
  1578. // If custom pricing is enabled and can be retrieved, override detected
  1579. // node pricing with the custom values.
  1580. customPricingConfig, err := cm.Provider.GetConfig()
  1581. if err != nil {
  1582. log.Warningf("CostModel: failed to load custom pricing: %s", err)
  1583. }
  1584. if cloud.CustomPricesEnabled(cm.Provider) && customPricingConfig != nil {
  1585. return cm.getCustomNodePricing(node.Preemptible)
  1586. }
  1587. node.Source = "prometheus"
  1588. // If any of the values are NaN or zero, replace them with the custom
  1589. // values as default.
  1590. // TODO:CLEANUP can't we parse these custom prices once? why do we store
  1591. // them as strings like this?
  1592. if node.CostPerCPUHr == 0 || math.IsNaN(node.CostPerCPUHr) {
  1593. log.Warningf("CostModel: node pricing has illegal CostPerCPUHr; replacing with custom pricing: %s", nodeKey)
  1594. cpuCostStr := customPricingConfig.CPU
  1595. if node.Preemptible {
  1596. cpuCostStr = customPricingConfig.SpotCPU
  1597. }
  1598. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1599. if err != nil {
  1600. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1601. }
  1602. node.CostPerCPUHr = costPerCPUHr
  1603. node.Source += "/customCPU"
  1604. }
  1605. if math.IsNaN(node.CostPerGPUHr) {
  1606. log.Warningf("CostModel: node pricing has illegal CostPerGPUHr; replacing with custom pricing: %s", nodeKey)
  1607. gpuCostStr := customPricingConfig.GPU
  1608. if node.Preemptible {
  1609. gpuCostStr = customPricingConfig.SpotGPU
  1610. }
  1611. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1612. if err != nil {
  1613. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1614. }
  1615. node.CostPerGPUHr = costPerGPUHr
  1616. node.Source += "/customGPU"
  1617. }
  1618. if node.CostPerRAMGiBHr == 0 || math.IsNaN(node.CostPerRAMGiBHr) {
  1619. log.Warningf("CostModel: node pricing has illegal CostPerRAMHr; replacing with custom pricing: %s", nodeKey)
  1620. ramCostStr := customPricingConfig.RAM
  1621. if node.Preemptible {
  1622. ramCostStr = customPricingConfig.SpotRAM
  1623. }
  1624. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1625. if err != nil {
  1626. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1627. }
  1628. node.CostPerRAMGiBHr = costPerRAMHr
  1629. node.Source += "/customRAM"
  1630. }
  1631. return node
  1632. }
  1633. // getCustomNodePricing converts the CostModel's configured custom pricing
  1634. // values into a NodePricing instance.
  1635. func (cm *CostModel) getCustomNodePricing(spot bool) *NodePricing {
  1636. customPricingConfig, err := cm.Provider.GetConfig()
  1637. if err != nil {
  1638. return nil
  1639. }
  1640. cpuCostStr := customPricingConfig.CPU
  1641. gpuCostStr := customPricingConfig.GPU
  1642. ramCostStr := customPricingConfig.RAM
  1643. if spot {
  1644. cpuCostStr = customPricingConfig.SpotCPU
  1645. gpuCostStr = customPricingConfig.SpotGPU
  1646. ramCostStr = customPricingConfig.SpotRAM
  1647. }
  1648. node := &NodePricing{Source: "custom"}
  1649. costPerCPUHr, err := strconv.ParseFloat(cpuCostStr, 64)
  1650. if err != nil {
  1651. log.Warningf("CostModel: custom pricing has illegal CPU cost: %s", cpuCostStr)
  1652. }
  1653. node.CostPerCPUHr = costPerCPUHr
  1654. costPerGPUHr, err := strconv.ParseFloat(gpuCostStr, 64)
  1655. if err != nil {
  1656. log.Warningf("CostModel: custom pricing has illegal GPU cost: %s", gpuCostStr)
  1657. }
  1658. node.CostPerGPUHr = costPerGPUHr
  1659. costPerRAMHr, err := strconv.ParseFloat(ramCostStr, 64)
  1660. if err != nil {
  1661. log.Warningf("CostModel: custom pricing has illegal RAM cost: %s", ramCostStr)
  1662. }
  1663. node.CostPerRAMGiBHr = costPerRAMHr
  1664. return node
  1665. }
  1666. // NodePricing describes the resource costs associated with a given node, as
  1667. // well as the source of the information (e.g. prometheus, custom)
  1668. type NodePricing struct {
  1669. Name string
  1670. NodeType string
  1671. ProviderID string
  1672. Preemptible bool
  1673. CostPerCPUHr float64
  1674. CostPerRAMGiBHr float64
  1675. CostPerGPUHr float64
  1676. Discount float64
  1677. Source string
  1678. }
  1679. // Pod describes a running pod's start and end time within a Window and
  1680. // all the Allocations (i.e. containers) contained within it.
  1681. type Pod struct {
  1682. Window kubecost.Window
  1683. Start time.Time
  1684. End time.Time
  1685. Key podKey
  1686. Allocations map[string]*kubecost.Allocation
  1687. }
  1688. // AppendContainer adds an entry for the given container name to the Pod.
  1689. func (p Pod) AppendContainer(container string) {
  1690. name := fmt.Sprintf("%s/%s/%s/%s", p.Key.Cluster, p.Key.Namespace, p.Key.Pod, container)
  1691. alloc := &kubecost.Allocation{
  1692. Name: name,
  1693. Properties: &kubecost.AllocationProperties{},
  1694. Window: p.Window.Clone(),
  1695. Start: p.Start,
  1696. End: p.End,
  1697. }
  1698. alloc.Properties.Container = container
  1699. alloc.Properties.Pod = p.Key.Pod
  1700. alloc.Properties.Namespace = p.Key.Namespace
  1701. alloc.Properties.Cluster = p.Key.Cluster
  1702. p.Allocations[container] = alloc
  1703. }
  1704. // PVC describes a PersistentVolumeClaim
  1705. // TODO:CLEANUP move to pkg/kubecost?
  1706. // TODO:CLEANUP add PersistentVolumeClaims field to type Allocation?
  1707. type PVC struct {
  1708. Bytes float64 `json:"bytes"`
  1709. Count int `json:"count"`
  1710. Name string `json:"name"`
  1711. Cluster string `json:"cluster"`
  1712. Namespace string `json:"namespace"`
  1713. Volume *PV `json:"persistentVolume"`
  1714. Mounted bool `json:"mounted"`
  1715. Start time.Time `json:"start"`
  1716. End time.Time `json:"end"`
  1717. }
  1718. // Cost computes the cumulative cost of the PVC
  1719. func (pvc *PVC) Cost() float64 {
  1720. if pvc == nil || pvc.Volume == nil {
  1721. return 0.0
  1722. }
  1723. gib := pvc.Bytes / 1024 / 1024 / 1024
  1724. hrs := pvc.Minutes() / 60.0
  1725. return pvc.Volume.CostPerGiBHour * gib * hrs
  1726. }
  1727. // Minutes computes the number of minutes over which the PVC is defined
  1728. func (pvc *PVC) Minutes() float64 {
  1729. if pvc == nil {
  1730. return 0.0
  1731. }
  1732. return pvc.End.Sub(pvc.Start).Minutes()
  1733. }
  1734. // String returns a string representation of the PVC
  1735. func (pvc *PVC) String() string {
  1736. if pvc == nil {
  1737. return "<nil>"
  1738. }
  1739. 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))
  1740. }
  1741. // PV describes a PersistentVolume
  1742. // TODO:CLEANUP move to pkg/kubecost?
  1743. type PV struct {
  1744. Bytes float64 `json:"bytes"`
  1745. CostPerGiBHour float64 `json:"costPerGiBHour"`
  1746. Cluster string `json:"cluster"`
  1747. Name string `json:"name"`
  1748. StorageClass string `json:"storageClass"`
  1749. }
  1750. // String returns a string representation of the PV
  1751. func (pv *PV) String() string {
  1752. if pv == nil {
  1753. return "<nil>"
  1754. }
  1755. return fmt.Sprintf("%s/%s{Bytes:%.2f, Cost/GiB*Hr:%.6f, StorageClass:%s}", pv.Cluster, pv.Name, pv.Bytes, pv.CostPerGiBHour, pv.StorageClass)
  1756. }