provider.go 55 KB

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