/
costmodel.go
2613 lines (2291 loc) · 91.5 KB
/
costmodel.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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ghgmodel
import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
"time"
prometheus "github.com/prometheus/client_golang/api"
prometheusClient "github.com/prometheus/client_golang/api"
costAnalyzerCloud "github.com/tkennes/openghg/pkg/cloud/models"
"github.com/tkennes/openghg/pkg/clustercache"
"github.com/tkennes/openghg/pkg/env"
"github.com/tkennes/openghg/pkg/ghgmodel/clusters"
"github.com/tkennes/openghg/pkg/kubecost"
"github.com/tkennes/openghg/pkg/log"
"github.com/tkennes/openghg/pkg/prom"
"github.com/tkennes/openghg/pkg/util"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"golang.org/x/sync/singleflight"
)
const (
statusAPIError = 422
profileThreshold = 1000 * 1000 * 1000 // 1s (in ns)
apiPrefix = "/api/v1"
epAlertManagers = apiPrefix + "/alertmanagers"
epLabelValues = apiPrefix + "/label/:name/values"
epSeries = apiPrefix + "/series"
epTargets = apiPrefix + "/targets"
epSnapshot = apiPrefix + "/admin/tsdb/snapshot"
epDeleteSeries = apiPrefix + "/admin/tsdb/delete_series"
epCleanTombstones = apiPrefix + "/admin/tsdb/clean_tombstones"
epConfig = apiPrefix + "/status/config"
epFlags = apiPrefix + "/status/flags"
)
// isCron matches a CronJob name and captures the non-timestamp name
//
// We support either a 10 character timestamp OR an 8 character timestamp
// because batch/v1beta1 CronJobs creates Jobs with 10 character timestamps
// and batch/v1 CronJobs create Jobs with 8 character timestamps.
var isCron = regexp.MustCompile(`^(.+)-(\d{10}|\d{8})$`)
type CostModel struct {
Cache clustercache.ClusterCache
ClusterMap clusters.ClusterMap
MaxPrometheusQueryDuration time.Duration
RequestGroup *singleflight.Group
ScrapeInterval time.Duration
PrometheusClient prometheus.Client
Provider costAnalyzerCloud.Provider
pricingMetadata *costAnalyzerCloud.PricingMatchMetadata
}
func NewCostModel(client prometheus.Client, provider costAnalyzerCloud.Provider, cache clustercache.ClusterCache, clusterMap clusters.ClusterMap, scrapeInterval time.Duration) *CostModel {
// request grouping to prevent over-requesting the same data prior to caching
requestGroup := new(singleflight.Group)
return &CostModel{
Cache: cache,
ClusterMap: clusterMap,
MaxPrometheusQueryDuration: env.GetETLMaxPrometheusQueryDuration(),
PrometheusClient: client,
Provider: provider,
RequestGroup: requestGroup,
ScrapeInterval: scrapeInterval,
}
}
type CostData struct {
Name string `json:"name,omitempty"`
PodName string `json:"podName,omitempty"`
NodeName string `json:"nodeName,omitempty"`
NodeData *costAnalyzerCloud.Node `json:"node,omitempty"`
Namespace string `json:"namespace,omitempty"`
Deployments []string `json:"deployments,omitempty"`
Services []string `json:"services,omitempty"`
Daemonsets []string `json:"daemonsets,omitempty"`
Statefulsets []string `json:"statefulsets,omitempty"`
Jobs []string `json:"jobs,omitempty"`
RAMReq []*util.Vector `json:"ramreq,omitempty"`
RAMUsed []*util.Vector `json:"ramused,omitempty"`
RAMAllocation []*util.Vector `json:"ramallocated,omitempty"`
CPUReq []*util.Vector `json:"cpureq,omitempty"`
CPUUsed []*util.Vector `json:"cpuused,omitempty"`
CPUAllocation []*util.Vector `json:"cpuallocated,omitempty"`
GPUReq []*util.Vector `json:"gpureq,omitempty"`
PVCData []*PersistentVolumeClaimData `json:"pvcData,omitempty"`
NetworkData []*util.Vector `json:"network,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
NamespaceLabels map[string]string `json:"namespaceLabels,omitempty"`
ClusterID string `json:"clusterId"`
ClusterName string `json:"clusterName"`
}
func (cd *CostData) String() string {
return fmt.Sprintf("\n\tName: %s; PodName: %s, NodeName: %s\n\tNamespace: %s\n\tDeployments: %s\n\tServices: %s\n\tCPU (req, used, alloc): %d, %d, %d\n\tRAM (req, used, alloc): %d, %d, %d",
cd.Name, cd.PodName, cd.NodeName, cd.Namespace, strings.Join(cd.Deployments, ", "), strings.Join(cd.Services, ", "),
len(cd.CPUReq), len(cd.CPUUsed), len(cd.CPUAllocation),
len(cd.RAMReq), len(cd.RAMUsed), len(cd.RAMAllocation))
}
func (cd *CostData) GetController() (name string, kind string, hasController bool) {
hasController = false
if len(cd.Deployments) > 0 {
name = cd.Deployments[0]
kind = "deployment"
hasController = true
} else if len(cd.Statefulsets) > 0 {
name = cd.Statefulsets[0]
kind = "statefulset"
hasController = true
} else if len(cd.Daemonsets) > 0 {
name = cd.Daemonsets[0]
kind = "daemonset"
hasController = true
} else if len(cd.Jobs) > 0 {
name = cd.Jobs[0]
kind = "job"
hasController = true
match := isCron.FindStringSubmatch(name)
if match != nil {
name = match[1]
}
}
return name, kind, hasController
}
const (
queryRAMRequestsStr = `avg(
label_replace(
label_replace(
avg(
count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="",container!="POD", node!="", %s}[%s] %s)
*
avg_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", container!="",container!="POD", node!="", %s}[%s] %s)
) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
), "pod_name","$1","pod","(.+)"
)
) by (namespace,container_name,pod_name,node,%s)`
queryRAMUsageStr = `sort_desc(
avg(
label_replace(
label_replace(
label_replace(
count_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
), "container_name", "$1", "container", "(.+)"
), "pod_name", "$1", "pod", "(.+)"
)
*
label_replace(
label_replace(
label_replace(
avg_over_time(container_memory_working_set_bytes{container!="", container!="POD", instance!="", %s}[%s] %s), "node", "$1", "instance", "(.+)"
), "container_name", "$1", "container", "(.+)"
), "pod_name", "$1", "pod", "(.+)"
)
) by (namespace, container_name, pod_name, node, %s)
)`
queryCPURequestsStr = `avg(
label_replace(
label_replace(
avg(
count_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="",container!="POD", node!="", %s}[%s] %s)
*
avg_over_time(kube_pod_container_resource_requests{resource="cpu", unit="core", container!="",container!="POD", node!="", %s}[%s] %s)
) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
), "pod_name","$1","pod","(.+)"
)
) by (namespace,container_name,pod_name,node,%s)`
queryCPUUsageStr = `avg(
label_replace(
label_replace(
label_replace(
rate(
container_cpu_usage_seconds_total{container!="", container!="POD", instance!="", %s}[%s] %s
), "node", "$1", "instance", "(.+)"
), "container_name", "$1", "container", "(.+)"
), "pod_name", "$1", "pod", "(.+)"
)
) by (namespace, container_name, pod_name, node, %s)`
queryGPURequestsStr = `avg(
label_replace(
label_replace(
avg(
count_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s] %s)
*
avg_over_time(kube_pod_container_resource_requests{resource="nvidia_com_gpu", container!="",container!="POD", node!="", %s}[%s] %s)
* %f
) by (namespace,container,pod,node,%s) , "container_name","$1","container","(.+)"
), "pod_name","$1","pod","(.+)"
)
) by (namespace,container_name,pod_name,node,%s)
* on (pod_name, namespace, %s) group_left(container) label_replace(avg(avg_over_time(kube_pod_status_phase{phase="Running", %s}[%s] %s)) by (pod,namespace,%s), "pod_name","$1","pod","(.+)")`
queryPVRequestsStr = `avg(avg(kube_persistentvolumeclaim_info{volumename != "", %s}) by (persistentvolumeclaim, storageclass, namespace, volumename, %s, kubernetes_node)
*
on (persistentvolumeclaim, namespace, %s, kubernetes_node) group_right(storageclass, volumename)
sum(kube_persistentvolumeclaim_resource_requests_storage_bytes{%s}) by (persistentvolumeclaim, namespace, %s, kubernetes_node, kubernetes_name)) by (persistentvolumeclaim, storageclass, namespace, %s, volumename, kubernetes_node)`
// queryRAMAllocationByteHours yields the total byte-hour RAM allocation over the given
// window, aggregated by container.
// [line 3] sum_over_time(each byte) = [byte*scrape] by metric
// [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
// [lines 2,4] sum(") by unique container key and multiply [byte*scrape] * [hours/scrape] for byte*hours
// [lines 1,5] relabeling
queryRAMAllocationByteHours = `
label_replace(label_replace(
sum(
sum_over_time(container_memory_allocation_bytes{container!="",container!="POD", node!="", %s}[%s])
) by (namespace,container,pod,node,%s) * %f / 60 / 60
, "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
// queryCPUAllocationVCPUHours yields the total VCPU-hour CPU allocation over the given
// window, aggregated by container.
// [line 3] sum_over_time(each VCPU*mins in window) = [VCPU*scrape] by metric
// [line 4] (scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by container
// [lines 2,4] sum(") by unique container key and multiply [VCPU*scrape] * [hours/scrape] for VCPU*hours
// [lines 1,5] relabeling
queryCPUAllocationVCPUHours = `
label_replace(label_replace(
sum(
sum_over_time(container_cpu_allocation{container!="",container!="POD", node!="", %s}[%s])
) by (namespace,container,pod,node,%s) * %f / 60 / 60
, "container_name","$1","container","(.+)"), "pod_name","$1","pod","(.+)")`
// queryPVCAllocationFmt yields the total byte-hour PVC allocation over the given window.
// sum_over_time(each byte) = [byte*scrape] by metric *(scalar(avg(prometheus_target_interval_length_seconds)) = [seconds/scrape] / 60 / 60 = [hours/scrape] by pod
queryPVCAllocationFmt = `sum(sum_over_time(pod_pvc_allocation{%s}[%s])) by (%s, namespace, pod, persistentvolume, persistentvolumeclaim) * %f/60/60`
queryPVHourlyCostFmt = `avg_over_time(pv_hourly_cost{%s}[%s])`
queryNSLabels = `avg_over_time(kube_namespace_labels{%s}[%s])`
queryPodLabels = `avg_over_time(kube_pod_labels{%s}[%s])`
queryNSAnnotations = `avg_over_time(kube_namespace_annotations{%s}[%s])`
queryPodAnnotations = `avg_over_time(kube_pod_annotations{%s}[%s])`
queryDeploymentLabels = `avg_over_time(deployment_match_labels{%s}[%s])`
queryStatefulsetLabels = `avg_over_time(statefulSet_match_labels{%s}[%s])`
queryPodDaemonsets = `sum(kube_pod_owner{owner_kind="DaemonSet", %s}) by (namespace,pod,owner_name,%s)`
queryPodJobs = `sum(kube_pod_owner{owner_kind="Job", %s}) by (namespace,pod,owner_name,%s)`
queryServiceLabels = `avg_over_time(service_selector_labels{%s}[%s])`
queryZoneNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
queryRegionNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="false", sameZone="false", sameRegion="false", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
queryInternetNetworkUsage = `sum(increase(kubecost_pod_network_egress_bytes_total{internet="true", %s}[%s] %s)) by (namespace,pod_name,%s) / 1024 / 1024 / 1024`
normalizationStr = `max(count_over_time(kube_pod_container_resource_requests{resource="memory", unit="byte", %s}[%s] %s))`
)
func (cm *CostModel) ComputeCostData(cli prometheusClient.Client, cp costAnalyzerCloud.Provider, window string, offset string, filterNamespace string) (map[string]*CostData, error) {
queryRAMUsage := fmt.Sprintf(queryRAMUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
queryCPUUsage := fmt.Sprintf(queryCPUUsageStr, env.GetPromClusterFilter(), window, offset, env.GetPromClusterLabel())
queryNetZoneRequests := fmt.Sprintf(queryZoneNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
queryNetRegionRequests := fmt.Sprintf(queryRegionNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
queryNetInternetRequests := fmt.Sprintf(queryInternetNetworkUsage, env.GetPromClusterFilter(), window, "", env.GetPromClusterLabel())
queryNormalization := fmt.Sprintf(normalizationStr, env.GetPromClusterFilter(), window, offset)
// Cluster ID is specific to the source cluster
clusterID := env.GetClusterID()
// Submit all Prometheus queries asynchronously
ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
resChRAMUsage := ctx.Query(queryRAMUsage)
resChCPUUsage := ctx.Query(queryCPUUsage)
resChNetZoneRequests := ctx.Query(queryNetZoneRequests)
resChNetRegionRequests := ctx.Query(queryNetRegionRequests)
resChNetInternetRequests := ctx.Query(queryNetInternetRequests)
resChNormalization := ctx.Query(queryNormalization)
// Pull pod information from k8s API
podlist := cm.Cache.GetAllPods()
podDeploymentsMapping, err := getPodDeployments(cm.Cache, podlist, clusterID)
if err != nil {
return nil, err
}
podServicesMapping, err := getPodServices(cm.Cache, podlist, clusterID)
if err != nil {
return nil, err
}
namespaceLabelsMapping, err := getNamespaceLabels(cm.Cache, clusterID)
if err != nil {
return nil, err
}
namespaceAnnotationsMapping, err := getNamespaceAnnotations(cm.Cache, clusterID)
if err != nil {
return nil, err
}
// Process Prometheus query results. Handle errors using ctx.Errors.
resRAMUsage, _ := resChRAMUsage.Await()
resCPUUsage, _ := resChCPUUsage.Await()
resNetZoneRequests, _ := resChNetZoneRequests.Await()
resNetRegionRequests, _ := resChNetRegionRequests.Await()
resNetInternetRequests, _ := resChNetInternetRequests.Await()
resNormalization, _ := resChNormalization.Await()
// NOTE: The way we currently handle errors and warnings only early returns if there is an error. Warnings
// NOTE: will not propagate unless coupled with errors.
if ctx.HasErrors() {
// To keep the context of where the errors are occurring, we log the errors here and pass them the error
// back to the caller. The caller should handle the specific case where error is an ErrorCollection
for _, promErr := range ctx.Errors() {
if promErr.Error != nil {
log.Errorf("ComputeCostData: Request Error: %s", promErr.Error)
}
if promErr.ParseError != nil {
log.Errorf("ComputeCostData: Parsing Error: %s", promErr.ParseError)
}
}
// ErrorCollection is an collection of errors wrapped in a single error implementation
// We opt to not return an error for the sake of running as a pure exporter.
log.Warnf("ComputeCostData: continuing despite prometheus errors: %s", ctx.ErrorCollection().Error())
}
defer measureTime(time.Now(), profileThreshold, "ComputeCostData: Processing Query Data")
normalizationValue, err := getNormalization(resNormalization)
if err != nil {
// We opt to not return an error for the sake of running as a pure exporter.
log.Warnf("ComputeCostData: continuing despite error parsing normalization values from %s: %s", queryNormalization, err.Error())
}
// Determine if there are vgpus configured and if so get the total allocatable number
// If there are no vgpus, the coefficient is set to 1.0
vgpuCount, err := getAllocatableVGPUs(cm.Cache)
vgpuCoeff := 10.0
if vgpuCount > 0.0 {
vgpuCoeff = vgpuCount
}
nodes, err := cm.GetNodeCost(cp)
if err != nil {
log.Warnf("GetNodeCost: no node cost model available: " + err.Error())
return nil, err
}
// Unmounted PVs represent the PVs that are not mounted or tied to a volume on a container
unmountedPVs := make(map[string][]*PersistentVolumeClaimData)
pvClaimMapping, err := GetPVInfoLocal(cm.Cache, clusterID)
if err != nil {
log.Warnf("GetPVInfo: unable to get PV data: %s", err.Error())
}
if pvClaimMapping != nil {
err = addPVData(cm.Cache, pvClaimMapping, cp)
if err != nil {
return nil, err
}
// copy claim mappings into zombies, then remove as they're discovered
for k, v := range pvClaimMapping {
unmountedPVs[k] = []*PersistentVolumeClaimData{v}
}
}
networkUsageMap, err := GetNetworkUsageData(resNetZoneRequests, resNetRegionRequests, resNetInternetRequests, clusterID)
if err != nil {
log.Warnf("Unable to get Network Cost Data: %s", err.Error())
networkUsageMap = make(map[string]*NetworkUsageData)
}
containerNameCost := make(map[string]*CostData)
containers := make(map[string]bool)
RAMUsedMap, err := GetContainerMetricVector(resRAMUsage, true, normalizationValue, clusterID)
if err != nil {
return nil, err
}
for key := range RAMUsedMap {
containers[key] = true
}
CPUUsedMap, err := GetContainerMetricVector(resCPUUsage, false, 0, clusterID) // No need to normalize here, as this comes from a counter
if err != nil {
return nil, err
}
for key := range CPUUsedMap {
containers[key] = true
}
currentContainers := make(map[string]v1.Pod)
for _, pod := range podlist {
if pod.Status.Phase != v1.PodRunning {
continue
}
cs, err := NewContainerMetricsFromPod(pod, clusterID)
if err != nil {
return nil, err
}
for _, c := range cs {
containers[c.Key()] = true // captures any containers that existed for a time < a prometheus scrape interval. We currently charge 0 for this but should charge something.
currentContainers[c.Key()] = *pod
}
}
missingNodes := make(map[string]*costAnalyzerCloud.Node)
missingContainers := make(map[string]*CostData)
for key := range containers {
if _, ok := containerNameCost[key]; ok {
continue // because ordering is important for the allocation model (all PV's applied to the first), just dedupe if it's already been added.
}
// The _else_ case for this statement is the case in which the container has been
// deleted so we have usage information but not request information. In that case,
// we return partial data for CPU and RAM: only usage and not requests.
if pod, ok := currentContainers[key]; ok {
podName := pod.GetObjectMeta().GetName()
ns := pod.GetObjectMeta().GetNamespace()
nsLabels := namespaceLabelsMapping[ns+","+clusterID]
podLabels := pod.GetObjectMeta().GetLabels()
if podLabels == nil {
podLabels = make(map[string]string)
}
for k, v := range nsLabels {
if _, ok := podLabels[k]; !ok {
podLabels[k] = v
}
}
nsAnnotations := namespaceAnnotationsMapping[ns+","+clusterID]
podAnnotations := pod.GetObjectMeta().GetAnnotations()
if podAnnotations == nil {
podAnnotations = make(map[string]string)
}
for k, v := range nsAnnotations {
if _, ok := podAnnotations[k]; !ok {
podAnnotations[k] = v
}
}
nodeName := pod.Spec.NodeName
var nodeData *costAnalyzerCloud.Node
if _, ok := nodes[nodeName]; ok {
nodeData = nodes[nodeName]
}
nsKey := ns + "," + clusterID
var podDeployments []string
if _, ok := podDeploymentsMapping[nsKey]; ok {
if ds, ok := podDeploymentsMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
podDeployments = ds
} else {
podDeployments = []string{}
}
}
var podPVs []*PersistentVolumeClaimData
podClaims := pod.Spec.Volumes
for _, vol := range podClaims {
if vol.PersistentVolumeClaim != nil {
name := vol.PersistentVolumeClaim.ClaimName
key := ns + "," + name + "," + clusterID
if pvClaim, ok := pvClaimMapping[key]; ok {
pvClaim.TimesClaimed++
podPVs = append(podPVs, pvClaim)
// Remove entry from potential unmounted pvs
delete(unmountedPVs, key)
}
}
}
var podNetCosts []*util.Vector
if usage, ok := networkUsageMap[ns+","+podName+","+clusterID]; ok {
netCosts, err := GetNetworkCost(usage, cp)
if err != nil {
log.Debugf("Error pulling network costs: %s", err.Error())
} else {
podNetCosts = netCosts
}
}
var podServices []string
if _, ok := podServicesMapping[nsKey]; ok {
if svcs, ok := podServicesMapping[nsKey][pod.GetObjectMeta().GetName()]; ok {
podServices = svcs
} else {
podServices = []string{}
}
}
for i, container := range pod.Spec.Containers {
containerName := container.Name
// recreate the key and look up data for this container
newKey := NewContainerMetricFromValues(ns, podName, containerName, pod.Spec.NodeName, clusterID).Key()
// k8s.io/apimachinery/pkg/api/resource/amount.go and
// k8s.io/apimachinery/pkg/api/resource/quantity.go for
// details on the "amount" API. See
// https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-types
// for the units of memory and CPU.
ramRequestBytes := container.Resources.Requests.Memory().Value()
// Because information on container RAM & CPU requests isn't
// coming from Prometheus, it won't have a timestamp associated
// with it. We need to provide a timestamp.
RAMReqV := []*util.Vector{
{
Value: float64(ramRequestBytes),
Timestamp: float64(time.Now().UTC().Unix()),
},
}
// use millicores so we can convert to cores in a float64 format
cpuRequestMilliCores := container.Resources.Requests.Cpu().MilliValue()
CPUReqV := []*util.Vector{
{
Value: float64(cpuRequestMilliCores) / 1000,
Timestamp: float64(time.Now().UTC().Unix()),
},
}
gpuReqCount := 0.0
if g, ok := container.Resources.Requests["nvidia.com/gpu"]; ok {
gpuReqCount = g.AsApproximateFloat64()
} else if g, ok := container.Resources.Limits["nvidia.com/gpu"]; ok {
gpuReqCount = g.AsApproximateFloat64()
} else if g, ok := container.Resources.Requests["k8s.amazonaws.com/vgpu"]; ok {
// divide vgpu request/limits by total vgpus to get the portion of physical gpus requested
gpuReqCount = g.AsApproximateFloat64() / vgpuCoeff
} else if g, ok := container.Resources.Limits["k8s.amazonaws.com/vgpu"]; ok {
gpuReqCount = g.AsApproximateFloat64() / vgpuCoeff
}
GPUReqV := []*util.Vector{
{
Value: float64(gpuReqCount),
Timestamp: float64(time.Now().UTC().Unix()),
},
}
RAMUsedV, ok := RAMUsedMap[newKey]
if !ok {
log.Debug("no RAM usage for " + newKey)
RAMUsedV = []*util.Vector{{}}
}
CPUUsedV, ok := CPUUsedMap[newKey]
if !ok {
log.Debug("no CPU usage for " + newKey)
CPUUsedV = []*util.Vector{{}}
}
var pvReq []*PersistentVolumeClaimData
var netReq []*util.Vector
if i == 0 { // avoid duplicating by just assigning all claims to the first container.
pvReq = podPVs
netReq = podNetCosts
}
costs := &CostData{
Name: containerName,
PodName: podName,
NodeName: nodeName,
Namespace: ns,
Deployments: podDeployments,
Services: podServices,
Daemonsets: getDaemonsetsOfPod(pod),
Jobs: getJobsOfPod(pod),
Statefulsets: getStatefulSetsOfPod(pod),
NodeData: nodeData,
RAMReq: RAMReqV,
RAMUsed: RAMUsedV,
CPUReq: CPUReqV,
CPUUsed: CPUUsedV,
GPUReq: GPUReqV,
PVCData: pvReq,
NetworkData: netReq,
Annotations: podAnnotations,
Labels: podLabels,
NamespaceLabels: nsLabels,
ClusterID: clusterID,
ClusterName: cm.ClusterMap.NameFor(clusterID),
}
var cpuReq, cpuUse *util.Vector
if len(costs.CPUReq) > 0 {
cpuReq = costs.CPUReq[0]
}
if len(costs.CPUUsed) > 0 {
cpuUse = costs.CPUUsed[0]
}
costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
var ramReq, ramUse *util.Vector
if len(costs.RAMReq) > 0 {
ramReq = costs.RAMReq[0]
}
if len(costs.RAMUsed) > 0 {
ramUse = costs.RAMUsed[0]
}
costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
if filterNamespace == "" {
containerNameCost[newKey] = costs
} else if costs.Namespace == filterNamespace {
containerNameCost[newKey] = costs
}
}
} else {
// The container has been deleted. Not all information is sent to prometheus via ksm, so fill out what we can without k8s api
log.Debug("The container " + key + " has been deleted. Calculating allocation but resulting object will be missing data.")
c, err := NewContainerMetricFromKey(key)
if err != nil {
return nil, err
}
// CPU and RAM requests are obtained from the Kubernetes API.
// If this case has been reached, the Kubernetes API will not
// have information about the pod because it no longer exists.
//
// The case where this matters is minimal, mainly in environments
// with very short-lived pods that over-request resources.
RAMReqV := []*util.Vector{{}}
CPUReqV := []*util.Vector{{}}
GPUReqV := []*util.Vector{{}}
RAMUsedV, ok := RAMUsedMap[key]
if !ok {
log.Debug("no RAM usage for " + key)
RAMUsedV = []*util.Vector{{}}
}
CPUUsedV, ok := CPUUsedMap[key]
if !ok {
log.Debug("no CPU usage for " + key)
CPUUsedV = []*util.Vector{{}}
}
node, ok := nodes[c.NodeName]
if !ok {
log.Debugf("Node \"%s\" has been deleted from Kubernetes. Query historical data to get it.", c.NodeName)
if n, ok := missingNodes[c.NodeName]; ok {
node = n
} else {
node = &costAnalyzerCloud.Node{}
missingNodes[c.NodeName] = node
}
}
namespacelabels, _ := namespaceLabelsMapping[c.Namespace+","+c.ClusterID]
namespaceAnnotations, _ := namespaceAnnotationsMapping[c.Namespace+","+c.ClusterID]
costs := &CostData{
Name: c.ContainerName,
PodName: c.PodName,
NodeName: c.NodeName,
NodeData: node,
Namespace: c.Namespace,
RAMReq: RAMReqV,
RAMUsed: RAMUsedV,
CPUReq: CPUReqV,
CPUUsed: CPUUsedV,
GPUReq: GPUReqV,
Annotations: namespaceAnnotations,
NamespaceLabels: namespacelabels,
ClusterID: c.ClusterID,
ClusterName: cm.ClusterMap.NameFor(c.ClusterID),
}
var cpuReq, cpuUse *util.Vector
if len(costs.CPUReq) > 0 {
cpuReq = costs.CPUReq[0]
}
if len(costs.CPUUsed) > 0 {
cpuUse = costs.CPUUsed[0]
}
costs.CPUAllocation = getContainerAllocation(cpuReq, cpuUse, "CPU")
var ramReq, ramUse *util.Vector
if len(costs.RAMReq) > 0 {
ramReq = costs.RAMReq[0]
}
if len(costs.RAMUsed) > 0 {
ramUse = costs.RAMUsed[0]
}
costs.RAMAllocation = getContainerAllocation(ramReq, ramUse, "RAM")
if filterNamespace == "" {
containerNameCost[key] = costs
missingContainers[key] = costs
} else if costs.Namespace == filterNamespace {
containerNameCost[key] = costs
missingContainers[key] = costs
}
}
}
// Use unmounted pvs to create a mapping of "Unmounted-<Namespace>" containers
// to pass along the cost data
unmounted := findUnmountedPVCostData(cm.ClusterMap, unmountedPVs, namespaceLabelsMapping, namespaceAnnotationsMapping)
for k, costs := range unmounted {
log.Debugf("Unmounted PVs in Namespace/ClusterID: %s/%s", costs.Namespace, costs.ClusterID)
if filterNamespace == "" {
containerNameCost[k] = costs
} else if costs.Namespace == filterNamespace {
containerNameCost[k] = costs
}
}
err = findDeletedNodeInfo(cli, missingNodes, window, "")
if err != nil {
log.Errorf("Error fetching historical node data: %s", err.Error())
}
err = findDeletedPodInfo(cli, missingContainers, window)
if err != nil {
log.Errorf("Error fetching historical pod data: %s", err.Error())
}
return containerNameCost, err
}
func findUnmountedPVCostData(clusterMap clusters.ClusterMap, unmountedPVs map[string][]*PersistentVolumeClaimData, namespaceLabelsMapping map[string]map[string]string, namespaceAnnotationsMapping map[string]map[string]string) map[string]*CostData {
costs := make(map[string]*CostData)
if len(unmountedPVs) == 0 {
return costs
}
for k, pv := range unmountedPVs {
keyParts := strings.Split(k, ",")
if len(keyParts) != 3 {
log.Warnf("Unmounted PV used key with incorrect parts: %s", k)
continue
}
ns, _, clusterID := keyParts[0], keyParts[1], keyParts[2]
namespacelabels, _ := namespaceLabelsMapping[ns+","+clusterID]
namespaceAnnotations, _ := namespaceAnnotationsMapping[ns+","+clusterID]
// Should be a unique "Unmounted" cost data type
name := "unmounted-pvs"
metric := NewContainerMetricFromValues(ns, name, name, "", clusterID)
key := metric.Key()
if costData, ok := costs[key]; !ok {
costs[key] = &CostData{
Name: name,
PodName: name,
NodeName: "",
Annotations: namespaceAnnotations,
Namespace: ns,
NamespaceLabels: namespacelabels,
Labels: namespacelabels,
ClusterID: clusterID,
ClusterName: clusterMap.NameFor(clusterID),
PVCData: pv,
}
} else {
costData.PVCData = append(costData.PVCData, pv...)
}
}
return costs
}
func findDeletedPodInfo(cli prometheusClient.Client, missingContainers map[string]*CostData, window string) error {
if len(missingContainers) > 0 {
queryHistoricalPodLabels := fmt.Sprintf(`kube_pod_labels{%s}[%s]`, env.GetPromClusterFilter(), window)
podLabelsResult, _, err := prom.NewNamedContext(cli, prom.ComputeCostDataContextName).QuerySync(queryHistoricalPodLabels)
if err != nil {
log.Errorf("failed to parse historical pod labels: %s", err.Error())
}
podLabels := make(map[string]map[string]string)
if podLabelsResult != nil {
podLabels, err = parsePodLabels(podLabelsResult)
if err != nil {
log.Errorf("failed to parse historical pod labels: %s", err.Error())
}
}
for key, costData := range missingContainers {
cm, _ := NewContainerMetricFromKey(key)
labels, ok := podLabels[cm.PodName]
if !ok {
labels = make(map[string]string)
}
for k, v := range costData.NamespaceLabels {
labels[k] = v
}
costData.Labels = labels
}
}
return nil
}
func findDeletedNodeInfo(cli prometheusClient.Client, missingNodes map[string]*costAnalyzerCloud.Node, window, offset string) error {
if len(missingNodes) > 0 {
defer measureTime(time.Now(), profileThreshold, "Finding Deleted Node Info")
offsetStr := ""
if offset != "" {
offsetStr = fmt.Sprintf("offset %s", offset)
}
queryHistoricalCPUCost := fmt.Sprintf(`avg(avg_over_time(node_cpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
queryHistoricalRAMCost := fmt.Sprintf(`avg(avg_over_time(node_ram_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
queryHistoricalGPUCost := fmt.Sprintf(`avg(avg_over_time(node_gpu_hourly_cost{%s}[%s] %s)) by (node, instance, %s)`, env.GetPromClusterFilter(), window, offsetStr, env.GetPromClusterLabel())
ctx := prom.NewNamedContext(cli, prom.ComputeCostDataContextName)
cpuCostResCh := ctx.Query(queryHistoricalCPUCost)
ramCostResCh := ctx.Query(queryHistoricalRAMCost)
gpuCostResCh := ctx.Query(queryHistoricalGPUCost)
cpuCostRes, _ := cpuCostResCh.Await()
ramCostRes, _ := ramCostResCh.Await()
gpuCostRes, _ := gpuCostResCh.Await()
if ctx.HasErrors() {
return ctx.ErrorCollection()
}
cpuCosts, err := getCost(cpuCostRes)
if err != nil {
return err
}
ramCosts, err := getCost(ramCostRes)
if err != nil {
return err
}
gpuCosts, err := getCost(gpuCostRes)
if err != nil {
return err
}
if len(cpuCosts) == 0 {
log.Infof("Kubecost prometheus metrics not currently available. Ingest this server's /metrics endpoint to get that data.")
}
for node, costv := range cpuCosts {
if _, ok := missingNodes[node]; ok {
missingNodes[node].VCPUCost = fmt.Sprintf("%f", costv[0].Value)
} else {
log.DedupedWarningf(5, "Node `%s` in prometheus but not k8s api", node)
}
}
for node, costv := range ramCosts {
if _, ok := missingNodes[node]; ok {
missingNodes[node].RAMCost = fmt.Sprintf("%f", costv[0].Value)
}
}
for node, costv := range gpuCosts {
if _, ok := missingNodes[node]; ok {
missingNodes[node].GPUCost = fmt.Sprintf("%f", costv[0].Value)
}
}
}
return nil
}
// getContainerAllocation takes the max between request and usage. This function
// returns a slice containing a single element describing the container's
// allocation.
//
// Additionally, the timestamp of the allocation will be the highest value
// timestamp between the two vectors. This mitigates situations where
// Timestamp=0. This should have no effect on the metrics emitted by the
// CostModelMetricsEmitter
func getContainerAllocation(req *util.Vector, used *util.Vector, allocationType string) []*util.Vector {
var result []*util.Vector
if req != nil && used != nil {
x1 := req.Value
if math.IsNaN(x1) {
log.Warnf("NaN value found during %s allocation calculation for requests.", allocationType)
x1 = 0.0
}
y1 := used.Value
if math.IsNaN(y1) {
log.Warnf("NaN value found during %s allocation calculation for used.", allocationType)
y1 = 0.0
}
result = []*util.Vector{
{
Value: math.Max(x1, y1),
Timestamp: math.Max(req.Timestamp, used.Timestamp),
},
}
if result[0].Value == 0 && result[0].Timestamp == 0 {
log.Warnf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
}
} else if req != nil {
result = []*util.Vector{
{
Value: req.Value,
Timestamp: req.Timestamp,
},
}
} else if used != nil {
result = []*util.Vector{
{
Value: used.Value,
Timestamp: used.Timestamp,
},
}
} else {
log.Warnf("No request or usage data found during %s allocation calculation. Setting allocation to 0.", allocationType)
result = []*util.Vector{
{
Value: 0,
Timestamp: float64(time.Now().UTC().Unix()),
},
}
}
return result
}
func addPVData(cache clustercache.ClusterCache, pvClaimMapping map[string]*PersistentVolumeClaimData, cloud costAnalyzerCloud.Provider) error {
cfg, err := cloud.GetConfig()
if err != nil {
return err
}
// Pull a region from the first node
var defaultRegion string
nodeList := cache.GetAllNodes()
if len(nodeList) > 0 {
defaultRegion, _ = util.GetRegion(nodeList[0].Labels)
}
storageClasses := cache.GetAllStorageClasses()
storageClassMap := make(map[string]map[string]string)
for _, storageClass := range storageClasses {
params := storageClass.Parameters
storageClassMap[storageClass.ObjectMeta.Name] = params
if storageClass.GetAnnotations()["storageclass.kubernetes.io/is-default-class"] == "true" || storageClass.GetAnnotations()["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
storageClassMap["default"] = params
storageClassMap[""] = params
}
}
pvs := cache.GetAllPersistentVolumes()
pvMap := make(map[string]*costAnalyzerCloud.PV)
for _, pv := range pvs {
parameters, ok := storageClassMap[pv.Spec.StorageClassName]
if !ok {
log.Debugf("Unable to find parameters for storage class \"%s\". Does pv \"%s\" have a storageClassName?", pv.Spec.StorageClassName, pv.Name)
}
var region string
if r, ok := util.GetRegion(pv.Labels); ok {
region = r
} else {
region = defaultRegion
}
cacPv := &costAnalyzerCloud.PV{
Class: pv.Spec.StorageClassName,
Region: region,
Parameters: parameters,
}
err := GetPVCost(cacPv, pv, cloud, region)
if err != nil {
return err
}
pvMap[pv.Name] = cacPv
}
for _, pvc := range pvClaimMapping {
if vol, ok := pvMap[pvc.VolumeName]; ok {
pvc.Volume = vol
} else {
log.Debugf("PV not found, using default")
pvc.Volume = &costAnalyzerCloud.PV{
Cost: cfg.Storage,
}
}
}
return nil
}
func GetPVCost(pv *costAnalyzerCloud.PV, kpv *v1.PersistentVolume, cp costAnalyzerCloud.Provider, defaultRegion string) error {
cfg, err := cp.GetConfig()
if err != nil {
return err
}
key := cp.GetPVKey(kpv, pv.Parameters, defaultRegion)
pv.ProviderID = key.ID()
pvWithCost, err := cp.PVPricing(key)
if err != nil {
pv.Cost = cfg.Storage
return err
}
if pvWithCost == nil || pvWithCost.Cost == "" {
pv.Cost = cfg.Storage
return nil // set default cost
}
pv.Cost = pvWithCost.Cost