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