allocation.go 37 KB

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