aliyunprovider.go 54 KB

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