allocation.go 76 KB

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