allocation.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/opencost/opencost/pkg/util/timeutil"
  6. "github.com/opencost/opencost/pkg/env"
  7. "github.com/opencost/opencost/pkg/kubecost"
  8. "github.com/opencost/opencost/pkg/log"
  9. "github.com/opencost/opencost/pkg/prom"
  10. )
  11. const (
  12. queryFmtPods = `avg(kube_pod_container_status_running{}) by (pod, namespace, %s)[%s:%s]`
  13. queryFmtPodsUID = `avg(kube_pod_container_status_running{}) by (pod, namespace, uid, %s)[%s:%s]`
  14. queryFmtRAMBytesAllocated = `avg(avg_over_time(container_memory_allocation_bytes{container!="", container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s, provider_id)`
  15. queryFmtRAMRequests = `avg(avg_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="", container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s)`
  16. queryFmtRAMUsageAvg = `avg(avg_over_time(container_memory_working_set_bytes{container!="", container_name!="POD", container!="POD"}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  17. queryFmtRAMUsageMax = `max(max_over_time(container_memory_working_set_bytes{container!="", container_name!="POD", container!="POD"}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  18. queryFmtCPUCoresAllocated = `avg(avg_over_time(container_cpu_allocation{container!="", container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s)`
  19. queryFmtCPURequests = `avg(avg_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="", container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s)`
  20. queryFmtCPUUsageAvg = `avg(rate(container_cpu_usage_seconds_total{container!="", container_name!="POD", container!="POD"}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  21. queryFmtGPUsRequested = `avg(avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s)`
  22. queryFmtGPUsAllocated = `avg(avg_over_time(container_gpu_allocation{container!="", container!="POD", node!=""}[%s])) by (container, pod, namespace, node, %s)`
  23. queryFmtNodeCostPerCPUHr = `avg(avg_over_time(node_cpu_hourly_cost[%s])) by (node, %s, instance_type, provider_id)`
  24. queryFmtNodeCostPerRAMGiBHr = `avg(avg_over_time(node_ram_hourly_cost[%s])) by (node, %s, instance_type, provider_id)`
  25. queryFmtNodeCostPerGPUHr = `avg(avg_over_time(node_gpu_hourly_cost[%s])) by (node, %s, instance_type, provider_id)`
  26. queryFmtNodeIsSpot = `avg_over_time(kubecost_node_is_spot[%s])`
  27. queryFmtPVCInfo = `avg(kube_persistentvolumeclaim_info{volumename != ""}) by (persistentvolumeclaim, storageclass, volumename, namespace, %s)[%s:%s]`
  28. queryFmtPodPVCAllocation = `avg(avg_over_time(pod_pvc_allocation[%s])) by (persistentvolume, persistentvolumeclaim, pod, namespace, %s)`
  29. queryFmtPVCBytesRequested = `avg(avg_over_time(kube_persistentvolumeclaim_resource_requests_storage_bytes{}[%s])) by (persistentvolumeclaim, namespace, %s)`
  30. queryFmtPVActiveMins = `count(kube_persistentvolume_capacity_bytes) by (persistentvolume, %s)[%s:%s]`
  31. queryFmtPVBytes = `avg(avg_over_time(kube_persistentvolume_capacity_bytes[%s])) by (persistentvolume, %s)`
  32. queryFmtPVCostPerGiBHour = `avg(avg_over_time(pv_hourly_cost[%s])) by (volumename, %s)`
  33. queryFmtNetZoneGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true"}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  34. queryFmtNetZoneCostPerGiB = `avg(avg_over_time(kubecost_network_zone_egress_cost{}[%s])) by (%s)`
  35. queryFmtNetRegionGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false"}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  36. queryFmtNetRegionCostPerGiB = `avg(avg_over_time(kubecost_network_region_egress_cost{}[%s])) by (%s)`
  37. queryFmtNetInternetGiB = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true"}[%s])) by (pod_name, namespace, %s) / 1024 / 1024 / 1024`
  38. queryFmtNetInternetCostPerGiB = `avg(avg_over_time(kubecost_network_internet_egress_cost{}[%s])) by (%s)`
  39. queryFmtNetReceiveBytes = `sum(increase(container_network_receive_bytes_total{pod!=""}[%s])) by (pod_name, pod, namespace, %s)`
  40. queryFmtNetTransferBytes = `sum(increase(container_network_transmit_bytes_total{pod!=""}[%s])) by (pod_name, pod, namespace, %s)`
  41. queryFmtNodeLabels = `avg_over_time(kube_node_labels[%s])`
  42. queryFmtNamespaceLabels = `avg_over_time(kube_namespace_labels[%s])`
  43. queryFmtNamespaceAnnotations = `avg_over_time(kube_namespace_annotations[%s])`
  44. queryFmtPodLabels = `avg_over_time(kube_pod_labels[%s])`
  45. queryFmtPodAnnotations = `avg_over_time(kube_pod_annotations[%s])`
  46. queryFmtServiceLabels = `avg_over_time(service_selector_labels[%s])`
  47. queryFmtDeploymentLabels = `avg_over_time(deployment_match_labels[%s])`
  48. queryFmtStatefulSetLabels = `avg_over_time(statefulSet_match_labels[%s])`
  49. queryFmtDaemonSetLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="DaemonSet"}[%s])) by (pod, owner_name, namespace, %s)`
  50. queryFmtJobLabels = `sum(avg_over_time(kube_pod_owner{owner_kind="Job"}[%s])) by (pod, owner_name, namespace ,%s)`
  51. queryFmtPodsWithReplicaSetOwner = `sum(avg_over_time(kube_pod_owner{owner_kind="ReplicaSet"}[%s])) by (pod, owner_name, namespace ,%s)`
  52. queryFmtReplicaSetsWithoutOwners = `avg(avg_over_time(kube_replicaset_owner{owner_kind="<none>", owner_name="<none>"}[%s])) by (replicaset, namespace, %s)`
  53. queryFmtLBCostPerHr = `avg(avg_over_time(kubecost_load_balancer_cost[%s])) by (namespace, service_name, %s)`
  54. queryFmtLBActiveMins = `count(kubecost_load_balancer_cost) by (namespace, service_name, %s)[%s:%s]`
  55. // Because we use container_cpu_usage_seconds_total to calculate CPU usage
  56. // at any given "instant" of time, we need to use an irate or rate. To then
  57. // calculate a max (or any aggregation) we have to perform an aggregation
  58. // query on top of an instant-by-instant maximum. Prometheus supports this
  59. // type of query with a "subquery" [1], however it is reportedly expensive
  60. // to make such a query. By default, Kubecost's Prometheus config includes
  61. // a recording rule that keeps track of the instant-by-instant irate for CPU
  62. // usage. The metric in this query is created by that recording rule.
  63. //
  64. // [1] https://prometheus.io/blog/2019/01/28/subquery-support/
  65. //
  66. // If changing the name of the recording rule, make sure to update the
  67. // corresponding diagnostic query to avoid confusion.
  68. queryFmtCPUUsageMaxRecordingRule = `max(max_over_time(kubecost_container_cpu_usage_irate{}[%s])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  69. // This is the subquery equivalent of the above recording rule query. It is
  70. // more expensive, but does not require the recording rule. It should be
  71. // used as a fallback query if the recording rule data does not exist.
  72. queryFmtCPUUsageMaxSubquery = `max(max_over_time(irate(container_cpu_usage_seconds_total{container_name!="POD", container_name!=""}[5m])[%s:1m])) by (container_name, container, pod_name, pod, namespace, instance, %s)`
  73. )
  74. // Constants for Network Cost Subtype
  75. const (
  76. networkCrossZoneCost = "NetworkCrossZoneCost"
  77. networkCrossRegionCost = "NetworkCrossRegionCost"
  78. networkInternetCost = "NetworkInternetCost"
  79. )
  80. // CanCompute should return true if CostModel can act as a valid source for the
  81. // given time range. In the case of CostModel we want to attempt to compute as
  82. // long as the range starts in the past. If the CostModel ends up not having
  83. // data to match, that's okay, and should be communicated with an error
  84. // response from ComputeAllocation.
  85. func (cm *CostModel) CanCompute(start, end time.Time) bool {
  86. return start.Before(time.Now())
  87. }
  88. // Name returns the name of the Source
  89. func (cm *CostModel) Name() string {
  90. return "CostModel"
  91. }
  92. // ComputeAllocation uses the CostModel instance to compute an AllocationSet
  93. // for the window defined by the given start and end times. The Allocations
  94. // returned are unaggregated (i.e. down to the container level).
  95. func (cm *CostModel) ComputeAllocation(start, end time.Time, resolution time.Duration) (*kubecost.AllocationSet, error) {
  96. // If the duration is short enough, compute the AllocationSet directly
  97. if end.Sub(start) <= cm.MaxPrometheusQueryDuration {
  98. return cm.computeAllocation(start, end, resolution)
  99. }
  100. // If the duration exceeds the configured MaxPrometheusQueryDuration, then
  101. // query for maximum-sized AllocationSets, collect them, and accumulate.
  102. // s and e track the coverage of the entire given window over multiple
  103. // internal queries.
  104. s, e := start, start
  105. // Collect AllocationSets in a range, then accumulate
  106. // TODO optimize by collecting consecutive AllocationSets, accumulating as we go
  107. asr := kubecost.NewAllocationSetRange()
  108. for e.Before(end) {
  109. // By default, query for the full remaining duration. But do not let
  110. // any individual query duration exceed the configured max Prometheus
  111. // query duration.
  112. duration := end.Sub(e)
  113. if duration > cm.MaxPrometheusQueryDuration {
  114. duration = cm.MaxPrometheusQueryDuration
  115. }
  116. // Set start and end parameters (s, e) for next individual computation.
  117. e = s.Add(duration)
  118. // Compute the individual AllocationSet for just (s, e)
  119. as, err := cm.computeAllocation(s, e, resolution)
  120. if err != nil {
  121. return kubecost.NewAllocationSet(start, end), fmt.Errorf("error computing allocation for %s: %s", kubecost.NewClosedWindow(s, e), err)
  122. }
  123. // Append to the range
  124. asr.Append(as)
  125. // Set s equal to e to set up the next query, if one exists.
  126. s = e
  127. }
  128. // Populate annotations, labels, and services on each Allocation. This is
  129. // necessary because Properties.Intersection does not propagate any values
  130. // stored in maps or slices for performance reasons. In this case, however,
  131. // it is both acceptable and necessary to do so.
  132. allocationAnnotations := map[string]map[string]string{}
  133. allocationLabels := map[string]map[string]string{}
  134. allocationServices := map[string]map[string]bool{}
  135. // Also record errors and warnings, then append them to the results later.
  136. errors := []string{}
  137. warnings := []string{}
  138. for _, as := range asr.Allocations {
  139. for k, a := range as.Allocations {
  140. if len(a.Properties.Annotations) > 0 {
  141. if _, ok := allocationAnnotations[k]; !ok {
  142. allocationAnnotations[k] = map[string]string{}
  143. }
  144. for name, val := range a.Properties.Annotations {
  145. allocationAnnotations[k][name] = val
  146. }
  147. }
  148. if len(a.Properties.Labels) > 0 {
  149. if _, ok := allocationLabels[k]; !ok {
  150. allocationLabels[k] = map[string]string{}
  151. }
  152. for name, val := range a.Properties.Labels {
  153. allocationLabels[k][name] = val
  154. }
  155. }
  156. if len(a.Properties.Services) > 0 {
  157. if _, ok := allocationServices[k]; !ok {
  158. allocationServices[k] = map[string]bool{}
  159. }
  160. for _, val := range a.Properties.Services {
  161. allocationServices[k][val] = true
  162. }
  163. }
  164. }
  165. errors = append(errors, as.Errors...)
  166. warnings = append(warnings, as.Warnings...)
  167. }
  168. // Accumulate to yield the result AllocationSet. After this step, we will
  169. // be nearly complete, but without the raw allocation data, which must be
  170. // recomputed.
  171. resultASR, err := asr.Accumulate(kubecost.AccumulateOptionAll)
  172. if err != nil {
  173. return kubecost.NewAllocationSet(start, end), fmt.Errorf("error accumulating data for %s: %s", kubecost.NewClosedWindow(s, e), err)
  174. }
  175. if resultASR != nil && len(resultASR.Allocations) == 0 {
  176. return kubecost.NewAllocationSet(start, end), nil
  177. }
  178. if length := len(resultASR.Allocations); length != 1 {
  179. return kubecost.NewAllocationSet(start, end), fmt.Errorf("expected 1 accumulated allocation set, found %d sets", length)
  180. }
  181. result := resultASR.Allocations[0]
  182. // Apply the annotations, labels, and services to the post-accumulation
  183. // results. (See above for why this is necessary.)
  184. for k, a := range result.Allocations {
  185. if annotations, ok := allocationAnnotations[k]; ok {
  186. a.Properties.Annotations = annotations
  187. }
  188. if labels, ok := allocationLabels[k]; ok {
  189. a.Properties.Labels = labels
  190. }
  191. if services, ok := allocationServices[k]; ok {
  192. a.Properties.Services = []string{}
  193. for s := range services {
  194. a.Properties.Services = append(a.Properties.Services, s)
  195. }
  196. }
  197. // Expand the Window of all Allocations within the AllocationSet
  198. // to match the Window of the AllocationSet, which gets expanded
  199. // at the end of this function.
  200. a.Window = a.Window.ExpandStart(start).ExpandEnd(end)
  201. }
  202. // Maintain RAM and CPU max usage values by iterating over the range,
  203. // computing maximums on a rolling basis, and setting on the result set.
  204. for _, as := range asr.Allocations {
  205. for key, alloc := range as.Allocations {
  206. resultAlloc := result.Get(key)
  207. if resultAlloc == nil {
  208. continue
  209. }
  210. if resultAlloc.RawAllocationOnly == nil {
  211. resultAlloc.RawAllocationOnly = &kubecost.RawAllocationOnlyData{}
  212. }
  213. if alloc.RawAllocationOnly == nil {
  214. // This will happen inevitably for unmounted disks, but should
  215. // ideally not happen for any allocation with CPU and RAM data.
  216. if !alloc.IsUnmounted() {
  217. log.DedupedWarningf(10, "ComputeAllocation: raw allocation data missing for %s", key)
  218. }
  219. continue
  220. }
  221. if alloc.RawAllocationOnly.CPUCoreUsageMax > resultAlloc.RawAllocationOnly.CPUCoreUsageMax {
  222. resultAlloc.RawAllocationOnly.CPUCoreUsageMax = alloc.RawAllocationOnly.CPUCoreUsageMax
  223. }
  224. if alloc.RawAllocationOnly.RAMBytesUsageMax > resultAlloc.RawAllocationOnly.RAMBytesUsageMax {
  225. resultAlloc.RawAllocationOnly.RAMBytesUsageMax = alloc.RawAllocationOnly.RAMBytesUsageMax
  226. }
  227. }
  228. }
  229. // Expand the window to match the queried time range.
  230. result.Window = result.Window.ExpandStart(start).ExpandEnd(end)
  231. // Append errors and warnings
  232. result.Errors = errors
  233. result.Warnings = warnings
  234. return result, nil
  235. }
  236. func (cm *CostModel) computeAllocation(start, end time.Time, resolution time.Duration) (*kubecost.AllocationSet, error) {
  237. // 1. Build out Pod map from resolution-tuned, batched Pod start/end query
  238. // 2. Run and apply the results of the remaining queries to
  239. // 3. Build out AllocationSet from completed Pod map
  240. // Create a window spanning the requested query
  241. window := kubecost.NewWindow(&start, &end)
  242. // Create an empty AllocationSet. For safety, in the case of an error, we
  243. // should prefer to return this empty set with the error. (In the case of
  244. // no error, of course we populate the set and return it.)
  245. allocSet := kubecost.NewAllocationSet(start, end)
  246. // (1) Build out Pod map
  247. // Build out a map of Allocations as a mapping from pod-to-container-to-
  248. // underlying-Allocation instance, starting with (start, end) so that we
  249. // begin with minutes, from which we compute resource allocation and cost
  250. // totals from measured rate data.
  251. podMap := map[podKey]*pod{}
  252. // clusterStarts and clusterEnds record the earliest start and latest end
  253. // times, respectively, on a cluster-basis. These are used for unmounted
  254. // PVs and other "virtual" Allocations so that minutes are maximally
  255. // accurate during start-up or spin-down of a cluster
  256. clusterStart := map[string]time.Time{}
  257. clusterEnd := map[string]time.Time{}
  258. // If ingesting pod UID, we query kube_pod_container_status_running avg
  259. // by uid as well as the default values, and all podKeys/pods have their
  260. // names changed to "<pod_name> <pod_uid>". Because other metrics need
  261. // to generate keys to match pods but don't have UIDs, podUIDKeyMap
  262. // stores values of format:
  263. // default podKey : []{edited podkey 1, edited podkey 2}
  264. // This is because ingesting UID allows us to catch uncontrolled pods
  265. // with the same names. However, this will lead to a many-to-one metric
  266. // to podKey relation, so this map allows us to map the metric's
  267. // "<pod_name>" key to the edited "<pod_name> <pod_uid>" keys in podMap.
  268. ingestPodUID := env.IsIngestingPodUID()
  269. podUIDKeyMap := make(map[podKey][]podKey)
  270. if ingestPodUID {
  271. log.Debugf("CostModel.ComputeAllocation: ingesting UID data from KSM metrics...")
  272. }
  273. // TODO:CLEANUP remove "max batch" idea and clusterStart/End
  274. err := cm.buildPodMap(window, resolution, env.GetETLMaxPrometheusQueryDuration(), podMap, clusterStart, clusterEnd, ingestPodUID, podUIDKeyMap)
  275. if err != nil {
  276. log.Errorf("CostModel.ComputeAllocation: failed to build pod map: %s", err.Error())
  277. }
  278. // (2) Run and apply remaining queries
  279. // Query for the duration between start and end
  280. durStr := timeutil.DurationString(end.Sub(start))
  281. if durStr == "" {
  282. return allocSet, fmt.Errorf("illegal duration value for %s", kubecost.NewClosedWindow(start, end))
  283. }
  284. // Convert resolution duration to a query-ready string
  285. resStr := timeutil.DurationString(resolution)
  286. ctx := prom.NewNamedContext(cm.PrometheusClient, prom.AllocationContextName)
  287. queryRAMBytesAllocated := fmt.Sprintf(queryFmtRAMBytesAllocated, durStr, env.GetPromClusterLabel())
  288. resChRAMBytesAllocated := ctx.QueryAtTime(queryRAMBytesAllocated, end)
  289. queryRAMRequests := fmt.Sprintf(queryFmtRAMRequests, durStr, env.GetPromClusterLabel())
  290. resChRAMRequests := ctx.QueryAtTime(queryRAMRequests, end)
  291. queryRAMUsageAvg := fmt.Sprintf(queryFmtRAMUsageAvg, durStr, env.GetPromClusterLabel())
  292. resChRAMUsageAvg := ctx.QueryAtTime(queryRAMUsageAvg, end)
  293. queryRAMUsageMax := fmt.Sprintf(queryFmtRAMUsageMax, durStr, env.GetPromClusterLabel())
  294. resChRAMUsageMax := ctx.QueryAtTime(queryRAMUsageMax, end)
  295. queryCPUCoresAllocated := fmt.Sprintf(queryFmtCPUCoresAllocated, durStr, env.GetPromClusterLabel())
  296. resChCPUCoresAllocated := ctx.QueryAtTime(queryCPUCoresAllocated, end)
  297. queryCPURequests := fmt.Sprintf(queryFmtCPURequests, durStr, env.GetPromClusterLabel())
  298. resChCPURequests := ctx.QueryAtTime(queryCPURequests, end)
  299. queryCPUUsageAvg := fmt.Sprintf(queryFmtCPUUsageAvg, durStr, env.GetPromClusterLabel())
  300. resChCPUUsageAvg := ctx.QueryAtTime(queryCPUUsageAvg, end)
  301. queryCPUUsageMax := fmt.Sprintf(queryFmtCPUUsageMaxRecordingRule, durStr, env.GetPromClusterLabel())
  302. resChCPUUsageMax := ctx.QueryAtTime(queryCPUUsageMax, end)
  303. resCPUUsageMax, _ := resChCPUUsageMax.Await()
  304. // If the recording rule has no data, try to fall back to the subquery.
  305. if len(resCPUUsageMax) == 0 {
  306. queryCPUUsageMax = fmt.Sprintf(queryFmtCPUUsageMaxSubquery, durStr, env.GetPromClusterLabel())
  307. resChCPUUsageMax = ctx.QueryAtTime(queryCPUUsageMax, end)
  308. resCPUUsageMax, _ = resChCPUUsageMax.Await()
  309. // This avoids logspam if there is no data for either metric (e.g. if
  310. // the Prometheus didn't exist in the queried window of time).
  311. if len(resCPUUsageMax) > 0 {
  312. log.Debugf("CPU usage recording rule query returned an empty result when queried at %s over %s. Fell back to subquery. Consider setting up Kubecost CPU usage recording role to reduce query load on Prometheus; subqueries are expensive.", end.String(), durStr)
  313. }
  314. }
  315. queryGPUsRequested := fmt.Sprintf(queryFmtGPUsRequested, durStr, env.GetPromClusterLabel())
  316. resChGPUsRequested := ctx.QueryAtTime(queryGPUsRequested, end)
  317. queryGPUsAllocated := fmt.Sprintf(queryFmtGPUsAllocated, durStr, env.GetPromClusterLabel())
  318. resChGPUsAllocated := ctx.QueryAtTime(queryGPUsAllocated, end)
  319. queryNodeCostPerCPUHr := fmt.Sprintf(queryFmtNodeCostPerCPUHr, durStr, env.GetPromClusterLabel())
  320. resChNodeCostPerCPUHr := ctx.QueryAtTime(queryNodeCostPerCPUHr, end)
  321. queryNodeCostPerRAMGiBHr := fmt.Sprintf(queryFmtNodeCostPerRAMGiBHr, durStr, env.GetPromClusterLabel())
  322. resChNodeCostPerRAMGiBHr := ctx.QueryAtTime(queryNodeCostPerRAMGiBHr, end)
  323. queryNodeCostPerGPUHr := fmt.Sprintf(queryFmtNodeCostPerGPUHr, durStr, env.GetPromClusterLabel())
  324. resChNodeCostPerGPUHr := ctx.QueryAtTime(queryNodeCostPerGPUHr, end)
  325. queryNodeIsSpot := fmt.Sprintf(queryFmtNodeIsSpot, durStr)
  326. resChNodeIsSpot := ctx.QueryAtTime(queryNodeIsSpot, end)
  327. queryPVCInfo := fmt.Sprintf(queryFmtPVCInfo, env.GetPromClusterLabel(), durStr, resStr)
  328. resChPVCInfo := ctx.QueryAtTime(queryPVCInfo, end)
  329. queryPodPVCAllocation := fmt.Sprintf(queryFmtPodPVCAllocation, durStr, env.GetPromClusterLabel())
  330. resChPodPVCAllocation := ctx.QueryAtTime(queryPodPVCAllocation, end)
  331. queryPVCBytesRequested := fmt.Sprintf(queryFmtPVCBytesRequested, durStr, env.GetPromClusterLabel())
  332. resChPVCBytesRequested := ctx.QueryAtTime(queryPVCBytesRequested, end)
  333. queryPVActiveMins := fmt.Sprintf(queryFmtPVActiveMins, env.GetPromClusterLabel(), durStr, resStr)
  334. resChPVActiveMins := ctx.QueryAtTime(queryPVActiveMins, end)
  335. queryPVBytes := fmt.Sprintf(queryFmtPVBytes, durStr, env.GetPromClusterLabel())
  336. resChPVBytes := ctx.QueryAtTime(queryPVBytes, end)
  337. queryPVCostPerGiBHour := fmt.Sprintf(queryFmtPVCostPerGiBHour, durStr, env.GetPromClusterLabel())
  338. resChPVCostPerGiBHour := ctx.QueryAtTime(queryPVCostPerGiBHour, end)
  339. queryNetTransferBytes := fmt.Sprintf(queryFmtNetTransferBytes, durStr, env.GetPromClusterLabel())
  340. resChNetTransferBytes := ctx.QueryAtTime(queryNetTransferBytes, end)
  341. queryNetReceiveBytes := fmt.Sprintf(queryFmtNetReceiveBytes, durStr, env.GetPromClusterLabel())
  342. resChNetReceiveBytes := ctx.QueryAtTime(queryNetReceiveBytes, end)
  343. queryNetZoneGiB := fmt.Sprintf(queryFmtNetZoneGiB, durStr, env.GetPromClusterLabel())
  344. resChNetZoneGiB := ctx.QueryAtTime(queryNetZoneGiB, end)
  345. queryNetZoneCostPerGiB := fmt.Sprintf(queryFmtNetZoneCostPerGiB, durStr, env.GetPromClusterLabel())
  346. resChNetZoneCostPerGiB := ctx.QueryAtTime(queryNetZoneCostPerGiB, end)
  347. queryNetRegionGiB := fmt.Sprintf(queryFmtNetRegionGiB, durStr, env.GetPromClusterLabel())
  348. resChNetRegionGiB := ctx.QueryAtTime(queryNetRegionGiB, end)
  349. queryNetRegionCostPerGiB := fmt.Sprintf(queryFmtNetRegionCostPerGiB, durStr, env.GetPromClusterLabel())
  350. resChNetRegionCostPerGiB := ctx.QueryAtTime(queryNetRegionCostPerGiB, end)
  351. queryNetInternetGiB := fmt.Sprintf(queryFmtNetInternetGiB, durStr, env.GetPromClusterLabel())
  352. resChNetInternetGiB := ctx.QueryAtTime(queryNetInternetGiB, end)
  353. queryNetInternetCostPerGiB := fmt.Sprintf(queryFmtNetInternetCostPerGiB, durStr, env.GetPromClusterLabel())
  354. resChNetInternetCostPerGiB := ctx.QueryAtTime(queryNetInternetCostPerGiB, end)
  355. var resChNodeLabels prom.QueryResultsChan
  356. if env.GetAllocationNodeLabelsEnabled() {
  357. queryNodeLabels := fmt.Sprintf(queryFmtNodeLabels, durStr)
  358. resChNodeLabels = ctx.QueryAtTime(queryNodeLabels, end)
  359. }
  360. queryNamespaceLabels := fmt.Sprintf(queryFmtNamespaceLabels, durStr)
  361. resChNamespaceLabels := ctx.QueryAtTime(queryNamespaceLabels, end)
  362. queryNamespaceAnnotations := fmt.Sprintf(queryFmtNamespaceAnnotations, durStr)
  363. resChNamespaceAnnotations := ctx.QueryAtTime(queryNamespaceAnnotations, end)
  364. queryPodLabels := fmt.Sprintf(queryFmtPodLabels, durStr)
  365. resChPodLabels := ctx.QueryAtTime(queryPodLabels, end)
  366. queryPodAnnotations := fmt.Sprintf(queryFmtPodAnnotations, durStr)
  367. resChPodAnnotations := ctx.QueryAtTime(queryPodAnnotations, end)
  368. queryServiceLabels := fmt.Sprintf(queryFmtServiceLabels, durStr)
  369. resChServiceLabels := ctx.QueryAtTime(queryServiceLabels, end)
  370. queryDeploymentLabels := fmt.Sprintf(queryFmtDeploymentLabels, durStr)
  371. resChDeploymentLabels := ctx.QueryAtTime(queryDeploymentLabels, end)
  372. queryStatefulSetLabels := fmt.Sprintf(queryFmtStatefulSetLabels, durStr)
  373. resChStatefulSetLabels := ctx.QueryAtTime(queryStatefulSetLabels, end)
  374. queryDaemonSetLabels := fmt.Sprintf(queryFmtDaemonSetLabels, durStr, env.GetPromClusterLabel())
  375. resChDaemonSetLabels := ctx.QueryAtTime(queryDaemonSetLabels, end)
  376. queryPodsWithReplicaSetOwner := fmt.Sprintf(queryFmtPodsWithReplicaSetOwner, durStr, env.GetPromClusterLabel())
  377. resChPodsWithReplicaSetOwner := ctx.QueryAtTime(queryPodsWithReplicaSetOwner, end)
  378. queryReplicaSetsWithoutOwners := fmt.Sprintf(queryFmtReplicaSetsWithoutOwners, durStr, env.GetPromClusterLabel())
  379. resChReplicaSetsWithoutOwners := ctx.QueryAtTime(queryReplicaSetsWithoutOwners, end)
  380. queryJobLabels := fmt.Sprintf(queryFmtJobLabels, durStr, env.GetPromClusterLabel())
  381. resChJobLabels := ctx.QueryAtTime(queryJobLabels, end)
  382. queryLBCostPerHr := fmt.Sprintf(queryFmtLBCostPerHr, durStr, env.GetPromClusterLabel())
  383. resChLBCostPerHr := ctx.QueryAtTime(queryLBCostPerHr, end)
  384. queryLBActiveMins := fmt.Sprintf(queryFmtLBActiveMins, env.GetPromClusterLabel(), durStr, resStr)
  385. resChLBActiveMins := ctx.QueryAtTime(queryLBActiveMins, end)
  386. resCPUCoresAllocated, _ := resChCPUCoresAllocated.Await()
  387. resCPURequests, _ := resChCPURequests.Await()
  388. resCPUUsageAvg, _ := resChCPUUsageAvg.Await()
  389. resRAMBytesAllocated, _ := resChRAMBytesAllocated.Await()
  390. resRAMRequests, _ := resChRAMRequests.Await()
  391. resRAMUsageAvg, _ := resChRAMUsageAvg.Await()
  392. resRAMUsageMax, _ := resChRAMUsageMax.Await()
  393. resGPUsRequested, _ := resChGPUsRequested.Await()
  394. resGPUsAllocated, _ := resChGPUsAllocated.Await()
  395. resNodeCostPerCPUHr, _ := resChNodeCostPerCPUHr.Await()
  396. resNodeCostPerRAMGiBHr, _ := resChNodeCostPerRAMGiBHr.Await()
  397. resNodeCostPerGPUHr, _ := resChNodeCostPerGPUHr.Await()
  398. resNodeIsSpot, _ := resChNodeIsSpot.Await()
  399. resPVActiveMins, _ := resChPVActiveMins.Await()
  400. resPVBytes, _ := resChPVBytes.Await()
  401. resPVCostPerGiBHour, _ := resChPVCostPerGiBHour.Await()
  402. resPVCInfo, _ := resChPVCInfo.Await()
  403. resPVCBytesRequested, _ := resChPVCBytesRequested.Await()
  404. resPodPVCAllocation, _ := resChPodPVCAllocation.Await()
  405. resNetTransferBytes, _ := resChNetTransferBytes.Await()
  406. resNetReceiveBytes, _ := resChNetReceiveBytes.Await()
  407. resNetZoneGiB, _ := resChNetZoneGiB.Await()
  408. resNetZoneCostPerGiB, _ := resChNetZoneCostPerGiB.Await()
  409. resNetRegionGiB, _ := resChNetRegionGiB.Await()
  410. resNetRegionCostPerGiB, _ := resChNetRegionCostPerGiB.Await()
  411. resNetInternetGiB, _ := resChNetInternetGiB.Await()
  412. resNetInternetCostPerGiB, _ := resChNetInternetCostPerGiB.Await()
  413. var resNodeLabels []*prom.QueryResult
  414. if env.GetAllocationNodeLabelsEnabled() {
  415. if env.GetAllocationNodeLabelsEnabled() {
  416. resNodeLabels, _ = resChNodeLabels.Await()
  417. }
  418. }
  419. resNamespaceLabels, _ := resChNamespaceLabels.Await()
  420. resNamespaceAnnotations, _ := resChNamespaceAnnotations.Await()
  421. resPodLabels, _ := resChPodLabels.Await()
  422. resPodAnnotations, _ := resChPodAnnotations.Await()
  423. resServiceLabels, _ := resChServiceLabels.Await()
  424. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  425. resStatefulSetLabels, _ := resChStatefulSetLabels.Await()
  426. resDaemonSetLabels, _ := resChDaemonSetLabels.Await()
  427. resPodsWithReplicaSetOwner, _ := resChPodsWithReplicaSetOwner.Await()
  428. resReplicaSetsWithoutOwners, _ := resChReplicaSetsWithoutOwners.Await()
  429. resJobLabels, _ := resChJobLabels.Await()
  430. resLBCostPerHr, _ := resChLBCostPerHr.Await()
  431. resLBActiveMins, _ := resChLBActiveMins.Await()
  432. if ctx.HasErrors() {
  433. for _, err := range ctx.Errors() {
  434. log.Errorf("CostModel.ComputeAllocation: query context error %s", err)
  435. }
  436. return allocSet, ctx.ErrorCollection()
  437. }
  438. // We choose to apply allocation before requests in the cases of RAM and
  439. // CPU so that we can assert that allocation should always be greater than
  440. // or equal to request.
  441. applyCPUCoresAllocated(podMap, resCPUCoresAllocated, podUIDKeyMap)
  442. applyCPUCoresRequested(podMap, resCPURequests, podUIDKeyMap)
  443. applyCPUCoresUsedAvg(podMap, resCPUUsageAvg, podUIDKeyMap)
  444. applyCPUCoresUsedMax(podMap, resCPUUsageMax, podUIDKeyMap)
  445. applyRAMBytesAllocated(podMap, resRAMBytesAllocated, podUIDKeyMap)
  446. applyRAMBytesRequested(podMap, resRAMRequests, podUIDKeyMap)
  447. applyRAMBytesUsedAvg(podMap, resRAMUsageAvg, podUIDKeyMap)
  448. applyRAMBytesUsedMax(podMap, resRAMUsageMax, podUIDKeyMap)
  449. applyGPUsAllocated(podMap, resGPUsRequested, resGPUsAllocated, podUIDKeyMap)
  450. applyNetworkTotals(podMap, resNetTransferBytes, resNetReceiveBytes, podUIDKeyMap)
  451. applyNetworkAllocation(podMap, resNetZoneGiB, resNetZoneCostPerGiB, podUIDKeyMap, networkCrossZoneCost)
  452. applyNetworkAllocation(podMap, resNetRegionGiB, resNetRegionCostPerGiB, podUIDKeyMap, networkCrossRegionCost)
  453. applyNetworkAllocation(podMap, resNetInternetGiB, resNetInternetCostPerGiB, podUIDKeyMap, networkInternetCost)
  454. // In the case that a two pods with the same name had different containers,
  455. // we will double-count the containers. There is no way to associate each
  456. // container with the proper pod from the usage metrics above. This will
  457. // show up as a pod having two Allocations running for the whole pod runtime.
  458. // Other than that case, Allocations should be associated with pods by the
  459. // above functions.
  460. // At this point, we expect "Node" to be set by one of the above functions
  461. // (e.g. applyCPUCoresAllocated, etc.) -- otherwise, node labels will fail
  462. // to correctly apply to the pods.
  463. var nodeLabels map[nodeKey]map[string]string
  464. if env.GetAllocationNodeLabelsEnabled() {
  465. nodeLabels = resToNodeLabels(resNodeLabels)
  466. }
  467. namespaceLabels := resToNamespaceLabels(resNamespaceLabels)
  468. podLabels := resToPodLabels(resPodLabels, podUIDKeyMap, ingestPodUID)
  469. namespaceAnnotations := resToNamespaceAnnotations(resNamespaceAnnotations)
  470. podAnnotations := resToPodAnnotations(resPodAnnotations, podUIDKeyMap, ingestPodUID)
  471. applyLabels(podMap, nodeLabels, namespaceLabels, podLabels)
  472. applyAnnotations(podMap, namespaceAnnotations, podAnnotations)
  473. podDeploymentMap := labelsToPodControllerMap(podLabels, resToDeploymentLabels(resDeploymentLabels))
  474. podStatefulSetMap := labelsToPodControllerMap(podLabels, resToStatefulSetLabels(resStatefulSetLabels))
  475. podDaemonSetMap := resToPodDaemonSetMap(resDaemonSetLabels, podUIDKeyMap, ingestPodUID)
  476. podJobMap := resToPodJobMap(resJobLabels, podUIDKeyMap, ingestPodUID)
  477. podReplicaSetMap := resToPodReplicaSetMap(resPodsWithReplicaSetOwner, resReplicaSetsWithoutOwners, podUIDKeyMap, ingestPodUID)
  478. applyControllersToPods(podMap, podDeploymentMap)
  479. applyControllersToPods(podMap, podStatefulSetMap)
  480. applyControllersToPods(podMap, podDaemonSetMap)
  481. applyControllersToPods(podMap, podJobMap)
  482. applyControllersToPods(podMap, podReplicaSetMap)
  483. serviceLabels := getServiceLabels(resServiceLabels)
  484. allocsByService := map[serviceKey][]*kubecost.Allocation{}
  485. applyServicesToPods(podMap, podLabels, allocsByService, serviceLabels)
  486. // TODO breakdown network costs?
  487. // Build out the map of all PVs with class, size and cost-per-hour.
  488. // Note: this does not record time running, which we may want to
  489. // include later for increased PV precision. (As long as the PV has
  490. // a PVC, we get time running there, so this is only inaccurate
  491. // for short-lived, unmounted PVs.)
  492. pvMap := map[pvKey]*pv{}
  493. buildPVMap(resolution, pvMap, resPVCostPerGiBHour, resPVActiveMins)
  494. applyPVBytes(pvMap, resPVBytes)
  495. // Build out the map of all PVCs with time running, bytes requested,
  496. // and connect to the correct PV from pvMap. (If no PV exists, that
  497. // is noted, but does not result in any allocation/cost.)
  498. pvcMap := map[pvcKey]*pvc{}
  499. buildPVCMap(resolution, pvcMap, pvMap, resPVCInfo)
  500. applyPVCBytesRequested(pvcMap, resPVCBytesRequested)
  501. // Build out the relationships of pods to their PVCs. This step
  502. // populates the pvc.Count field so that pvc allocation can be
  503. // split appropriately among each pod's container allocation.
  504. podPVCMap := map[podKey][]*pvc{}
  505. buildPodPVCMap(podPVCMap, pvMap, pvcMap, podMap, resPodPVCAllocation, podUIDKeyMap, ingestPodUID)
  506. applyPVCsToPods(window, podMap, podPVCMap, pvcMap)
  507. // Identify PVCs without pods and add pv costs to the unmounted Allocation for the pvc's cluster
  508. applyUnmountedPVCs(window, podMap, pvcMap)
  509. // Identify PVs without PVCs and add PV costs to the unmounted Allocation for the PV's cluster
  510. applyUnmountedPVs(window, podMap, pvMap, pvcMap)
  511. lbMap := make(map[serviceKey]*lbCost)
  512. getLoadBalancerCosts(lbMap, resLBCostPerHr, resLBActiveMins, resolution)
  513. applyLoadBalancersToPods(window, podMap, lbMap, allocsByService)
  514. // Build out a map of Nodes with resource costs, discounts, and node types
  515. // for converting resource allocation data to cumulative costs.
  516. nodeMap := map[nodeKey]*nodePricing{}
  517. applyNodeCostPerCPUHr(nodeMap, resNodeCostPerCPUHr)
  518. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr)
  519. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr)
  520. applyNodeSpot(nodeMap, resNodeIsSpot)
  521. applyNodeDiscount(nodeMap, cm)
  522. cm.applyNodesToPod(podMap, nodeMap)
  523. // (3) Build out AllocationSet from Pod map
  524. for _, pod := range podMap {
  525. for _, alloc := range pod.Allocations {
  526. cluster := alloc.Properties.Cluster
  527. nodeName := alloc.Properties.Node
  528. namespace := alloc.Properties.Namespace
  529. podName := alloc.Properties.Pod
  530. container := alloc.Properties.Container
  531. // Make sure that the name is correct (node may not be present at this
  532. // point due to it missing from queryMinutes) then insert.
  533. alloc.Name = fmt.Sprintf("%s/%s/%s/%s/%s", cluster, nodeName, namespace, podName, container)
  534. allocSet.Set(alloc)
  535. }
  536. }
  537. return allocSet, nil
  538. }