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