allocation.go 29 KB

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