provider.go 54 KB

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