azureprovider.go 16 KB

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