allocation.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. package costmodel
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/opencost/opencost/core/pkg/opencost"
  6. "github.com/opencost/opencost/core/pkg/source"
  7. "github.com/opencost/opencost/core/pkg/util/timeutil"
  8. "github.com/opencost/opencost/core/pkg/log"
  9. "github.com/opencost/opencost/pkg/env"
  10. )
  11. // CanCompute should return true if CostModel can act as a valid source for the
  12. // given time range. In the case of CostModel we want to attempt to compute as
  13. // long as the range starts in the past. If the CostModel ends up not having
  14. // data to match, that's okay, and should be communicated with an error
  15. // response from ComputeAllocation.
  16. func (cm *CostModel) CanCompute(start, end time.Time) bool {
  17. return start.Before(time.Now())
  18. }
  19. // Name returns the name of the Source
  20. func (cm *CostModel) Name() string {
  21. return "CostModel"
  22. }
  23. // ComputeAllocation uses the CostModel instance to compute an AllocationSet
  24. // for the window defined by the given start and end times. The Allocations
  25. // returned are unaggregated (i.e. down to the container level).
  26. func (cm *CostModel) ComputeAllocation(start, end time.Time) (*opencost.AllocationSet, error) {
  27. // If the duration is short enough, compute the AllocationSet directly
  28. if end.Sub(start) <= cm.BatchDuration {
  29. as, _, err := cm.computeAllocation(start, end)
  30. return as, err
  31. }
  32. // If the duration exceeds the configured MaxPrometheusQueryDuration, then
  33. // query for maximum-sized AllocationSets, collect them, and accumulate.
  34. // s and e track the coverage of the entire given window over multiple
  35. // internal queries.
  36. s, e := start, start
  37. // Collect AllocationSets in a range, then accumulate
  38. // TODO optimize by collecting consecutive AllocationSets, accumulating as we go
  39. asr := opencost.NewAllocationSetRange()
  40. for e.Before(end) {
  41. // By default, query for the full remaining duration. But do not let
  42. // any individual query duration exceed the configured max Prometheus
  43. // query duration.
  44. duration := end.Sub(e)
  45. if duration > cm.BatchDuration {
  46. duration = cm.BatchDuration
  47. }
  48. // Set start and end parameters (s, e) for next individual computation.
  49. e = s.Add(duration)
  50. // Compute the individual AllocationSet for just (s, e)
  51. as, _, err := cm.computeAllocation(s, e)
  52. if err != nil {
  53. return opencost.NewAllocationSet(start, end), fmt.Errorf("error computing allocation for %s: %s", opencost.NewClosedWindow(s, e), err)
  54. }
  55. // Append to the range
  56. asr.Append(as)
  57. // Set s equal to e to set up the next query, if one exists.
  58. s = e
  59. }
  60. // Populate annotations, labels, and services on each Allocation. This is
  61. // necessary because Properties.Intersection does not propagate any values
  62. // stored in maps or slices for performance reasons. In this case, however,
  63. // it is both acceptable and necessary to do so.
  64. allocationAnnotations := map[string]map[string]string{}
  65. allocationLabels := map[string]map[string]string{}
  66. allocationServices := map[string]map[string]bool{}
  67. // Also record errors and warnings, then append them to the results later.
  68. errors := []string{}
  69. warnings := []string{}
  70. for _, as := range asr.Allocations {
  71. for k, a := range as.Allocations {
  72. if len(a.Properties.Annotations) > 0 {
  73. if _, ok := allocationAnnotations[k]; !ok {
  74. allocationAnnotations[k] = map[string]string{}
  75. }
  76. for name, val := range a.Properties.Annotations {
  77. allocationAnnotations[k][name] = val
  78. }
  79. }
  80. if len(a.Properties.Labels) > 0 {
  81. if _, ok := allocationLabels[k]; !ok {
  82. allocationLabels[k] = map[string]string{}
  83. }
  84. for name, val := range a.Properties.Labels {
  85. allocationLabels[k][name] = val
  86. }
  87. }
  88. if len(a.Properties.Services) > 0 {
  89. if _, ok := allocationServices[k]; !ok {
  90. allocationServices[k] = map[string]bool{}
  91. }
  92. for _, val := range a.Properties.Services {
  93. allocationServices[k][val] = true
  94. }
  95. }
  96. }
  97. errors = append(errors, as.Errors...)
  98. warnings = append(warnings, as.Warnings...)
  99. }
  100. // Accumulate to yield the result AllocationSet. After this step, we will
  101. // be nearly complete, but without the raw allocation data, which must be
  102. // recomputed.
  103. resultASR, err := asr.Accumulate(opencost.AccumulateOptionAll)
  104. if err != nil {
  105. return opencost.NewAllocationSet(start, end), fmt.Errorf("error accumulating data for %s: %s", opencost.NewClosedWindow(s, e), err)
  106. }
  107. if resultASR != nil && len(resultASR.Allocations) == 0 {
  108. return opencost.NewAllocationSet(start, end), nil
  109. }
  110. if length := len(resultASR.Allocations); length != 1 {
  111. return opencost.NewAllocationSet(start, end), fmt.Errorf("expected 1 accumulated allocation set, found %d sets", length)
  112. }
  113. result := resultASR.Allocations[0]
  114. // Apply the annotations, labels, and services to the post-accumulation
  115. // results. (See above for why this is necessary.)
  116. for k, a := range result.Allocations {
  117. if annotations, ok := allocationAnnotations[k]; ok {
  118. a.Properties.Annotations = annotations
  119. }
  120. if labels, ok := allocationLabels[k]; ok {
  121. a.Properties.Labels = labels
  122. }
  123. if services, ok := allocationServices[k]; ok {
  124. a.Properties.Services = []string{}
  125. for s := range services {
  126. a.Properties.Services = append(a.Properties.Services, s)
  127. }
  128. }
  129. // Expand the Window of all Allocations within the AllocationSet
  130. // to match the Window of the AllocationSet, which gets expanded
  131. // at the end of this function.
  132. a.Window = a.Window.ExpandStart(start).ExpandEnd(end)
  133. }
  134. // Maintain RAM and CPU max usage values by iterating over the range,
  135. // computing maximums on a rolling basis, and setting on the result set.
  136. for _, as := range asr.Allocations {
  137. for key, alloc := range as.Allocations {
  138. resultAlloc := result.Get(key)
  139. if resultAlloc == nil {
  140. continue
  141. }
  142. if resultAlloc.RawAllocationOnly == nil {
  143. resultAlloc.RawAllocationOnly = &opencost.RawAllocationOnlyData{}
  144. }
  145. if alloc.RawAllocationOnly == nil {
  146. // This will happen inevitably for unmounted disks, but should
  147. // ideally not happen for any allocation with CPU and RAM data.
  148. if !alloc.IsUnmounted() {
  149. log.DedupedWarningf(10, "ComputeAllocation: raw allocation data missing for %s", key)
  150. }
  151. continue
  152. }
  153. if alloc.RawAllocationOnly.CPUCoreUsageMax > resultAlloc.RawAllocationOnly.CPUCoreUsageMax {
  154. resultAlloc.RawAllocationOnly.CPUCoreUsageMax = alloc.RawAllocationOnly.CPUCoreUsageMax
  155. }
  156. if alloc.RawAllocationOnly.RAMBytesUsageMax > resultAlloc.RawAllocationOnly.RAMBytesUsageMax {
  157. resultAlloc.RawAllocationOnly.RAMBytesUsageMax = alloc.RawAllocationOnly.RAMBytesUsageMax
  158. }
  159. if alloc.RawAllocationOnly.GPUUsageMax != nil && resultAlloc.RawAllocationOnly.GPUUsageMax != nil {
  160. if *alloc.RawAllocationOnly.GPUUsageMax > *resultAlloc.RawAllocationOnly.GPUUsageMax {
  161. resultAlloc.RawAllocationOnly.GPUUsageMax = alloc.RawAllocationOnly.GPUUsageMax
  162. }
  163. }
  164. }
  165. }
  166. // Expand the window to match the queried time range.
  167. result.Window = result.Window.ExpandStart(start).ExpandEnd(end)
  168. // Append errors and warnings
  169. result.Errors = errors
  170. result.Warnings = warnings
  171. // Convert any NaNs to 0 to avoid JSON marshaling issues and avoid cascading NaN appearances elsewhere
  172. result.SanitizeNaN()
  173. return result, nil
  174. }
  175. // DateRange checks the data (up to 90 days in the past), and returns the oldest and newest sample timestamp from opencost scraping metric
  176. // it supposed to be a good indicator of available allocation data
  177. func (cm *CostModel) DateRange(limitDays int) (time.Time, time.Time, error) {
  178. return cm.DataSource.Metrics().QueryDataCoverage(limitDays)
  179. }
  180. func (cm *CostModel) computeAllocation(start, end time.Time) (*opencost.AllocationSet, map[nodeKey]*nodePricing, error) {
  181. // 1. Build out Pod map from resolution-tuned, batched Pod start/end query
  182. // 2. Run and apply the results of the remaining queries to
  183. // 3. Build out AllocationSet from completed Pod map
  184. resolution := cm.DataSource.Resolution()
  185. // Create a window spanning the requested query
  186. window := opencost.NewWindow(&start, &end)
  187. // Create an empty AllocationSet. For safety, in the case of an error, we
  188. // should prefer to return this empty set with the error. (In the case of
  189. // no error, of course we populate the set and return it.)
  190. allocSet := opencost.NewAllocationSet(start, end)
  191. // (1) Build out Pod map
  192. // Build out a map of Allocations as a mapping from pod-to-container-to-
  193. // underlying-Allocation instance, starting with (start, end) so that we
  194. // begin with minutes, from which we compute resource allocation and cost
  195. // totals from measured rate data.
  196. podMap := map[podKey]*pod{}
  197. // If ingesting pod UID, we query kube_pod_container_status_running avg
  198. // by uid as well as the default values, and all podKeys/pods have their
  199. // names changed to "<pod_name> <pod_uid>". Because other metrics need
  200. // to generate keys to match pods but don't have UIDs, podUIDKeyMap
  201. // stores values of format:
  202. // default podKey : []{edited podkey 1, edited podkey 2}
  203. // This is because ingesting UID allows us to catch uncontrolled pods
  204. // with the same names. However, this will lead to a many-to-one metric
  205. // to podKey relation, so this map allows us to map the metric's
  206. // "<pod_name>" key to the edited "<pod_name> <pod_uid>" keys in podMap.
  207. ingestPodUID := env.IsIngestingPodUID()
  208. podUIDKeyMap := make(map[podKey][]podKey)
  209. if ingestPodUID {
  210. log.Debugf("CostModel.ComputeAllocation: ingesting UID data from KSM metrics...")
  211. }
  212. err := cm.buildPodMap(window, podMap, ingestPodUID, podUIDKeyMap)
  213. if err != nil {
  214. log.Errorf("CostModel.ComputeAllocation: failed to build pod map: %s", err.Error())
  215. }
  216. // (2) Run and apply remaining queries
  217. // Query for the duration between start and end
  218. durStr := timeutil.DurationString(end.Sub(start))
  219. if durStr == "" {
  220. return allocSet, nil, fmt.Errorf("illegal duration value for %s", opencost.NewClosedWindow(start, end))
  221. }
  222. grp := source.NewQueryGroup()
  223. ds := cm.DataSource.Metrics()
  224. resChRAMBytesAllocated := source.WithGroup(grp, ds.QueryRAMBytesAllocated(start, end))
  225. resChRAMRequests := source.WithGroup(grp, ds.QueryRAMRequests(start, end))
  226. resChRAMLimits := source.WithGroup(grp, ds.QueryRAMLimits(start, end))
  227. resChRAMUsageAvg := source.WithGroup(grp, ds.QueryRAMUsageAvg(start, end))
  228. resChRAMUsageMax := source.WithGroup(grp, ds.QueryRAMUsageMax(start, end))
  229. resChCPUCoresAllocated := source.WithGroup(grp, ds.QueryCPUCoresAllocated(start, end))
  230. resChCPURequests := source.WithGroup(grp, ds.QueryCPURequests(start, end))
  231. resChCPULimits := source.WithGroup(grp, ds.QueryCPULimits(start, end))
  232. resChCPUUsageAvg := source.WithGroup(grp, ds.QueryCPUUsageAvg(start, end))
  233. resChCPUUsageMax := source.WithGroup(grp, ds.QueryCPUUsageMax(start, end))
  234. resCPUUsageMax, _ := resChCPUUsageMax.Await()
  235. // This avoids logspam if there is no data for either metric (e.g. if
  236. // the Prometheus didn't exist in the queried window of time).
  237. if len(resCPUUsageMax) > 0 {
  238. log.Debugf("CPU usage recording rule query returned an empty result when queried at %s over %s. Fell back to subquery. Consider setting up Kubecost CPU usage recording role to reduce query load on Prometheus; subqueries are expensive.", end.String(), durStr)
  239. }
  240. // GPU Queries
  241. resChIsGpuShared := source.WithGroup(grp, ds.QueryIsGPUShared(start, end))
  242. resChGPUsAllocated := source.WithGroup(grp, ds.QueryGPUsAllocated(start, end))
  243. resChGPUsRequested := source.WithGroup(grp, ds.QueryGPUsRequested(start, end))
  244. resChGPUsUsageAvg := source.WithGroup(grp, ds.QueryGPUsUsageAvg(start, end))
  245. resChGPUsUsageMax := source.WithGroup(grp, ds.QueryGPUsUsageMax(start, end))
  246. resChGetGPUInfo := source.WithGroup(grp, ds.QueryGPUInfo(start, end))
  247. resChNodeCostPerCPUHr := source.WithGroup(grp, ds.QueryNodeCPUPricePerHr(start, end))
  248. resChNodeCostPerRAMGiBHr := source.WithGroup(grp, ds.QueryNodeRAMPricePerGiBHr(start, end))
  249. resChNodeCostPerGPUHr := source.WithGroup(grp, ds.QueryNodeGPUPricePerHr(start, end))
  250. resChNodeIsSpot := source.WithGroup(grp, ds.QueryNodeIsSpot(start, end))
  251. resChPVCInfo := source.WithGroup(grp, ds.QueryPVCInfo(start, end))
  252. resChPodPVCAllocation := source.WithGroup(grp, ds.QueryPodPVCAllocation(start, end))
  253. resChPVCBytesRequested := source.WithGroup(grp, ds.QueryPVCBytesRequested(start, end))
  254. resChPVActiveMins := source.WithGroup(grp, ds.QueryPVActiveMinutes(start, end))
  255. resChPVBytes := source.WithGroup(grp, ds.QueryPVBytes(start, end))
  256. resChPVCostPerGiBHour := source.WithGroup(grp, ds.QueryPVPricePerGiBHour(start, end))
  257. resChPVMeta := source.WithGroup(grp, ds.QueryPVInfo(start, end))
  258. resChNetTransferBytes := source.WithGroup(grp, ds.QueryNetTransferBytes(start, end))
  259. resChNetReceiveBytes := source.WithGroup(grp, ds.QueryNetReceiveBytes(start, end))
  260. resChNetZoneGiB := source.WithGroup(grp, ds.QueryNetZoneGiB(start, end))
  261. resChNetZonePricePerGiB := source.WithGroup(grp, ds.QueryNetZonePricePerGiB(start, end))
  262. resChNetRegionGiB := source.WithGroup(grp, ds.QueryNetRegionGiB(start, end))
  263. resChNetRegionPricePerGiB := source.WithGroup(grp, ds.QueryNetRegionPricePerGiB(start, end))
  264. resChNetInternetGiB := source.WithGroup(grp, ds.QueryNetInternetGiB(start, end))
  265. resChNetInternetPricePerGiB := source.WithGroup(grp, ds.QueryNetInternetPricePerGiB(start, end))
  266. resChNetNatGatewayGiB := source.WithGroup(grp, ds.QueryNetNatGatewayGiB(start, end))
  267. resChNetNatGatewayEgressPricePerGiB := source.WithGroup(grp, ds.QueryNetNatGatewayPricePerGiB(start, end))
  268. resChNetNatGatewayIngressGiB := source.WithGroup(grp, ds.QueryNetNatGatewayIngressGiB(start, end))
  269. resChNetNatGatewayIngressPricePerGiB := source.WithGroup(grp, ds.QueryNetNatGatewayIngressPricePerGiB(start, end))
  270. var resChNodeLabels *source.QueryGroupFuture[source.NodeLabelsResult]
  271. if env.IsAllocationNodeLabelsEnabled() {
  272. resChNodeLabels = source.WithGroup(grp, ds.QueryNodeLabels(start, end))
  273. }
  274. resChNamespaceLabels := source.WithGroup(grp, ds.QueryNamespaceLabels(start, end))
  275. resChNamespaceAnnotations := source.WithGroup(grp, ds.QueryNamespaceAnnotations(start, end))
  276. resChPodLabels := source.WithGroup(grp, ds.QueryPodLabels(start, end))
  277. resChPodAnnotations := source.WithGroup(grp, ds.QueryPodAnnotations(start, end))
  278. resChServiceLabels := source.WithGroup(grp, ds.QueryServiceLabels(start, end))
  279. resChDeploymentLabels := source.WithGroup(grp, ds.QueryDeploymentLabels(start, end))
  280. resChStatefulSetLabels := source.WithGroup(grp, ds.QueryStatefulSetLabels(start, end))
  281. resChDaemonSetLabels := source.WithGroup(grp, ds.QueryDaemonSetLabels(start, end))
  282. resChPodsWithReplicaSetOwner := source.WithGroup(grp, ds.QueryPodsWithReplicaSetOwner(start, end))
  283. resChReplicaSetsWithoutOwners := source.WithGroup(grp, ds.QueryReplicaSetsWithoutOwners(start, end))
  284. resChReplicaSetsWithRolloutOwner := source.WithGroup(grp, ds.QueryReplicaSetsWithRollout(start, end))
  285. resChJobLabels := source.WithGroup(grp, ds.QueryJobLabels(start, end))
  286. resChLBCostPerHr := source.WithGroup(grp, ds.QueryLBPricePerHr(start, end))
  287. resChLBActiveMins := source.WithGroup(grp, ds.QueryLBActiveMinutes(start, end))
  288. resCPUCoresAllocated, _ := resChCPUCoresAllocated.Await()
  289. resCPURequests, _ := resChCPURequests.Await()
  290. resCPULimits, _ := resChCPULimits.Await()
  291. resCPUUsageAvg, _ := resChCPUUsageAvg.Await()
  292. resRAMBytesAllocated, _ := resChRAMBytesAllocated.Await()
  293. resRAMRequests, _ := resChRAMRequests.Await()
  294. resRAMLimits, _ := resChRAMLimits.Await()
  295. resRAMUsageAvg, _ := resChRAMUsageAvg.Await()
  296. resRAMUsageMax, _ := resChRAMUsageMax.Await()
  297. resGPUsRequested, _ := resChGPUsRequested.Await()
  298. resGPUsUsageAvg, _ := resChGPUsUsageAvg.Await()
  299. resGPUsUsageMax, _ := resChGPUsUsageMax.Await()
  300. resGPUsAllocated, _ := resChGPUsAllocated.Await()
  301. resIsGpuShared, _ := resChIsGpuShared.Await()
  302. resGetGPUInfo, _ := resChGetGPUInfo.Await()
  303. resNodeCostPerCPUHr, _ := resChNodeCostPerCPUHr.Await()
  304. resNodeCostPerRAMGiBHr, _ := resChNodeCostPerRAMGiBHr.Await()
  305. resNodeCostPerGPUHr, _ := resChNodeCostPerGPUHr.Await()
  306. resNodeIsSpot, _ := resChNodeIsSpot.Await()
  307. nodeExtendedData, _ := queryExtendedNodeData(grp, ds, start, end)
  308. resPVActiveMins, _ := resChPVActiveMins.Await()
  309. resPVBytes, _ := resChPVBytes.Await()
  310. resPVCostPerGiBHour, _ := resChPVCostPerGiBHour.Await()
  311. resPVMeta, _ := resChPVMeta.Await()
  312. resPVCInfo, _ := resChPVCInfo.Await()
  313. resPVCBytesRequested, _ := resChPVCBytesRequested.Await()
  314. resPodPVCAllocation, _ := resChPodPVCAllocation.Await()
  315. resNetTransferBytes, _ := resChNetTransferBytes.Await()
  316. resNetReceiveBytes, _ := resChNetReceiveBytes.Await()
  317. resNetZoneGiB, _ := resChNetZoneGiB.Await()
  318. resNetZonePricePerGiB, _ := resChNetZonePricePerGiB.Await()
  319. resNetRegionGiB, _ := resChNetRegionGiB.Await()
  320. resNetRegionPricePerGiB, _ := resChNetRegionPricePerGiB.Await()
  321. resNetInternetGiB, _ := resChNetInternetGiB.Await()
  322. resNetInternetPricePerGiB, _ := resChNetInternetPricePerGiB.Await()
  323. resNetNatGatewayGiB, _ := resChNetNatGatewayGiB.Await()
  324. resNetNatGatewayEgressPricePerGiB, _ := resChNetNatGatewayEgressPricePerGiB.Await()
  325. resNetNatGatewayIngressGiB, _ := resChNetNatGatewayIngressGiB.Await()
  326. resNetNatGatewayIngressPricePerGiB, _ := resChNetNatGatewayIngressPricePerGiB.Await()
  327. var resNodeLabels []*source.NodeLabelsResult
  328. if env.IsAllocationNodeLabelsEnabled() {
  329. resNodeLabels, _ = resChNodeLabels.Await()
  330. }
  331. resNamespaceLabels, _ := resChNamespaceLabels.Await()
  332. resNamespaceAnnotations, _ := resChNamespaceAnnotations.Await()
  333. resPodLabels, _ := resChPodLabels.Await()
  334. resPodAnnotations, _ := resChPodAnnotations.Await()
  335. resServiceLabels, _ := resChServiceLabels.Await()
  336. resDeploymentLabels, _ := resChDeploymentLabels.Await()
  337. resStatefulSetLabels, _ := resChStatefulSetLabels.Await()
  338. resDaemonSetLabels, _ := resChDaemonSetLabels.Await()
  339. resPodsWithReplicaSetOwner, _ := resChPodsWithReplicaSetOwner.Await()
  340. resReplicaSetsWithoutOwners, _ := resChReplicaSetsWithoutOwners.Await()
  341. resReplicaSetsWithRolloutOwner, _ := resChReplicaSetsWithRolloutOwner.Await()
  342. resJobLabels, _ := resChJobLabels.Await()
  343. resLBCostPerHr, _ := resChLBCostPerHr.Await()
  344. resLBActiveMins, _ := resChLBActiveMins.Await()
  345. if grp.HasErrors() {
  346. for _, err := range grp.Errors() {
  347. log.Errorf("CostModel.ComputeAllocation: query context error %s", err)
  348. }
  349. return allocSet, nil, grp.Error()
  350. }
  351. // We choose to apply allocation before requests in the cases of RAM and
  352. // CPU so that we can assert that allocation should always be greater than
  353. // or equal to request.
  354. applyCPUCoresAllocated(podMap, resCPUCoresAllocated, podUIDKeyMap)
  355. applyCPUCoresRequested(podMap, resCPURequests, podUIDKeyMap)
  356. applyCPUCoresLimits(podMap, resCPULimits, podUIDKeyMap)
  357. applyCPUCoresUsedAvg(podMap, resCPUUsageAvg, podUIDKeyMap)
  358. applyCPUCoresUsedMax(podMap, resCPUUsageMax, podUIDKeyMap)
  359. applyRAMBytesAllocated(podMap, resRAMBytesAllocated, podUIDKeyMap)
  360. applyRAMBytesRequested(podMap, resRAMRequests, podUIDKeyMap)
  361. applyRAMBytesLimits(podMap, resRAMLimits, podUIDKeyMap)
  362. applyRAMBytesUsedAvg(podMap, resRAMUsageAvg, podUIDKeyMap)
  363. applyRAMBytesUsedMax(podMap, resRAMUsageMax, podUIDKeyMap)
  364. applyGPUUsageAvg(podMap, resGPUsUsageAvg, podUIDKeyMap)
  365. applyGPUUsageMax(podMap, resGPUsUsageMax, podUIDKeyMap)
  366. applyGPUUsageShared(podMap, resIsGpuShared, podUIDKeyMap)
  367. applyGPUInfo(podMap, resGetGPUInfo, podUIDKeyMap)
  368. applyGPUsAllocated(podMap, resGPUsRequested, resGPUsAllocated, podUIDKeyMap)
  369. applyNetworkTotals(podMap, resNetTransferBytes, resNetReceiveBytes, podUIDKeyMap)
  370. applyNetworkAllocation(podMap, resNetZoneGiB, resNetZonePricePerGiB, podUIDKeyMap, applyCrossZoneNetworkAllocation)
  371. applyNetworkAllocation(podMap, resNetRegionGiB, resNetRegionPricePerGiB, podUIDKeyMap, applyCrossRegionNetworkAllocation)
  372. applyNetworkAllocation(podMap, resNetInternetGiB, resNetInternetPricePerGiB, podUIDKeyMap, applyInternetNetworkAllocation)
  373. applyNetworkAllocation(podMap, resNetNatGatewayGiB, resNetNatGatewayEgressPricePerGiB, podUIDKeyMap, applyNatGatewayEgressAllocation)
  374. applyNetworkAllocation(podMap, resNetNatGatewayIngressGiB, resNetNatGatewayIngressPricePerGiB, podUIDKeyMap, applyNatGatewayIngressAllocation)
  375. // In the case that a two pods with the same name had different containers,
  376. // we will double-count the containers. There is no way to associate each
  377. // container with the proper pod from the usage metrics above. This will
  378. // show up as a pod having two Allocations running for the whole pod runtime.
  379. // Other than that case, Allocations should be associated with pods by the
  380. // above functions.
  381. // At this point, we expect "Node" to be set by one of the above functions
  382. // (e.g. applyCPUCoresAllocated, etc.) -- otherwise, node labels will fail
  383. // to correctly apply to the pods.
  384. var nodeLabels map[nodeKey]map[string]string
  385. if env.IsAllocationNodeLabelsEnabled() {
  386. nodeLabels = resToNodeLabels(resNodeLabels)
  387. }
  388. namespaceLabels := resToNamespaceLabels(resNamespaceLabels)
  389. podLabels := resToPodLabels(resPodLabels, podUIDKeyMap, ingestPodUID)
  390. namespaceAnnotations := resToNamespaceAnnotations(resNamespaceAnnotations)
  391. podAnnotations := resToPodAnnotations(resPodAnnotations, podUIDKeyMap, ingestPodUID)
  392. applyLabels(podMap, nodeLabels, namespaceLabels, podLabels)
  393. applyAnnotations(podMap, namespaceAnnotations, podAnnotations)
  394. podDeploymentMap := labelsToPodControllerMap(podLabels, resToDeploymentLabels(resDeploymentLabels))
  395. podStatefulSetMap := labelsToPodControllerMap(podLabels, resToStatefulSetLabels(resStatefulSetLabels))
  396. podDaemonSetMap := resToPodDaemonSetMap(resDaemonSetLabels, podUIDKeyMap, ingestPodUID)
  397. podJobMap := resToPodJobMap(resJobLabels, podUIDKeyMap, ingestPodUID)
  398. podReplicaSetMap := resToPodReplicaSetMap(resPodsWithReplicaSetOwner, resReplicaSetsWithoutOwners, resReplicaSetsWithRolloutOwner, podUIDKeyMap, ingestPodUID)
  399. applyControllersToPods(podMap, podDeploymentMap)
  400. applyControllersToPods(podMap, podStatefulSetMap)
  401. applyControllersToPods(podMap, podDaemonSetMap)
  402. applyControllersToPods(podMap, podJobMap)
  403. applyControllersToPods(podMap, podReplicaSetMap)
  404. serviceLabels := getServiceLabels(resServiceLabels)
  405. allocsByService := map[serviceKey][]*opencost.Allocation{}
  406. applyServicesToPods(podMap, podLabels, allocsByService, serviceLabels)
  407. // TODO breakdown network costs?
  408. // Build out the map of all PVs with class, size and cost-per-hour.
  409. // Note: this does not record time running, which we may want to
  410. // include later for increased PV precision. (As long as the PV has
  411. // a PVC, we get time running there, so this is only inaccurate
  412. // for short-lived, unmounted PVs.)
  413. pvMap := map[pvKey]*pv{}
  414. buildPVMap(resolution, pvMap, resPVCostPerGiBHour, resPVActiveMins, resPVMeta, window)
  415. applyPVBytes(pvMap, resPVBytes)
  416. // Build out the map of all PVCs with time running, bytes requested,
  417. // and connect to the correct PV from pvMap. (If no PV exists, that
  418. // is noted, but does not result in any allocation/cost.)
  419. pvcMap := map[pvcKey]*pvc{}
  420. buildPVCMap(resolution, pvcMap, pvMap, resPVCInfo, window)
  421. applyPVCBytesRequested(pvcMap, resPVCBytesRequested)
  422. // Build out the relationships of pods to their PVCs. This step
  423. // populates the pvc.Count field so that pvc allocation can be
  424. // split appropriately among each pod's container allocation.
  425. podPVCMap := map[podKey][]*pvc{}
  426. buildPodPVCMap(podPVCMap, pvMap, pvcMap, podMap, resPodPVCAllocation, podUIDKeyMap, ingestPodUID)
  427. applyPVCsToPods(window, podMap, podPVCMap, pvcMap)
  428. // Identify PVCs without pods and add pv costs to the unmounted Allocation for the pvc's cluster
  429. applyUnmountedPVCs(window, podMap, pvcMap)
  430. // Identify PVs without PVCs and add PV costs to the unmounted Allocation for the PV's cluster
  431. applyUnmountedPVs(window, podMap, pvMap, pvcMap)
  432. lbMap := make(map[serviceKey]*lbCost)
  433. getLoadBalancerCosts(lbMap, resLBCostPerHr, resLBActiveMins, resolution, window)
  434. applyLoadBalancersToPods(window, podMap, lbMap, allocsByService)
  435. // Build out a map of Nodes with resource costs, discounts, and node types
  436. // for converting resource allocation data to cumulative costs.
  437. nodeMap := map[nodeKey]*nodePricing{}
  438. applyNodeCostPerCPUHr(nodeMap, resNodeCostPerCPUHr)
  439. applyNodeCostPerRAMGiBHr(nodeMap, resNodeCostPerRAMGiBHr)
  440. applyNodeCostPerGPUHr(nodeMap, resNodeCostPerGPUHr)
  441. applyNodeSpot(nodeMap, resNodeIsSpot)
  442. applyNodeDiscount(nodeMap, cm)
  443. applyExtendedNodeData(nodeMap, nodeExtendedData)
  444. cm.applyNodesToPod(podMap, nodeMap)
  445. // (3) Build out AllocationSet from Pod map
  446. for _, pod := range podMap {
  447. for _, alloc := range pod.Allocations {
  448. cluster := alloc.Properties.Cluster
  449. nodeName := alloc.Properties.Node
  450. namespace := alloc.Properties.Namespace
  451. podName := alloc.Properties.Pod
  452. container := alloc.Properties.Container
  453. // Make sure that the name is correct (node may not be present at this
  454. // point due to it missing from queryMinutes) then insert.
  455. alloc.Name = fmt.Sprintf("%s/%s/%s/%s/%s", cluster, nodeName, namespace, podName, container)
  456. allocSet.Set(alloc)
  457. }
  458. }
  459. return allocSet, nodeMap, nil
  460. }