azureprovider.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-09-01/skus"
  15. "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice"
  16. "github.com/Azure/azure-sdk-for-go/services/preview/commerce/mgmt/2015-06-01-preview/commerce"
  17. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
  18. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
  19. "github.com/Azure/go-autorest/autorest"
  20. "github.com/Azure/go-autorest/autorest/azure"
  21. "github.com/Azure/go-autorest/autorest/azure/auth"
  22. v1 "k8s.io/api/core/v1"
  23. "k8s.io/klog"
  24. )
  25. var (
  26. regionCodeMappings = map[string]string{
  27. "ap": "asia",
  28. "au": "australia",
  29. "br": "brazil",
  30. "ca": "canada",
  31. "eu": "europe",
  32. "fr": "france",
  33. "in": "india",
  34. "ja": "japan",
  35. "kr": "korea",
  36. "uk": "uk",
  37. "us": "us",
  38. "za": "southafrica",
  39. }
  40. // mtBasic, _ = regexp.Compile("^BASIC.A\\d+[_Promo]*$")
  41. // mtStandardA, _ = regexp.Compile("^A\\d+[_Promo]*$")
  42. mtStandardB, _ = regexp.Compile(`^Standard_B\d+m?[_v\d]*[_Promo]*$`)
  43. mtStandardD, _ = regexp.Compile(`^Standard_D\d[_v\d]*[_Promo]*$`)
  44. mtStandardE, _ = regexp.Compile(`^Standard_E\d+i?[_v\d]*[_Promo]*$`)
  45. mtStandardF, _ = regexp.Compile(`^Standard_F\d+[_v\d]*[_Promo]*$`)
  46. mtStandardG, _ = regexp.Compile(`^Standard_G\d+[_v\d]*[_Promo]*$`)
  47. mtStandardL, _ = regexp.Compile(`^Standard_L\d+[_v\d]*[_Promo]*$`)
  48. mtStandardM, _ = regexp.Compile(`^Standard_M\d+[m|t|l]*s[_v\d]*[_Promo]*$`)
  49. mtStandardN, _ = regexp.Compile(`^Standard_N[C|D|V]\d+r?[_v\d]*[_Promo]*$`)
  50. )
  51. type regionParts []string
  52. func (r regionParts) String() string {
  53. var result string
  54. for _, p := range r {
  55. result += p
  56. }
  57. return result
  58. }
  59. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  60. allLocations := make(map[string]string)
  61. supLocations := make(map[string]string)
  62. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  63. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  64. // fill up the map: DisplayName - > Name
  65. for _, loc := range *locations.Value {
  66. allLocations[*loc.DisplayName] = *loc.Name
  67. }
  68. } else {
  69. return nil, err
  70. }
  71. // identify supported locations for the namespace and resource type
  72. const (
  73. providerNamespaceForCompute = "Microsoft.Compute"
  74. resourceTypeForCompute = "locations/vmSizes"
  75. providerNamespaceForAks = "Microsoft.ContainerService"
  76. resourceTypeForAks = "managedClusters"
  77. )
  78. switch service {
  79. case "aks":
  80. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  81. for _, pr := range *providers.ResourceTypes {
  82. if *pr.ResourceType == resourceTypeForAks {
  83. for _, displName := range *pr.Locations {
  84. if loc, ok := allLocations[displName]; ok {
  85. supLocations[loc] = displName
  86. } else {
  87. klog.V(1).Infof("unsupported cloud region %s", loc)
  88. }
  89. }
  90. break
  91. }
  92. }
  93. } else {
  94. return nil, err
  95. }
  96. return supLocations, nil
  97. default:
  98. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  99. for _, pr := range *providers.ResourceTypes {
  100. if *pr.ResourceType == resourceTypeForCompute {
  101. for _, displName := range *pr.Locations {
  102. if loc, ok := allLocations[displName]; ok {
  103. supLocations[loc] = displName
  104. } else {
  105. klog.V(1).Infof("unsupported cloud region %s", loc)
  106. }
  107. }
  108. break
  109. }
  110. }
  111. } else {
  112. return nil, err
  113. }
  114. return supLocations, nil
  115. }
  116. }
  117. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  118. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  119. regionCode := regionCodeMappings[rp[0]]
  120. lastPart := rp[len(rp)-1]
  121. var regionIds []string
  122. if _, err := strconv.Atoi(lastPart); err == nil {
  123. regionIds = []string{
  124. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  125. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  126. }
  127. } else {
  128. regionIds = []string{
  129. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  130. fmt.Sprintf("%s%s", rp[1:], regionCode),
  131. }
  132. }
  133. for _, regionID := range regionIds {
  134. if checkRegionID(regionID, regions) {
  135. return regionID, nil
  136. }
  137. }
  138. return "", fmt.Errorf("Couldn't find region")
  139. }
  140. func checkRegionID(regionID string, regions map[string]string) bool {
  141. for region := range regions {
  142. if regionID == region {
  143. return true
  144. }
  145. }
  146. return false
  147. }
  148. type Azure struct {
  149. allPrices map[string]*Node
  150. DownloadPricingDataLock sync.RWMutex
  151. }
  152. type azureKey struct {
  153. Labels map[string]string
  154. }
  155. func (k *azureKey) Features() string {
  156. region := strings.ToLower(k.Labels[v1.LabelZoneRegion])
  157. instance := k.Labels[v1.LabelInstanceType]
  158. usageType := "ondemand"
  159. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  160. }
  161. func (k *azureKey) GPUType() string {
  162. return ""
  163. }
  164. func (k *azureKey) ID() string {
  165. return ""
  166. }
  167. func (az *Azure) GetKey(labels map[string]string) Key {
  168. return &azureKey{
  169. Labels: labels,
  170. }
  171. }
  172. // CreateString builds strings effectively
  173. func createString(keys ...string) string {
  174. var b strings.Builder
  175. for _, key := range keys {
  176. b.WriteString(key)
  177. }
  178. return b.String()
  179. }
  180. func transformMachineType(subCategory string, mt []string) []string {
  181. switch {
  182. case strings.Contains(subCategory, "Basic"):
  183. return []string{createString("Basic_", mt[0])}
  184. case len(mt) == 2:
  185. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  186. default:
  187. return []string{createString("Standard_", mt[0])}
  188. }
  189. }
  190. func addSuffix(mt string, suffixes ...string) []string {
  191. result := make([]string, len(suffixes))
  192. var suffix string
  193. parts := strings.Split(mt, "_")
  194. if len(parts) > 2 {
  195. for _, p := range parts[2:] {
  196. suffix = createString(suffix, "_", p)
  197. }
  198. }
  199. for i, s := range suffixes {
  200. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  201. }
  202. return result
  203. }
  204. func getMachineTypeVariants(mt string) []string {
  205. switch {
  206. case mtStandardB.MatchString(mt):
  207. return []string{createString(mt, "s")}
  208. case mtStandardD.MatchString(mt):
  209. var result []string
  210. result = append(result, addSuffix(mt, "s")[0])
  211. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  212. result = append(result, dsType)
  213. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  214. return result
  215. case mtStandardE.MatchString(mt):
  216. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  217. case mtStandardF.MatchString(mt):
  218. return addSuffix(mt, "s")
  219. case mtStandardG.MatchString(mt):
  220. var result []string
  221. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  222. result = append(result, gsType)
  223. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  224. case mtStandardL.MatchString(mt):
  225. return addSuffix(mt, "s")
  226. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  227. base := strings.TrimSuffix(mt, "ms")
  228. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  229. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  230. return []string{}
  231. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  232. base := strings.TrimSuffix(mt, "s")
  233. return addSuffix(base, "", "m")
  234. case mtStandardN.MatchString(mt):
  235. return addSuffix(mt, "s")
  236. }
  237. return []string{}
  238. }
  239. // DownloadPricingData uses provided azure "best guesses" for pricing
  240. func (az *Azure) DownloadPricingData() error {
  241. config, err := az.GetConfig()
  242. if err != nil {
  243. return err
  244. }
  245. var authorizer autorest.Authorizer
  246. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  247. credentialsConfig := auth.NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID)
  248. a, err := credentialsConfig.Authorizer()
  249. if err != nil {
  250. return err
  251. }
  252. authorizer = a
  253. }
  254. if authorizer == nil {
  255. a, err := auth.NewAuthorizerFromEnvironment()
  256. authorizer = a
  257. if err != nil { // Failed to create authorizer from environment, try from file
  258. a, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
  259. if err != nil {
  260. return err
  261. }
  262. authorizer = a
  263. }
  264. }
  265. sClient := subscriptions.NewClient()
  266. sClient.Authorizer = authorizer
  267. rcClient := commerce.NewRateCardClient("054a7688-d090-43a0-bfa4-795cced8cd68")
  268. rcClient.Authorizer = authorizer
  269. skusClient := skus.NewResourceSkusClient("054a7688-d090-43a0-bfa4-795cced8cd68")
  270. skusClient.Authorizer = authorizer
  271. providersClient := resources.NewProvidersClient("054a7688-d090-43a0-bfa4-795cced8cd68")
  272. providersClient.Authorizer = authorizer
  273. containerServiceClient := containerservice.NewContainerServicesClient("054a7688-d090-43a0-bfa4-795cced8cd68")
  274. containerServiceClient.Authorizer = authorizer
  275. rateCardFilter := "OfferDurableId eq 'MS-AZR-0003p' and Currency eq 'USD' and Locale eq 'en-US' and RegionInfo eq 'US'"
  276. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  277. if err != nil {
  278. return err
  279. }
  280. allPrices := make(map[string]*Node)
  281. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  282. if err != nil {
  283. return err
  284. }
  285. c, err := az.GetConfig()
  286. if err != nil {
  287. return err
  288. }
  289. baseCPUPrice := c.CPU
  290. for _, v := range *result.Meters {
  291. region, err := toRegionID(*v.MeterRegion, regions)
  292. if err != nil {
  293. continue
  294. }
  295. meterName := *v.MeterName
  296. sc := *v.MeterSubCategory
  297. // not available now
  298. if strings.Contains(sc, "Promo") {
  299. continue
  300. }
  301. usageType := ""
  302. if !strings.Contains(meterName, "Low Priority") {
  303. usageType = "ondemand"
  304. } else {
  305. usageType = "preemptible"
  306. }
  307. var instanceTypes []string
  308. name := strings.TrimSuffix(meterName, " Low Priority")
  309. instanceType := strings.Split(name, "/")
  310. for _, it := range instanceType {
  311. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  312. }
  313. instanceTypes = transformMachineType(sc, instanceTypes)
  314. if strings.Contains(name, "Expired") {
  315. instanceTypes = []string{}
  316. }
  317. var priceInUsd float64
  318. if len(v.MeterRates) < 1 {
  319. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  320. continue
  321. }
  322. for _, rate := range v.MeterRates {
  323. priceInUsd += *rate
  324. }
  325. priceStr := fmt.Sprintf("%f", priceInUsd)
  326. for _, instanceType := range instanceTypes {
  327. klog.V(1).Infof("region: %s \n", region)
  328. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  329. allPrices[key] = &Node{
  330. Cost: priceStr,
  331. BaseCPUPrice: baseCPUPrice,
  332. }
  333. mts := getMachineTypeVariants(instanceType)
  334. for _, mt := range mts {
  335. key := fmt.Sprintf("%s,%s,%s", region, mt, usageType)
  336. allPrices[key] = &Node{
  337. Cost: priceStr,
  338. BaseCPUPrice: baseCPUPrice,
  339. }
  340. }
  341. }
  342. }
  343. az.allPrices = allPrices
  344. return nil
  345. }
  346. // AllNodePricing returns the Azure pricing objects stored
  347. func (az *Azure) AllNodePricing() (interface{}, error) {
  348. az.DownloadPricingDataLock.RLock()
  349. defer az.DownloadPricingDataLock.RUnlock()
  350. return az.allPrices, nil
  351. }
  352. // NodePricing returns Azure pricing data for a single node
  353. func (az *Azure) NodePricing(key Key) (*Node, error) {
  354. az.DownloadPricingDataLock.RLock()
  355. defer az.DownloadPricingDataLock.RUnlock()
  356. if n, ok := az.allPrices[key.Features()]; ok {
  357. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", key, n, key.Features())
  358. return n, nil
  359. }
  360. klog.V(1).Infof("Warning: no pricing data found for %s: %s", key.Features(), key)
  361. return nil, fmt.Errorf("Warning: no pricing data found for %s", key)
  362. }
  363. type azurePvKey struct {
  364. Labels map[string]string
  365. StorageClass string
  366. StorageClassParameters map[string]string
  367. }
  368. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string) PVKey {
  369. return &azurePvKey{
  370. Labels: pv.Labels,
  371. StorageClass: pv.Spec.StorageClassName,
  372. StorageClassParameters: parameters,
  373. }
  374. }
  375. func (key *azurePvKey) Features() string {
  376. storageClass := key.StorageClassParameters["type"]
  377. if storageClass == "pd-ssd" {
  378. storageClass = "ssd"
  379. } else if storageClass == "pd-standard" {
  380. storageClass = "pdstandard"
  381. }
  382. return key.Labels[v1.LabelZoneRegion] + "," + storageClass
  383. }
  384. func (*Azure) GetDisks() ([]byte, error) {
  385. return nil, nil
  386. }
  387. func (az *Azure) ClusterName() ([]byte, error) {
  388. return nil, nil
  389. }
  390. func (az *Azure) AddServiceKey(url url.Values) error {
  391. return nil
  392. }
  393. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  394. c, err := GetDefaultPricingData("azure.json")
  395. if err != nil {
  396. return nil, err
  397. }
  398. path := os.Getenv("CONFIG_PATH")
  399. if path == "" {
  400. path = "/models/"
  401. }
  402. a := make(map[string]string)
  403. err = json.NewDecoder(r).Decode(&a)
  404. if err != nil {
  405. return nil, err
  406. }
  407. for k, v := range a {
  408. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  409. err := SetCustomPricingField(c, kUpper, v)
  410. if err != nil {
  411. return nil, err
  412. }
  413. }
  414. cj, err := json.Marshal(c)
  415. if err != nil {
  416. return nil, err
  417. }
  418. configPath := path + "azure.json"
  419. err = ioutil.WriteFile(configPath, cj, 0644)
  420. if err != nil {
  421. return nil, err
  422. }
  423. return c, nil
  424. }
  425. func (az *Azure) GetConfig() (*CustomPricing, error) {
  426. c, err := GetDefaultPricingData("azure.json")
  427. if err != nil {
  428. return nil, err
  429. }
  430. return c, nil
  431. }
  432. func (az *Azure) ExternalAllocations(string, string, string) ([]*OutOfClusterAllocation, error) {
  433. return nil, nil
  434. }
  435. func (az *Azure) PVPricing(PVKey) (*PV, error) {
  436. return nil, nil
  437. }