azureprovider.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "github.com/kubecost/cost-model/pkg/clustercache"
  13. "github.com/kubecost/cost-model/pkg/env"
  14. "github.com/kubecost/cost-model/pkg/util"
  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. const (
  27. AzureFilePremiumStorageClass = "premium_smb"
  28. AzureFileStandardStorageClass = "standard_smb"
  29. AzureDiskPremiumSSDStorageClass = "premium_ssd"
  30. AzureDiskStandardSSDStorageClass = "standard_ssd"
  31. AzureDiskStandardStorageClass = "standard_hdd"
  32. )
  33. var (
  34. regionCodeMappings = map[string]string{
  35. "ap": "asia",
  36. "au": "australia",
  37. "br": "brazil",
  38. "ca": "canada",
  39. "eu": "europe",
  40. "fr": "france",
  41. "in": "india",
  42. "ja": "japan",
  43. "kr": "korea",
  44. "uk": "uk",
  45. "us": "us",
  46. "za": "southafrica",
  47. }
  48. //mtBasic, _ = regexp.Compile("^BASIC.A\\d+[_Promo]*$")
  49. //mtStandardA, _ = regexp.Compile("^A\\d+[_Promo]*$")
  50. mtStandardB, _ = regexp.Compile(`^Standard_B\d+m?[_v\d]*[_Promo]*$`)
  51. mtStandardD, _ = regexp.Compile(`^Standard_D\d[_v\d]*[_Promo]*$`)
  52. mtStandardE, _ = regexp.Compile(`^Standard_E\d+i?[_v\d]*[_Promo]*$`)
  53. mtStandardF, _ = regexp.Compile(`^Standard_F\d+[_v\d]*[_Promo]*$`)
  54. mtStandardG, _ = regexp.Compile(`^Standard_G\d+[_v\d]*[_Promo]*$`)
  55. mtStandardL, _ = regexp.Compile(`^Standard_L\d+[_v\d]*[_Promo]*$`)
  56. mtStandardM, _ = regexp.Compile(`^Standard_M\d+[m|t|l]*s[_v\d]*[_Promo]*$`)
  57. mtStandardN, _ = regexp.Compile(`^Standard_N[C|D|V]\d+r?[_v\d]*[_Promo]*$`)
  58. )
  59. var loadedAzureSecret bool = false
  60. var azureSecret *AzureServiceKey = nil
  61. type regionParts []string
  62. func (r regionParts) String() string {
  63. var result string
  64. for _, p := range r {
  65. result += p
  66. }
  67. return result
  68. }
  69. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  70. allLocations := make(map[string]string)
  71. supLocations := make(map[string]string)
  72. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  73. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  74. // fill up the map: DisplayName - > Name
  75. for _, loc := range *locations.Value {
  76. allLocations[*loc.DisplayName] = *loc.Name
  77. }
  78. } else {
  79. return nil, err
  80. }
  81. // identify supported locations for the namespace and resource type
  82. const (
  83. providerNamespaceForCompute = "Microsoft.Compute"
  84. resourceTypeForCompute = "locations/vmSizes"
  85. providerNamespaceForAks = "Microsoft.ContainerService"
  86. resourceTypeForAks = "managedClusters"
  87. )
  88. switch service {
  89. case "aks":
  90. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  91. for _, pr := range *providers.ResourceTypes {
  92. if *pr.ResourceType == resourceTypeForAks {
  93. for _, displName := range *pr.Locations {
  94. if loc, ok := allLocations[displName]; ok {
  95. supLocations[loc] = displName
  96. } else {
  97. klog.V(1).Infof("unsupported cloud region %s", loc)
  98. }
  99. }
  100. break
  101. }
  102. }
  103. } else {
  104. return nil, err
  105. }
  106. return supLocations, nil
  107. default:
  108. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  109. for _, pr := range *providers.ResourceTypes {
  110. if *pr.ResourceType == resourceTypeForCompute {
  111. for _, displName := range *pr.Locations {
  112. if loc, ok := allLocations[displName]; ok {
  113. supLocations[loc] = displName
  114. } else {
  115. klog.V(1).Infof("unsupported cloud region %s", loc)
  116. }
  117. }
  118. break
  119. }
  120. }
  121. } else {
  122. return nil, err
  123. }
  124. return supLocations, nil
  125. }
  126. }
  127. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  128. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  129. regionCode := regionCodeMappings[rp[0]]
  130. lastPart := rp[len(rp)-1]
  131. var regionIds []string
  132. if _, err := strconv.Atoi(lastPart); err == nil {
  133. regionIds = []string{
  134. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  135. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  136. }
  137. } else {
  138. regionIds = []string{
  139. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  140. fmt.Sprintf("%s%s", rp[1:], regionCode),
  141. }
  142. }
  143. for _, regionID := range regionIds {
  144. if checkRegionID(regionID, regions) {
  145. return regionID, nil
  146. }
  147. }
  148. return "", fmt.Errorf("Couldn't find region")
  149. }
  150. func checkRegionID(regionID string, regions map[string]string) bool {
  151. for region := range regions {
  152. if regionID == region {
  153. return true
  154. }
  155. }
  156. return false
  157. }
  158. // AzurePricing either contains a Node or PV
  159. type AzurePricing struct {
  160. Node *Node
  161. PV *PV
  162. }
  163. type Azure struct {
  164. Pricing map[string]*AzurePricing
  165. DownloadPricingDataLock sync.RWMutex
  166. Clientset clustercache.ClusterCache
  167. Config *ProviderConfig
  168. }
  169. type azureKey struct {
  170. Labels map[string]string
  171. GPULabel string
  172. GPULabelValue string
  173. }
  174. func (k *azureKey) Features() string {
  175. region := strings.ToLower(k.Labels[v1.LabelZoneRegion])
  176. instance := k.Labels[v1.LabelInstanceType]
  177. usageType := "ondemand"
  178. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  179. }
  180. func (k *azureKey) GPUType() string {
  181. if t, ok := k.Labels[k.GPULabel]; ok {
  182. return t
  183. }
  184. return ""
  185. }
  186. func (k *azureKey) ID() string {
  187. return ""
  188. }
  189. // Represents an azure app key
  190. type AzureAppKey struct {
  191. AppID string `json:"appId"`
  192. DisplayName string `json:"displayName"`
  193. Name string `json:"name"`
  194. Password string `json:"password"`
  195. Tenant string `json:"tenant"`
  196. }
  197. // Azure service key for a specific subscription
  198. type AzureServiceKey struct {
  199. SubscriptionID string `json:"subscriptionId"`
  200. ServiceKey *AzureAppKey `json:"serviceKey"`
  201. }
  202. // Validity check on service key
  203. func (ask *AzureServiceKey) IsValid() bool {
  204. return ask.SubscriptionID != "" &&
  205. ask.ServiceKey != nil &&
  206. ask.ServiceKey.AppID != "" &&
  207. ask.ServiceKey.Password != "" &&
  208. ask.ServiceKey.Tenant != ""
  209. }
  210. // Loads the azure authentication via configuration or a secret set at install time.
  211. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  212. // 1. Check config values first (set from frontend UI)
  213. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  214. subscriptionID = cp.AzureSubscriptionID
  215. clientID = cp.AzureClientID
  216. clientSecret = cp.AzureClientSecret
  217. tenantID = cp.AzureTenantID
  218. return
  219. }
  220. // 2. Check for secret
  221. s, _ := az.loadAzureAuthSecret(forceReload)
  222. if s != nil && s.IsValid() {
  223. subscriptionID = s.SubscriptionID
  224. clientID = s.ServiceKey.AppID
  225. clientSecret = s.ServiceKey.Password
  226. tenantID = s.ServiceKey.Tenant
  227. return
  228. }
  229. // 3. Empty values
  230. return "", "", "", ""
  231. }
  232. // Load once and cache the result (even on failure). This is an install time secret, so
  233. // we don't expect the secret to change. If it does, however, we can force reload using
  234. // the input parameter.
  235. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  236. if !force && loadedAzureSecret {
  237. return azureSecret, nil
  238. }
  239. loadedAzureSecret = true
  240. exists, err := util.FileExists(authSecretPath)
  241. if !exists || err != nil {
  242. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  243. }
  244. result, err := ioutil.ReadFile(authSecretPath)
  245. if err != nil {
  246. return nil, err
  247. }
  248. var ask AzureServiceKey
  249. err = json.Unmarshal(result, &ask)
  250. if err != nil {
  251. return nil, err
  252. }
  253. azureSecret = &ask
  254. return azureSecret, nil
  255. }
  256. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  257. cfg, err := az.GetConfig()
  258. if err != nil {
  259. klog.Infof("Error loading azure custom pricing information")
  260. }
  261. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  262. gpuLabel := "accelerator"
  263. gpuLabelValue := "nvidia"
  264. if cfg.GpuLabel != "" {
  265. gpuLabel = cfg.GpuLabel
  266. }
  267. if cfg.GpuLabelValue != "" {
  268. gpuLabelValue = cfg.GpuLabelValue
  269. }
  270. return &azureKey{
  271. Labels: labels,
  272. GPULabel: gpuLabel,
  273. GPULabelValue: gpuLabelValue,
  274. }
  275. }
  276. // CreateString builds strings effectively
  277. func createString(keys ...string) string {
  278. var b strings.Builder
  279. for _, key := range keys {
  280. b.WriteString(key)
  281. }
  282. return b.String()
  283. }
  284. func transformMachineType(subCategory string, mt []string) []string {
  285. switch {
  286. case strings.Contains(subCategory, "Basic"):
  287. return []string{createString("Basic_", mt[0])}
  288. case len(mt) == 2:
  289. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  290. default:
  291. return []string{createString("Standard_", mt[0])}
  292. }
  293. }
  294. func addSuffix(mt string, suffixes ...string) []string {
  295. result := make([]string, len(suffixes))
  296. var suffix string
  297. parts := strings.Split(mt, "_")
  298. if len(parts) > 2 {
  299. for _, p := range parts[2:] {
  300. suffix = createString(suffix, "_", p)
  301. }
  302. }
  303. for i, s := range suffixes {
  304. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  305. }
  306. return result
  307. }
  308. func getMachineTypeVariants(mt string) []string {
  309. switch {
  310. case mtStandardB.MatchString(mt):
  311. return []string{createString(mt, "s")}
  312. case mtStandardD.MatchString(mt):
  313. var result []string
  314. result = append(result, addSuffix(mt, "s")[0])
  315. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  316. result = append(result, dsType)
  317. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  318. return result
  319. case mtStandardE.MatchString(mt):
  320. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  321. case mtStandardF.MatchString(mt):
  322. return addSuffix(mt, "s")
  323. case mtStandardG.MatchString(mt):
  324. var result []string
  325. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  326. result = append(result, gsType)
  327. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  328. case mtStandardL.MatchString(mt):
  329. return addSuffix(mt, "s")
  330. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  331. base := strings.TrimSuffix(mt, "ms")
  332. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  333. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  334. return []string{}
  335. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  336. base := strings.TrimSuffix(mt, "s")
  337. return addSuffix(base, "", "m")
  338. case mtStandardN.MatchString(mt):
  339. return addSuffix(mt, "s")
  340. }
  341. return []string{}
  342. }
  343. func (az *Azure) GetManagementPlatform() (string, error) {
  344. nodes := az.Clientset.GetAllNodes()
  345. if len(nodes) > 0 {
  346. n := nodes[0]
  347. providerID := n.Spec.ProviderID
  348. if strings.Contains(providerID, "aks") {
  349. return "aks", nil
  350. }
  351. }
  352. return "", nil
  353. }
  354. // DownloadPricingData uses provided azure "best guesses" for pricing
  355. func (az *Azure) DownloadPricingData() error {
  356. az.DownloadPricingDataLock.Lock()
  357. defer az.DownloadPricingDataLock.Unlock()
  358. config, err := az.GetConfig()
  359. if err != nil {
  360. return err
  361. }
  362. // Load the service provider keys
  363. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(false, config)
  364. config.AzureSubscriptionID = subscriptionID
  365. config.AzureClientID = clientID
  366. config.AzureClientSecret = clientSecret
  367. config.AzureTenantID = tenantID
  368. var authorizer autorest.Authorizer
  369. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  370. credentialsConfig := auth.NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID)
  371. a, err := credentialsConfig.Authorizer()
  372. if err != nil {
  373. return err
  374. }
  375. authorizer = a
  376. }
  377. if authorizer == nil {
  378. a, err := auth.NewAuthorizerFromEnvironment()
  379. authorizer = a
  380. if err != nil { // Failed to create authorizer from environment, try from file
  381. a, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
  382. if err != nil {
  383. return err
  384. }
  385. authorizer = a
  386. }
  387. }
  388. sClient := subscriptions.NewClient()
  389. sClient.Authorizer = authorizer
  390. rcClient := commerce.NewRateCardClient(config.AzureSubscriptionID)
  391. rcClient.Authorizer = authorizer
  392. skusClient := skus.NewResourceSkusClient(config.AzureSubscriptionID)
  393. skusClient.Authorizer = authorizer
  394. providersClient := resources.NewProvidersClient(config.AzureSubscriptionID)
  395. providersClient.Authorizer = authorizer
  396. containerServiceClient := containerservice.NewContainerServicesClient(config.AzureSubscriptionID)
  397. containerServiceClient.Authorizer = authorizer
  398. 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)
  399. klog.Infof("Using ratecard query %s", rateCardFilter)
  400. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  401. if err != nil {
  402. return err
  403. }
  404. allPrices := make(map[string]*AzurePricing)
  405. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  406. if err != nil {
  407. return err
  408. }
  409. c, err := az.GetConfig()
  410. if err != nil {
  411. return err
  412. }
  413. baseCPUPrice := c.CPU
  414. for _, v := range *result.Meters {
  415. meterName := *v.MeterName
  416. meterRegion := *v.MeterRegion
  417. meterCategory := *v.MeterCategory
  418. meterSubCategory := *v.MeterSubCategory
  419. region, err := toRegionID(meterRegion, regions)
  420. if err != nil {
  421. continue
  422. }
  423. if !strings.Contains(meterSubCategory, "Windows") {
  424. if strings.Contains(meterCategory, "Storage") {
  425. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  426. var storageClass string = ""
  427. if strings.Contains(meterName, "P4 ") {
  428. storageClass = AzureDiskPremiumSSDStorageClass
  429. } else if strings.Contains(meterName, "E4 ") {
  430. storageClass = AzureDiskStandardSSDStorageClass
  431. } else if strings.Contains(meterName, "S4 ") {
  432. storageClass = AzureDiskStandardStorageClass
  433. } else if strings.Contains(meterName, "LRS Provisioned") {
  434. storageClass = AzureFilePremiumStorageClass
  435. }
  436. if storageClass != "" {
  437. var priceInUsd float64
  438. if len(v.MeterRates) < 1 {
  439. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  440. continue
  441. }
  442. for _, rate := range v.MeterRates {
  443. priceInUsd += *rate
  444. }
  445. // rate is in disk per month, resolve price per hour, then GB per hour
  446. pricePerHour := priceInUsd / 730.0 / 32.0
  447. priceStr := fmt.Sprintf("%f", pricePerHour)
  448. key := region + "," + storageClass
  449. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  450. allPrices[key] = &AzurePricing{
  451. PV: &PV{
  452. Cost: priceStr,
  453. Region: region,
  454. },
  455. }
  456. }
  457. }
  458. }
  459. if strings.Contains(meterCategory, "Virtual Machines") {
  460. usageType := ""
  461. if !strings.Contains(meterName, "Low Priority") {
  462. usageType = "ondemand"
  463. } else {
  464. usageType = "preemptible"
  465. }
  466. var instanceTypes []string
  467. name := strings.TrimSuffix(meterName, " Low Priority")
  468. instanceType := strings.Split(name, "/")
  469. for _, it := range instanceType {
  470. if strings.Contains(meterSubCategory, "Promo") {
  471. it = it + " Promo"
  472. }
  473. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  474. }
  475. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  476. if strings.Contains(name, "Expired") {
  477. instanceTypes = []string{}
  478. }
  479. var priceInUsd float64
  480. if len(v.MeterRates) < 1 {
  481. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  482. continue
  483. }
  484. for _, rate := range v.MeterRates {
  485. priceInUsd += *rate
  486. }
  487. priceStr := fmt.Sprintf("%f", priceInUsd)
  488. for _, instanceType := range instanceTypes {
  489. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  490. allPrices[key] = &AzurePricing{
  491. Node: &Node{
  492. Cost: priceStr,
  493. BaseCPUPrice: baseCPUPrice,
  494. },
  495. }
  496. }
  497. }
  498. }
  499. }
  500. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  501. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  502. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  503. zeroPrice := "0.0"
  504. for region := range regions {
  505. key := region + "," + AzureFileStandardStorageClass
  506. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  507. allPrices[key] = &AzurePricing{
  508. PV: &PV{
  509. Cost: zeroPrice,
  510. Region: region,
  511. },
  512. }
  513. }
  514. az.Pricing = allPrices
  515. return nil
  516. }
  517. // AllNodePricing returns the Azure pricing objects stored
  518. func (az *Azure) AllNodePricing() (interface{}, error) {
  519. az.DownloadPricingDataLock.RLock()
  520. defer az.DownloadPricingDataLock.RUnlock()
  521. return az.Pricing, nil
  522. }
  523. // NodePricing returns Azure pricing data for a single node
  524. func (az *Azure) NodePricing(key Key) (*Node, error) {
  525. az.DownloadPricingDataLock.RLock()
  526. defer az.DownloadPricingDataLock.RUnlock()
  527. if n, ok := az.Pricing[key.Features()]; ok {
  528. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", key, n, key.Features())
  529. if key.GPUType() != "" {
  530. n.Node.GPU = "1" // TODO: support multiple GPUs
  531. }
  532. return n.Node, nil
  533. }
  534. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", key.Features(), key)
  535. c, err := az.GetConfig()
  536. if err != nil {
  537. return nil, fmt.Errorf("No default pricing data available")
  538. }
  539. if key.GPUType() != "" {
  540. return &Node{
  541. VCPUCost: c.CPU,
  542. RAMCost: c.RAM,
  543. GPUCost: c.GPU,
  544. GPU: "1", // TODO: support multiple GPUs
  545. }, nil
  546. }
  547. return &Node{
  548. VCPUCost: c.CPU,
  549. RAMCost: c.RAM,
  550. UsesBaseCPUPrice: true,
  551. }, nil
  552. }
  553. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  554. func (az *Azure) NetworkPricing() (*Network, error) {
  555. cpricing, err := az.Config.GetCustomPricingData()
  556. if err != nil {
  557. return nil, err
  558. }
  559. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  560. if err != nil {
  561. return nil, err
  562. }
  563. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  564. if err != nil {
  565. return nil, err
  566. }
  567. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  568. if err != nil {
  569. return nil, err
  570. }
  571. return &Network{
  572. ZoneNetworkEgressCost: znec,
  573. RegionNetworkEgressCost: rnec,
  574. InternetNetworkEgressCost: inec,
  575. }, nil
  576. }
  577. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  578. fffrc := 0.025
  579. afrc := 0.010
  580. lbidc := 0.008
  581. numForwardingRules := 1.0
  582. dataIngressGB := 0.0
  583. var totalCost float64
  584. if numForwardingRules < 5 {
  585. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  586. } else {
  587. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  588. }
  589. return &LoadBalancer{
  590. Cost: totalCost,
  591. }, nil
  592. }
  593. type azurePvKey struct {
  594. Labels map[string]string
  595. StorageClass string
  596. StorageClassParameters map[string]string
  597. DefaultRegion string
  598. }
  599. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  600. return &azurePvKey{
  601. Labels: pv.Labels,
  602. StorageClass: pv.Spec.StorageClassName,
  603. StorageClassParameters: parameters,
  604. DefaultRegion: defaultRegion,
  605. }
  606. }
  607. func (key *azurePvKey) ID() string {
  608. return ""
  609. }
  610. func (key *azurePvKey) GetStorageClass() string {
  611. return key.StorageClass
  612. }
  613. func (key *azurePvKey) Features() string {
  614. storageClass := key.StorageClassParameters["storageaccounttype"]
  615. storageSKU := key.StorageClassParameters["skuName"]
  616. if storageClass != "" {
  617. if strings.EqualFold(storageClass, "Premium_LRS") {
  618. storageClass = AzureDiskPremiumSSDStorageClass
  619. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  620. storageClass = AzureDiskStandardSSDStorageClass
  621. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  622. storageClass = AzureDiskStandardStorageClass
  623. }
  624. } else {
  625. if strings.EqualFold(storageSKU, "Premium_LRS") {
  626. storageClass = AzureFilePremiumStorageClass
  627. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  628. storageClass = AzureFileStandardStorageClass
  629. }
  630. }
  631. if region, ok := key.Labels[v1.LabelZoneRegion]; ok {
  632. return region + "," + storageClass
  633. }
  634. return key.DefaultRegion + "," + storageClass
  635. }
  636. func (*Azure) GetAddresses() ([]byte, error) {
  637. return nil, nil
  638. }
  639. func (*Azure) GetDisks() ([]byte, error) {
  640. return nil, nil
  641. }
  642. func (az *Azure) ClusterInfo() (map[string]string, error) {
  643. remoteEnabled := env.IsRemoteEnabled()
  644. m := make(map[string]string)
  645. m["name"] = "Azure Cluster #1"
  646. c, err := az.GetConfig()
  647. if err != nil {
  648. return nil, err
  649. }
  650. if c.ClusterName != "" {
  651. m["name"] = c.ClusterName
  652. }
  653. m["provider"] = "azure"
  654. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  655. m["id"] = env.GetClusterID()
  656. return m, nil
  657. }
  658. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  659. return az.Config.UpdateFromMap(a)
  660. }
  661. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  662. defer az.DownloadPricingData()
  663. return az.Config.Update(func(c *CustomPricing) error {
  664. a := make(map[string]interface{})
  665. err := json.NewDecoder(r).Decode(&a)
  666. if err != nil {
  667. return err
  668. }
  669. for k, v := range a {
  670. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  671. vstr, ok := v.(string)
  672. if ok {
  673. err := SetCustomPricingField(c, kUpper, vstr)
  674. if err != nil {
  675. return err
  676. }
  677. } else {
  678. sci := v.(map[string]interface{})
  679. sc := make(map[string]string)
  680. for k, val := range sci {
  681. sc[k] = val.(string)
  682. }
  683. c.SharedCosts = sc //todo: support reflection/multiple map fields
  684. }
  685. }
  686. if env.IsRemoteEnabled() {
  687. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  688. if err != nil {
  689. return err
  690. }
  691. }
  692. return nil
  693. })
  694. }
  695. func (az *Azure) GetConfig() (*CustomPricing, error) {
  696. c, err := az.Config.GetCustomPricingData()
  697. if c.Discount == "" {
  698. c.Discount = "0%"
  699. }
  700. if c.NegotiatedDiscount == "" {
  701. c.NegotiatedDiscount = "0%"
  702. }
  703. if c.CurrencyCode == "" {
  704. c.CurrencyCode = "USD"
  705. }
  706. if c.AzureBillingRegion == "" {
  707. c.AzureBillingRegion = "US"
  708. }
  709. if err != nil {
  710. return nil, err
  711. }
  712. return c, nil
  713. }
  714. func (az *Azure) ExternalAllocations(string, string, []string, string, string, bool) ([]*OutOfClusterAllocation, error) {
  715. return nil, nil
  716. }
  717. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  718. }
  719. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  720. az.DownloadPricingDataLock.RLock()
  721. defer az.DownloadPricingDataLock.RUnlock()
  722. pricing, ok := az.Pricing[pvk.Features()]
  723. if !ok {
  724. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  725. return &PV{}, nil
  726. }
  727. return pricing.PV, nil
  728. }
  729. func (az *Azure) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  730. return ""
  731. }
  732. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  733. return &ServiceAccountStatus{
  734. Checks: []*ServiceAccountCheck{},
  735. }
  736. }
  737. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  738. return "", 0.0, nil
  739. }
  740. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  741. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  742. }
  743. func (az *Azure) ParseID(id string) string {
  744. return id
  745. }
  746. func (az *Azure) ParsePVID(id string) string {
  747. return id
  748. }