-
Notifications
You must be signed in to change notification settings - Fork 519
/
provider.go
1407 lines (1241 loc) · 54.3 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 alibaba
import (
"errors"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/opencost/opencost/pkg/cloud/models"
"github.com/opencost/opencost/pkg/cloud/utils"
"github.com/opencost/opencost/pkg/clustercache"
"github.com/opencost/opencost/pkg/env"
"github.com/opencost/opencost/pkg/kubecost"
"github.com/opencost/opencost/pkg/log"
"github.com/opencost/opencost/pkg/util/fileutil"
"github.com/opencost/opencost/pkg/util/json"
"github.com/opencost/opencost/pkg/util/stringutil"
"golang.org/x/exp/slices"
v1 "k8s.io/api/core/v1"
)
const (
ALIBABA_ECS_PRODUCT_CODE = "ecs"
ALIBABA_ECS_VERSION = "2014-05-26"
ALIBABA_ECS_DOMAIN = "ecs.aliyuncs.com"
ALIBABA_DESCRIBE_PRICE_API_ACTION = "DescribePrice"
ALIBABA_DESCRIBE_DISK_API_ACTION = "DescribeDisks"
ALIBABA_INSTANCE_RESOURCE_TYPE = "instance"
ALIBABA_DISK_RESOURCE_TYPE = "disk"
ALIBABA_PAY_AS_YOU_GO_BILLING = "Pay-As-You-Go"
ALIBABA_SUBSCRIPTION_BILLING = "Subscription"
ALIBABA_PREEMPTIBLE_BILLING = "Preemptible"
ALIBABA_OPTIMIZE_KEYWORD = "optimize"
ALIBABA_NON_OPTIMIZE_KEYWORD = "nonoptimize"
ALIBABA_HOUR_PRICE_UNIT = "Hour"
ALIBABA_MONTH_PRICE_UNIT = "Month"
ALIBABA_YEAR_PRICE_UNIT = "Year"
ALIBABA_UNKNOWN_INSTANCE_FAMILY_TYPE = "unknown"
ALIBABA_NOT_SUPPORTED_INSTANCE_FAMILY_TYPE = "unsupported"
ALIBABA_DISK_CLOUD_ESSD_CATEGORY = "cloud_essd"
ALIBABA_DISK_CLOUD_CATEGORY = "cloud"
ALIBABA_DATA_DISK_CATEGORY = "data"
ALIBABA_SYSTEM_DISK_CATEGORY = "system"
ALIBABA_DATA_DISK_PREFIX = "DataDisk"
ALIBABA_PV_CLOUD_DISK_TYPE = "CloudDisk"
ALIBABA_PV_NAS_TYPE = "NAS"
ALIBABA_PV_OSS_TYPE = "OSS"
ALIBABA_DEFAULT_DATADISK_SIZE = "2000"
ALIBABA_DISK_TOPOLOGY_REGION_LABEL = "topology.diskplugin.csi.alibabacloud.com/region"
ALIBABA_DISK_TOPOLOGY_ZONE_LABEL = "topology.diskplugin.csi.alibabacloud.com/zone"
)
var (
// Regular expression to get the numerical value of PV suffix with GiB from *v1.PersistentVolume.
sizeRegEx = regexp.MustCompile("(.*?)Gi")
)
// Variable to keep track of instance families that fail in DescribePrice API due improper defaulting of systemDisk if the information is not available
var alibabaDefaultToCloudEssd = []string{"g6e", "r6e", "r7", "g7", "g7a", "r7a"}
// Why predefined and dependency on code? Can be converted to API call - https://www.alibabacloud.com/help/en/elastic-compute-service/latest/regions-describeregions
var alibabaRegions = []string{
"cn-qingdao",
"cn-beijing",
"cn-zhangjiakou",
"cn-huhehaote",
"cn-wulanchabu",
"cn-hangzhou",
"cn-shanghai",
"cn-nanjing",
"cn-fuzhou",
"cn-shenzhen",
"cn-guangzhou",
"cn-chengdu",
"cn-hongkong",
"ap-southeast-1",
"ap-southeast-2",
"ap-southeast-3",
"ap-southeast-5",
"ap-southeast-6",
"ap-southeast-7",
"ap-south-1",
"ap-northeast-1",
"ap-northeast-2",
"us-west-1",
"us-east-1",
"eu-central-1",
"me-east-1",
}
// To-Do: Convert to API call - https://www.alibabacloud.com/help/en/elastic-compute-service/latest/describeinstancetypefamilies
// Also first pass only completely tested pricing API for General pupose instances families & memory optimized instance families
var alibabaInstanceFamilies = []string{
"g7",
"g7a",
"g6e",
"g6",
"g5",
"sn2",
"sn2ne",
"r7",
"r7a",
"r6e",
"r6a",
"r6",
"r5",
"se1",
"se1ne",
"re6",
"re6p",
"re4",
"se1",
}
// AlibabaInfo contains configuration for Alibaba's CUR integration
// Deprecated: v1.104 Use BOAConfiguration instead
type AlibabaInfo struct {
AlibabaClusterRegion string `json:"ClusterRegion"`
AlibabaServiceKeyName string `json:"serviceKeyName"`
AlibabaServiceKeySecret string `json:"serviceKeySecret"`
AlibabaAccountID string `json:"accountID"`
}
// IsEmpty returns true if all fields in config are empty, false if not.
func (ai *AlibabaInfo) IsEmpty() bool {
return ai.AlibabaClusterRegion == "" &&
ai.AlibabaServiceKeyName == "" &&
ai.AlibabaServiceKeySecret == "" &&
ai.AlibabaAccountID == ""
}
// AlibabaAccessKey holds Alibaba credentials parsing from the service-key.json file.
// Deprecated: v1.104 Use AccessKey instead
type AlibabaAccessKey struct {
AccessKeyID string `json:"alibaba_access_key_id"`
SecretAccessKey string `json:"alibaba_secret_access_key"`
}
// Slim Version of k8s disk assigned to a node or PV.
type SlimK8sDisk struct {
DiskType string
RegionID string
PriceUnit string
SizeInGiB string
DiskCategory string
PerformanceLevel string
ProviderID string
StorageClass string
}
func NewSlimK8sDisk(diskType, regionID, priceUnit, diskCategory, performanceLevel, providerID, storageClass, sizeInGiB string) *SlimK8sDisk {
return &SlimK8sDisk{
DiskType: diskType,
RegionID: regionID,
PriceUnit: priceUnit,
SizeInGiB: sizeInGiB,
DiskCategory: diskCategory,
PerformanceLevel: performanceLevel,
ProviderID: providerID,
StorageClass: storageClass,
}
}
// Slim version of a k8s v1.node just to pass along the object of this struct instead of constant getting the labels from within v1.Node & unit testing.
type SlimK8sNode struct {
InstanceType string
RegionID string
PriceUnit string
MemorySizeInKiB string // TO-DO : Possible to convert to float?
IsIoOptimized bool
OSType string
ProviderID string
SystemDisk *SlimK8sDisk
InstanceTypeFamily string // Bug in DescribePrice, doesn't default to enhanced type correctly and you get an error in DescribePrice to get around need the family of the InstanceType.
}
func NewSlimK8sNode(instanceType, regionID, priceUnit, memorySizeInKiB, osType, providerID, instanceTypeFamily string, isIOOptimized bool, systemDiskInfo *SlimK8sDisk) *SlimK8sNode {
return &SlimK8sNode{
InstanceType: instanceType,
RegionID: regionID,
PriceUnit: priceUnit,
MemorySizeInKiB: memorySizeInKiB,
IsIoOptimized: isIOOptimized,
OSType: osType,
SystemDisk: systemDiskInfo,
ProviderID: providerID,
InstanceTypeFamily: instanceTypeFamily,
}
}
// AlibabaNodeAttributes represents metadata about the Node in its pricing information.
// Basic Attributes needed atleast to get the key, Some attributes from k8s Node response
// be populated directly into *Node object.
type AlibabaNodeAttributes struct {
// InstanceType represents the type of instance.
InstanceType string `json:"instanceType"`
// MemorySizeInKiB represents the size of memory of instance.
MemorySizeInKiB string `json:"memorySizeInKiB"`
// IsIoOptimized represents the if instance is I/O optimized.
IsIoOptimized bool `json:"isIoOptimized"`
// OSType represents the OS installed in the Instance.
OSType string `json:"osType"`
// SystemDiskCategory represents the exact category of the system disk attached to the node.
SystemDiskCategory string `json:"systemDiskCategory"`
// SystemDiskSizeInGiB represents the size of the system disk attached to the node.
SystemDiskSizeInGiB string `json:"systemDiskSizeInGiB"`
// SystemDiskPerformanceLevel represents the performance level of the system disk attached to the node.
SystemDiskPerformanceLevel string `json:"systemPerformanceLevel"`
}
func NewAlibabaNodeAttributes(node *SlimK8sNode) *AlibabaNodeAttributes {
if node == nil {
return nil
}
var diskCategory, sizeInGiB, performanceLevel string
if node.SystemDisk != nil {
diskCategory = node.SystemDisk.DiskCategory
sizeInGiB = node.SystemDisk.SizeInGiB
performanceLevel = node.SystemDisk.PerformanceLevel
}
return &AlibabaNodeAttributes{
InstanceType: node.InstanceType,
MemorySizeInKiB: node.MemorySizeInKiB,
IsIoOptimized: node.IsIoOptimized,
OSType: node.OSType,
SystemDiskCategory: diskCategory,
SystemDiskSizeInGiB: sizeInGiB,
SystemDiskPerformanceLevel: performanceLevel,
}
}
// AlibabaPVAttributes represents metadata the PV in its pricing information.
// Basic Attributes needed atleast to get the keys. Some attributes from k8s PV response
// be populated directly into *PV object.
type AlibabaPVAttributes struct {
// PVType can be Cloud Disk, NetWork Attached Storage(NAS) or Object Storage Service (OSS).
// Represents the way the PV was attached
PVType string `json:"pvType"`
// PVSubType represent the sub category of PVType. This is Data in case of Cloud Disk.
PVSubType string `json:"pvSubType"`
// Example for PVCategory with cloudDisk PVType are cloud, cloud_efficiency, cloud_ssd,
// ephemeral_ssd and cloud_essd. If not present returns empty.
PVCategory string `json:"pvCategory"`
// Example for PerformanceLevel with cloudDisk PVType are PL0,PL1,PL2 &PL3. If not present returns empty.
PVPerformanceLevel string `json:"performanceLevel"`
// The Size of the PV in terms of GiB
SizeInGiB string `json:"sizeInGiB"`
}
// TO-Do: next iteration of Alibaba provider support NetWork Attached Storage(NAS) and Object Storage Service (OSS type PVs).
// Currently defaulting to cloudDisk with provision to add work in future.
func NewAlibabaPVAttributes(disk *SlimK8sDisk) *AlibabaPVAttributes {
if disk == nil {
return nil
}
return &AlibabaPVAttributes{
PVType: ALIBABA_PV_CLOUD_DISK_TYPE,
PVSubType: disk.DiskType,
PVCategory: disk.DiskCategory,
PVPerformanceLevel: disk.PerformanceLevel,
SizeInGiB: disk.SizeInGiB,
}
}
// Stage 1 support will be Pay-As-You-Go with HourlyPrice equal to TradePrice with PriceUnit as Hour
// TO-DO: Subscription and Premptible support, Information can be gathered from describing instance for subscription type
// and spotprice can be gather from DescribeSpotPriceHistory API.
// TO-DO: how would you calculate hourly price for subscription type, is it PRICE_YEARLY/HOURS_IN_THE_YEAR|MONTH?
type AlibabaPricingDetails struct {
// Represents hourly price for the given Alibaba cloud Product.
HourlyPrice float32 `json:"hourlyPrice"`
// Represents the unit in which Alibaba Product is billed can be Hour, Month or Year based on the billingMethod.
PriceUnit string `json:"priceUnit"`
// Original Price paid to acquire the Alibaba Product.
TradePrice float32 `json:"tradePrice"`
// Represents the currency unit of the price for billing Alibaba Product.
CurrencyCode string `json:"currencyCode"`
}
func NewAlibabaPricingDetails(hourlyPrice float32, priceUnit string, tradePrice float32, currencyCode string) *AlibabaPricingDetails {
return &AlibabaPricingDetails{
HourlyPrice: hourlyPrice,
PriceUnit: priceUnit,
TradePrice: tradePrice,
CurrencyCode: currencyCode,
}
}
// AlibabaPricingTerms can have three types of supported billing method Pay-As-You-Go, Subscription and Premptible
type AlibabaPricingTerms struct {
BillingMethod string `json:"billingMethod"`
PricingDetails *AlibabaPricingDetails `json:"pricingDetails"`
}
func NewAlibabaPricingTerms(billingMethod string, pricingDetails *AlibabaPricingDetails) *AlibabaPricingTerms {
return &AlibabaPricingTerms{
BillingMethod: billingMethod,
PricingDetails: pricingDetails,
}
}
// Alibaba Pricing struct carry the Attributes and pricing information for Node or PV
type AlibabaPricing struct {
NodeAttributes *AlibabaNodeAttributes
PVAttributes *AlibabaPVAttributes
PricingTerms *AlibabaPricingTerms
Node *models.Node
PV *models.PV
}
// Alibaba cloud's Provider struct
type Alibaba struct {
// Data to store Alibaba cloud's pricing struct, key in the map represents exact match to
// node.features() or pv.features for easy lookup
Pricing map[string]*AlibabaPricing
// Lock Needed to provide thread safe
DownloadPricingDataLock sync.RWMutex
Clientset clustercache.ClusterCache
Config models.ProviderConfig
ServiceAccountChecks *models.ServiceAccountChecks
ClusterAccountId string
ClusterRegion string
// The following fields are unexported because of avoiding any leak of secrets of these keys.
// Alibaba Access key used specifically in signer interface used to sign API calls
accessKey *credentials.AccessKeyCredential
// Map of regionID to sdk.client to call API for that region
clients map[string]*sdk.Client
}
// GetAlibabaAccessKey return the Access Key used to interact with the Alibaba cloud, if not set it
// set it first by looking at env variables else load it from secret files.
func (alibaba *Alibaba) GetAlibabaAccessKey() (*credentials.AccessKeyCredential, error) {
if alibaba.accessKeyisLoaded() {
return alibaba.accessKey, nil
}
config, err := alibaba.GetConfig()
if err != nil {
return nil, fmt.Errorf("error getting the default config for Alibaba Cloud provider: %w", err)
}
if config.AlibabaServiceKeyName == "" {
config.AlibabaServiceKeyName = env.GetAlibabaAccessKeyID()
}
if config.AlibabaServiceKeySecret == "" {
config.AlibabaServiceKeySecret = env.GetAlibabaAccessKeySecret()
}
if config.AlibabaServiceKeyName == "" && config.AlibabaServiceKeySecret == "" {
log.Debugf("missing service key values for Alibaba cloud integration attempting to use service account integration")
err := alibaba.loadAlibabaAuthSecretAndSetEnv(true)
if err != nil {
return nil, fmt.Errorf("unable to set the Alibaba Cloud key/secret from config file %w", err)
}
config.AlibabaServiceKeyName = env.GetAlibabaAccessKeyID()
config.AlibabaServiceKeySecret = env.GetAlibabaAccessKeySecret()
}
if config.AlibabaServiceKeyName == "" && config.AlibabaServiceKeySecret == "" {
return nil, fmt.Errorf("failed to get the access key for the current alibaba account")
}
// At this point either user is using the alibaba key and secret from secret passed in helm config if not he will use the secret that is passed in custom pricing
// There's no check at this time for if the custom pricing key and secret is valid and that's on the user else there will be errors recorded.
// Key and secret passed in config will supersede key and secret passed while installing Closed source helm chart.
alibaba.accessKey = &credentials.AccessKeyCredential{AccessKeyId: config.AlibabaServiceKeyName, AccessKeySecret: config.AlibabaServiceKeySecret}
return alibaba.accessKey, nil
}
func (alibaba *Alibaba) GetAlibabaCloudInfo() (*AlibabaInfo, error) {
config, err := alibaba.GetConfig()
if err != nil {
return nil, fmt.Errorf("could not retrieve AlibabaCloudInfo %s", err)
}
aak, err := alibaba.GetAlibabaAccessKey()
if err != nil {
return nil, err
}
return &AlibabaInfo{
AlibabaClusterRegion: config.AlibabaClusterRegion,
AlibabaServiceKeyName: aak.AccessKeyId,
AlibabaServiceKeySecret: aak.AccessKeySecret,
AlibabaAccountID: config.ProjectID,
}, nil
}
// DownloadPricingData satisfies the provider interface and downloads the prices for Node instances and PVs.
func (alibaba *Alibaba) DownloadPricingData() error {
alibaba.DownloadPricingDataLock.Lock()
defer alibaba.DownloadPricingDataLock.Unlock()
var aak *credentials.AccessKeyCredential
var err error
if !alibaba.accessKeyisLoaded() {
aak, err = alibaba.GetAlibabaAccessKey()
if err != nil {
return fmt.Errorf("unable to get the access key information: %w", err)
}
} else {
aak = alibaba.accessKey
}
c, err := alibaba.Config.GetCustomPricingData()
if err != nil {
return fmt.Errorf("error downloading default pricing data: %w", err)
}
// Get all the nodes from Alibaba cluster.
nodeList := alibaba.Clientset.GetAllNodes()
var client *sdk.Client
var signer *signers.AccessKeySigner
var ok bool
var lookupKey string
alibaba.clients = make(map[string]*sdk.Client)
alibaba.Pricing = make(map[string]*AlibabaPricing)
for _, node := range nodeList {
pricingObj := &AlibabaPricing{}
slimK8sNode := generateSlimK8sNodeFromV1Node(node)
if client, ok = alibaba.clients[slimK8sNode.RegionID]; !ok {
client, err = sdk.NewClientWithAccessKey(slimK8sNode.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
if err != nil {
return fmt.Errorf("unable to initiate alibaba cloud sdk client for region %s : %w", slimK8sNode.RegionID, err)
}
alibaba.clients[slimK8sNode.RegionID] = client
}
signer = signers.NewAccessKeySigner(aak)
// Adjust the system Disk information of a Node by retrieving the details of associated disk. If unable to retrieve set it to empty
// system disk to pass through and use defaults with Alibaba pricing API.
instanceID := getInstanceIDFromProviderID(slimK8sNode.ProviderID)
slimK8sNode.SystemDisk = getSystemDiskInfoOfANode(instanceID, slimK8sNode.RegionID, client, signer)
lookupKey, err = determineKeyForPricing(slimK8sNode)
if err != nil {
return fmt.Errorf("unable to determine key for pricing: %w", err)
}
if _, ok := alibaba.Pricing[lookupKey]; ok {
log.Debugf("Pricing information for node with same features %s already exists hence skipping", lookupKey)
continue
}
pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sNode, signer, c)
if err != nil {
return fmt.Errorf("failed to create pricing information for node with type %s with error: %w", slimK8sNode.InstanceType, err)
}
alibaba.Pricing[lookupKey] = pricingObj
}
// set the first occurrence of region from the node
if alibaba.ClusterRegion == "" {
for _, node := range nodeList {
if regionID, ok := node.Labels["topology.kubernetes.io/region"]; ok {
alibaba.ClusterRegion = regionID
break
}
}
}
// PV pricing for only Cloud Disk for now.
// TO-DO: Support both NAS(Network Attached storage) and OSS(Object Storage Service) type PVs
pvList := alibaba.Clientset.GetAllPersistentVolumes()
for _, pv := range pvList {
pvRegion := determinePVRegion(pv)
if pvRegion == "" {
pvRegion = alibaba.ClusterRegion
}
pricingObj := &AlibabaPricing{}
slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, pvRegion)
lookupKey, err = determineKeyForPricing(slimK8sDisk)
if err != nil {
return fmt.Errorf("unable to determine key for pricing: %w", err)
}
if _, ok := alibaba.Pricing[lookupKey]; ok {
log.Debugf("Pricing information for pv with same features %s already exists hence skipping", lookupKey)
continue
}
if client, ok = alibaba.clients[slimK8sDisk.RegionID]; !ok {
client, err = sdk.NewClientWithAccessKey(slimK8sDisk.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
if err != nil {
return fmt.Errorf("unable to initiate alibaba cloud sdk client for region %s : %w", slimK8sDisk.RegionID, err)
}
alibaba.clients[slimK8sDisk.RegionID] = client
}
signer = signers.NewAccessKeySigner(aak)
pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sDisk, signer, c)
if err != nil {
return fmt.Errorf("failed to create pricing information for pv with category %s with error: %w", slimK8sDisk.DiskCategory, err)
}
alibaba.Pricing[lookupKey] = pricingObj
}
return nil
}
// AllNodePricing returns all the pricing data for all nodes and pvs
func (alibaba *Alibaba) AllNodePricing() (interface{}, error) {
alibaba.DownloadPricingDataLock.RLock()
defer alibaba.DownloadPricingDataLock.RUnlock()
return alibaba.Pricing, nil
}
// NodePricing gives pricing information of a specific node given by the key
func (alibaba *Alibaba) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
alibaba.DownloadPricingDataLock.RLock()
defer alibaba.DownloadPricingDataLock.RUnlock()
// Get node features for the key
keyFeature := key.Features()
meta := models.PricingMetadata{}
pricing, ok := alibaba.Pricing[keyFeature]
if !ok {
log.Errorf("Node pricing information not found for node with feature: %s", keyFeature)
return nil, meta, fmt.Errorf("Node pricing information not found for node with feature: %s letting it use default values", keyFeature)
}
log.Debugf("returning the node price for the node with feature: %s", keyFeature)
returnNode := pricing.Node
return returnNode, meta, nil
}
// PVPricing gives a pricing information of a specific PV given by PVkey
func (alibaba *Alibaba) PVPricing(pvk models.PVKey) (*models.PV, error) {
alibaba.DownloadPricingDataLock.RLock()
defer alibaba.DownloadPricingDataLock.RUnlock()
keyFeature := pvk.Features()
pricing, ok := alibaba.Pricing[keyFeature]
if !ok {
log.Errorf("Persistent Volume pricing not found for PV with feature: %s", keyFeature)
return nil, fmt.Errorf("Persistent Volume pricing not found for PV with feature: %s letting it use default values", keyFeature)
}
log.Debugf("returning the PV price for the node with feature: %s", keyFeature)
return pricing.PV, nil
}
// Inter zone and Inter region network cost are defaulted based on https://www.alibabacloud.com/help/en/cloud-data-transmission/latest/cross-region-data-transfers
// Internet cost is default based on https://www.alibabacloud.com/help/en/elastic-compute-service/latest/public-bandwidth to $0.123
func (alibaba *Alibaba) NetworkPricing() (*models.Network, error) {
cpricing, err := alibaba.Config.GetCustomPricingData()
if err != nil {
return nil, err
}
znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
if err != nil {
return nil, err
}
rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
if err != nil {
return nil, err
}
inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
if err != nil {
return nil, err
}
return &models.Network{
ZoneNetworkEgressCost: znec,
RegionNetworkEgressCost: rnec,
InternetNetworkEgressCost: inec,
}, nil
}
// Alibaba loadbalancer has three different types https://www.alibabacloud.com/product/server-load-balancer,
// defaulted price to classic load balancer https://www.alibabacloud.com/help/en/server-load-balancer/latest/pay-as-you-go.
func (alibaba *Alibaba) LoadBalancerPricing() (*models.LoadBalancer, error) {
cpricing, err := alibaba.Config.GetCustomPricingData()
if err != nil {
return nil, err
}
lbPricing, err := strconv.ParseFloat(cpricing.DefaultLBPrice, 64)
if err != nil {
return nil, err
}
return &models.LoadBalancer{
Cost: lbPricing,
}, nil
}
func (alibaba *Alibaba) GetConfig() (*models.CustomPricing, error) {
c, err := alibaba.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
}
// Load once and cache the result (even on failure). This is an install time secret, so
// we don't expect the secret to change. If it does, however, we can force reload using
// the input parameter.
func (alibaba *Alibaba) loadAlibabaAuthSecretAndSetEnv(force bool) error {
if !force && alibaba.accessKeyisLoaded() {
return nil
}
exists, err := fileutil.FileExists(models.AuthSecretPath)
if !exists || err != nil {
return fmt.Errorf("failed to locate service account file: %s with err: %w", models.AuthSecretPath, err)
}
result, err := os.ReadFile(models.AuthSecretPath)
if err != nil {
return fmt.Errorf("failed to read service account file: %s with err: %w", models.AuthSecretPath, err)
}
var ak *AlibabaAccessKey
err = json.Unmarshal(result, &ak)
if err != nil {
return fmt.Errorf("failed to unmarshall access key id and access key secret with err: %w", err)
}
err = env.Set(env.AlibabaAccessKeyIDEnvVar, ak.AccessKeyID)
if err != nil {
return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeyIDEnvVar, err)
}
err = env.Set(env.AlibabaAccessKeySecretEnvVar, ak.SecretAccessKey)
if err != nil {
return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeySecretEnvVar, err)
}
alibaba.accessKey = &credentials.AccessKeyCredential{
AccessKeyId: ak.AccessKeyID,
AccessKeySecret: ak.SecretAccessKey,
}
return nil
}
// Regions returns a current supported list of Alibaba regions
func (alibaba *Alibaba) Regions() []string {
regionOverrides := env.GetRegionOverrideList()
if len(regionOverrides) > 0 {
log.Debugf("Overriding Alibaba regions with configured region list: %+v", regionOverrides)
return regionOverrides
}
return alibabaRegions
}
// ClusterInfo returns information about Alibaba Cloud cluster, as provided by metadata.
func (alibaba *Alibaba) ClusterInfo() (map[string]string, error) {
c, err := alibaba.GetConfig()
if err != nil {
return nil, fmt.Errorf("failed to getConfig with err: %w", err)
}
var clusterName string
if c.ClusterName != "" {
clusterName = c.ClusterName
}
// Set it to environment clusterID if not set at this point
if clusterName == "" {
clusterName = env.GetClusterID()
}
m := make(map[string]string)
m["name"] = clusterName
m["provider"] = kubecost.AlibabaProvider
m["project"] = alibaba.ClusterAccountId
m["region"] = alibaba.ClusterRegion
m["id"] = env.GetClusterID()
return m, nil
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) GetAddresses() ([]byte, error) {
return nil, nil
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) GetDisks() ([]byte, error) {
return nil, nil
}
func (alibaba *Alibaba) GetOrphanedResources() ([]models.OrphanedResource, error) {
return nil, errors.New("not implemented")
}
func (alibaba *Alibaba) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
return alibaba.Config.Update(func(c *models.CustomPricing) error {
if updateType != "" {
return fmt.Errorf("UpdateConfig for Alibaba Provider doesn't support updateType %s at this time", updateType)
} 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 env.IsRemoteEnabled() {
err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
if err != nil {
return err
}
}
return nil
})
}
func (alibaba *Alibaba) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
return alibaba.Config.UpdateFromMap(cm)
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) GetManagementPlatform() (string, error) {
return "", nil
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
return ""
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) ServiceAccountStatus() *models.ServiceAccountStatus {
return &models.ServiceAccountStatus{}
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) PricingSourceStatus() map[string]*models.PricingSource {
return map[string]*models.PricingSource{}
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) ClusterManagementPricing() (string, float64, error) {
return "", 0.0, nil
}
// Will look at this in Next PR if needed
func (alibaba *Alibaba) CombinedDiscountForNode(string, bool, float64, float64) float64 {
return 0.0
}
func (alibaba *Alibaba) accessKeyisLoaded() bool {
if alibaba.accessKey == nil {
return false
}
if alibaba.accessKey.AccessKeyId == "" {
return false
}
if alibaba.accessKey.AccessKeySecret == "" {
return false
}
return true
}
type AlibabaNodeKey struct {
ProviderID string
RegionID string
InstanceType string
OSType string
OptimizedKeyword string //If IsIoOptimized is true use the word optimize in the Node key and if its not optimized use the word nonoptimize
SystemDiskCategory string
SystemDiskSizeInGiB string
SystemDiskPerformanceLevel string
}
func NewAlibabaNodeKey(node *SlimK8sNode, optimizedKeyword, systemDiskCategory, systemDiskSizeInGiB, systemDiskPerfromanceLevel string) *AlibabaNodeKey {
var providerID, regionID, instanceType, osType string
if node != nil {
providerID = node.ProviderID
regionID = node.RegionID
instanceType = node.InstanceType
osType = node.OSType
}
return &AlibabaNodeKey{
ProviderID: providerID,
RegionID: regionID,
InstanceType: instanceType,
OSType: osType,
OptimizedKeyword: optimizedKeyword,
SystemDiskCategory: systemDiskCategory,
SystemDiskSizeInGiB: systemDiskSizeInGiB,
SystemDiskPerformanceLevel: systemDiskPerfromanceLevel,
}
}
func (alibabaNodeKey *AlibabaNodeKey) ID() string {
return alibabaNodeKey.ProviderID
}
func (alibabaNodeKey *AlibabaNodeKey) Features() string {
keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaNodeKey.RegionID, alibabaNodeKey.InstanceType, alibabaNodeKey.OSType,
alibabaNodeKey.OptimizedKeyword, alibabaNodeKey.SystemDiskCategory, alibabaNodeKey.SystemDiskSizeInGiB, alibabaNodeKey.SystemDiskPerformanceLevel})
return strings.Join(keyLookup, "::")
}
func (alibabaNodeKey *AlibabaNodeKey) GPUType() string {
return ""
}
func (alibabaNodeKey *AlibabaNodeKey) GPUCount() int {
return 0
}
// Get's the key for the k8s node input
func (alibaba *Alibaba) GetKey(mapValue map[string]string, node *v1.Node) models.Key {
slimK8sNode := generateSlimK8sNodeFromV1Node(node)
var aak *credentials.AccessKeyCredential
var err error
var ok bool
var client *sdk.Client
var signer *signers.AccessKeySigner
optimizedKeyword := ""
if slimK8sNode.IsIoOptimized {
optimizedKeyword = ALIBABA_OPTIMIZE_KEYWORD
} else {
optimizedKeyword = ALIBABA_NON_OPTIMIZE_KEYWORD
}
var diskCategory, diskSizeInGiB, diskPerformanceLevel string
if !alibaba.accessKeyisLoaded() {
aak, err = alibaba.GetAlibabaAccessKey()
if err != nil {
log.Warnf("unable to set the signer for node with providerID %s to retrieve the key skipping SystemDisk Retrieval with err: %v", slimK8sNode.ProviderID, err)
return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
}
} else {
aak = alibaba.accessKey
}
signer = signers.NewAccessKeySigner(aak)
if aak == nil {
log.Warnf("unable to retrieve the Alibaba API keys for node with providerID %s hence skipping SystemDisk Retrieval", slimK8sNode.ProviderID)
return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
}
if client, ok = alibaba.clients[slimK8sNode.RegionID]; !ok {
client, err = sdk.NewClientWithAccessKey(slimK8sNode.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
if err != nil {
log.Warnf("unable to set the client for node with providerID %s to retrieve the key skipping SystemDisk Retrieval with err: %v", slimK8sNode.ProviderID, err)
return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
}
alibaba.clients[slimK8sNode.RegionID] = client
}
instanceID := getInstanceIDFromProviderID(slimK8sNode.ProviderID)
slimK8sNode.SystemDisk = getSystemDiskInfoOfANode(instanceID, slimK8sNode.RegionID, client, signer)
if slimK8sNode.SystemDisk != nil {
diskCategory = slimK8sNode.SystemDisk.DiskCategory
diskSizeInGiB = slimK8sNode.SystemDisk.SizeInGiB
diskPerformanceLevel = slimK8sNode.SystemDisk.PerformanceLevel
}
return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
}
type AlibabaPVKey struct {
ProviderID string
RegionID string
PVType string
PVSubType string
PVCategory string
PVPerformaceLevel string
StorageClassName string
SizeInGiB string
}
func (alibaba *Alibaba) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
regionID := defaultRegion
// If default Region is not passed default it to cluster region ID.
if defaultRegion == "" {
regionID = alibaba.ClusterRegion
}
slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, defaultRegion)
return &AlibabaPVKey{
ProviderID: slimK8sDisk.ProviderID,
RegionID: regionID,
PVType: ALIBABA_PV_CLOUD_DISK_TYPE,
PVSubType: slimK8sDisk.DiskType,
PVCategory: slimK8sDisk.DiskCategory,
PVPerformaceLevel: slimK8sDisk.PerformanceLevel,
StorageClassName: pv.Spec.StorageClassName,
SizeInGiB: slimK8sDisk.SizeInGiB,
}
}
func (alibabaPVKey *AlibabaPVKey) Features() string {
keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaPVKey.RegionID, alibabaPVKey.PVSubType, alibabaPVKey.PVCategory, alibabaPVKey.PVPerformaceLevel, alibabaPVKey.SizeInGiB})
return strings.Join(keyLookup, "::")
}
func (alibabaPVKey *AlibabaPVKey) ID() string {
return alibabaPVKey.ProviderID
}
// Get storage class information for PV.
func (alibabaPVKey *AlibabaPVKey) GetStorageClass() string {
return alibabaPVKey.StorageClassName
}
// Helper functions for alibabaprovider.go
// createDescribePriceACSRequest creates the HTTP GET request for the required resources' Price information,
// When supporting subscription and Premptible resources this HTTP call needs to be modified with PriceUnit information
// When supporting different new type of instances like Compute Optimized, Memory Optimized etc make sure you add the instance type
// in unit test and check if it works or not to create the ack request and processDescribePriceAndCreateAlibabaPricing function
// else more parameters need to be pulled from kubernetes node response or gather information from elsewhere and function modified.
func createDescribePriceACSRequest(i interface{}) (*requests.CommonRequest, error) {
request := requests.NewCommonRequest()
request.Method = requests.GET
request.Product = ALIBABA_ECS_PRODUCT_CODE
request.Domain = ALIBABA_ECS_DOMAIN
request.Version = ALIBABA_ECS_VERSION
request.Scheme = requests.HTTPS
request.ApiName = ALIBABA_DESCRIBE_PRICE_API_ACTION
switch i.(type) {
case *SlimK8sNode:
node := i.(*SlimK8sNode)
request.QueryParams["RegionId"] = node.RegionID
request.QueryParams["ResourceType"] = ALIBABA_INSTANCE_RESOURCE_TYPE
request.QueryParams["InstanceType"] = node.InstanceType
request.QueryParams["PriceUnit"] = node.PriceUnit
if node.SystemDisk != nil {
// Only if the required information is present it should be overridden else default it via the API
if node.SystemDisk.DiskCategory != "" {
request.QueryParams["SystemDisk.Category"] = node.SystemDisk.DiskCategory
}
if node.SystemDisk.SizeInGiB != "" {
request.QueryParams["SystemDisk.Size"] = node.SystemDisk.SizeInGiB
}
if node.SystemDisk.PerformanceLevel != "" {
request.QueryParams["SystemDisk.PerformanceLevel"] = node.SystemDisk.PerformanceLevel
}
} else {
// When System Disk information is not available for instance family g6e, r7 and r6e the defaults in
// DescribePrice dont default rightly to cloud_essd for these instances.
if slices.Contains(alibabaDefaultToCloudEssd, node.InstanceTypeFamily) {
request.QueryParams["SystemDisk.Category"] = ALIBABA_DISK_CLOUD_ESSD_CATEGORY
}
}
request.TransToAcsRequest()
return request, nil
case *SlimK8sDisk:
disk := i.(*SlimK8sDisk)
request.QueryParams["RegionId"] = disk.RegionID
request.QueryParams["PriceUnit"] = disk.PriceUnit
request.QueryParams["ResourceType"] = ALIBABA_DISK_RESOURCE_TYPE