provider.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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 err != nil {
  407. return fmt.Errorf("unable to determine key for pricing: %w", err)
  408. }
  409. if _, ok := alibaba.Pricing[lookupKey]; ok {
  410. log.Debugf("Pricing information for node with same features %s already exists hence skipping", lookupKey)
  411. continue
  412. }
  413. pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sNode, signer, c)
  414. if err != nil {
  415. return fmt.Errorf("failed to create pricing information for node with type %s with error: %w", slimK8sNode.InstanceType, err)
  416. }
  417. alibaba.Pricing[lookupKey] = pricingObj
  418. }
  419. // set the first occurrence of region from the node
  420. if alibaba.ClusterRegion == "" {
  421. for _, node := range nodeList {
  422. if regionID, ok := node.Labels["topology.kubernetes.io/region"]; ok {
  423. alibaba.ClusterRegion = regionID
  424. break
  425. }
  426. }
  427. }
  428. // PV pricing for only Cloud Disk for now.
  429. // TO-DO: Support both NAS(Network Attached storage) and OSS(Object Storage Service) type PVs
  430. pvList := alibaba.Clientset.GetAllPersistentVolumes()
  431. for _, pv := range pvList {
  432. pvRegion := determinePVRegion(pv)
  433. if pvRegion == "" {
  434. pvRegion = alibaba.ClusterRegion
  435. }
  436. pricingObj := &AlibabaPricing{}
  437. slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, pvRegion)
  438. lookupKey, err = determineKeyForPricing(slimK8sDisk)
  439. if err != nil {
  440. return fmt.Errorf("unable to determine key for pricing: %w", err)
  441. }
  442. if _, ok := alibaba.Pricing[lookupKey]; ok {
  443. log.Debugf("Pricing information for pv with same features %s already exists hence skipping", lookupKey)
  444. continue
  445. }
  446. if client, ok = alibaba.clients[slimK8sDisk.RegionID]; !ok {
  447. client, err = sdk.NewClientWithAccessKey(slimK8sDisk.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
  448. if err != nil {
  449. return fmt.Errorf("unable to initiate alibaba cloud sdk client for region %s : %w", slimK8sDisk.RegionID, err)
  450. }
  451. alibaba.clients[slimK8sDisk.RegionID] = client
  452. }
  453. signer = signers.NewAccessKeySigner(aak)
  454. pricingObj, err = processDescribePriceAndCreateAlibabaPricing(client, slimK8sDisk, signer, c)
  455. if err != nil {
  456. return fmt.Errorf("failed to create pricing information for pv with category %s with error: %w", slimK8sDisk.DiskCategory, err)
  457. }
  458. alibaba.Pricing[lookupKey] = pricingObj
  459. }
  460. return nil
  461. }
  462. // AllNodePricing returns all the pricing data for all nodes and pvs
  463. func (alibaba *Alibaba) AllNodePricing() (interface{}, error) {
  464. alibaba.DownloadPricingDataLock.RLock()
  465. defer alibaba.DownloadPricingDataLock.RUnlock()
  466. return alibaba.Pricing, nil
  467. }
  468. // NodePricing gives pricing information of a specific node given by the key
  469. func (alibaba *Alibaba) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  470. alibaba.DownloadPricingDataLock.RLock()
  471. defer alibaba.DownloadPricingDataLock.RUnlock()
  472. // Get node features for the key
  473. keyFeature := key.Features()
  474. meta := models.PricingMetadata{}
  475. pricing, ok := alibaba.Pricing[keyFeature]
  476. if !ok {
  477. log.Errorf("Node pricing information not found for node with feature: %s", keyFeature)
  478. return nil, meta, fmt.Errorf("Node pricing information not found for node with feature: %s letting it use default values", keyFeature)
  479. }
  480. log.Debugf("returning the node price for the node with feature: %s", keyFeature)
  481. returnNode := pricing.Node
  482. return returnNode, meta, nil
  483. }
  484. // PVPricing gives a pricing information of a specific PV given by PVkey
  485. func (alibaba *Alibaba) PVPricing(pvk models.PVKey) (*models.PV, error) {
  486. alibaba.DownloadPricingDataLock.RLock()
  487. defer alibaba.DownloadPricingDataLock.RUnlock()
  488. keyFeature := pvk.Features()
  489. pricing, ok := alibaba.Pricing[keyFeature]
  490. if !ok {
  491. log.Errorf("Persistent Volume pricing not found for PV with feature: %s", keyFeature)
  492. return nil, fmt.Errorf("Persistent Volume pricing not found for PV with feature: %s letting it use default values", keyFeature)
  493. }
  494. log.Debugf("returning the PV price for the node with feature: %s", keyFeature)
  495. return pricing.PV, nil
  496. }
  497. // 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
  498. // Internet cost is default based on https://www.alibabacloud.com/help/en/elastic-compute-service/latest/public-bandwidth to $0.123
  499. func (alibaba *Alibaba) NetworkPricing() (*models.Network, error) {
  500. cpricing, err := alibaba.Config.GetCustomPricingData()
  501. if err != nil {
  502. return nil, err
  503. }
  504. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  505. if err != nil {
  506. return nil, err
  507. }
  508. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  509. if err != nil {
  510. return nil, err
  511. }
  512. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  513. if err != nil {
  514. return nil, err
  515. }
  516. return &models.Network{
  517. ZoneNetworkEgressCost: znec,
  518. RegionNetworkEgressCost: rnec,
  519. InternetNetworkEgressCost: inec,
  520. }, nil
  521. }
  522. // Alibaba loadbalancer has three different types https://www.alibabacloud.com/product/server-load-balancer,
  523. // defaulted price to classic load balancer https://www.alibabacloud.com/help/en/server-load-balancer/latest/pay-as-you-go.
  524. func (alibaba *Alibaba) LoadBalancerPricing() (*models.LoadBalancer, error) {
  525. cpricing, err := alibaba.Config.GetCustomPricingData()
  526. if err != nil {
  527. return nil, err
  528. }
  529. lbPricing, err := strconv.ParseFloat(cpricing.DefaultLBPrice, 64)
  530. if err != nil {
  531. return nil, err
  532. }
  533. return &models.LoadBalancer{
  534. Cost: lbPricing,
  535. }, nil
  536. }
  537. func (alibaba *Alibaba) GetConfig() (*models.CustomPricing, error) {
  538. c, err := alibaba.Config.GetCustomPricingData()
  539. if err != nil {
  540. return nil, err
  541. }
  542. if c.Discount == "" {
  543. c.Discount = "0%"
  544. }
  545. if c.NegotiatedDiscount == "" {
  546. c.NegotiatedDiscount = "0%"
  547. }
  548. if c.ShareTenancyCosts == "" {
  549. c.ShareTenancyCosts = models.DefaultShareTenancyCost
  550. }
  551. return c, nil
  552. }
  553. // Load once and cache the result (even on failure). This is an install time secret, so
  554. // we don't expect the secret to change. If it does, however, we can force reload using
  555. // the input parameter.
  556. func (alibaba *Alibaba) loadAlibabaAuthSecretAndSetEnv(force bool) error {
  557. if !force && alibaba.accessKeyisLoaded() {
  558. return nil
  559. }
  560. exists, err := fileutil.FileExists(models.AuthSecretPath)
  561. if !exists || err != nil {
  562. return fmt.Errorf("failed to locate service account file: %s with err: %w", models.AuthSecretPath, err)
  563. }
  564. result, err := os.ReadFile(models.AuthSecretPath)
  565. if err != nil {
  566. return fmt.Errorf("failed to read service account file: %s with err: %w", models.AuthSecretPath, err)
  567. }
  568. var ak *AlibabaAccessKey
  569. err = json.Unmarshal(result, &ak)
  570. if err != nil {
  571. return fmt.Errorf("failed to unmarshall access key id and access key secret with err: %w", err)
  572. }
  573. err = env.Set(env.AlibabaAccessKeyIDEnvVar, ak.AccessKeyID)
  574. if err != nil {
  575. return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeyIDEnvVar, err)
  576. }
  577. err = env.Set(env.AlibabaAccessKeySecretEnvVar, ak.SecretAccessKey)
  578. if err != nil {
  579. return fmt.Errorf("failed to set environment variable: %s with err: %w", env.AlibabaAccessKeySecretEnvVar, err)
  580. }
  581. alibaba.accessKey = &credentials.AccessKeyCredential{
  582. AccessKeyId: ak.AccessKeyID,
  583. AccessKeySecret: ak.SecretAccessKey,
  584. }
  585. return nil
  586. }
  587. // Regions returns a current supported list of Alibaba regions
  588. func (alibaba *Alibaba) Regions() []string {
  589. regionOverrides := env.GetRegionOverrideList()
  590. if len(regionOverrides) > 0 {
  591. log.Debugf("Overriding Alibaba regions with configured region list: %+v", regionOverrides)
  592. return regionOverrides
  593. }
  594. return alibabaRegions
  595. }
  596. // ClusterInfo returns information about Alibaba Cloud cluster, as provided by metadata.
  597. func (alibaba *Alibaba) ClusterInfo() (map[string]string, error) {
  598. c, err := alibaba.GetConfig()
  599. if err != nil {
  600. return nil, fmt.Errorf("failed to getConfig with err: %w", err)
  601. }
  602. var clusterName string
  603. if c.ClusterName != "" {
  604. clusterName = c.ClusterName
  605. }
  606. // Set it to environment clusterID if not set at this point
  607. if clusterName == "" {
  608. clusterName = env.GetClusterID()
  609. }
  610. m := make(map[string]string)
  611. m["name"] = clusterName
  612. m["provider"] = kubecost.AlibabaProvider
  613. m["project"] = alibaba.ClusterAccountId
  614. m["region"] = alibaba.ClusterRegion
  615. m["id"] = env.GetClusterID()
  616. return m, nil
  617. }
  618. // Will look at this in Next PR if needed
  619. func (alibaba *Alibaba) GetAddresses() ([]byte, error) {
  620. return nil, nil
  621. }
  622. // Will look at this in Next PR if needed
  623. func (alibaba *Alibaba) GetDisks() ([]byte, error) {
  624. return nil, nil
  625. }
  626. func (alibaba *Alibaba) GetOrphanedResources() ([]models.OrphanedResource, error) {
  627. return nil, errors.New("not implemented")
  628. }
  629. func (alibaba *Alibaba) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  630. return alibaba.Config.Update(func(c *models.CustomPricing) error {
  631. if updateType != "" {
  632. return fmt.Errorf("UpdateConfig for Alibaba Provider doesn't support updateType %s at this time", updateType)
  633. } else {
  634. a := make(map[string]interface{})
  635. err := json.NewDecoder(r).Decode(&a)
  636. if err != nil {
  637. return err
  638. }
  639. for k, v := range a {
  640. kUpper := utils.ToTitle.String(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  641. vstr, ok := v.(string)
  642. if ok {
  643. err := models.SetCustomPricingField(c, kUpper, vstr)
  644. if err != nil {
  645. return fmt.Errorf("error setting custom pricing field: %w", err)
  646. }
  647. } else {
  648. return fmt.Errorf("type error while updating config for %s", kUpper)
  649. }
  650. }
  651. }
  652. if env.IsRemoteEnabled() {
  653. err := utils.UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  654. if err != nil {
  655. return err
  656. }
  657. }
  658. return nil
  659. })
  660. }
  661. func (alibaba *Alibaba) UpdateConfigFromConfigMap(cm map[string]string) (*models.CustomPricing, error) {
  662. return alibaba.Config.UpdateFromMap(cm)
  663. }
  664. // Will look at this in Next PR if needed
  665. func (alibaba *Alibaba) GetManagementPlatform() (string, error) {
  666. return "", nil
  667. }
  668. // Will look at this in Next PR if needed
  669. func (alibaba *Alibaba) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  670. return ""
  671. }
  672. // Will look at this in Next PR if needed
  673. func (alibaba *Alibaba) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  674. }
  675. // Will look at this in Next PR if needed
  676. func (alibaba *Alibaba) ServiceAccountStatus() *models.ServiceAccountStatus {
  677. return &models.ServiceAccountStatus{}
  678. }
  679. // Will look at this in Next PR if needed
  680. func (alibaba *Alibaba) PricingSourceStatus() map[string]*models.PricingSource {
  681. return map[string]*models.PricingSource{}
  682. }
  683. // Will look at this in Next PR if needed
  684. func (alibaba *Alibaba) ClusterManagementPricing() (string, float64, error) {
  685. return "", 0.0, nil
  686. }
  687. // Will look at this in Next PR if needed
  688. func (alibaba *Alibaba) CombinedDiscountForNode(string, bool, float64, float64) float64 {
  689. return 0.0
  690. }
  691. func (alibaba *Alibaba) accessKeyisLoaded() bool {
  692. if alibaba.accessKey == nil {
  693. return false
  694. }
  695. if alibaba.accessKey.AccessKeyId == "" {
  696. return false
  697. }
  698. if alibaba.accessKey.AccessKeySecret == "" {
  699. return false
  700. }
  701. return true
  702. }
  703. type AlibabaNodeKey struct {
  704. ProviderID string
  705. RegionID string
  706. InstanceType string
  707. OSType string
  708. OptimizedKeyword string //If IsIoOptimized is true use the word optimize in the Node key and if its not optimized use the word nonoptimize
  709. SystemDiskCategory string
  710. SystemDiskSizeInGiB string
  711. SystemDiskPerformanceLevel string
  712. }
  713. func NewAlibabaNodeKey(node *SlimK8sNode, optimizedKeyword, systemDiskCategory, systemDiskSizeInGiB, systemDiskPerfromanceLevel string) *AlibabaNodeKey {
  714. var providerID, regionID, instanceType, osType string
  715. if node != nil {
  716. providerID = node.ProviderID
  717. regionID = node.RegionID
  718. instanceType = node.InstanceType
  719. osType = node.OSType
  720. }
  721. return &AlibabaNodeKey{
  722. ProviderID: providerID,
  723. RegionID: regionID,
  724. InstanceType: instanceType,
  725. OSType: osType,
  726. OptimizedKeyword: optimizedKeyword,
  727. SystemDiskCategory: systemDiskCategory,
  728. SystemDiskSizeInGiB: systemDiskSizeInGiB,
  729. SystemDiskPerformanceLevel: systemDiskPerfromanceLevel,
  730. }
  731. }
  732. func (alibabaNodeKey *AlibabaNodeKey) ID() string {
  733. return alibabaNodeKey.ProviderID
  734. }
  735. func (alibabaNodeKey *AlibabaNodeKey) Features() string {
  736. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaNodeKey.RegionID, alibabaNodeKey.InstanceType, alibabaNodeKey.OSType,
  737. alibabaNodeKey.OptimizedKeyword, alibabaNodeKey.SystemDiskCategory, alibabaNodeKey.SystemDiskSizeInGiB, alibabaNodeKey.SystemDiskPerformanceLevel})
  738. return strings.Join(keyLookup, "::")
  739. }
  740. func (alibabaNodeKey *AlibabaNodeKey) GPUType() string {
  741. return ""
  742. }
  743. func (alibabaNodeKey *AlibabaNodeKey) GPUCount() int {
  744. return 0
  745. }
  746. // Get's the key for the k8s node input
  747. func (alibaba *Alibaba) GetKey(mapValue map[string]string, node *v1.Node) models.Key {
  748. slimK8sNode := generateSlimK8sNodeFromV1Node(node)
  749. var aak *credentials.AccessKeyCredential
  750. var err error
  751. var ok bool
  752. var client *sdk.Client
  753. var signer *signers.AccessKeySigner
  754. optimizedKeyword := ""
  755. if slimK8sNode.IsIoOptimized {
  756. optimizedKeyword = ALIBABA_OPTIMIZE_KEYWORD
  757. } else {
  758. optimizedKeyword = ALIBABA_NON_OPTIMIZE_KEYWORD
  759. }
  760. var diskCategory, diskSizeInGiB, diskPerformanceLevel string
  761. if !alibaba.accessKeyisLoaded() {
  762. aak, err = alibaba.GetAlibabaAccessKey()
  763. if err != nil {
  764. 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)
  765. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  766. }
  767. } else {
  768. aak = alibaba.accessKey
  769. }
  770. signer = signers.NewAccessKeySigner(aak)
  771. if aak == nil {
  772. log.Warnf("unable to retrieve the Alibaba API keys for node with providerID %s hence skipping SystemDisk Retrieval", slimK8sNode.ProviderID)
  773. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  774. }
  775. if client, ok = alibaba.clients[slimK8sNode.RegionID]; !ok {
  776. client, err = sdk.NewClientWithAccessKey(slimK8sNode.RegionID, aak.AccessKeyId, aak.AccessKeySecret)
  777. if err != nil {
  778. 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)
  779. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  780. }
  781. alibaba.clients[slimK8sNode.RegionID] = client
  782. }
  783. instanceID := getInstanceIDFromProviderID(slimK8sNode.ProviderID)
  784. slimK8sNode.SystemDisk = getSystemDiskInfoOfANode(instanceID, slimK8sNode.RegionID, client, signer)
  785. if slimK8sNode.SystemDisk != nil {
  786. diskCategory = slimK8sNode.SystemDisk.DiskCategory
  787. diskSizeInGiB = slimK8sNode.SystemDisk.SizeInGiB
  788. diskPerformanceLevel = slimK8sNode.SystemDisk.PerformanceLevel
  789. }
  790. return NewAlibabaNodeKey(slimK8sNode, optimizedKeyword, diskCategory, diskSizeInGiB, diskPerformanceLevel)
  791. }
  792. type AlibabaPVKey struct {
  793. ProviderID string
  794. RegionID string
  795. PVType string
  796. PVSubType string
  797. PVCategory string
  798. PVPerformaceLevel string
  799. StorageClassName string
  800. SizeInGiB string
  801. }
  802. func (alibaba *Alibaba) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  803. regionID := defaultRegion
  804. // If default Region is not passed default it to cluster region ID.
  805. if defaultRegion == "" {
  806. regionID = alibaba.ClusterRegion
  807. }
  808. slimK8sDisk := generateSlimK8sDiskFromV1PV(pv, defaultRegion)
  809. return &AlibabaPVKey{
  810. ProviderID: slimK8sDisk.ProviderID,
  811. RegionID: regionID,
  812. PVType: ALIBABA_PV_CLOUD_DISK_TYPE,
  813. PVSubType: slimK8sDisk.DiskType,
  814. PVCategory: slimK8sDisk.DiskCategory,
  815. PVPerformaceLevel: slimK8sDisk.PerformanceLevel,
  816. StorageClassName: pv.Spec.StorageClassName,
  817. SizeInGiB: slimK8sDisk.SizeInGiB,
  818. }
  819. }
  820. func (alibabaPVKey *AlibabaPVKey) Features() string {
  821. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{alibabaPVKey.RegionID, alibabaPVKey.PVSubType, alibabaPVKey.PVCategory, alibabaPVKey.PVPerformaceLevel, alibabaPVKey.SizeInGiB})
  822. return strings.Join(keyLookup, "::")
  823. }
  824. func (alibabaPVKey *AlibabaPVKey) ID() string {
  825. return alibabaPVKey.ProviderID
  826. }
  827. // Get storage class information for PV.
  828. func (alibabaPVKey *AlibabaPVKey) GetStorageClass() string {
  829. return alibabaPVKey.StorageClassName
  830. }
  831. // Helper functions for alibabaprovider.go
  832. // createDescribePriceACSRequest creates the HTTP GET request for the required resources' Price information,
  833. // When supporting subscription and Premptible resources this HTTP call needs to be modified with PriceUnit information
  834. // When supporting different new type of instances like Compute Optimized, Memory Optimized etc make sure you add the instance type
  835. // in unit test and check if it works or not to create the ack request and processDescribePriceAndCreateAlibabaPricing function
  836. // else more parameters need to be pulled from kubernetes node response or gather information from elsewhere and function modified.
  837. func createDescribePriceACSRequest(i interface{}) (*requests.CommonRequest, error) {
  838. request := requests.NewCommonRequest()
  839. request.Method = requests.GET
  840. request.Product = ALIBABA_ECS_PRODUCT_CODE
  841. request.Domain = ALIBABA_ECS_DOMAIN
  842. request.Version = ALIBABA_ECS_VERSION
  843. request.Scheme = requests.HTTPS
  844. request.ApiName = ALIBABA_DESCRIBE_PRICE_API_ACTION
  845. switch i.(type) {
  846. case *SlimK8sNode:
  847. node := i.(*SlimK8sNode)
  848. request.QueryParams["RegionId"] = node.RegionID
  849. request.QueryParams["ResourceType"] = ALIBABA_INSTANCE_RESOURCE_TYPE
  850. request.QueryParams["InstanceType"] = node.InstanceType
  851. request.QueryParams["PriceUnit"] = node.PriceUnit
  852. if node.SystemDisk != nil {
  853. // Only if the required information is present it should be overridden else default it via the API
  854. if node.SystemDisk.DiskCategory != "" {
  855. request.QueryParams["SystemDisk.Category"] = node.SystemDisk.DiskCategory
  856. }
  857. if node.SystemDisk.SizeInGiB != "" {
  858. request.QueryParams["SystemDisk.Size"] = node.SystemDisk.SizeInGiB
  859. }
  860. if node.SystemDisk.PerformanceLevel != "" {
  861. request.QueryParams["SystemDisk.PerformanceLevel"] = node.SystemDisk.PerformanceLevel
  862. }
  863. } else {
  864. // When System Disk information is not available for instance family g6e, r7 and r6e the defaults in
  865. // DescribePrice dont default rightly to cloud_essd for these instances.
  866. if slices.Contains(alibabaDefaultToCloudEssd, node.InstanceTypeFamily) {
  867. request.QueryParams["SystemDisk.Category"] = ALIBABA_DISK_CLOUD_ESSD_CATEGORY
  868. }
  869. }
  870. request.TransToAcsRequest()
  871. return request, nil
  872. case *SlimK8sDisk:
  873. disk := i.(*SlimK8sDisk)
  874. request.QueryParams["RegionId"] = disk.RegionID
  875. request.QueryParams["PriceUnit"] = disk.PriceUnit
  876. request.QueryParams["ResourceType"] = ALIBABA_DISK_RESOURCE_TYPE
  877. request.QueryParams[fmt.Sprintf("%s.%d.Size", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.SizeInGiB
  878. request.QueryParams[fmt.Sprintf("%s.%d.Category", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.DiskCategory
  879. // Performance level defaults to PL1 if not present in volume attribute.
  880. if disk.PerformanceLevel != "" {
  881. request.QueryParams[fmt.Sprintf("%s.%d.PerformanceLevel", ALIBABA_DATA_DISK_PREFIX, 1)] = disk.PerformanceLevel
  882. }
  883. request.TransToAcsRequest()
  884. return request, nil
  885. default:
  886. return nil, fmt.Errorf("unsupported ECS type (%T) for DescribePrice at this time", i)
  887. }
  888. }
  889. // createDescribeDisksCSRequest creates the HTTP GET Request to map the system disk to the InstanceID
  890. func createDescribeDisksACSRequest(instanceID, regionID, diskType string) (*requests.CommonRequest, error) {
  891. request := requests.NewCommonRequest()
  892. request.Method = requests.GET
  893. request.Product = ALIBABA_ECS_PRODUCT_CODE
  894. request.Domain = ALIBABA_ECS_DOMAIN
  895. request.Version = ALIBABA_ECS_VERSION
  896. request.Scheme = requests.HTTPS
  897. request.ApiName = ALIBABA_DESCRIBE_DISK_API_ACTION
  898. request.QueryParams["RegionId"] = regionID
  899. request.QueryParams["InstanceId"] = instanceID
  900. request.QueryParams["DiskType"] = diskType
  901. request.TransToAcsRequest()
  902. return request, nil
  903. }
  904. // determineKeyForPricing generate a unique key from SlimK8sNode object that is constructed from v1.Node object and
  905. // SlimK8sDisk that is constructed from v1.PersistentVolume.
  906. func determineKeyForPricing(i interface{}) (string, error) {
  907. if i == nil {
  908. return "", fmt.Errorf("nil component passed to determine key")
  909. }
  910. switch i.(type) {
  911. case *SlimK8sNode:
  912. node := i.(*SlimK8sNode)
  913. var diskCategory, diskSizeInGiB, diskPerformanceLevel string
  914. if node.SystemDisk != nil {
  915. diskCategory = node.SystemDisk.DiskCategory
  916. diskSizeInGiB = node.SystemDisk.SizeInGiB
  917. diskPerformanceLevel = node.SystemDisk.PerformanceLevel
  918. }
  919. if node.IsIoOptimized {
  920. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{node.RegionID, node.InstanceType, node.OSType, ALIBABA_OPTIMIZE_KEYWORD, diskCategory, diskSizeInGiB, diskPerformanceLevel})
  921. return strings.Join(keyLookup, "::"), nil
  922. } else {
  923. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{node.RegionID, node.InstanceType, node.OSType, ALIBABA_NON_OPTIMIZE_KEYWORD, diskCategory, diskSizeInGiB, diskPerformanceLevel})
  924. return strings.Join(keyLookup, "::"), nil
  925. }
  926. case *SlimK8sDisk:
  927. disk := i.(*SlimK8sDisk)
  928. keyLookup := stringutil.DeleteEmptyStringsFromArray([]string{disk.RegionID, disk.DiskType, disk.DiskCategory, disk.PerformanceLevel, disk.SizeInGiB})
  929. return strings.Join(keyLookup, "::"), nil
  930. default:
  931. return "", fmt.Errorf("unsupported ECS type (%T) at this time", i)
  932. }
  933. }
  934. // Below structs are used to unmarshal json response of Alibaba cloud's API DescribePrice
  935. type Price struct {
  936. OriginalPrice float32 `json:"OriginalPrice"`
  937. ReservedInstanceHourPrice float32 `json:"ReservedInstanceHourPrice"`
  938. DiscountPrice float32 `json:"DiscountPrice"`
  939. Currency string `json:"Currency"`
  940. TradePrice float32 `json:"TradePrice"`
  941. }
  942. type PriceInfo struct {
  943. Price Price `json:"Price"`
  944. }
  945. type DescribePriceResponse struct {
  946. RequestId string `json:"RequestId"`
  947. PriceInfo PriceInfo `json:"PriceInfo"`
  948. }
  949. // processDescribePriceAndCreateAlibabaPricing processes the DescribePrice API and generates the pricing information for alibaba node resource and alibaba pv resource that's backed by cloud disk.
  950. func processDescribePriceAndCreateAlibabaPricing(client *sdk.Client, i interface{}, signer *signers.AccessKeySigner, custom *models.CustomPricing) (pricing *AlibabaPricing, err error) {
  951. pricing = &AlibabaPricing{}
  952. var response DescribePriceResponse
  953. if i == nil {
  954. return nil, fmt.Errorf("nil component passed to process the pricing information")
  955. }
  956. switch i.(type) {
  957. case *SlimK8sNode:
  958. node := i.(*SlimK8sNode)
  959. req, err := createDescribePriceACSRequest(node)
  960. if err != nil {
  961. return nil, err
  962. }
  963. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  964. pricing.NodeAttributes = NewAlibabaNodeAttributes(node)
  965. if err != nil || resp.GetHttpStatus() != 200 {
  966. // Can be defaulted to some value here?
  967. return nil, fmt.Errorf("unable to fetch information for node with InstanceType: %v", node.InstanceType)
  968. } else {
  969. // This is where population of Pricing happens
  970. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  971. if err != nil {
  972. return nil, fmt.Errorf("unable to unmarshall json response to custom struct with err: %w", err)
  973. }
  974. // TO-DO : Ask in PR How to get the defaults is it equal to AWS/GCP defaults? And what needs to be returned
  975. pricing.Node = &models.Node{
  976. Cost: fmt.Sprintf("%f", response.PriceInfo.Price.TradePrice),
  977. BaseCPUPrice: custom.CPU,
  978. BaseRAMPrice: custom.RAM,
  979. BaseGPUPrice: custom.GPU,
  980. }
  981. // TO-DO : Currently with Pay-As-You-go Offering TradePrice = HourlyPrice , When support happens to other type HourlyPrice Need to be determined.
  982. 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))
  983. }
  984. case *SlimK8sDisk:
  985. disk := i.(*SlimK8sDisk)
  986. req, err := createDescribePriceACSRequest(disk)
  987. if err != nil {
  988. return nil, err
  989. }
  990. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  991. if err != nil || resp.GetHttpStatus() != 200 {
  992. return nil, fmt.Errorf("unable to fetch information for disk with DiskType: %v with err: %w", disk.DiskCategory, err)
  993. } else {
  994. // This is where population of Pricing happens
  995. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  996. if err != nil {
  997. return nil, fmt.Errorf("unable to unmarshall json response to custom struct with err: %w", err)
  998. }
  999. pricing.PVAttributes = NewAlibabaPVAttributes(disk)
  1000. pricing.PV = &models.PV{
  1001. Cost: fmt.Sprintf("%f", response.PriceInfo.Price.TradePrice),
  1002. }
  1003. // 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.
  1004. 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))
  1005. }
  1006. default:
  1007. return nil, fmt.Errorf("unsupported ECS Pricing component of type (%T) at this time", i)
  1008. }
  1009. return pricing, nil
  1010. }
  1011. // This function is to get the InstanceFamily from the InstanceType , convention followed in
  1012. // instance type is ecs.[FamilyName].[DifferentSize], it gets the familyName , if it is unable to get it
  1013. // it lists the instance family name as Unknown.
  1014. func getInstanceFamilyFromType(instanceType string) string {
  1015. splitinstanceType := strings.Split(instanceType, ".")
  1016. if len(splitinstanceType) != 3 {
  1017. log.Warnf("unable to find the family of the instance type %s, returning its family type unknown", instanceType)
  1018. return ALIBABA_UNKNOWN_INSTANCE_FAMILY_TYPE
  1019. }
  1020. if !slices.Contains(alibabaInstanceFamilies, splitinstanceType[1]) {
  1021. log.Warnf("currently the instance family type %s is not valid or not tested completely for pricing API", instanceType)
  1022. return ALIBABA_NOT_SUPPORTED_INSTANCE_FAMILY_TYPE
  1023. }
  1024. return splitinstanceType[1]
  1025. }
  1026. // getInstanceIDFromProviderID returns the instance ID associated with the Node. A *v1.Node providerID in Alibaba cloud
  1027. // is of <REGION-ID>.<INSTANCE-ID>. This function returns the Instance ID for the given ProviderID. if its unable to interpret
  1028. // it defaults to empty string.
  1029. func getInstanceIDFromProviderID(providerID string) string {
  1030. if providerID == "" {
  1031. return ""
  1032. }
  1033. splitStrings := strings.Split(providerID, ".")
  1034. if len(splitStrings) < 2 {
  1035. return ""
  1036. }
  1037. return splitStrings[1]
  1038. }
  1039. type Disk struct {
  1040. Category string `json:"Category"`
  1041. Size int `json:"Size"`
  1042. PerformanceLevel string `json:"PerformanceLevel"`
  1043. Type string `json:"Type"`
  1044. RegionId string `json:"RegionId"`
  1045. DiskId string `json:"DiskId"`
  1046. DiskChargeType string `json:"DiskChargeType"`
  1047. }
  1048. type Disks struct {
  1049. Disk []*Disk `json:"Disk"`
  1050. }
  1051. type DescribeDiskResponse struct {
  1052. TotalCount int `json:"TotalCount"`
  1053. Disks *Disks `json:"Disks"`
  1054. }
  1055. // getSystemDiskInfoOfANode gets the relevant System disk information associated with the Node given by the instanceID
  1056. // in form of a SlimK8sDisk with only relevant information that can adjust the node pricing. If any error occurs return
  1057. // an empty disk to not impact any default set at the price retrieval of the node.
  1058. func getSystemDiskInfoOfANode(instanceID, regionID string, client *sdk.Client, signer *signers.AccessKeySigner) (systemDisk *SlimK8sDisk) {
  1059. systemDisk = &SlimK8sDisk{}
  1060. var response DescribeDiskResponse
  1061. // if instanceID is empty string return an empty k8s
  1062. if instanceID == "" {
  1063. return
  1064. }
  1065. req, err := createDescribeDisksACSRequest(instanceID, regionID, ALIBABA_SYSTEM_DISK_CATEGORY)
  1066. // if any error occurs return an empty disk to not impact default pricing.
  1067. if err != nil {
  1068. 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)
  1069. return
  1070. }
  1071. resp, err := client.ProcessCommonRequestWithSigner(req, signer)
  1072. if err != nil || resp.GetHttpStatus() != 200 {
  1073. 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)
  1074. return
  1075. } else {
  1076. // This is where population of Pricing happens
  1077. err = json.Unmarshal(resp.GetHttpContentBytes(), &response)
  1078. if err != nil {
  1079. 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)
  1080. return
  1081. }
  1082. // 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,
  1083. // if TotalCount is not 1 just return empty and let it not impact default pricing.
  1084. if response.TotalCount != 1 {
  1085. 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)
  1086. return
  1087. }
  1088. if response.Disks == nil {
  1089. log.Warnf("Disks information missing for node with InstanceID: %s, hence defaulting it to an empty system disk to pass through to defaults", instanceID)
  1090. return
  1091. }
  1092. if len(response.Disks.Disk) < 1 {
  1093. 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)
  1094. return
  1095. }
  1096. // TO-DO: When supporting Subscription type disk, you can leverge the disk.DiskChargeType here to map it to subscription type.
  1097. systemDisk := response.Disks.Disk[0]
  1098. return NewSlimK8sDisk(systemDisk.Type, systemDisk.RegionId, ALIBABA_HOUR_PRICE_UNIT, systemDisk.Category, systemDisk.PerformanceLevel, systemDisk.DiskId, "", fmt.Sprintf("%d", systemDisk.Size))
  1099. }
  1100. }
  1101. // generateSlimK8sNodeFromV1Node generates SlimK8sNode struct from v1.Node to fetch pricing information and call alibaba API.
  1102. func generateSlimK8sNodeFromV1Node(node *v1.Node) *SlimK8sNode {
  1103. var regionID, osType, instanceType, providerID, priceUnit, instanceFamily string
  1104. var memorySizeInKiB string // TO-DO: try to convert it into float
  1105. var ok, IsIoOptimized bool
  1106. if regionID, ok = node.Labels["topology.kubernetes.io/region"]; !ok {
  1107. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1108. log.Debugf("No RegionID label for the node: %s", node.Name)
  1109. }
  1110. if osType, ok = node.Labels["beta.kubernetes.io/os"]; !ok {
  1111. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1112. log.Debugf("OS type undetected for the node: %s", node.Name)
  1113. }
  1114. if instanceType, ok = node.Labels["node.kubernetes.io/instance-type"]; !ok {
  1115. // HIGHLY UNLIKELY THAT THIS LABEL WONT BE THERE.
  1116. log.Debugf("Instance Type undetected for the node: %s", node.Name)
  1117. }
  1118. instanceFamily = getInstanceFamilyFromType(instanceType)
  1119. memorySizeInKiB = fmt.Sprintf("%s", node.Status.Capacity.Memory())
  1120. providerID = node.Spec.ProviderID // Alibaba Cloud provider doesnt follow convention of prefix with cloud provider name
  1121. // 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
  1122. // Basic price Json has it as part of the key so defaulting to true.
  1123. IsIoOptimized = true
  1124. priceUnit = ALIBABA_HOUR_PRICE_UNIT
  1125. systemDisk := &SlimK8sDisk{}
  1126. return NewSlimK8sNode(instanceType, regionID, priceUnit, memorySizeInKiB, osType, providerID, instanceFamily, IsIoOptimized, systemDisk)
  1127. }
  1128. // getNumericalValueFromResourceQuantity returns the numericalValue of the resourceQuantity
  1129. // An example is: 20Gi returns to 20. If any error occurs it returns the default value used in describePrice API which is 2000.
  1130. func getNumericalValueFromResourceQuantity(quantity string) (value string) {
  1131. // defaulting when any panic or empty string occurs.
  1132. defer func() {
  1133. log.Debugf("unable to determine the size of the PV so defaulting the size to %s", ALIBABA_DEFAULT_DATADISK_SIZE)
  1134. if err := recover(); err != nil {
  1135. value = ALIBABA_DEFAULT_DATADISK_SIZE
  1136. }
  1137. if value == "" {
  1138. value = ALIBABA_DEFAULT_DATADISK_SIZE
  1139. }
  1140. }()
  1141. res := sizeRegEx.FindAllStringSubmatch(quantity, 1)
  1142. value = res[0][1]
  1143. return
  1144. }
  1145. // generateSlimK8sDiskFromV1PV function generates SlimK8sDisk from v1.PersistentVolume
  1146. // to generate slim disk type that can be used to fetch pricing information for Data disk type.
  1147. func generateSlimK8sDiskFromV1PV(pv *v1.PersistentVolume, regionID string) *SlimK8sDisk {
  1148. // All PVs are data disks while local disk are categorized as system disk
  1149. diskType := ALIBABA_DATA_DISK_CATEGORY
  1150. //TO-DO: Disk supports month and hour prices , defaulting to hour
  1151. priceUnit := ALIBABA_HOUR_PRICE_UNIT
  1152. sizeQuantity := fmt.Sprintf("%s", pv.Spec.Capacity.Storage())
  1153. // res := sizeRegEx.FindAllStringSubmatch(sizeQuantity, 1)
  1154. sizeInGiB := getNumericalValueFromResourceQuantity(sizeQuantity)
  1155. providerID := ""
  1156. if pv.Spec.CSI != nil {
  1157. providerID = pv.Spec.CSI.VolumeHandle
  1158. } else {
  1159. providerID = pv.Name // Looks like pv name is same as providerID in Alibaba k8s cluster
  1160. }
  1161. // Performance level being empty string gets defaulted in describePrice to PL1.
  1162. performanceLevel := ""
  1163. diskCategory := ""
  1164. if pv.Spec.CSI != nil {
  1165. if val, ok := pv.Spec.CSI.VolumeAttributes["performanceLevel"]; ok {
  1166. performanceLevel = val
  1167. }
  1168. if val, ok := pv.Spec.CSI.VolumeAttributes["type"]; ok {
  1169. diskCategory = val
  1170. }
  1171. }
  1172. // Highly unlikely that label pv.Spec.CSI.VolumeAttributes["type"] doesn't exist but if occurred default to cloud (most basic disk type)
  1173. if diskCategory == "" {
  1174. diskCategory = ALIBABA_DISK_CLOUD_CATEGORY
  1175. }
  1176. return NewSlimK8sDisk(diskType, regionID, priceUnit, diskCategory, performanceLevel, providerID, pv.Spec.StorageClassName, sizeInGiB)
  1177. }
  1178. // 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!
  1179. // if topology.diskplugin.csi.alibabacloud.com/region label/annotation is passed during PV creation return that as the PV region.
  1180. // if topology.diskplugin.csi.alibabacloud.com/zone label/annotation is passed during PV creation determine the region based on this pv label.
  1181. // if neither of the above label/annotation is present check node affinity for the zone affinity and determine the region based on this zone.
  1182. // if nether of the above yields a region , return empty string to default it to cluster region.
  1183. func determinePVRegion(pv *v1.PersistentVolume) string {
  1184. // if "topology.diskplugin.csi.alibabacloud.com/region" is present as a label or annotation return that as the PV region
  1185. if val, ok := pv.Labels[ALIBABA_DISK_TOPOLOGY_REGION_LABEL]; ok {
  1186. log.Debugf("determinePVRegion returned a region value of: %s through label: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_REGION_LABEL, pv.Name)
  1187. return val
  1188. }
  1189. if val, ok := pv.Annotations[ALIBABA_DISK_TOPOLOGY_REGION_LABEL]; ok {
  1190. log.Debugf("determinePVRegion returned a region value of: %s through annotation: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_REGION_LABEL, pv.Name)
  1191. return val
  1192. }
  1193. // 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
  1194. var pvZone string
  1195. if val, ok := pv.Labels[ALIBABA_DISK_TOPOLOGY_ZONE_LABEL]; ok {
  1196. log.Debugf("determinePVRegion will set zone value to: %s through label: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_ZONE_LABEL, pv.Name)
  1197. pvZone = val
  1198. }
  1199. if pvZone == "" {
  1200. if val, ok := pv.Annotations[ALIBABA_DISK_TOPOLOGY_ZONE_LABEL]; ok {
  1201. log.Debugf("determinePVRegion will set zone value to: %s through annotation: %s for PV name: %s", val, ALIBABA_DISK_TOPOLOGY_ZONE_LABEL, pv.Name)
  1202. pvZone = val
  1203. }
  1204. }
  1205. if pvZone == "" {
  1206. // 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
  1207. // 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.
  1208. if pv.Spec.NodeAffinity != nil {
  1209. nodeAffinity := pv.Spec.NodeAffinity
  1210. if nodeAffinity.Required != nil && nodeAffinity.Required.NodeSelectorTerms != nil {
  1211. for _, nodeSelectorTerm := range nodeAffinity.Required.NodeSelectorTerms {
  1212. matchExpression := nodeSelectorTerm.MatchExpressions
  1213. for _, nodeSelectorRequirement := range matchExpression {
  1214. if nodeSelectorRequirement.Key == ALIBABA_DISK_TOPOLOGY_ZONE_LABEL {
  1215. 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)
  1216. pvZone = nodeSelectorRequirement.Values[0]
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. }
  1223. regionOverrides := env.GetRegionOverrideList()
  1224. regions := alibabaRegions
  1225. if len(regionOverrides) > 0 {
  1226. regions = regionOverrides
  1227. }
  1228. for _, region := range regions {
  1229. if strings.Contains(pvZone, region) {
  1230. log.Debugf("determinePVRegion determined region of %s through zone affiliation of the PV %s\n", region, pvZone)
  1231. return region
  1232. }
  1233. }
  1234. return ""
  1235. }
  1236. // PricingSourceSummary returns the pricing source summary for the provider.
  1237. // The summary represents what was _parsed_ from the pricing source, not
  1238. // everything that was _available_ in the pricing source.
  1239. func (a *Alibaba) PricingSourceSummary() interface{} {
  1240. return a.Pricing
  1241. }