provider.go 54 KB

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