2
0

azureprovider.go 16 KB

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