-
Notifications
You must be signed in to change notification settings - Fork 519
/
provider.go
2469 lines (2189 loc) · 74.7 KB
/
provider.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 aws
import (
"bytes"
"compress/gzip"
"context"
"encoding/csv"
"errors"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/smithy-go"
"github.com/opencost/opencost/pkg/cloud/models"
"github.com/opencost/opencost/pkg/cloud/utils"
"github.com/opencost/opencost/core/pkg/env"
"github.com/opencost/opencost/core/pkg/log"
"github.com/opencost/opencost/core/pkg/opencost"
"github.com/opencost/opencost/core/pkg/util"
"github.com/opencost/opencost/core/pkg/util/fileutil"
"github.com/opencost/opencost/core/pkg/util/json"
"github.com/opencost/opencost/core/pkg/util/timeutil"
"github.com/opencost/opencost/pkg/clustercache"
ocenv "github.com/opencost/opencost/pkg/env"
errs "github.com/opencost/opencost/pkg/errors"
awsSDK "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/athena"
athenaTypes "github.com/aws/aws-sdk-go-v2/service/athena/types"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/jszwec/csvutil"
v1 "k8s.io/api/core/v1"
)
const (
supportedSpotFeedVersion = "1"
SpotInfoUpdateType = "spotinfo"
AthenaInfoUpdateType = "athenainfo"
PreemptibleType = "preemptible"
APIPricingSource = "Public API"
SpotPricingSource = "Spot Data Feed"
ReservedInstancePricingSource = "Savings Plan, Reserved Instance, and Out-Of-Cluster"
InUseState = "in-use"
AttachedState = "attached"
AWSHourlyPublicIPCost = 0.005
EKSCapacityTypeLabel = "eks.amazonaws.com/capacityType"
EKSCapacitySpotTypeValue = "SPOT"
)
var (
// It's of the form aws:///us-east-2a/i-0fea4fd46592d050b and we want i-0fea4fd46592d050b, if it exists
provIdRx = regexp.MustCompile("aws:///([^/]+)/([^/]+)")
usageTypeRegx = regexp.MustCompile(".*(-|^)(EBS.+)")
versionRx = regexp.MustCompile(`^#Version: (\\d+)\\.\\d+$`)
regionRx = regexp.MustCompile("([a-z]+-[a-z]+-[0-9])")
// StorageClassProvisionerDefaults specifies the default storage class types depending upon the provisioner
StorageClassProvisionerDefaults = map[string]string{
"kubernetes.io/aws-ebs": "gp2",
"ebs.csi.aws.com": "gp3",
// TODO: add efs provisioner
}
)
func (aws *AWS) PricingSourceStatus() map[string]*models.PricingSource {
sources := make(map[string]*models.PricingSource)
sps := &models.PricingSource{
Name: SpotPricingSource,
Enabled: true,
}
if !aws.SpotRefreshEnabled() {
sps.Available = false
sps.Error = "Spot instances not set up"
sps.Enabled = false
} else {
sps.Error = ""
if aws.SpotPricingError != nil {
sps.Error = aws.SpotPricingError.Error()
}
if sps.Error != "" {
sps.Available = false
} else if len(aws.SpotPricingByInstanceID) > 0 {
sps.Available = true
} else {
sps.Error = "No spot instances detected"
}
}
sources[SpotPricingSource] = sps
rps := &models.PricingSource{
Name: ReservedInstancePricingSource,
Enabled: true,
}
rps.Error = ""
if aws.RIPricingError != nil {
rps.Error = aws.RIPricingError.Error()
}
if rps.Error != "" {
rps.Available = false
} else {
rps.Available = true
}
sources[ReservedInstancePricingSource] = rps
return sources
}
// SpotRefreshDuration represents how much time must pass before we refresh
const SpotRefreshDuration = 15 * time.Minute
var awsRegions = []string{
"us-east-2",
"us-east-1",
"us-west-1",
"us-west-2",
"ap-east-1",
"ap-south-1",
"ap-northeast-3",
"ap-northeast-2",
"ap-southeast-1",
"ap-southeast-2",
"ap-northeast-1",
"ap-southeast-3",
"ca-central-1",
"cn-north-1",
"cn-northwest-1",
"eu-central-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"eu-north-1",
"eu-south-1",
"me-south-1",
"sa-east-1",
"af-south-1",
"us-gov-east-1",
"us-gov-west-1",
}
// AWS represents an Amazon Provider
type AWS struct {
Pricing map[string]*AWSProductTerms
SpotPricingByInstanceID map[string]*spotInfo
SpotPricingUpdatedAt *time.Time
SpotRefreshRunning bool
SpotPricingLock sync.RWMutex
SpotPricingError error
RIPricingByInstanceID map[string]*RIData
RIPricingError error
RIDataRunning bool
RIDataLock sync.RWMutex
SavingsPlanDataByInstanceID map[string]*SavingsPlanData
SavingsPlanDataRunning bool
SavingsPlanDataLock sync.RWMutex
ValidPricingKeys map[string]bool
Clientset clustercache.ClusterCache
BaseCPUPrice string
BaseRAMPrice string
BaseGPUPrice string
BaseSpotCPUPrice string
BaseSpotRAMPrice string
BaseSpotGPUPrice string
SpotLabelName string
SpotLabelValue string
SpotDataRegion string
SpotDataBucket string
SpotDataPrefix string
ProjectID string
DownloadPricingDataLock sync.RWMutex
Config models.ProviderConfig
ServiceAccountChecks *models.ServiceAccountChecks
clusterManagementPrice float64
ClusterRegion string
ClusterAccountID string
clusterProvisioner string
}
// AWSAccessKey holds AWS credentials and fulfils the awsV2.CredentialsProvider interface
// Deprecated: v1.104 Use AccessKey instead
type AWSAccessKey struct {
AccessKeyID string `json:"aws_access_key_id"`
SecretAccessKey string `json:"aws_secret_access_key"`
}
// Retrieve returns a set of awsV2 credentials using the AWSAccessKey's key and secret.
// This fulfils the awsV2.CredentialsProvider interface contract.
func (accessKey AWSAccessKey) Retrieve(ctx context.Context) (awsSDK.Credentials, error) {
return awsSDK.Credentials{
AccessKeyID: accessKey.AccessKeyID,
SecretAccessKey: accessKey.SecretAccessKey,
}, nil
}
// CreateConfig creates an AWS SDK V2 Config for the credentials that it contains for the provided region
func (accessKey AWSAccessKey) CreateConfig(region string) (awsSDK.Config, error) {
var cfg awsSDK.Config
var err error
// If accessKey values have not been provided, attempt to load cfg from service key annotations
if accessKey.AccessKeyID == "" && accessKey.SecretAccessKey == "" {
cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
if err != nil {
return cfg, fmt.Errorf("failed to initialize AWS SDK config for region from annotation %s: %s", region, err)
}
} else {
// The AWS SDK v2 requires an object fulfilling the CredentialsProvider interface, which cloud.AWSAccessKey does
cfg, err = config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(accessKey), config.WithRegion(region))
if err != nil {
return cfg, fmt.Errorf("failed to initialize AWS SDK config for region %s: %s", region, err)
}
}
return cfg, nil
}
// AWSPricing maps a k8s node to an AWS Pricing "product"
type AWSPricing struct {
Products map[string]*AWSProduct `json:"products"`
Terms AWSPricingTerms `json:"terms"`
}
// AWSProduct represents a purchased SKU
type AWSProduct struct {
Sku string `json:"sku"`
Attributes AWSProductAttributes `json:"attributes"`
}
// AWSProductAttributes represents metadata about the product used to map to a node.
type AWSProductAttributes struct {
Location string `json:"location"`
InstanceType string `json:"instanceType"`
Memory string `json:"memory"`
Storage string `json:"storage"`
VCpu string `json:"vcpu"`
UsageType string `json:"usagetype"`
OperatingSystem string `json:"operatingSystem"`
PreInstalledSw string `json:"preInstalledSw"`
InstanceFamily string `json:"instanceFamily"`
CapacityStatus string `json:"capacitystatus"`
GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
}
// AWSPricingTerms are how you pay for the node: OnDemand, Reserved, or (TODO) Spot
type AWSPricingTerms struct {
OnDemand map[string]map[string]*AWSOfferTerm `json:"OnDemand"`
Reserved map[string]map[string]*AWSOfferTerm `json:"Reserved"`
}
// AWSOfferTerm is a sku extension used to pay for the node.
type AWSOfferTerm struct {
Sku string `json:"sku"`
OfferTermCode string `json:"offerTermCode"`
PriceDimensions map[string]*AWSRateCode `json:"priceDimensions"`
}
func (ot *AWSOfferTerm) String() string {
var strs []string
for k, rc := range ot.PriceDimensions {
strs = append(strs, fmt.Sprintf("%s:%s", k, rc.String()))
}
return fmt.Sprintf("%s:%s", ot.Sku, strings.Join(strs, ","))
}
// AWSRateCode encodes data about the price of a product
type AWSRateCode struct {
Unit string `json:"unit"`
PricePerUnit AWSCurrencyCode `json:"pricePerUnit"`
}
func (rc *AWSRateCode) String() string {
return fmt.Sprintf("{unit: %s, pricePerUnit: %v", rc.Unit, rc.PricePerUnit)
}
// AWSCurrencyCode is the localized currency. (TODO: support non-USD)
type AWSCurrencyCode struct {
USD string `json:"USD,omitempty"`
CNY string `json:"CNY,omitempty"`
}
// AWSProductTerms represents the full terms of the product
type AWSProductTerms struct {
Sku string `json:"sku"`
OnDemand *AWSOfferTerm `json:"OnDemand"`
Reserved *AWSOfferTerm `json:"Reserved"`
Memory string `json:"memory"`
Storage string `json:"storage"`
VCpu string `json:"vcpu"`
GPU string `json:"gpu"` // GPU represents the number of GPU on the instance
PV *models.PV `json:"pv"`
}
// ClusterIdEnvVar is the environment variable in which one can manually set the ClusterId
const ClusterIdEnvVar = "AWS_CLUSTER_ID"
// OnDemandRateCodes is are sets of identifiers for offerTermCodes matching 'On Demand' rates
var OnDemandRateCodes = map[string]struct{}{
"JRTCKXETXF": {},
}
var OnDemandRateCodesCn = map[string]struct{}{
"99YE2YK9UR": {},
"5Y9WH78GDR": {},
"KW44MY7SZN": {},
}
// HourlyRateCode is appended to a node sku
const HourlyRateCode = "6YS6EN2CT7"
const HourlyRateCodeCn = "Q7UJUT2CE6"
// volTypes are used to map between AWS UsageTypes and
// EBS volume types, as they would appear in K8s storage class
// name and the EC2 API.
var volTypes = map[string]string{
"EBS:VolumeUsage.gp2": "gp2",
"EBS:VolumeUsage.gp3": "gp3",
"EBS:VolumeUsage": "standard",
"EBS:VolumeUsage.sc1": "sc1",
"EBS:VolumeP-IOPS.piops": "io1",
"EBS:VolumeUsage.st1": "st1",
"EBS:VolumeUsage.piops": "io1",
"gp2": "EBS:VolumeUsage.gp2",
"gp3": "EBS:VolumeUsage.gp3",
"standard": "EBS:VolumeUsage",
"sc1": "EBS:VolumeUsage.sc1",
"io1": "EBS:VolumeUsage.piops",
"st1": "EBS:VolumeUsage.st1",
}
// locationToRegion maps AWS region names (As they come from Billing)
// to actual region identifiers
var locationToRegion = map[string]string{
"US East (Ohio)": "us-east-2",
"US East (N. Virginia)": "us-east-1",
"US West (N. California)": "us-west-1",
"US West (Oregon)": "us-west-2",
"Asia Pacific (Hong Kong)": "ap-east-1",
"Asia Pacific (Mumbai)": "ap-south-1",
"Asia Pacific (Osaka)": "ap-northeast-3",
"Asia Pacific (Seoul)": "ap-northeast-2",
"Asia Pacific (Singapore)": "ap-southeast-1",
"Asia Pacific (Sydney)": "ap-southeast-2",
"Asia Pacific (Tokyo)": "ap-northeast-1",
"Asia Pacific (Jakarta)": "ap-southeast-3",
"Canada (Central)": "ca-central-1",
"China (Beijing)": "cn-north-1",
"China (Ningxia)": "cn-northwest-1",
"EU (Frankfurt)": "eu-central-1",
"EU (Ireland)": "eu-west-1",
"EU (London)": "eu-west-2",
"EU (Paris)": "eu-west-3",
"EU (Stockholm)": "eu-north-1",
"EU (Milan)": "eu-south-1",
"South America (Sao Paulo)": "sa-east-1",
"Africa (Cape Town)": "af-south-1",
"AWS GovCloud (US-East)": "us-gov-east-1",
"AWS GovCloud (US-West)": "us-gov-west-1",
}
var loadedAWSSecret bool = false
var awsSecret *AWSAccessKey = nil
func (aws *AWS) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
return ""
}
// KubeAttrConversion maps the k8s labels for region to an aws region
func (aws *AWS) KubeAttrConversion(location, instanceType, operatingSystem string) string {
operatingSystem = strings.ToLower(operatingSystem)
region := locationToRegion[location]
return region + "," + instanceType + "," + operatingSystem
}
// AwsSpotFeedInfo contains configuration for spot feed integration
type AwsSpotFeedInfo struct {
BucketName string `json:"bucketName"`
Prefix string `json:"prefix"`
Region string `json:"region"`
AccountID string `json:"projectID"`
ServiceKeyName string `json:"serviceKeyName"`
ServiceKeySecret string `json:"serviceKeySecret"`
SpotLabel string `json:"spotLabel"`
SpotLabelValue string `json:"spotLabelValue"`
}
// AwsAthenaInfo contains configuration for CUR integration
// Deprecated: v1.104 Use AthenaConfiguration instead
type AwsAthenaInfo struct {
AthenaBucketName string `json:"athenaBucketName"`
AthenaRegion string `json:"athenaRegion"`
AthenaDatabase string `json:"athenaDatabase"`
AthenaCatalog string `json:"athenaCatalog"`
AthenaTable string `json:"athenaTable"`
AthenaWorkgroup string `json:"athenaWorkgroup"`
ServiceKeyName string `json:"serviceKeyName"`
ServiceKeySecret string `json:"serviceKeySecret"`
AccountID string `json:"projectID"`
MasterPayerARN string `json:"masterPayerARN"`
}
// IsEmpty returns true if all fields in config are empty, false if not.
func (aai *AwsAthenaInfo) IsEmpty() bool {
return aai.AthenaBucketName == "" &&
aai.AthenaRegion == "" &&
aai.AthenaDatabase == "" &&
aai.AthenaCatalog == "" &&
aai.AthenaTable == "" &&
aai.AthenaWorkgroup == "" &&
aai.ServiceKeyName == "" &&
aai.ServiceKeySecret == "" &&
aai.AccountID == "" &&
aai.MasterPayerARN == ""
}
// CreateConfig creates an AWS SDK V2 Config for the credentials that it contains
func (aai *AwsAthenaInfo) CreateConfig() (awsSDK.Config, error) {
keyProvider := AWSAccessKey{AccessKeyID: aai.ServiceKeyName, SecretAccessKey: aai.ServiceKeySecret}
cfg, err := keyProvider.CreateConfig(aai.AthenaRegion)
if err != nil {
return cfg, err
}
if aai.MasterPayerARN != "" {
// Create the credentials from AssumeRoleProvider to assume the role
// referenced by the roleARN.
stsSvc := sts.NewFromConfig(cfg)
creds := stscreds.NewAssumeRoleProvider(stsSvc, aai.MasterPayerARN)
cfg.Credentials = awsSDK.NewCredentialsCache(creds)
}
return cfg, nil
}
func (aws *AWS) GetManagementPlatform() (string, error) {
nodes := aws.Clientset.GetAllNodes()
if len(nodes) > 0 {
n := nodes[0]
version := n.Status.NodeInfo.KubeletVersion
if strings.Contains(version, "eks") {
return "eks", nil
}
if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
return "kops", nil
}
}
return "", nil
}
func (aws *AWS) GetConfig() (*models.CustomPricing, error) {
c, err := aws.Config.GetCustomPricingData()
if err != nil {
return nil, err
}
if c.Discount == "" {
c.Discount = "0%"
}
if c.NegotiatedDiscount == "" {
c.NegotiatedDiscount = "0%"
}
if c.ShareTenancyCosts == "" {
c.ShareTenancyCosts = models.DefaultShareTenancyCost
}
return c, nil
}
// GetAWSAccessKey generate an AWSAccessKey object from the config
func (aws *AWS) GetAWSAccessKey() (*AWSAccessKey, error) {
config, err := aws.GetConfig()
if err != nil {
return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
}
err = aws.ConfigureAuthWith(config)
if err != nil {
return nil, fmt.Errorf("error configuring Cloud Provider %s", err)
}
//Look for service key values in env if not present in config
if config.ServiceKeyName == "" {
config.ServiceKeyName = ocenv.GetAWSAccessKeyID()
}
if config.ServiceKeySecret == "" {
config.ServiceKeySecret = ocenv.GetAWSAccessKeySecret()
}
if config.ServiceKeyName == "" && config.ServiceKeySecret == "" {
log.DedupedInfof(1, "missing service key values for AWS cloud integration attempting to use service account integration")
}
return &AWSAccessKey{AccessKeyID: config.ServiceKeyName, SecretAccessKey: config.ServiceKeySecret}, nil
}
// GetAWSAthenaInfo generate an AWSAthenaInfo object from the config
func (aws *AWS) GetAWSAthenaInfo() (*AwsAthenaInfo, error) {
config, err := aws.GetConfig()
if err != nil {
return nil, fmt.Errorf("could not retrieve AwsAthenaInfo %s", err)
}
aak, err := aws.GetAWSAccessKey()
if err != nil {
return nil, err
}
return &AwsAthenaInfo{
AthenaBucketName: config.AthenaBucketName,
AthenaRegion: config.AthenaRegion,
AthenaDatabase: config.AthenaDatabase,
AthenaCatalog: config.AthenaCatalog,
AthenaTable: config.AthenaTable,
AthenaWorkgroup: config.AthenaWorkgroup,
ServiceKeyName: aak.AccessKeyID,
ServiceKeySecret: aak.SecretAccessKey,
AccountID: config.AthenaProjectID,
MasterPayerARN: config.MasterPayerARN,
}, nil
}
func (aws *AWS) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
return aws.Config.UpdateFromMap(cm)
}
func (aws *AWS) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
return aws.Config.Update(func(c *models.CustomPricing) error {
if updateType == SpotInfoUpdateType {
asfi := AwsSpotFeedInfo{}
err := json.NewDecoder(r).Decode(&asfi)
if err != nil {
return err
}
// If the sample nil service key name is set, zero it out so that it is not
// misinterpreted as a real service key.
if asfi.ServiceKeyName == "AKIXXX" {
asfi.ServiceKeyName = ""
}
c.ServiceKeyName = asfi.ServiceKeyName
if asfi.ServiceKeySecret != "" {
c.ServiceKeySecret = asfi.ServiceKeySecret
}
c.SpotDataPrefix = asfi.Prefix
c.SpotDataBucket = asfi.BucketName
c.ProjectID = asfi.AccountID
c.SpotDataRegion = asfi.Region
c.SpotLabel = asfi.SpotLabel
c.SpotLabelValue = asfi.SpotLabelValue
} else if updateType == AthenaInfoUpdateType {
aai := AwsAthenaInfo{}
err := json.NewDecoder(r).Decode(&aai)
if err != nil {
return err
}
// If the sample nil service key name is set, zero it out so that it is not
// misinterpreted as a real service key.
if aai.ServiceKeyName == "AKIXXX" {
aai.ServiceKeyName = ""
}
c.AthenaBucketName = aai.AthenaBucketName
c.AthenaRegion = aai.AthenaRegion
c.AthenaDatabase = aai.AthenaDatabase
c.AthenaCatalog = aai.AthenaCatalog
c.AthenaTable = aai.AthenaTable
c.AthenaWorkgroup = aai.AthenaWorkgroup
c.ServiceKeyName = aai.ServiceKeyName
if aai.ServiceKeySecret != "" {
c.ServiceKeySecret = aai.ServiceKeySecret
}
if aai.MasterPayerARN != "" {
c.MasterPayerARN = aai.MasterPayerARN
}
c.AthenaProjectID = aai.AccountID
} else {
a := make(map[string]interface{})
err := json.NewDecoder(r).Decode(&a)
if err != nil {
return err
}
for k, v := range a {
kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
vstr, ok := v.(string)
if ok {
err := models.SetCustomPricingField(c, kUpper, vstr)
if err != nil {
return fmt.Errorf("error setting custom pricing field: %w", err)
}
} else {
return fmt.Errorf("type error while updating config for %s", kUpper)
}
}
}
if ocenv.IsRemoteEnabled() {
err := utils.UpdateClusterMeta(ocenv.GetClusterID(), c.ClusterName)
if err != nil {
return err
}
}
return nil
})
}
type awsKey struct {
SpotLabelName string
SpotLabelValue string
Labels map[string]string
ProviderID string
}
func (k *awsKey) GPUCount() int {
return 0
}
func (k *awsKey) GPUType() string {
return ""
}
func (k *awsKey) ID() string {
for matchNum, group := range provIdRx.FindStringSubmatch(k.ProviderID) {
if matchNum == 2 {
return group
}
}
log.Warnf("Could not find instance ID in \"%s\"", k.ProviderID)
return ""
}
// Features will return a comma separated list of features for the given node
// If the node has a spot label, it will be included in the list
// Otherwise, the list include instance type, operating system, and the region
func (k *awsKey) Features() string {
instanceType, _ := util.GetInstanceType(k.Labels)
operatingSystem, _ := util.GetOperatingSystem(k.Labels)
region, _ := util.GetRegion(k.Labels)
key := region + "," + instanceType + "," + operatingSystem
usageType := k.getUsageType(k.Labels)
spotKey := key + "," + usageType
if l, ok := k.Labels["lifecycle"]; ok && l == "EC2Spot" {
return spotKey
}
if l, ok := k.Labels[k.SpotLabelName]; ok && l == k.SpotLabelValue {
return spotKey
}
if usageType == PreemptibleType {
return spotKey
}
return key
}
// getUsageType returns the usage type of the instance
// If the instance is a spot instance, it will return PreemptibleType
// Otherwise returns an empty string
func (k *awsKey) getUsageType(labels map[string]string) string {
if kLabel, ok := labels[k.SpotLabelName]; ok && kLabel == k.SpotLabelValue {
return PreemptibleType
}
if eksLabel, ok := labels[EKSCapacityTypeLabel]; ok && eksLabel == EKSCapacitySpotTypeValue {
// We currently write out spot instances as "preemptible" in the pricing data, so these need to match
return PreemptibleType
}
if kLabel, ok := labels[models.KarpenterCapacityTypeLabel]; ok && kLabel == models.KarpenterCapacitySpotTypeValue {
return PreemptibleType
}
return ""
}
func (aws *AWS) PVPricing(pvk models.PVKey) (*models.PV, error) {
pricing, ok := aws.Pricing[pvk.Features()]
if !ok {
log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
return &models.PV{}, nil
}
return pricing.PV, nil
}
type awsPVKey struct {
Labels map[string]string
StorageClassParameters map[string]string
StorageClassName string
Name string
DefaultRegion string
ProviderID string
}
func (aws *AWS) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
providerID := ""
if pv.Spec.AWSElasticBlockStore != nil {
providerID = pv.Spec.AWSElasticBlockStore.VolumeID
} else if pv.Spec.CSI != nil {
providerID = pv.Spec.CSI.VolumeHandle
}
return &awsPVKey{
Labels: pv.Labels,
StorageClassName: pv.Spec.StorageClassName,
StorageClassParameters: parameters,
Name: pv.Name,
DefaultRegion: defaultRegion,
ProviderID: providerID,
}
}
func (key *awsPVKey) ID() string {
return key.ProviderID
}
func (key *awsPVKey) GetStorageClass() string {
return key.StorageClassName
}
func (key *awsPVKey) Features() string {
storageClass, ok := key.StorageClassParameters["type"]
if !ok {
log.Debugf("storage class %s doesn't have a 'type' parameter", key.Name)
storageClass = getStorageClassTypeFrom(key.StorageClassParameters["provisioner"])
}
if storageClass == "standard" {
storageClass = "gp2"
}
// Storage class names are generally EBS volume types (gp2)
// Keys in Pricing are based on UsageTypes (EBS:VolumeType.gp2)
// Converts between the 2
region, ok := util.GetRegion(key.Labels)
if !ok {
region = key.DefaultRegion
}
class, ok := volTypes[storageClass]
if !ok {
log.Debugf("No voltype mapping for %s's storageClass: %s", key.Name, storageClass)
}
return region + "," + class
}
// getStorageClassTypeFrom returns the default ebs volume type for a provider provisioner
func getStorageClassTypeFrom(provisioner string) string {
// if there isn't any provided provisioner, return empty volume type
if provisioner == "" {
return ""
}
scType, ok := StorageClassProvisionerDefaults[provisioner]
if ok {
log.Debugf("using default voltype %s for provisioner %s", scType, provisioner)
return scType
}
return ""
}
// GetKey maps node labels to information needed to retrieve pricing data
func (aws *AWS) GetKey(labels map[string]string, n *v1.Node) models.Key {
return &awsKey{
SpotLabelName: aws.SpotLabelName,
SpotLabelValue: aws.SpotLabelValue,
Labels: labels,
ProviderID: labels["providerID"],
}
}
func (aws *AWS) isPreemptible(key string) bool {
s := strings.Split(key, ",")
if len(s) == 4 && s[3] == PreemptibleType {
return true
}
return false
}
func (aws *AWS) ClusterManagementPricing() (string, float64, error) {
return aws.clusterProvisioner, aws.clusterManagementPrice, nil
}
// Use the pricing data from the current region. Fall back to using all region data if needed.
func (aws *AWS) getRegionPricing(nodeList []*v1.Node) (*http.Response, string, error) {
pricingURL := "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/"
region := ""
multiregion := false
for _, n := range nodeList {
labels := n.GetLabels()
currentNodeRegion := ""
if r, ok := util.GetRegion(labels); ok {
currentNodeRegion = r
// Switch to Chinese endpoint for regions with the Chinese prefix
if strings.HasPrefix(currentNodeRegion, "cn-") {
pricingURL = "https://pricing.cn-north-1.amazonaws.com.cn/offers/v1.0/cn/AmazonEC2/current/"
}
} else {
multiregion = true // We weren't able to detect the node's region, so pull all data.
break
}
if region == "" { // We haven't set a region yet
region = currentNodeRegion
} else if region != "" && currentNodeRegion != region { // If two nodes have different regions here, we'll need to fetch all pricing data.
multiregion = true
break
}
}
// Chinese multiregion endpoint only contains data for Chinese regions and Chinese regions are excluded from other endpoint
if region != "" && !multiregion {
pricingURL += region + "/"
}
pricingURL += "index.json"
if ocenv.GetAWSPricingURL() != "" { // Allow override of pricing URL
pricingURL = ocenv.GetAWSPricingURL()
}
log.Infof("starting download of \"%s\", which is quite large ...", pricingURL)
resp, err := http.Get(pricingURL)
if err != nil {
log.Errorf("Bogus fetch of \"%s\": %v", pricingURL, err)
return nil, pricingURL, err
}
return resp, pricingURL, err
}
// SpotRefreshEnabled determines whether the required configs to run the spot feed query have been set up
func (aws *AWS) SpotRefreshEnabled() bool {
// Need a valid value for at least one of these fields to consider spot pricing as enabled
return len(aws.SpotDataBucket) != 0 || len(aws.SpotDataRegion) != 0 || len(aws.ProjectID) != 0
}
// DownloadPricingData fetches data from the AWS Pricing API
func (aws *AWS) DownloadPricingData() error {
aws.DownloadPricingDataLock.Lock()
defer aws.DownloadPricingDataLock.Unlock()
c, err := aws.Config.GetCustomPricingData()
if err != nil {
log.Errorf("Error downloading default pricing data: %s", err.Error())
}
aws.BaseCPUPrice = c.CPU
aws.BaseRAMPrice = c.RAM
aws.BaseGPUPrice = c.GPU
aws.BaseSpotCPUPrice = c.SpotCPU
aws.BaseSpotRAMPrice = c.SpotRAM
aws.BaseSpotGPUPrice = c.SpotGPU
aws.SpotLabelName = c.SpotLabel
aws.SpotLabelValue = c.SpotLabelValue
aws.SpotDataBucket = c.SpotDataBucket
aws.SpotDataPrefix = c.SpotDataPrefix
aws.ProjectID = c.ProjectID
aws.SpotDataRegion = c.SpotDataRegion
aws.ConfigureAuthWith(c) // load aws authentication from configuration or secret
if len(aws.SpotDataBucket) != 0 && len(aws.ProjectID) == 0 {
log.Warnf("using SpotDataBucket \"%s\" without ProjectID will not end well", aws.SpotDataBucket)
}
nodeList := aws.Clientset.GetAllNodes()
inputkeys := make(map[string]bool)
for _, n := range nodeList {
if _, ok := n.Labels["eks.amazonaws.com/nodegroup"]; ok {
aws.clusterManagementPrice = 0.10
aws.clusterProvisioner = "EKS"
} else if _, ok := n.Labels["kops.k8s.io/instancegroup"]; ok {
aws.clusterProvisioner = "KOPS"
}
labels := n.GetObjectMeta().GetLabels()
key := aws.GetKey(labels, n)
inputkeys[key.Features()] = true
}
pvList := aws.Clientset.GetAllPersistentVolumes()
storageClasses := aws.Clientset.GetAllStorageClasses()
storageClassMap := make(map[string]map[string]string)
for _, storageClass := range storageClasses {
params := storageClass.Parameters
if params != nil {
params["provisioner"] = storageClass.Provisioner
}
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
}
}
pvkeys := make(map[string]models.PVKey)
for _, pv := range pvList {
params, ok := storageClassMap[pv.Spec.StorageClassName]
if !ok {
log.Infof("Unable to find params for storageClassName %s, falling back to default pricing", pv.Spec.StorageClassName)
continue
}
key := aws.GetPVKey(pv, params, "")
pvkeys[key.Features()] = key
}
// RIDataRunning establishes the existence of the goroutine. Since it's possible we
// run multiple downloads, we don't want to create multiple go routines if one already exists
if !aws.RIDataRunning {
err = aws.GetReservationDataFromAthena() // Block until one run has completed.
if err != nil {
log.Errorf("Failed to lookup reserved instance data: %s", err.Error())
} else { // If we make one successful run, check on new reservation data every hour
go func() {
defer errs.HandlePanic()
aws.RIDataRunning = true
for {
log.Infof("Reserved Instance watcher running... next update in 1h")
time.Sleep(time.Hour)
err := aws.GetReservationDataFromAthena()
if err != nil {
log.Infof("Error updating RI data: %s", err.Error())
}
}
}()
}
}
if !aws.SavingsPlanDataRunning {
err = aws.GetSavingsPlanDataFromAthena()
if err != nil {
log.Errorf("Failed to lookup savings plan data: %s", err.Error())
} else {
go func() {
defer errs.HandlePanic()
aws.SavingsPlanDataRunning = true
for {
log.Infof("Savings Plan watcher running... next update in 1h")
time.Sleep(time.Hour)
err := aws.GetSavingsPlanDataFromAthena()
if err != nil {
log.Infof("Error updating Savings Plan data: %s", err.Error())
}
}
}()
}
}
aws.ValidPricingKeys = make(map[string]bool)
resp, pricingURL, err := aws.getRegionPricing(nodeList)
if err != nil {
return err
}
err = aws.populatePricing(resp, inputkeys)
if err != nil {
return err
}
log.Infof("Finished downloading \"%s\"", pricingURL)
if !aws.SpotRefreshEnabled() {
return nil
}
// Always run spot pricing refresh when performing download
aws.refreshSpotPricing(true)
// Only start a single refresh goroutine
if !aws.SpotRefreshRunning {
aws.SpotRefreshRunning = true
go func() {
defer errs.HandlePanic()
for {
log.Infof("Spot Pricing Refresh scheduled in %.2f minutes.", SpotRefreshDuration.Minutes())
time.Sleep(SpotRefreshDuration)
// Reoccurring refresh checks update times
aws.refreshSpotPricing(false)
}
}()
}
return nil
}
func (aws *AWS) populatePricing(resp *http.Response, inputkeys map[string]bool) error {
aws.Pricing = make(map[string]*AWSProductTerms)