allocation.go 69 KB

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