allocation.go 23 KB

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