allocation.go 30 KB

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