allocation.go 32 KB

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