allocation.go 37 KB

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