provider.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. package alibaba
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
  13. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
  14. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers"
  15. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  16. "github.com/opencost/opencost/pkg/cloud/models"
  17. "github.com/opencost/opencost/pkg/cloud/utils"
  18. "github.com/opencost/opencost/pkg/clustercache"
  19. "github.com/opencost/opencost/pkg/env"
  20. "github.com/opencost/opencost/pkg/kubecost"
  21. "github.com/opencost/opencost/pkg/log"
  22. "github.com/opencost/opencost/pkg/util/fileutil"
  23. "github.com/opencost/opencost/pkg/util/json"
  24. "github.com/opencost/opencost/pkg/util/stringutil"
  25. "golang.org/x/exp/slices"
  26. v1 "k8s.io/api/core/v1"
  27. )
  28. const (
  29. ALIBABA_ECS_PRODUCT_CODE = "ecs"
  30. ALIBABA_ECS_VERSION = "2014-05-26"
  31. ALIBABA_ECS_DOMAIN = "ecs.aliyuncs.com"
  32. ALIBABA_DESCRIBE_PRICE_API_ACTION = "DescribePrice"
  33. ALIBABA_DESCRIBE_DISK_API_ACTION = "DescribeDisks"
  34. ALIBABA_INSTANCE_RESOURCE_TYPE = "instance"
  35. ALIBABA_DISK_RESOURCE_TYPE = "disk"
  36. ALIBABA_PAY_AS_YOU_GO_BILLING = "Pay-As-You-Go"
  37. ALIBABA_SUBSCRIPTION_BILLING = "Subscription"
  38. ALIBABA_PREEMPTIBLE_BILLING = "Preemptible"
  39. ALIBABA_OPTIMIZE_KEYWORD = "optimize"
  40. ALIBABA_NON_OPTIMIZE_KEYWORD = "nonoptimize"
  41. ALIBABA_HOUR_PRICE_UNIT = "Hour"
  42. ALIBABA_MONTH_PRICE_UNIT = "Month"
  43. ALIBABA_YEAR_PRICE_UNIT = "Year"
  44. ALIBABA_UNKNOWN_INSTANCE_FAMILY_TYPE = "unknown"
  45. ALIBABA_NOT_SUPPORTED_INSTANCE_FAMILY_TYPE = "unsupported"
  46. ALIBABA_DISK_CLOUD_ESSD_CATEGORY = "cloud_essd"
  47. ALIBABA_DISK_CLOUD_CATEGORY = "cloud"
  48. ALIBABA_DATA_DISK_CATEGORY = "data"
  49. ALIBABA_SYSTEM_DISK_CATEGORY = "system"
  50. ALIBABA_DATA_DISK_PREFIX = "DataDisk"
  51. ALIBABA_PV_CLOUD_DISK_TYPE = "CloudDisk"
  52. ALIBABA_PV_NAS_TYPE = "NAS"
  53. ALIBABA_PV_OSS_TYPE = "OSS"
  54. ALIBABA_DEFAULT_DATADISK_SIZE = "2000"
  55. ALIBABA_DISK_TOPOLOGY_REGION_LABEL = "topology.diskplugin.csi.alibabacloud.com/region"
  56. ALIBABA_DISK_TOPOLOGY_ZONE_LABEL = "topology.diskplugin.csi.alibabacloud.com/zone"
  57. )
  58. var (
  59. // Regular expression to get the numerical value of PV suffix with GiB from *v1.PersistentVolume.
  60. sizeRegEx = regexp.MustCompile("(.*?)Gi")
  61. )
  62. // Variable to keep track of instance families that fail in DescribePrice API due improper defaulting of systemDisk if the information is not available
  63. var alibabaDefaultToCloudEssd = []string{"g6e", "r6e", "r7", "g7", "g7a", "r7a"}
  64. // Why predefined and dependency on code? Can be converted to API call - https://www.alibabacloud.com/help/en/elastic-compute-service/latest/regions-describeregions
  65. var alibabaRegions = []string{
  66. "cn-qingdao",
  67. "cn-beijing",
  68. "cn-zhangjiakou",
  69. "cn-huhehaote",
  70. "cn-wulanchabu",
  71. "cn-hangzhou",
  72. "cn-shanghai",
  73. "cn-nanjing",
  74. "cn-fuzhou",
  75. "cn-shenzhen",
  76. "cn-guangzhou",
  77. "cn-chengdu",
  78. "cn-hongkong",
  79. "ap-southeast-1",
  80. "ap-southeast-2",
  81. "ap-southeast-3",
  82. "ap-southeast-5",
  83. "ap-southeast-6",
  84. "ap-southeast-7",
  85. "ap-south-1",
  86. "ap-northeast-1",
  87. "ap-northeast-2",
  88. "us-west-1",
  89. "us-east-1",
  90. "eu-central-1",
  91. "me-east-1",
  92. }
  93. // To-Do: Convert to API call - https://www.alibabacloud.com/help/en/elastic-compute-service/latest/describeinstancetypefamilies
  94. // Also first pass only completely tested pricing API for General pupose instances families & memory optimized instance families
  95. var alibabaInstanceFamilies = []string{
  96. "g7",
  97. "g7a",
  98. "g6e",
  99. "g6",
  100. "g5",
  101. "sn2",
  102. "sn2ne",
  103. "r7",
  104. "r7a",
  105. "r6e",
  106. "r6a",
  107. "r6",
  108. "r5",
  109. "se1",
  110. "se1ne",
  111. "re6",
  112. "re6p",
  113. "re4",
  114. "se1",
  115. }
  116. // AlibabaInfo contains configuration for Alibaba's CUR integration
  117. // Deprecated: v1.104 Use BOAConfiguration instead
  118. type AlibabaInfo struct {
  119. AlibabaClusterRegion string `json:"ClusterRegion"`
  120. AlibabaServiceKeyName string `json:"serviceKeyName"`
  121. AlibabaServiceKeySecret string `json:"serviceKeySecret"`
  122. AlibabaAccountID string `json:"accountID"`
  123. }
  124. // IsEmpty returns true if all fields in config are empty, false if not.
  125. func (ai *AlibabaInfo) IsEmpty() bool {
  126. return ai.AlibabaClusterRegion == "" &&
  127. ai.AlibabaServiceKeyName == "" &&
  128. ai.AlibabaServiceKeySecret == "" &&
  129. ai.AlibabaAccountID == ""
  130. }
  131. // AlibabaAccessKey holds Alibaba credentials parsing from the service-key.json file.
  132. // Deprecated: v1.104 Use AccessKey instead
  133. type AlibabaAccessKey struct {
  134. AccessKeyID string `json:"alibaba_access_key_id"`
  135. SecretAccessKey string `json:"alibaba_secret_access_key"`
  136. }
  137. // Slim Version of k8s disk assigned to a node or PV.
  138. type SlimK8sDisk struct {
  139. DiskType string
  140. RegionID string
  141. PriceUnit string
  142. SizeInGiB string
  143. DiskCategory string
  144. PerformanceLevel string
  145. ProviderID string
  146. StorageClass string
  147. }
  148. func NewSlimK8sDisk(diskType, regionID, priceUnit, diskCategory, performanceLevel, providerID, storageClass, sizeInGiB string) *SlimK8sDisk {
  149. return &SlimK8sDisk{
  150. DiskType: diskType,
  151. RegionID: regionID,
  152. PriceUnit: priceUnit,
  153. SizeInGiB: sizeInGiB,
  154. DiskCategory: diskCategory,
  155. PerformanceLevel: performanceLevel,
  156. ProviderID: providerID,
  157. StorageClass: storageClass,
  158. }
  159. }
  160. // 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.
  161. type SlimK8sNode struct {
  162. InstanceType string
  163. RegionID string
  164. PriceUnit string
  165. MemorySizeInKiB string // TO-DO : Possible to convert to float?
  166. IsIoOptimized bool
  167. OSType string
  168. ProviderID string
  169. SystemDisk *SlimK8sDisk
  170. 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.
  171. }
  172. func NewSlimK8sNode(instanceType, regionID, priceUnit, memorySizeInKiB, osType, providerID, instanceTypeFamily string, isIOOptimized bool, systemDiskInfo *SlimK8sDisk) *SlimK8sNode {
  173. return &SlimK8sNode{
  174. InstanceType: instanceType,
  175. RegionID: regionID,
  176. PriceUnit: priceUnit,
  177. MemorySizeInKiB: memorySizeInKiB,
  178. IsIoOptimized: isIOOptimized,
  179. OSType: osType,
  180. SystemDisk: systemDiskInfo,
  181. ProviderID: providerID,
  182. InstanceTypeFamily: instanceTypeFamily,
  183. }
  184. }
  185. // AlibabaNodeAttributes represents metadata about the Node in its pricing information.
  186. // Basic Attributes needed atleast to get the key, Some attributes from k8s Node response
  187. // be populated directly into *Node object.
  188. type AlibabaNodeAttributes struct {
  189. // InstanceType represents the type of instance.
  190. InstanceType string `json:"instanceType"`
  191. // MemorySizeInKiB represents the size of memory of instance.
  192. MemorySizeInKiB string `json:"memorySizeInKiB"`
  193. // IsIoOptimized represents the if instance is I/O optimized.
  194. IsIoOptimized bool `json:"isIoOptimized"`
  195. // OSType represents the OS installed in the Instance.
  196. OSType string `json:"osType"`
  197. // SystemDiskCategory represents the exact category of the system disk attached to the node.
  198. SystemDiskCategory string `json:"systemDiskCategory"`
  199. // SystemDiskSizeInGiB represents the size of the system disk attached to the node.
  200. SystemDiskSizeInGiB string `json:"systemDiskSizeInGiB"`
  201. // SystemDiskPerformanceLevel represents the performance level of the system disk attached to the node.
  202. SystemDiskPerformanceLevel string `json:"systemPerformanceLevel"`
  203. }
  204. func NewAlibabaNodeAttributes(node *SlimK8sNode) *AlibabaNodeAttributes {
  205. if node == nil {
  206. return nil
  207. }
  208. var diskCategory, sizeInGiB, performanceLevel string
  209. if node.SystemDisk != nil {
  210. diskCategory = node.SystemDisk.DiskCategory
  211. sizeInGiB = node.SystemDisk.SizeInGiB
  212. performanceLevel = node.SystemDisk.PerformanceLevel
  213. }
  214. return &AlibabaNodeAttributes{
  215. InstanceType: node.InstanceType,
  216. MemorySizeInKiB: node.MemorySizeInKiB,
  217. IsIoOptimized: node.IsIoOptimized,
  218. OSType: node.OSType,
  219. SystemDiskCategory: diskCategory,
  220. SystemDiskSizeInGiB: sizeInGiB,
  221. SystemDiskPerformanceLevel: performanceLevel,
  222. }
  223. }
  224. // AlibabaPVAttributes represents metadata the PV in its pricing information.
  225. // Basic Attributes needed atleast to get the keys. Some attributes from k8s PV response
  226. // be populated directly into *PV object.
  227. type AlibabaPVAttributes struct {
  228. // PVType can be Cloud Disk, NetWork Attached Storage(NAS) or Object Storage Service (OSS).
  229. // Represents the way the PV was attached
  230. PVType string `json:"pvType"`
  231. // PVSubType represent the sub category of PVType. This is Data in case of Cloud Disk.
  232. PVSubType string `json:"pvSubType"`
  233. // Example for PVCategory with cloudDisk PVType are cloud, cloud_efficiency, cloud_ssd,
  234. // ephemeral_ssd and cloud_essd. If not present returns empty.
  235. PVCategory string `json:"pvCategory"`
  236. // Example for PerformanceLevel with cloudDisk PVType are PL0,PL1,PL2 &PL3. If not present returns empty.
  237. PVPerformanceLevel string `json:"performanceLevel"`
  238. // The Size of the PV in terms of GiB
  239. SizeInGiB string `json:"sizeInGiB"`
  240. }
  241. // TO-Do: next iteration of Alibaba provider support NetWork Attached Storage(NAS) and Object Storage Service (OSS type PVs).
  242. // Currently defaulting to cloudDisk with provision to add work in future.
  243. func NewAlibabaPVAttributes(disk *SlimK8sDisk) *AlibabaPVAttributes {
  244. if disk == nil {
  245. return nil
  246. }
  247. return &AlibabaPVAttributes{
  248. PVType: ALIBABA_PV_CLOUD_DISK_TYPE,
  249. PVSubType: disk.DiskType,
  250. PVCategory: disk.DiskCategory,
  251. PVPerformanceLevel: disk.PerformanceLevel,
  252. SizeInGiB: disk.SizeInGiB,
  253. }
  254. }
  255. // Stage 1 support will be Pay-As-You-Go with HourlyPrice equal to TradePrice with PriceUnit as Hour
  256. // TO-DO: Subscription and Premptible support, Information can be gathered from describing instance for subscription type
  257. // and spotprice can be gather from DescribeSpotPriceHistory API.
  258. // TO-DO: how would you calculate hourly price for subscription type, is it PRICE_YEARLY/HOURS_IN_THE_YEAR|MONTH?
  259. type AlibabaPricingDetails struct {
  260. // Represents hourly price for the given Alibaba cloud Product.
  261. HourlyPrice float32 `json:"hourlyPrice"`
  262. // Represents the unit in which Alibaba Product is billed can be Hour, Month or Year based on the billingMethod.
  263. PriceUnit string `json:"priceUnit"`
  264. // Original Price paid to acquire the Alibaba Product.
  265. TradePrice float32 `json:"tradePrice"`
  266. // Represents the currency unit of the price for billing Alibaba Product.
  267. CurrencyCode string `json:"currencyCode"`
  268. }
  269. func NewAlibabaPricingDetails(hourlyPrice float32, priceUnit string, tradePrice float32, currencyCode string) *AlibabaPricingDetails {
  270. return &AlibabaPricingDetails{
  271. HourlyPrice: hourlyPrice,
  272. PriceUnit: priceUnit,
  273. TradePrice: tradePrice,
  274. CurrencyCode: currencyCode,
  275. }
  276. }
  277. // AlibabaPricingTerms can have three types of supported billing method Pay-As-You-Go, Subscription and Premptible
  278. type AlibabaPricingTerms struct {
  279. BillingMethod string `json:"billingMethod"`
  280. PricingDetails *AlibabaPricingDetails `json:"pricingDetails"`
  281. }
  282. func NewAlibabaPricingTerms(billingMethod string, pricingDetails *AlibabaPricingDetails) *AlibabaPricingTerms {
  283. return &AlibabaPricingTerms{
  284. BillingMethod: billingMethod,
  285. PricingDetails: pricingDetails,
  286. }
  287. }
  288. // Alibaba Pricing struct carry the Attributes and pricing information for Node or PV
  289. type AlibabaPricing struct {
  290. NodeAttributes *AlibabaNodeAttributes
  291. PVAttributes *AlibabaPVAttributes
  292. PricingTerms *AlibabaPricingTerms
  293. Node *models.Node
  294. PV *models.PV
  295. }
  296. // Alibaba cloud's Provider struct
  297. type Alibaba struct {
  298. // Data to store Alibaba cloud's pricing struct, key in the map represents exact match to
  299. // node.features() or pv.features for easy lookup
  300. Pricing map[string]*AlibabaPricing
  301. // Lock Needed to provide thread safe
  302. DownloadPricingDataLock sync.RWMutex
  303. Clientset clustercache.ClusterCache
  304. Config models.ProviderConfig
  305. ServiceAccountChecks *models.ServiceAccountChecks
  306. ClusterAccountId string
  307. ClusterRegion string
  308. // The following fields are unexported because of avoiding any leak of secrets of these keys.
  309. // Alibaba Access key used specifically in signer interface used to sign API calls
  310. accessKey *credentials.AccessKeyCredential
  311. // Map of regionID to sdk.client to call API for that region
  312. clients map[string]*sdk.Client
  313. }
  314. // GetAlibabaAccessKey return the Access Key used to interact with the Alibaba cloud, if not set it
  315. // set it first by looking at env variables else load it from secret files.
  316. func (alibaba *Alibaba) GetAlibabaAccessKey() (*credentials.AccessKeyCredential, error) {
  317. if alibaba.accessKeyisLoaded() {
  318. return alibaba.accessKey, nil
  319. }
  320. config, err := alibaba.GetConfig()
  321. if err != nil {
  322. return nil, fmt.Errorf("error getting the default config for Alibaba Cloud provider: %w", err)
  323. }
  324. if config.AlibabaServiceKeyName == "" {
  325. config.AlibabaServiceKeyName = env.GetAlibabaAccessKeyID()
  326. }
  327. if config.AlibabaServiceKeySecret == "" {
  328. config.AlibabaServiceKeySecret = env.GetAlibabaAccessKeySecret()
  329. }
  330. if config.AlibabaServiceKeyName == "" && config.AlibabaServiceKeySecret == "" {
  331. log.Debugf("missing service key values for Alibaba cloud integration attempting to use service account integration")
  332. err := alibaba.loadAlibabaAuthSecretAndSetEnv(true)
  333. if err != nil {
  334. return nil, fmt.Errorf("unable to set the Alibaba Cloud key/secret from config file %w", err)
  335. }
  336. config.AlibabaServiceKeyName = env.GetAlibabaAccessKeyID()
  337. config.AlibabaServiceKeySecret = env.GetAlibabaAccessKeySecret()
  338. }
  339. if config.AlibabaServiceKeyName == "" && config.AlibabaServiceKeySecret == "" {
  340. return nil, fmt.Errorf("failed to get the access key for the current alibaba account")
  341. }
  342. // 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
  343. // 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.
  344. // Key and secret passed in config will supersede key and secret passed while installing Closed source helm chart.
  345. alibaba.accessKey = &credentials.AccessKeyCredential{AccessKeyId: config.AlibabaServiceKeyName, AccessKeySecret: config.AlibabaServiceKeySecret}
  346. return alibaba.accessKey, nil
  347. }
  348. func (alibaba *Alibaba) GetAlibabaCloudInfo() (*AlibabaInfo, error) {
  349. config, err := alibaba.GetConfig()
  350. if err != nil {
  351. return nil, fmt.Errorf("could not retrieve AlibabaCloudInfo %s", err)
  352. }
  353. aak, err := alibaba.GetAlibabaAccessKey()
  354. if err != nil {
  355. return nil, err
  356. }
  357. return &AlibabaInfo{
  358. AlibabaClusterRegion: config.AlibabaClusterRegion,
  359. AlibabaServiceKeyName: aak.AccessKeyId,
  360. AlibabaServiceKeySecret: aak.AccessKeySecret,
  361. AlibabaAccountID: config.ProjectID,
  362. }, nil
  363. }
  364. // DownloadPricingData satisfies the provider interface and downloads the prices for Node instances and PVs.
  365. func (alibaba *Alibaba) DownloadPricingData() error {
  366. alibaba.DownloadPricingDataLock.Lock()
  367. defer alibaba.DownloadPricingDataLock.Unlock()
  368. var aak *credentials.AccessKeyCredential
  369. var err error
  370. if !alibaba.accessKeyisLoaded() {
  371. aak, err = alibaba.GetAlibabaAccessKey()
  372. if err != nil {
  373. return fmt.Errorf("unable to get the access key information: %w", err)
  374. }
  375. } else {
  376. aak = alibaba.accessKey
  377. }
  378. c, err := alibaba.Config.GetCustomPricingData()
  379. if err != nil {
  380. return fmt.Errorf("error downloading default pricing data: %w", err)
  381. }
  382. // Get all the nodes from Alibaba cluster.
  383. nodeList := alibaba.Clientset.GetAllNodes()
  384. var client *sdk.Client
  385. var signer *signers.AccessKeySigner
  386. var ok bool
  387. var lookupKey string
  388. alibaba.clients = make(map[string]*sdk.Client)
  389. alibaba.Pricing = make(map[string]*AlibabaPricing)
  390. for _, node := range nodeList {
  391. pricingObj := &AlibabaPricing{}
  392. slimK8sNode := generateSlimK8sNodeFromV1Node(node)
  393. if client, ok = alibaba.clients[slimK8sNode.RegionID]; !ok {
  394. client, err = sdk.NewClientWithAccessKey(slimK8sNode.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
  395. if err != nil {
  396. return fmt.Errorf("unable to initiate alibaba cloud sdk client for region %s : %w", slimK8sNode.RegionID, err)
  397. }
  398. alibaba.clients[slimK8sNode.RegionID] = client
  399. }
  400. signer = signers.NewAccessKeySigner(aak)
  401. // Adjust the system Disk information of a Node by retrieving the details of associated disk. If unable to retrieve set it to empty
  402. // system disk to pass through and use defaults with Alibaba pricing API.
  403. instanceID := getInstanceIDFromProviderID(slimK8sNode.ProviderID)
  404. slimK8sNode.SystemDisk = getSystemDiskInfoOfANode(instanceID, slimK8sNode.RegionID, client, signer)
  405. lookupKey, err = determineKeyForPricing(slimK8sNode)
  406. if _, ok := alibaba.Pricing[lookupKey]; ok {
  407. log.Debugf("Pricing information for node with same features %s already exists hence skipping", lookupKey)
  408. continue
  409. }
  410. pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sNode, signer, c)
  411. if err != nil {
  412. return fmt.Errorf("failed to create pricing information for node with type %s with error: %w", slimK8sNode.InstanceType, err)
  413. }
  414. alibaba.Pricing[lookupKey] = pricingObj
  415. }
  416. // set the first occurrence of region from the node
  417. if alibaba.ClusterRegion == "" {
  418. for _, node := range nodeList {
  419. if regionID, ok := node.Labels["topology.kubernetes.io/region"]; ok {
  420. alibaba.ClusterRegion = regionID
  421. break
  422. }
  423. }
  424. }
  425. // PV pricing for only Cloud Disk for now.
  426. // TO-DO: Support both NAS(Network Attached storage) and OSS(Object Storage Service) type PVs
  427. pvList := alibaba.Clientset.GetAllPersistentVolumes()
  428. for _, pv := range pvList {
  429. pvRegion := determinePVRegion(pv)
  430. if pvRegion == "" {
  431. pvRegion = alibaba.ClusterRegion
  432. }
  433. pricingObj := &AlibabaPricing{}
  434. slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, pvRegion)
  435. lookupKey, err = determineKeyForPricing(slimK8sDisk)
  436. if _, ok := alibaba.Pricing[lookupKey]; ok {
  437. log.Debugf("Pricing information for pv with same features %s already exists hence skipping", lookupKey)
  438. continue
  439. }
  440. if client, ok = alibaba.clients[slimK8sDisk.RegionID]; !ok {
  441. client, err = sdk.NewClientWithAccessKey(slimK8sDisk.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
  442. if err != nil {
  443. return fmt.Errorf("unable to initiate alibaba cloud sdk client for region %s : %w", slimK8sDisk.RegionID, err)
  444. }
  445. alibaba.clients[slimK8sDisk.RegionID] = client
  446. }
  447. signer = signers.NewAccessKeySigner(aak)
  448. pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sDisk, signer, c)
  449. if err != nil {
  450. return fmt.Errorf("failed to create pricing information for pv with category %s with error: %w", slimK8sDisk.DiskCategory, err)
  451. }
  452. alibaba.Pricing[lookupKey] = pricingObj
  453. }
  454. return nil
  455. }
  456. // AllNodePricing returns all the pricing data for all nodes and pvs
  457. func (alibaba *Alibaba) AllNodePricing() (interface{}, error) {
  458. alibaba.DownloadPricingDataLock.RLock()
  459. defer alibaba.DownloadPricingDataLock.RUnlock()
  460. return alibaba.Pricing, nil
  461. }
  462. // NodePricing gives pricing information of a specific node given by the key
  463. func (alibaba *Alibaba) NodePricing(key models.Key) (*models.Node, error) {
  464. alibaba.DownloadPricingDataLock.RLock()
  465. defer alibaba.DownloadPricingDataLock.RUnlock()
  466. // Get node features for the key
  467. keyFeature := key.Features()
  468. pricing, ok := alibaba.Pricing[keyFeature]
  469. if !ok {
  470. log.Errorf("Node pricing information not found for node with feature: %s", keyFeature)
  471. return nil, fmt.Errorf("Node pricing information not found for node with feature: %s letting it use default values", keyFeature)
  472. }
  473. log.Debugf("returning the node price for the node with feature: %s", keyFeature)
  474. returnNode := pricing.Node
  475. return returnNode, nil
  476. }
  477. // PVPricing gives a pricing information of a specific PV given by PVkey
  478. func (alibaba *Alibaba) PVPricing(pvk models.PVKey) (*models.PV, error) {
  479. alibaba.DownloadPricingDataLock.RLock()
  480. defer alibaba.DownloadPricingDataLock.RUnlock()
  481. keyFeature := pvk.Features()
  482. pricing, ok := alibaba.Pricing[keyFeature]
  483. if !ok {
  484. log.Errorf("Persistent Volume pricing not found for PV with feature: %s", keyFeature)
  485. return nil, fmt.Errorf("Persistent Volume pricing not found for PV with feature: %s letting it use default values", keyFeature)
  486. }
  487. log.Debugf("returning the PV price for the node with feature: %s", keyFeature)
  488. return pricing.PV, nil
  489. }
  490. // 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
  491. // Internet cost is default based on https://www.alibabacloud.com/help/en/elastic-compute-service/latest/public-bandwidth to $0.123
  492. func (alibaba *Alibaba) NetworkPricing() (*models.Network, error) {
  493. cpricing, err := alibaba.Config.GetCustomPricingData()
  494. if err != nil {
  495. return nil, err
  496. }
  497. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  498. if err != nil {
  499. return nil, err
  500. }
  501. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  502. if err != nil {
  503. return nil, err
  504. }
  505. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  506. if err != nil {
  507. return nil, err
  508. }
  509. return &models.Network{
  510. ZoneNetworkEgressCost: znec,
  511. RegionNetworkEgressCost: rnec,
  512. InternetNetworkEgressCost: inec,
  513. }, nil
  514. }
  515. // Alibaba loadbalancer has three different types https://www.alibabacloud.com/product/server-load-balancer,
  516. // defaulted price to classic load balancer https://www.alibabacloud.com/help/en/server-load-balancer/latest/pay-as-you-go.
  517. func (alibaba *Alibaba) LoadBalancerPricing() (*models.LoadBalancer, error) {
  518. cpricing, err := alibaba.Config.GetCustomPricingData()
  519. if err != nil {
  520. return nil, err
  521. }
  522. lbPricing, err := strconv.ParseFloat(cpricing.DefaultLBPrice, 64)
  523. if err != nil {
  524. return nil, err
  525. }
  526. return &models.LoadBalancer{
  527. Cost: lbPricing,
  528. }, nil
  529. }
  530. func (alibaba *Alibaba) GetConfig() (*models.CustomPricing, error) {
  531. c, err := alibaba.Config.GetCustomPricingData()
  532. if err != nil {
  533. return nil, err
  534. }
  535. if c.Discount == "" {
  536. c.Discount = "0%"
  537. }
  538. if c.NegotiatedDiscount == "" {
  539. c.NegotiatedDiscount = "0%"
  540. }
  541. if c.ShareTenancyCosts == "" {
  542. c.ShareTenancyCosts = models.DefaultShareTenancyCost
  543. }
  544. return c, nil
  545. }
  546. // Load once and cache the result (even on failure). This is an install time secret, so
  547. // we don't expect the secret to change. If it does, however, we can force reload using
  548. // the input parameter.
  549. func (alibaba *Alibaba) loadAlibabaAuthSecretAndSetEnv(force bool) error {
  550. if !force && alibaba.accessKeyisLoaded() {
  551. return nil
  552. }
  553. exists, err := fileutil.FileExists(models.AuthSecretPath)
  554. if !exists || err != nil {
  555. return fmt.Errorf("failed to locate service account file: %s with err: %w", models.AuthSecretPath, err)
  556. }
  557. result, err := os.ReadFile(models.AuthSecretPath)
  558. if err != nil {
  559. return fmt.Errorf("failed to read service account file: %s with err: %w", models.AuthSecretPath, err)
  560. }
  561. var ak *AlibabaAccessKey
  562. err = json.Unmarshal(result, &ak)
  563. if err != nil {
  564. return fmt.Errorf("failed to unmarshall access key id and access key secret with err: %w", err)
  565. }
  566. err = env.Set(env.AlibabaAccessKeyIDEnvVar, ak.AccessKeyID)
  567. if err != nil {
  568. return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeyIDEnvVar, err)
  569. }
  570. err = env.Set(env.AlibabaAccessKeySecretEnvVar, ak.SecretAccessKey)
  571. if err != nil {
  572. return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeySecretEnvVar, err)
  573. }
  574. alibaba.accessKey = &credentials.AccessKeyCredential{
  575. AccessKeyId: ak.AccessKeyID,
  576. AccessKeySecret: ak.SecretAccessKey,
  577. }
  578. return nil
  579. }
  580. // Regions returns a current supported list of Alibaba regions
  581. func (alibaba *Alibaba) Regions() []string {
  582. regionOverrides := env.GetRegionOverrideList()
  583. if len(regionOverrides) > 0 {
  584. log.Debugf("Overriding Alibaba regions with configured region list: %+v", regionOverrides)
  585. return regionOverrides
  586. }
  587. return alibabaRegions
  588. }
  589. // ClusterInfo returns information about Alibaba Cloud cluster, as provided by metadata.
  590. func (alibaba *Alibaba) ClusterInfo() (map[string]string, error) {
  591. c, err := alibaba.GetConfig()
  592. if err != nil {
  593. return nil, fmt.Errorf("failed to getConfig with err: %w", err)
  594. }
  595. var clusterName string
  596. if c.ClusterName != "" {
  597. clusterName = c.ClusterName
  598. }
  599. // Set it to environment clusterID if not set at this point
  600. if clusterName == "" {
  601. clusterName = env.GetClusterID()
  602. }
  603. m := make(map[string]string)
  604. m["name"] = clusterName
  605. m["provider"] = kubecost.AlibabaProvider
  606. m["project"] = alibaba.ClusterAccountId
  607. m["region"] = alibaba.ClusterRegion
  608. m["id"] = env.GetClusterID()
  609. return m, nil
  610. }
  611. // Will look at this in Next PR if needed
  612. func (alibaba *Alibaba) GetAddresses() ([]byte, error) {
  613. return nil, nil
  614. }
  615. // Will look at this in Next PR if needed
  616. func (alibaba *Alibaba) GetDisks() ([]byte, error) {
  617. return nil, nil
  618. }
  619. func (alibaba *Alibaba) GetOrphanedResources() ([]models.OrphanedResource, error) {
  620. return nil, errors.New("not implemented")
  621. }
  622. func (alibaba *Alibaba) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  623. return alibaba.Config.Update(func(c *models.CustomPricing) error {
  624. if updateType != "" {
  625. return fmt.Errorf("UpdateConfig for Alibaba Provider doesn't support updateType %s at this time", updateType)
  626. } else {
  627. a := make(map[string]interface{})
  628. err := json.NewDecoder(r).Decode(&a)
  629. if err != nil {
  630. return err
  631. }
  632. for k, v := range a {
  633. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  634. vstr, ok := v.(string)
  635. if ok {
  636. err := models.SetCustomPricingField(c, kUpper, vstr)
  637. if err != nil {
  638. return err
  639. }
  640. } else {
  641. return fmt.Errorf("type error while updating config for %s", kUpper)
  642. }
  643. }
  644. }
  645. if env.IsRemoteEnabled() {
  646. err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  647. if err != nil {
  648. return err
  649. }
  650. }
  651. return nil
  652. })
  653. }
  654. func (alibaba *Alibaba) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
  655. return alibaba.Config.UpdateFromMap(cm)
  656. }
  657. // Will look at this in Next PR if needed
  658. func (alibaba *Alibaba) GetManagementPlatform() (string, error) {
  659. return "", nil
  660. }
  661. // Will look at this in Next PR if needed
  662. func (alibaba *Alibaba) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  663. return ""
  664. }
  665. // Will look at this in Next PR if needed
  666. func (alibaba *Alibaba) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  667. }
  668. // Will look at this in Next PR if needed
  669. func (alibaba *Alibaba) ServiceAccountStatus() *models.ServiceAccountStatus {
  670. return &models.ServiceAccountStatus{}
  671. }
  672. // Will look at this in Next PR if needed
  673. func (alibaba *Alibaba) PricingSourceStatus() map[string]*models.PricingSource {
  674. return map[string]*models.PricingSource{}
  675. }
  676. // Will look at this in Next PR if needed
  677. func (alibaba *Alibaba) ClusterManagementPricing() (string, float64, error) {
  678. return "", 0.0, nil
  679. }
  680. // Will look at this in Next PR if needed
  681. func (alibaba *Alibaba) CombinedDiscountForNode(string, bool, float64, float64) float64 {
  682. return 0.0
  683. }
  684. func (alibaba *Alibaba) accessKeyisLoaded() bool {
  685. if alibaba.accessKey == nil {
  686. return false
  687. }
  688. if alibaba.accessKey.AccessKeyId == "" {
  689. return false
  690. }
  691. if alibaba.accessKey.AccessKeySecret == "" {
  692. return false
  693. }
  694. return true
  695. }
  696. type AlibabaNodeKey struct {
  697. ProviderID string
  698. RegionID string
  699. InstanceType string
  700. OSType string
  701. OptimizedKeyword string //If IsIoOptimized is true use the word optimize in the Node key and if its not optimized use the word nonoptimize
  702. SystemDiskCategory string
  703. SystemDiskSizeInGiB string
  704. SystemDiskPerformanceLevel string
  705. }
  706. func NewAlibabaNodeKey(node *SlimK8sNode, optimizedKeyword, systemDiskCategory, systemDiskSizeInGiB, systemDiskPerfromanceLevel string) *AlibabaNodeKey {
  707. var providerID, regionID, instanceType, osType string
  708. if node != nil {
  709. providerID = node.ProviderID
  710. regionID = node.RegionID
  711. instanceType = node.InstanceType
  712. osType = node.OSType
  713. }
  714. return &AlibabaNodeKey{
  715. ProviderID: providerID,
  716. RegionID: regionID,
  717. InstanceType: instanceType,
  718. OSType: osType,
  719. OptimizedKeyword: optimizedKeyword,
  720. SystemDiskCategory: systemDiskCategory,
  721. SystemDiskSizeInGiB: systemDiskSizeInGiB,
  722. SystemDiskPerformanceLevel: systemDiskPerfromanceLevel,
  723. }
  724. }
  725. func (alibabaNodeKey *AlibabaNodeKey) ID() string {
  726. return alibabaNodeKey.ProviderID
  727. }
  728. func (alibabaNodeKey *AlibabaNodeKey) Features() string {
  729. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaNodeKey.RegionID, alibabaNodeKey.InstanceType, alibabaNodeKey.OSType,
  730. alibabaNodeKey.OptimizedKeyword, alibabaNodeKey.SystemDiskCategory, alibabaNodeKey.SystemDiskSizeInGiB, alibabaNodeKey.SystemDiskPerformanceLevel})
  731. return strings.Join(keyLookup, "::")
  732. }
  733. func (alibabaNodeKey *AlibabaNodeKey) GPUType() string {
  734. return ""
  735. }
  736. func (alibabaNodeKey *AlibabaNodeKey) GPUCount() int {
  737. return 0
  738. }
  739. // Get's the key for the k8s node input
  740. func (alibaba *Alibaba) GetKey(mapValue map[string]string, node *v1.Node) models.Key {
  741. slimK8sNode := generateSlimK8sNodeFromV1Node(node)
  742. var aak *credentials.AccessKeyCredential
  743. var err error
  744. var ok bool
  745. var client *sdk.Client
  746. var signer *signers.AccessKeySigner
  747. optimizedKeyword := ""
  748. if slimK8sNode.IsIoOptimized {
  749. optimizedKeyword = ALIBABA_OPTIMIZE_KEYWORD
  750. } else {
  751. optimizedKeyword = ALIBABA_NON_OPTIMIZE_KEYWORD
  752. }
  753. var diskCategory, diskSizeInGiB, diskPerformanceLevel string
  754. if !alibaba.accessKeyisLoaded() {
  755. aak, err = alibaba.GetAlibabaAccessKey()
  756. if err != nil {
  757. 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)
  758. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  759. }
  760. } else {
  761. aak = alibaba.accessKey
  762. }
  763. signer = signers.NewAccessKeySigner(aak)
  764. if aak == nil {
  765. log.Warnf("unable to retrieve the Alibaba API keys for node with providerID %s hence skipping SystemDisk Retrieval", slimK8sNode.ProviderID)
  766. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  767. }
  768. if client, ok = alibaba.clients[slimK8sNode.RegionID]; !ok {
  769. client, err = sdk.NewClientWithAccessKey(slimK8sNode.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
  770. if err != nil {
  771. 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)
  772. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  773. }
  774. alibaba.clients[slimK8sNode.RegionID] = client
  775. }
  776. instanceID := getInstanceIDFromProviderID(slimK8sNode.ProviderID)
  777. slimK8sNode.SystemDisk = getSystemDiskInfoOfANode(instanceID, slimK8sNode.RegionID, client, signer)
  778. if slimK8sNode.SystemDisk != nil {
  779. diskCategory = slimK8sNode.SystemDisk.DiskCategory
  780. diskSizeInGiB = slimK8sNode.SystemDisk.SizeInGiB
  781. diskPerformanceLevel = slimK8sNode.SystemDisk.PerformanceLevel
  782. }
  783. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  784. }
  785. type AlibabaPVKey struct {
  786. ProviderID string
  787. RegionID string
  788. PVType string
  789. PVSubType string
  790. PVCategory string
  791. PVPerformaceLevel string
  792. StorageClassName string
  793. SizeInGiB string
  794. }
  795. func (alibaba *Alibaba) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  796. regionID := defaultRegion
  797. // If default Region is not passed default it to cluster region ID.
  798. if defaultRegion == "" {
  799. regionID = alibaba.ClusterRegion
  800. }
  801. slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, defaultRegion)
  802. return &AlibabaPVKey{
  803. ProviderID: slimK8sDisk.ProviderID,
  804. RegionID: regionID,
  805. PVType: ALIBABA_PV_CLOUD_DISK_TYPE,
  806. PVSubType: slimK8sDisk.DiskType,
  807. PVCategory: slimK8sDisk.DiskCategory,
  808. PVPerformaceLevel: slimK8sDisk.PerformanceLevel,
  809. StorageClassName: pv.Spec.StorageClassName,
  810. SizeInGiB: slimK8sDisk.SizeInGiB,
  811. }
  812. }
  813. func (alibabaPVKey *AlibabaPVKey) Features() string {
  814. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaPVKey.RegionID, alibabaPVKey.PVSubType, alibabaPVKey.PVCategory, alibabaPVKey.PVPerformaceLevel, alibabaPVKey.SizeInGiB})
  815. return strings.Join(keyLookup, "::")
  816. }
  817. func (alibabaPVKey *AlibabaPVKey) ID() string {
  818. return alibabaPVKey.ProviderID
  819. }
  820. // Get storage class information for PV.
  821. func (alibabaPVKey *AlibabaPVKey) GetStorageClass() string {
  822. return alibabaPVKey.StorageClassName
  823. }
  824. // Helper functions for alibabaprovider.go
  825. // createDescribePriceACSRequest creates the HTTP GET request for the required resources' Price information,
  826. // When supporting subscription and Premptible resources this HTTP call needs to be modified with PriceUnit information
  827. // When supporting different new type of instances like Compute Optimized, Memory Optimized etc make sure you add the instance type
  828. // in unit test and check if it works or not to create the ack request and processDescribePriceAndCreateAlibabaPricing function
  829. // else more parameters need to be pulled from kubernetes node response or gather information from elsewhere and function modified.
  830. func createDescribePriceACSRequest(i interface{}) (*requests.CommonRequest, error) {
  831. request := requests.NewCommonRequest()
  832. request.Method = requests.GET
  833. request.Product = ALIBABA_ECS_PRODUCT_CODE
  834. request.Domain = ALIBABA_ECS_DOMAIN
  835. request.Version = ALIBABA_ECS_VERSION
  836. request.Scheme = requests.HTTPS
  837. request.ApiName = ALIBABA_DESCRIBE_PRICE_API_ACTION
  838. switch i.(type) {
  839. case *SlimK8sNode:
  840. node := i.(*SlimK8sNode)
  841. request.QueryParams["RegionId"] = node.RegionID
  842. request.QueryParams["ResourceType"] = ALIBABA_INSTANCE_RESOURCE_TYPE
  843. request.QueryParams["InstanceType"] = node.InstanceType
  844. request.QueryParams["PriceUnit"] = node.PriceUnit
  845. if node.SystemDisk != nil {
  846. // Only if the required information is present it should be overridden else default it via the API
  847. if node.SystemDisk.DiskCategory != "" {
  848. request.QueryParams["SystemDisk.Category"] = node.SystemDisk.DiskCategory
  849. }
  850. if node.SystemDisk.SizeInGiB != "" {
  851. request.QueryParams["SystemDisk.Size"] = node.SystemDisk.SizeInGiB
  852. }
  853. if node.SystemDisk.PerformanceLevel != "" {
  854. request.QueryParams["SystemDisk.PerformanceLevel"] = node.SystemDisk.PerformanceLevel
  855. }
  856. } else {
  857. // When System Disk information is not available for instance family g6e, r7 and r6e the defaults in
  858. // DescribePrice dont default rightly to cloud_essd for these instances.
  859. if slices.Contains(alibabaDefaultToCloudEssd, node.InstanceTypeFamily) {
  860. request.QueryParams["SystemDisk.Category"] = ALIBABA_DISK_CLOUD_ESSD_CATEGORY
  861. }
  862. }
  863. request.TransToAcsRequest()
  864. return request, nil
  865. case *SlimK8sDisk:
  866. disk := i.(*SlimK8sDisk)
  867. request.QueryParams["RegionId"] = disk.RegionID
  868. request.QueryParams["PriceUnit"] = disk.PriceUnit
  869. request.QueryParams["ResourceType"] = ALIBABA_DISK_RESOURCE_TYPE
  870. request.QueryParams[fmt.Sprintf("%s.%d.Size", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.SizeInGiB
  871. request.QueryParams[fmt.Sprintf("%s.%d.Category", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.DiskCategory
  872. // Performance level defaults to PL1 if not present in volume attribute.
  873. if disk.PerformanceLevel != "" {
  874. request.QueryParams[fmt.Sprintf("%s.%d.PerformanceLevel", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.PerformanceLevel
  875. }
  876. request.TransToAcsRequest()
  877. return request, nil
  878. default:
  879. return nil, fmt.Errorf("unsupported ECS type (%T) for DescribePrice at this time", i)
  880. }
  881. }
  882. // createDescribeDisksCSRequest creates the HTTP GET Request to map the system disk to the InstanceID
  883. func createDescribeDisksACSRequest(instanceID, regionID, diskType string) (*requests.CommonRequest, error) {
  884. request := requests.NewCommonRequest()
  885. request.Method = requests.GET
  886. request.Product = ALIBABA_ECS_PRODUCT_CODE
  887. request.Domain = ALIBABA_ECS_DOMAIN
  888. request.Version = ALIBABA_ECS_VERSION
  889. request.Scheme = requests.HTTPS
  890. request.ApiName = ALIBABA_DESCRIBE_DISK_API_ACTION
  891. request.QueryParams["RegionId"] = regionID
  892. request.QueryParams["InstanceId"] = instanceID
  893. request.QueryParams["DiskType"] = diskType
  894. request.TransToAcsRequest()
  895. return request, nil
  896. }
  897. // determineKeyForPricing generate a unique key from SlimK8sNode object that is constructed from v1.Node object and
  898. // SlimK8sDisk that is constructed from v1.PersistentVolume.
  899. func determineKeyForPricing(i interface{}) (string, error) {
  900. if i == nil {
  901. return "", fmt.Errorf("nil component passed to determine key")
  902. }
  903. switch i.(type) {
  904. case *SlimK8sNode:
  905. node := i.(*SlimK8sNode)
  906. var diskCategory, diskSizeInGiB, diskPerformanceLevel string
  907. if node.SystemDisk != nil {
  908. diskCategory = node.SystemDisk.DiskCategory
  909. diskSizeInGiB = node.SystemDisk.SizeInGiB
  910. diskPerformanceLevel = node.SystemDisk.PerformanceLevel
  911. }
  912. if node.IsIoOptimized {
  913. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{node.RegionID, node.InstanceType, node.OSType, ALIBABA_OPTIMIZE_KEYWORD, diskCategory, diskSizeInGiB, diskPerformanceLevel})
  914. return strings.Join(keyLookup, "::"), nil
  915. } else {
  916. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{node.RegionID, node.InstanceType, node.OSType, ALIBABA_NON_OPTIMIZE_KEYWORD, diskCategory, diskSizeInGiB, diskPerformanceLevel})
  917. return strings.Join(keyLookup, "::"), nil
  918. }
  919. case *SlimK8sDisk:
  920. disk := i.(*SlimK8sDisk)
  921. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{disk.RegionID, disk.DiskType, disk.DiskCategory, disk.PerformanceLevel, disk.SizeInGiB})
  922. return strings.Join(keyLookup, "::"), nil
  923. default:
  924. return "", fmt.Errorf("unsupported ECS type (%T) at this time", i)
  925. }
  926. }
  927. // Below structs are used to unmarshal json response of Alibaba cloud's API DescribePrice
  928. type Price struct {
  929. OriginalPrice float32 `json:"OriginalPrice"`
  930. ReservedInstanceHourPrice float32 `json:"ReservedInstanceHourPrice"`
  931. DiscountPrice float32 `json:"DiscountPrice"`
  932. Currency string `json:"Currency"`
  933. TradePrice float32 `json:"TradePrice"`
  934. }
  935. type PriceInfo struct {
  936. Price Price `json:"Price"`
  937. }
  938. type DescribePriceResponse struct {
  939. RequestId string `json:"RequestId"`
  940. PriceInfo PriceInfo `json:"PriceInfo"`
  941. }
  942. // processDescribePriceAndCreateAlibabaPricing processes the DescribePrice API and generates the pricing information for alibaba node resource and alibaba pv resource that's backed by cloud disk.
  943. func processDescribePriceAndCreateAlibabaPricing(client *sdk.Client, i interface{}, signer *signers.AccessKeySigner, custom *models.CustomPricing) (pricing *AlibabaPricing, err error) {
  944. pricing = &AlibabaPricing{}
  945. var response DescribePriceResponse
  946. if i == nil {
  947. return nil, fmt.Errorf("nil component passed to process the pricing information")
  948. }
  949. switch i.(type) {
  950. case *SlimK8sNode:
  951. node := i.(*SlimK8sNode)
  952. req, err := createDescribePriceACSRequest(node)
  953. if err != nil {
  954. return nil, err
  955. }
  956. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  957. pricing.NodeAttributes = NewAlibabaNodeAttributes(node)
  958. if err != nil || resp.GetHttpStatus() != 200 {
  959. // Can be defaulted to some value here?
  960. return nil, fmt.Errorf("unable to fetch information for node with InstanceType: %v", node.InstanceType)
  961. } else {
  962. // This is where population of Pricing happens
  963. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  964. if err != nil {
  965. return nil, fmt.Errorf("unable to unmarshall json response to custom struct with err: %w", err)
  966. }
  967. // TO-DO : Ask in PR How to get the defaults is it equal to AWS/GCP defaults? And what needs to be returned
  968. pricing.Node = &models.Node{
  969. Cost: fmt.Sprintf("%f", response.PriceInfo.Price.TradePrice),
  970. BaseCPUPrice: custom.CPU,
  971. BaseRAMPrice: custom.RAM,
  972. BaseGPUPrice: custom.GPU,
  973. }
  974. // TO-DO : Currently with Pay-As-You-go Offering TradePrice = HourlyPrice , When support happens to other type HourlyPrice Need to be determined.
  975. pricing.PricingTerms = NewAlibabaPricingTerms(ALIBABA_PAY_AS_YOU_GO_BILLING, NewAlibabaPricingDetails(response.PriceInfo.Price.TradePrice, ALIBABA_HOUR_PRICE_UNIT, response.PriceInfo.Price.TradePrice, response.PriceInfo.Price.Currency))
  976. }
  977. case *SlimK8sDisk:
  978. disk := i.(*SlimK8sDisk)
  979. req, err := createDescribePriceACSRequest(disk)
  980. if err != nil {
  981. return nil, err
  982. }
  983. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  984. if err != nil || resp.GetHttpStatus() != 200 {
  985. return nil, fmt.Errorf("unable to fetch information for disk with DiskType: %v with err: %w", disk.DiskCategory, err)
  986. } else {
  987. // This is where population of Pricing happens
  988. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  989. if err != nil {
  990. return nil, fmt.Errorf("unable to unmarshall json response to custom struct with err: %w", err)
  991. }
  992. pricing.PVAttributes = NewAlibabaPVAttributes(disk)
  993. pricing.PV = &models.PV{
  994. Cost: fmt.Sprintf("%f", response.PriceInfo.Price.TradePrice),
  995. }
  996. // TO-DO : Disk has support for Hour and Month but pricing API is failing for month for disk(Research why?) and same challenge as node pricing no prepaid/postpaid distinction in v1.PersistentVolume object have to look at APIs for th information.
  997. pricing.PricingTerms = NewAlibabaPricingTerms(ALIBABA_PAY_AS_YOU_GO_BILLING, NewAlibabaPricingDetails(response.PriceInfo.Price.TradePrice, ALIBABA_HOUR_PRICE_UNIT, response.PriceInfo.Price.TradePrice, response.PriceInfo.Price.Currency))
  998. }
  999. default:
  1000. return nil, fmt.Errorf("unsupported ECS Pricing component of type (%T) at this time", i)
  1001. }
  1002. return pricing, nil
  1003. }
  1004. // This function is to get the InstanceFamily from the InstanceType , convention followed in
  1005. // instance type is ecs.[FamilyName].[DifferentSize], it gets the familyName , if it is unable to get it
  1006. // it lists the instance family name as Unknown.
  1007. func getInstanceFamilyFromType(instanceType string) string {
  1008. splitinstanceType := strings.Split(instanceType, ".")
  1009. if len(splitinstanceType) != 3 {
  1010. log.Warnf("unable to find the family of the instance type %s, returning its family type unknown", instanceType)
  1011. return ALIBABA_UNKNOWN_INSTANCE_FAMILY_TYPE
  1012. }
  1013. if !slices.Contains(alibabaInstanceFamilies, splitinstanceType[1]) {
  1014. log.Warnf("currently the instance family type %s is not valid or not tested completely for pricing API", instanceType)
  1015. return ALIBABA_NOT_SUPPORTED_INSTANCE_FAMILY_TYPE
  1016. }
  1017. return splitinstanceType[1]
  1018. }
  1019. // getInstanceIDFromProviderID returns the instance ID associated with the Node. A *v1.Node providerID in Alibaba cloud
  1020. // is of <REGION-ID>.<INSTANCE-ID>. This function returns the Instance ID for the given ProviderID. if its unable to interpret
  1021. // it defaults to empty string.
  1022. func getInstanceIDFromProviderID(providerID string) string {
  1023. if providerID == "" {
  1024. return ""
  1025. }
  1026. splitStrings := strings.Split(providerID, ".")
  1027. if len(splitStrings) < 2 {
  1028. return ""
  1029. }
  1030. return splitStrings[1]
  1031. }
  1032. type Disk struct {
  1033. Category string `json:"Category"`
  1034. Size int `json:"Size"`
  1035. PerformanceLevel string `json:"PerformanceLevel"`
  1036. Type string `json:"Type"`
  1037. RegionId string `json:"RegionId"`
  1038. DiskId string `json:"DiskId"`
  1039. DiskChargeType string `json:"DiskChargeType"`
  1040. }
  1041. type Disks struct {
  1042. Disk []*Disk `json:"Disk"`
  1043. }
  1044. type DescribeDiskResponse struct {
  1045. TotalCount int `json:"TotalCount"`
  1046. Disks *Disks `json:"Disks"`
  1047. }
  1048. // getSystemDiskInfoOfANode gets the relevant System disk information associated with the Node given by the instanceID
  1049. // in form of a SlimK8sDisk with only relevant information that can adjust the node pricing. If any error occurs return
  1050. // an empty disk to not impact any default set at the price retrieval of the node.
  1051. func getSystemDiskInfoOfANode(instanceID, regionID string, client *sdk.Client, signer *signers.AccessKeySigner) (systemDisk *SlimK8sDisk) {
  1052. systemDisk = &SlimK8sDisk{}
  1053. var response DescribeDiskResponse
  1054. // if instanceID is empty string return an empty k8s
  1055. if instanceID == "" {
  1056. return
  1057. }
  1058. req, err := createDescribeDisksACSRequest(instanceID, regionID, ALIBABA_SYSTEM_DISK_CATEGORY)
  1059. // if any error occurs return an empty disk to not impact default pricing.
  1060. if err != nil {
  1061. log.Warnf("Unable to create Describe Disk Request with err: %v for node with InstanceID: %s, hence defaulting it to an empty system disk to pass through to defaults", err, instanceID)
  1062. return
  1063. }
  1064. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  1065. if err != nil || resp.GetHttpStatus() != 200 {
  1066. log.Warnf("Unable to process Describe Disk request with err: %v and errcode: %d for the node with InstanceID: %s, hence defaulting it to an empty system disk to pass through to defaults", err, resp.GetHttpStatus(), instanceID)
  1067. return
  1068. } else {
  1069. // This is where population of Pricing happens
  1070. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  1071. if err != nil {
  1072. log.Warnf("Unable to unmarshall Describe Disk response with err: %v for the node with InstanceID: %s, hence defaulting it to an empty system disk to pass through to defaults", err, instanceID)
  1073. return
  1074. }
  1075. // Every instance should only have one system disk per Alibaba Cloud documentation https://www.alibabacloud.com/help/en/elastic-compute-service/latest/block-storage-overview-disks,
  1076. // if TotalCount is not 1 just return empty and let it not impact default pricing.
  1077. if response.TotalCount != 1 {
  1078. log.Warnf("Total count of system disk for node with InstanceID: %s is not 1, hence defaulting it to an empty system disk to pass through to defaults", instanceID)
  1079. return
  1080. }
  1081. if response.Disks == nil {
  1082. log.Warnf("Disks information missing for node with InstanceID: %s, hence defaulting it to an empty system disk to pass through to defaults", instanceID)
  1083. return
  1084. }
  1085. if len(response.Disks.Disk) < 1 {
  1086. log.Warnf("Total number of system disk for node with InstanceID: %s is less than 1, hence defaulting it to an empty system disk to pass through to defaults", instanceID)
  1087. return
  1088. }
  1089. // TO-DO: When supporting Subscription type disk, you can leverge the disk.DiskChargeType here to map it to subscription type.
  1090. systemDisk := response.Disks.Disk[0]
  1091. return NewSlimK8sDisk(systemDisk.Type, systemDisk.RegionId, ALIBABA_HOUR_PRICE_UNIT, systemDisk.Category, systemDisk.PerformanceLevel, systemDisk.DiskId, "", fmt.Sprintf("%d", systemDisk.Size))
  1092. }
  1093. }
  1094. // generateSlimK8sNodeFromV1Node generates SlimK8sNode struct from v1.Node to fetch pricing information and call alibaba API.
  1095. func generateSlimK8sNodeFromV1Node(node *v1.Node) *SlimK8sNode {
  1096. var regionID, osType, instanceType, providerID, priceUnit, instanceFamily string
  1097. var memorySizeInKiB string // TO-DO: try to convert it into float
  1098. var ok, IsIoOptimized bool
  1099. if regionID, ok = node.Labels["topology.kubernetes.io/region"]; !ok {
  1100. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1101. log.Debugf("No RegionID label for the node: %s", node.Name)
  1102. }
  1103. if osType, ok = node.Labels["beta.kubernetes.io/os"]; !ok {
  1104. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1105. log.Debugf("OS type undetected for the node: %s", node.Name)
  1106. }
  1107. if instanceType, ok = node.Labels["node.kubernetes.io/instance-type"]; !ok {
  1108. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1109. log.Debugf("Instance Type undetected for the node: %s", node.Name)
  1110. }
  1111. instanceFamily = getInstanceFamilyFromType(instanceType)
  1112. memorySizeInKiB = fmt.Sprintf("%s", node.Status.Capacity.Memory())
  1113. providerID = node.Spec.ProviderID // Alibaba Cloud provider doesnt follow convention of prefix with cloud provider name
  1114. // Looking at current Instance offering , all of the Instances seem to be I/O optimized - https://www.alibabacloud.com/help/en/elastic-compute-service/latest/instance-family
  1115. // Basic price Json has it as part of the key so defaulting to true.
  1116. IsIoOptimized = true
  1117. priceUnit = ALIBABA_HOUR_PRICE_UNIT
  1118. systemDisk := &SlimK8sDisk{}
  1119. return NewSlimK8sNode(instanceType, regionID, priceUnit, memorySizeInKiB, osType, providerID, instanceFamily, IsIoOptimized, systemDisk)
  1120. }
  1121. // getNumericalValueFromResourceQuantity returns the numericalValue of the resourceQuantity
  1122. // An example is: 20Gi returns to 20. If any error occurs it returns the default value used in describePrice API which is 2000.
  1123. func getNumericalValueFromResourceQuantity(quantity string) (value string) {
  1124. // defaulting when any panic or empty string occurs.
  1125. defer func() {
  1126. log.Debugf("unable to determine the size of the PV so defaulting the size to %s", ALIBABA_DEFAULT_DATADISK_SIZE)
  1127. if err := recover(); err != nil {
  1128. value = ALIBABA_DEFAULT_DATADISK_SIZE
  1129. }
  1130. if value == "" {
  1131. value = ALIBABA_DEFAULT_DATADISK_SIZE
  1132. }
  1133. }()
  1134. res := sizeRegEx.FindAllStringSubmatch(quantity, 1)
  1135. value = res[0][1]
  1136. return
  1137. }
  1138. // generateSlimK8sDiskFromV1PV function generates SlimK8sDisk from v1.PersistentVolume
  1139. // to generate slim disk type that can be used to fetch pricing information for Data disk type.
  1140. func generateSlimK8sDiskFromV1PV(pv *v1.PersistentVolume, regionID string) *SlimK8sDisk {
  1141. // All PVs are data disks while local disk are categorized as system disk
  1142. diskType := ALIBABA_DATA_DISK_CATEGORY
  1143. //TO-DO: Disk supports month and hour prices , defaulting to hour
  1144. priceUnit := ALIBABA_HOUR_PRICE_UNIT
  1145. sizeQuantity := fmt.Sprintf("%s", pv.Spec.Capacity.Storage())
  1146. // res := sizeRegEx.FindAllStringSubmatch(sizeQuantity, 1)
  1147. sizeInGiB := getNumericalValueFromResourceQuantity(sizeQuantity)
  1148. providerID := ""
  1149. if pv.Spec.CSI != nil {
  1150. providerID = pv.Spec.CSI.VolumeHandle
  1151. } else {
  1152. providerID = pv.Name // Looks like pv name is same as providerID in Alibaba k8s cluster
  1153. }
  1154. // Performance level being empty string gets defaulted in describePrice to PL1.
  1155. performanceLevel := ""
  1156. diskCategory := ""
  1157. if pv.Spec.CSI != nil {
  1158. if val, ok := pv.Spec.CSI.VolumeAttributes["performanceLevel"]; ok {
  1159. performanceLevel = val
  1160. }
  1161. if val, ok := pv.Spec.CSI.VolumeAttributes["type"]; ok {
  1162. diskCategory = val
  1163. }
  1164. }
  1165. // Highly unlikely that label pv.Spec.CSI.VolumeAttributes["type"] doesn't exist but if occurred default to cloud (most basic disk type)
  1166. if diskCategory == "" {
  1167. diskCategory = ALIBABA_DISK_CLOUD_CATEGORY
  1168. }
  1169. return NewSlimK8sDisk(diskType, regionID, priceUnit, diskCategory, performanceLevel, providerID, pv.Spec.StorageClassName, sizeInGiB)
  1170. }
  1171. // determinePVRegion determines associated region for a particular PV based on the following priority, which can be changed and any other path to determine region can be added!
  1172. // if topology.diskplugin.csi.alibabacloud.com/region label/annotation is passed during PV creation return that as the PV region.
  1173. // if topology.diskplugin.csi.alibabacloud.com/zone label/annotation is passed during PV creation determine the region based on this pv label.
  1174. // if neither of the above label/annotation is present check node affinity for the zone affinity and determine the region based on this zone.
  1175. // if nether of the above yields a region , return empty string to default it to cluster region.
  1176. func determinePVRegion(pv *v1.PersistentVolume) string {
  1177. // if "topology.diskplugin.csi.alibabacloud.com/region" is present as a label or annotation return that as the PV region
  1178. if val, ok := pv.Labels[ALIBABA_DISK_TOPOLOGY_REGION_LABEL]; ok {
  1179. log.Debugf("determinePVRegion returned a region value of: %s through label: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_REGION_LABEL, pv.Name)
  1180. return val
  1181. }
  1182. if val, ok := pv.Annotations[ALIBABA_DISK_TOPOLOGY_REGION_LABEL]; ok {
  1183. log.Debugf("determinePVRegion returned a region value of: %s through annotation: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_REGION_LABEL, pv.Name)
  1184. return val
  1185. }
  1186. // if "topology.diskplugin.csi.alibabacloud.com/zone" is present as a label or annotation set it as the PV zone before looking at node affinity to determine the region PV belongs too
  1187. var pvZone string
  1188. if val, ok := pv.Labels[ALIBABA_DISK_TOPOLOGY_ZONE_LABEL]; ok {
  1189. log.Debugf("determinePVRegion will set zone value to: %s through label: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_ZONE_LABEL, pv.Name)
  1190. pvZone = val
  1191. }
  1192. if pvZone == "" {
  1193. if val, ok := pv.Annotations[ALIBABA_DISK_TOPOLOGY_ZONE_LABEL]; ok {
  1194. log.Debugf("determinePVRegion will set zone value to: %s through annotation: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_ZONE_LABEL, pv.Name)
  1195. pvZone = val
  1196. }
  1197. }
  1198. if pvZone == "" {
  1199. // zone and regionID labels are optional in Alibaba PV creation, while PV through UI creation put's a zone PV is associated with and the region
  1200. // can be determined from this information. If pv is provision via yaml and the block is missing that's the only time it gets defaulted to ClusterRegion.
  1201. if pv.Spec.NodeAffinity != nil {
  1202. nodeAffinity := pv.Spec.NodeAffinity
  1203. if nodeAffinity.Required != nil && nodeAffinity.Required.NodeSelectorTerms != nil {
  1204. for _, nodeSelectorTerm := range nodeAffinity.Required.NodeSelectorTerms {
  1205. matchExpression := nodeSelectorTerm.MatchExpressions
  1206. for _, nodeSelectorRequirement := range matchExpression {
  1207. if nodeSelectorRequirement.Key == ALIBABA_DISK_TOPOLOGY_ZONE_LABEL {
  1208. log.Debugf("determinePVRegion will set zone value to: %s through node affinity label: %s for PV name: %s", nodeSelectorRequirement.Values[0], ALIBABA_DISK_TOPOLOGY_ZONE_LABEL, pv.Name)
  1209. pvZone = nodeSelectorRequirement.Values[0]
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. regionOverrides := env.GetRegionOverrideList()
  1217. regions := alibabaRegions
  1218. if len(regionOverrides) > 0 {
  1219. regions = regionOverrides
  1220. }
  1221. for _, region := range regions {
  1222. if strings.Contains(pvZone, region) {
  1223. log.Debugf("determinePVRegion determined region of %s through zone affiliation of the PV %s\n", region, pvZone)
  1224. return region
  1225. }
  1226. }
  1227. return ""
  1228. }
  1229. // PricingSourceSummary returns the pricing source summary for the provider.
  1230. // The summary represents what was _parsed_ from the pricing source, not
  1231. // everything that was _available_ in the pricing source.
  1232. func (a *Alibaba) PricingSourceSummary() interface{} {
  1233. return a.Pricing
  1234. }