azureprovider.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. package cloud
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/kubecost/cost-model/pkg/log"
  15. "github.com/kubecost/cost-model/pkg/clustercache"
  16. "github.com/kubecost/cost-model/pkg/env"
  17. "github.com/kubecost/cost-model/pkg/util"
  18. "github.com/kubecost/cost-model/pkg/util/fileutil"
  19. "github.com/kubecost/cost-model/pkg/util/json"
  20. "github.com/Azure/azure-sdk-for-go/services/preview/commerce/mgmt/2015-06-01-preview/commerce"
  21. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
  22. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
  23. "github.com/Azure/go-autorest/autorest"
  24. "github.com/Azure/go-autorest/autorest/azure"
  25. "github.com/Azure/go-autorest/autorest/azure/auth"
  26. v1 "k8s.io/api/core/v1"
  27. "k8s.io/klog"
  28. )
  29. const (
  30. AzureFilePremiumStorageClass = "premium_smb"
  31. AzureFileStandardStorageClass = "standard_smb"
  32. AzureDiskPremiumSSDStorageClass = "premium_ssd"
  33. AzureDiskStandardSSDStorageClass = "standard_ssd"
  34. AzureDiskStandardStorageClass = "standard_hdd"
  35. defaultSpotLabel = "kubernetes.azure.com/scalesetpriority"
  36. defaultSpotLabelValue = "spot"
  37. )
  38. var (
  39. regionCodeMappings = map[string]string{
  40. "ap": "asia",
  41. "au": "australia",
  42. "br": "brazil",
  43. "ca": "canada",
  44. "eu": "europe",
  45. "fr": "france",
  46. "in": "india",
  47. "ja": "japan",
  48. "kr": "korea",
  49. "uk": "uk",
  50. "us": "us",
  51. "za": "southafrica",
  52. "no": "norway",
  53. }
  54. //mtBasic, _ = regexp.Compile("^BASIC.A\\d+[_Promo]*$")
  55. //mtStandardA, _ = regexp.Compile("^A\\d+[_Promo]*$")
  56. mtStandardB, _ = regexp.Compile(`^Standard_B\d+m?[_v\d]*[_Promo]*$`)
  57. mtStandardD, _ = regexp.Compile(`^Standard_D\d[_v\d]*[_Promo]*$`)
  58. mtStandardE, _ = regexp.Compile(`^Standard_E\d+i?[_v\d]*[_Promo]*$`)
  59. mtStandardF, _ = regexp.Compile(`^Standard_F\d+[_v\d]*[_Promo]*$`)
  60. mtStandardG, _ = regexp.Compile(`^Standard_G\d+[_v\d]*[_Promo]*$`)
  61. mtStandardL, _ = regexp.Compile(`^Standard_L\d+[_v\d]*[_Promo]*$`)
  62. mtStandardM, _ = regexp.Compile(`^Standard_M\d+[m|t|l]*s[_v\d]*[_Promo]*$`)
  63. mtStandardN, _ = regexp.Compile(`^Standard_N[C|D|V]\d+r?[_v\d]*[_Promo]*$`)
  64. )
  65. // List obtained by installing the Azure CLI tool "az", described here:
  66. // https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt
  67. // logging into an Azure account, and running command `az account list-locations`
  68. var azureRegions = []string{
  69. "eastus",
  70. "eastus2",
  71. "southcentralus",
  72. "westus2",
  73. "westus3",
  74. "australiaeast",
  75. "southeastasia",
  76. "northeurope",
  77. "swedencentral",
  78. "uksouth",
  79. "westeurope",
  80. "centralus",
  81. "northcentralus",
  82. "westus",
  83. "southafricanorth",
  84. "centralindia",
  85. "eastasia",
  86. "japaneast",
  87. "jioindiawest",
  88. "koreacentral",
  89. "canadacentral",
  90. "francecentral",
  91. "germanywestcentral",
  92. "norwayeast",
  93. "switzerlandnorth",
  94. "uaenorth",
  95. "brazilsouth",
  96. "centralusstage",
  97. "eastusstage",
  98. "eastus2stage",
  99. "northcentralusstage",
  100. "southcentralusstage",
  101. "westusstage",
  102. "westus2stage",
  103. "asia",
  104. "asiapacific",
  105. "australia",
  106. "brazil",
  107. "canada",
  108. "europe",
  109. "france",
  110. "germany",
  111. "global",
  112. "india",
  113. "japan",
  114. "korea",
  115. "norway",
  116. "southafrica",
  117. "switzerland",
  118. "uae",
  119. "uk",
  120. "unitedstates",
  121. "eastasiastage",
  122. "southeastasiastage",
  123. "centraluseuap",
  124. "eastus2euap",
  125. "westcentralus",
  126. "southafricawest",
  127. "australiacentral",
  128. "australiacentral2",
  129. "australiasoutheast",
  130. "japanwest",
  131. "jioindiacentral",
  132. "koreasouth",
  133. "southindia",
  134. "westindia",
  135. "canadaeast",
  136. "francesouth",
  137. "germanynorth",
  138. "norwaywest",
  139. "switzerlandwest",
  140. "ukwest",
  141. "uaecentral",
  142. "brazilsoutheast",
  143. "usgovarizona",
  144. "usgoviowa",
  145. "usgovvirginia",
  146. "usgovtexas",
  147. }
  148. type regionParts []string
  149. func (r regionParts) String() string {
  150. var result string
  151. for _, p := range r {
  152. result += p
  153. }
  154. return result
  155. }
  156. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  157. allLocations := make(map[string]string)
  158. supLocations := make(map[string]string)
  159. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  160. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  161. // fill up the map: DisplayName - > Name
  162. for _, loc := range *locations.Value {
  163. allLocations[*loc.DisplayName] = *loc.Name
  164. }
  165. } else {
  166. return nil, err
  167. }
  168. // identify supported locations for the namespace and resource type
  169. const (
  170. providerNamespaceForCompute = "Microsoft.Compute"
  171. resourceTypeForCompute = "locations/vmSizes"
  172. providerNamespaceForAks = "Microsoft.ContainerService"
  173. resourceTypeForAks = "managedClusters"
  174. )
  175. switch service {
  176. case "aks":
  177. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  178. for _, pr := range *providers.ResourceTypes {
  179. if *pr.ResourceType == resourceTypeForAks {
  180. for _, displName := range *pr.Locations {
  181. if loc, ok := allLocations[displName]; ok {
  182. supLocations[loc] = displName
  183. } else {
  184. klog.V(1).Infof("unsupported cloud region %s", loc)
  185. }
  186. }
  187. break
  188. }
  189. }
  190. } else {
  191. return nil, err
  192. }
  193. return supLocations, nil
  194. default:
  195. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  196. for _, pr := range *providers.ResourceTypes {
  197. if *pr.ResourceType == resourceTypeForCompute {
  198. for _, displName := range *pr.Locations {
  199. if loc, ok := allLocations[displName]; ok {
  200. supLocations[loc] = displName
  201. } else {
  202. klog.V(1).Infof("unsupported cloud region %s", loc)
  203. }
  204. }
  205. break
  206. }
  207. }
  208. } else {
  209. return nil, err
  210. }
  211. return supLocations, nil
  212. }
  213. }
  214. func getRetailPrice(region string, skuName string, currencyCode string, spot bool) (string, error) {
  215. pricingURL := "https://prices.azure.com/api/retail/prices?$skip=0"
  216. if currencyCode != "" {
  217. pricingURL += fmt.Sprintf("&currencyCode='%s'", currencyCode)
  218. }
  219. var filterParams []string
  220. if region != "" {
  221. regionParam := fmt.Sprintf("armRegionName eq '%s'", region)
  222. filterParams = append(filterParams, regionParam)
  223. }
  224. if skuName != "" {
  225. skuNameParam := fmt.Sprintf("armSkuName eq '%s'", skuName)
  226. filterParams = append(filterParams, skuNameParam)
  227. }
  228. if len(filterParams) > 0 {
  229. filterParamsEscaped := url.QueryEscape(strings.Join(filterParams[:], " and "))
  230. pricingURL += fmt.Sprintf("&$filter=%s", filterParamsEscaped)
  231. }
  232. log.Infof("starting download retail price payload from \"%s\"", pricingURL)
  233. resp, err := http.Get(pricingURL)
  234. if err != nil {
  235. return "", fmt.Errorf("bogus fetch of \"%s\": %v", pricingURL, err)
  236. }
  237. if resp.StatusCode < 200 && resp.StatusCode > 299 {
  238. return "", fmt.Errorf("retail price responded with error status code %d", resp.StatusCode)
  239. }
  240. pricingPayload := AzureRetailPricing{}
  241. body, err := ioutil.ReadAll(resp.Body)
  242. if err != nil {
  243. return "", fmt.Errorf("Error getting response: %v", err)
  244. }
  245. jsonErr := json.Unmarshal(body, &pricingPayload)
  246. if jsonErr != nil {
  247. return "", fmt.Errorf("Error unmarshalling data: %v", jsonErr)
  248. }
  249. retailPrice := ""
  250. for _, item := range pricingPayload.Items {
  251. if item.Type == "Consumption" && !strings.Contains(item.ProductName, "Windows") {
  252. // if spot is true SkuName should contain "spot, if it is false it should not
  253. if spot == strings.Contains(strings.ToLower(item.SkuName), " spot") {
  254. retailPrice = fmt.Sprintf("%f", item.RetailPrice)
  255. }
  256. }
  257. }
  258. log.DedupedInfof(5, "done parsing retail price payload from \"%s\"\n", pricingURL)
  259. if retailPrice == "" {
  260. return retailPrice, fmt.Errorf("Couldn't find price for product \"%s\" in \"%s\" region", skuName, region)
  261. }
  262. return retailPrice, nil
  263. }
  264. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  265. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  266. regionCode := regionCodeMappings[rp[0]]
  267. lastPart := rp[len(rp)-1]
  268. var regionIds []string
  269. if regionID, ok := regionIdByDisplayName[meterRegion]; ok {
  270. regionIds = []string{
  271. regionID,
  272. }
  273. } else if _, err := strconv.Atoi(lastPart); err == nil {
  274. regionIds = []string{
  275. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  276. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  277. }
  278. } else {
  279. regionIds = []string{
  280. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  281. fmt.Sprintf("%s%s", rp[1:], regionCode),
  282. }
  283. }
  284. for _, regionID := range regionIds {
  285. if checkRegionID(regionID, regions) {
  286. return regionID, nil
  287. }
  288. }
  289. return "", fmt.Errorf("Couldn't find region")
  290. }
  291. // azure has very inconsistent naming standards between display names from the rate card api and display names from the regions api
  292. // this map is to connect display names from the ratecard api to the appropriate id.
  293. var regionIdByDisplayName = map[string]string{
  294. "US Gov AZ": "usgovarizona",
  295. "US Gov TX": "usgovtexas",
  296. "US Gov": "usgovvirginia",
  297. }
  298. func checkRegionID(regionID string, regions map[string]string) bool {
  299. for region := range regions {
  300. if regionID == region {
  301. return true
  302. }
  303. }
  304. return false
  305. }
  306. // AzureRetailPricing struct for unmarshalling Azure Retail pricing api JSON response
  307. type AzureRetailPricing struct {
  308. BillingCurrency string `json:"BillingCurrency"`
  309. CustomerEntityId string `json:"CustomerEntityId"`
  310. CustomerEntityType string `json:"CustomerEntityType"`
  311. Items []AzureRetailPricingAttributes `json:"Items"`
  312. NextPageLink string `json:"NextPageLink"`
  313. Count int `json:"Count"`
  314. }
  315. //AzureRetailPricingAttributes struct for unmarshalling Azure Retail pricing api JSON response
  316. type AzureRetailPricingAttributes struct {
  317. CurrencyCode string `json:"currencyCode"`
  318. TierMinimumUnits float32 `json:"tierMinimumUnits"`
  319. RetailPrice float32 `json:"retailPrice"`
  320. UnitPrice float32 `json:"unitPrice"`
  321. ArmRegionName string `json:"armRegionName"`
  322. Location string `json:"location"`
  323. EffectiveStartDate *time.Time `json:"effectiveStartDate"`
  324. EffectiveEndDate *time.Time `json:"effectiveEndDate"`
  325. MeterId string `json:"meterId"`
  326. MeterName string `json:"meterName"`
  327. ProductId string `json:"productId"`
  328. SkuId string `json:"skuId"`
  329. ProductName string `json:"productName"`
  330. SkuName string `json:"skuName"`
  331. ServiceName string `json:"serviceName"`
  332. ServiceId string `json:"serviceId"`
  333. ServiceFamily string `json:"serviceFamily"`
  334. UnitOfMeasure string `json:"unitOfMeasure"`
  335. Type string `json:"type"`
  336. IsPrimaryMeterRegion bool `json:"isPrimaryMeterRegion"`
  337. ArmSkuName string `json:"armSkuName"`
  338. }
  339. // AzurePricing either contains a Node or PV
  340. type AzurePricing struct {
  341. Node *Node
  342. PV *PV
  343. }
  344. type Azure struct {
  345. Pricing map[string]*AzurePricing
  346. DownloadPricingDataLock sync.RWMutex
  347. Clientset clustercache.ClusterCache
  348. Config *ProviderConfig
  349. serviceAccountChecks *ServiceAccountChecks
  350. RateCardPricingError error
  351. clusterAccountId string
  352. clusterRegion string
  353. loadedAzureSecret bool
  354. azureSecret *AzureServiceKey
  355. loadedAzureStorageConfigSecret bool
  356. azureStorageConfig *AzureStorageConfig
  357. }
  358. type azureKey struct {
  359. Labels map[string]string
  360. GPULabel string
  361. GPULabelValue string
  362. }
  363. func (k *azureKey) Features() string {
  364. r, _ := util.GetRegion(k.Labels)
  365. region := strings.ToLower(r)
  366. instance, _ := util.GetInstanceType(k.Labels)
  367. usageType := "ondemand"
  368. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  369. }
  370. // GPUType returns value of GPULabel if present
  371. func (k *azureKey) GPUType() string {
  372. if t, ok := k.Labels[k.GPULabel]; ok {
  373. return t
  374. }
  375. return ""
  376. }
  377. func (k *azureKey) isValidGPUNode() bool {
  378. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  379. }
  380. func (k *azureKey) ID() string {
  381. return ""
  382. }
  383. func (k *azureKey) GetGPUCount() string {
  384. instance, _ := util.GetInstanceType(k.Labels)
  385. // Double digits that could get matches lower in logic
  386. if strings.Contains(instance, "NC64") {
  387. return "4"
  388. }
  389. if strings.Contains(instance, "ND96") ||
  390. strings.Contains(instance, "ND40") {
  391. return "8"
  392. }
  393. // Ordered asc because of some series have different gpu counts on different versions
  394. if strings.Contains(instance, "NC6") ||
  395. strings.Contains(instance, "NC4") ||
  396. strings.Contains(instance, "NC8") ||
  397. strings.Contains(instance, "NC16") ||
  398. strings.Contains(instance, "ND6") ||
  399. strings.Contains(instance, "NV12s") ||
  400. strings.Contains(instance, "NV6") {
  401. return "1"
  402. }
  403. if strings.Contains(instance, "NC12") ||
  404. strings.Contains(instance, "ND12") ||
  405. strings.Contains(instance, "NV24s") ||
  406. strings.Contains(instance, "NV12") {
  407. return "2"
  408. }
  409. if strings.Contains(instance, "NC24") ||
  410. strings.Contains(instance, "ND24") ||
  411. strings.Contains(instance, "NV48s") ||
  412. strings.Contains(instance, "NV24") {
  413. return "4"
  414. }
  415. return "0"
  416. }
  417. // AzureStorageConfig Represents an azure storage config
  418. type AzureStorageConfig struct {
  419. SubscriptionId string `json:"azureSubscriptionID"`
  420. AccountName string `json:"azureStorageAccount"`
  421. AccessKey string `json:"azureStorageAccessKey"`
  422. ContainerName string `json:"azureStorageContainer"`
  423. ContainerPath string `json:"azureContainerPath"`
  424. AzureCloud string `json:"azureCloud"`
  425. }
  426. // IsEmpty returns true if all fields in config are empty, false if not.
  427. func (asc *AzureStorageConfig) IsEmpty() bool {
  428. return asc.SubscriptionId == "" &&
  429. asc.AccountName == "" &&
  430. asc.AccessKey == "" &&
  431. asc.ContainerName == "" &&
  432. asc.ContainerPath == "" &&
  433. asc.AzureCloud == ""
  434. }
  435. // Represents an azure app key
  436. type AzureAppKey struct {
  437. AppID string `json:"appId"`
  438. DisplayName string `json:"displayName"`
  439. Name string `json:"name"`
  440. Password string `json:"password"`
  441. Tenant string `json:"tenant"`
  442. }
  443. // Azure service key for a specific subscription
  444. type AzureServiceKey struct {
  445. SubscriptionID string `json:"subscriptionId"`
  446. ServiceKey *AzureAppKey `json:"serviceKey"`
  447. }
  448. // Validity check on service key
  449. func (ask *AzureServiceKey) IsValid() bool {
  450. return ask.SubscriptionID != "" &&
  451. ask.ServiceKey != nil &&
  452. ask.ServiceKey.AppID != "" &&
  453. ask.ServiceKey.Password != "" &&
  454. ask.ServiceKey.Tenant != ""
  455. }
  456. // Loads the azure authentication via configuration or a secret set at install time.
  457. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  458. // 1. Check config values first (set from frontend UI)
  459. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  460. subscriptionID = cp.AzureSubscriptionID
  461. clientID = cp.AzureClientID
  462. clientSecret = cp.AzureClientSecret
  463. tenantID = cp.AzureTenantID
  464. return
  465. }
  466. // 2. Check for secret
  467. s, _ := az.loadAzureAuthSecret(forceReload)
  468. if s != nil && s.IsValid() {
  469. subscriptionID = s.SubscriptionID
  470. clientID = s.ServiceKey.AppID
  471. clientSecret = s.ServiceKey.Password
  472. tenantID = s.ServiceKey.Tenant
  473. return
  474. }
  475. // 3. Empty values
  476. return "", "", "", ""
  477. }
  478. // GetAzureStorageConfig retrieves storage config from secret and sets default values
  479. func (az *Azure) GetAzureStorageConfig(forceReload bool) (*AzureStorageConfig, error) {
  480. // retrieve config for default subscription id
  481. defaultSubscriptionID := ""
  482. config, err := az.GetConfig()
  483. if err == nil {
  484. defaultSubscriptionID = config.AzureSubscriptionID
  485. }
  486. // 1. Check for secret
  487. s, err := az.loadAzureStorageConfig(forceReload)
  488. if err != nil {
  489. log.Errorf("Error, %s", err.Error())
  490. }
  491. if s != nil && s.AccessKey != "" && s.AccountName != "" && s.ContainerName != "" {
  492. az.serviceAccountChecks.set("hasStorage", &ServiceAccountCheck{
  493. Message: "Azure Storage Config exists",
  494. Status: true,
  495. })
  496. // To support already configured users, subscriptionID may not be set in secret in which case, the subscriptionID
  497. // for the rate card API is used
  498. if s.SubscriptionId == "" {
  499. s.SubscriptionId = defaultSubscriptionID
  500. }
  501. return s, nil
  502. }
  503. az.serviceAccountChecks.set("hasStorage", &ServiceAccountCheck{
  504. Message: "Azure Storage Config exists",
  505. Status: false,
  506. })
  507. return nil, fmt.Errorf("azure storage config not found")
  508. }
  509. // Load once and cache the result (even on failure). This is an install time secret, so
  510. // we don't expect the secret to change. If it does, however, we can force reload using
  511. // the input parameter.
  512. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  513. if !force && az.loadedAzureSecret {
  514. return az.azureSecret, nil
  515. }
  516. az.loadedAzureSecret = true
  517. exists, err := fileutil.FileExists(authSecretPath)
  518. if !exists || err != nil {
  519. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  520. }
  521. result, err := ioutil.ReadFile(authSecretPath)
  522. if err != nil {
  523. return nil, err
  524. }
  525. var ask AzureServiceKey
  526. err = json.Unmarshal(result, &ask)
  527. if err != nil {
  528. return nil, err
  529. }
  530. az.azureSecret = &ask
  531. return &ask, nil
  532. }
  533. // Load once and cache the result (even on failure). This is an install time secret, so
  534. // we don't expect the secret to change. If it does, however, we can force reload using
  535. // the input parameter.
  536. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  537. if !force && az.loadedAzureStorageConfigSecret {
  538. return az.azureStorageConfig, nil
  539. }
  540. az.loadedAzureStorageConfigSecret = true
  541. exists, err := fileutil.FileExists(storageConfigSecretPath)
  542. if !exists || err != nil {
  543. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  544. }
  545. result, err := ioutil.ReadFile(storageConfigSecretPath)
  546. if err != nil {
  547. return nil, err
  548. }
  549. var asc AzureStorageConfig
  550. err = json.Unmarshal(result, &asc)
  551. if err != nil {
  552. return nil, err
  553. }
  554. az.azureStorageConfig = &asc
  555. return &asc, nil
  556. }
  557. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  558. cfg, err := az.GetConfig()
  559. if err != nil {
  560. klog.Infof("Error loading azure custom pricing information")
  561. }
  562. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  563. gpuLabel := "accelerator"
  564. gpuLabelValue := "nvidia"
  565. if cfg.GpuLabel != "" {
  566. gpuLabel = cfg.GpuLabel
  567. }
  568. if cfg.GpuLabelValue != "" {
  569. gpuLabelValue = cfg.GpuLabelValue
  570. }
  571. return &azureKey{
  572. Labels: labels,
  573. GPULabel: gpuLabel,
  574. GPULabelValue: gpuLabelValue,
  575. }
  576. }
  577. // CreateString builds strings effectively
  578. func createString(keys ...string) string {
  579. var b strings.Builder
  580. for _, key := range keys {
  581. b.WriteString(key)
  582. }
  583. return b.String()
  584. }
  585. func transformMachineType(subCategory string, mt []string) []string {
  586. switch {
  587. case strings.Contains(subCategory, "Basic"):
  588. return []string{createString("Basic_", mt[0])}
  589. case len(mt) == 2:
  590. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  591. default:
  592. return []string{createString("Standard_", mt[0])}
  593. }
  594. }
  595. func addSuffix(mt string, suffixes ...string) []string {
  596. result := make([]string, len(suffixes))
  597. var suffix string
  598. parts := strings.Split(mt, "_")
  599. if len(parts) > 2 {
  600. for _, p := range parts[2:] {
  601. suffix = createString(suffix, "_", p)
  602. }
  603. }
  604. for i, s := range suffixes {
  605. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  606. }
  607. return result
  608. }
  609. func getMachineTypeVariants(mt string) []string {
  610. switch {
  611. case mtStandardB.MatchString(mt):
  612. return []string{createString(mt, "s")}
  613. case mtStandardD.MatchString(mt):
  614. var result []string
  615. result = append(result, addSuffix(mt, "s")[0])
  616. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  617. result = append(result, dsType)
  618. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  619. return result
  620. case mtStandardE.MatchString(mt):
  621. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  622. case mtStandardF.MatchString(mt):
  623. return addSuffix(mt, "s")
  624. case mtStandardG.MatchString(mt):
  625. var result []string
  626. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  627. result = append(result, gsType)
  628. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  629. case mtStandardL.MatchString(mt):
  630. return addSuffix(mt, "s")
  631. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  632. base := strings.TrimSuffix(mt, "ms")
  633. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  634. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  635. return []string{}
  636. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  637. base := strings.TrimSuffix(mt, "s")
  638. return addSuffix(base, "", "m")
  639. case mtStandardN.MatchString(mt):
  640. return addSuffix(mt, "s")
  641. }
  642. return []string{}
  643. }
  644. func (az *Azure) GetManagementPlatform() (string, error) {
  645. nodes := az.Clientset.GetAllNodes()
  646. if len(nodes) > 0 {
  647. n := nodes[0]
  648. providerID := n.Spec.ProviderID
  649. if strings.Contains(providerID, "aks") {
  650. return "aks", nil
  651. }
  652. }
  653. return "", nil
  654. }
  655. // DownloadPricingData uses provided azure "best guesses" for pricing
  656. func (az *Azure) DownloadPricingData() error {
  657. az.DownloadPricingDataLock.Lock()
  658. defer az.DownloadPricingDataLock.Unlock()
  659. config, err := az.GetConfig()
  660. if err != nil {
  661. az.RateCardPricingError = err
  662. return err
  663. }
  664. // Load the service provider keys
  665. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(true, config)
  666. config.AzureSubscriptionID = subscriptionID
  667. config.AzureClientID = clientID
  668. config.AzureClientSecret = clientSecret
  669. config.AzureTenantID = tenantID
  670. var authorizer autorest.Authorizer
  671. azureEnv := determineCloudByRegion(az.clusterRegion)
  672. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  673. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  674. a, err := credentialsConfig.Authorizer()
  675. if err != nil {
  676. az.RateCardPricingError = err
  677. return err
  678. }
  679. authorizer = a
  680. }
  681. if authorizer == nil {
  682. a, err := auth.NewAuthorizerFromEnvironment()
  683. authorizer = a
  684. if err != nil {
  685. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  686. if err != nil {
  687. az.RateCardPricingError = err
  688. return err
  689. }
  690. authorizer = a
  691. }
  692. }
  693. sClient := subscriptions.NewClientWithBaseURI(azureEnv.ResourceManagerEndpoint)
  694. sClient.Authorizer = authorizer
  695. rcClient := commerce.NewRateCardClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  696. rcClient.Authorizer = authorizer
  697. providersClient := resources.NewProvidersClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  698. providersClient.Authorizer = authorizer
  699. rateCardFilter := fmt.Sprintf("OfferDurableId eq '%s' and Currency eq '%s' and Locale eq 'en-US' and RegionInfo eq '%s'", config.AzureOfferDurableID, config.CurrencyCode, config.AzureBillingRegion)
  700. klog.Infof("Using ratecard query %s", rateCardFilter)
  701. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  702. if err != nil {
  703. klog.Warningf("Error in pricing download query from API")
  704. az.RateCardPricingError = err
  705. return err
  706. }
  707. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  708. if err != nil {
  709. klog.Warningf("Error in pricing download regions from API")
  710. az.RateCardPricingError = err
  711. return err
  712. }
  713. baseCPUPrice := config.CPU
  714. allPrices := make(map[string]*AzurePricing)
  715. for _, v := range *result.Meters {
  716. meterName := *v.MeterName
  717. meterRegion := *v.MeterRegion
  718. meterCategory := *v.MeterCategory
  719. meterSubCategory := *v.MeterSubCategory
  720. region, err := toRegionID(meterRegion, regions)
  721. if err != nil {
  722. continue
  723. }
  724. if !strings.Contains(meterSubCategory, "Windows") {
  725. if strings.Contains(meterCategory, "Storage") {
  726. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  727. var storageClass string = ""
  728. if strings.Contains(meterName, "P4 ") {
  729. storageClass = AzureDiskPremiumSSDStorageClass
  730. } else if strings.Contains(meterName, "E4 ") {
  731. storageClass = AzureDiskStandardSSDStorageClass
  732. } else if strings.Contains(meterName, "S4 ") {
  733. storageClass = AzureDiskStandardStorageClass
  734. } else if strings.Contains(meterName, "LRS Provisioned") {
  735. storageClass = AzureFilePremiumStorageClass
  736. }
  737. if storageClass != "" {
  738. var priceInUsd float64
  739. if len(v.MeterRates) < 1 {
  740. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  741. continue
  742. }
  743. for _, rate := range v.MeterRates {
  744. priceInUsd += *rate
  745. }
  746. // rate is in disk per month, resolve price per hour, then GB per hour
  747. pricePerHour := priceInUsd / 730.0 / 32.0
  748. priceStr := fmt.Sprintf("%f", pricePerHour)
  749. key := region + "," + storageClass
  750. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  751. allPrices[key] = &AzurePricing{
  752. PV: &PV{
  753. Cost: priceStr,
  754. Region: region,
  755. },
  756. }
  757. }
  758. }
  759. }
  760. if strings.Contains(meterCategory, "Virtual Machines") {
  761. usageType := ""
  762. if !strings.Contains(meterName, "Low Priority") {
  763. usageType = "ondemand"
  764. } else {
  765. usageType = "preemptible"
  766. }
  767. var instanceTypes []string
  768. name := strings.TrimSuffix(meterName, " Low Priority")
  769. instanceType := strings.Split(name, "/")
  770. for _, it := range instanceType {
  771. if strings.Contains(meterSubCategory, "Promo") {
  772. it = it + " Promo"
  773. }
  774. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  775. }
  776. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  777. if strings.Contains(name, "Expired") {
  778. instanceTypes = []string{}
  779. }
  780. var priceInUsd float64
  781. if len(v.MeterRates) < 1 {
  782. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  783. continue
  784. }
  785. for _, rate := range v.MeterRates {
  786. priceInUsd += *rate
  787. }
  788. priceStr := fmt.Sprintf("%f", priceInUsd)
  789. for _, instanceType := range instanceTypes {
  790. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  791. allPrices[key] = &AzurePricing{
  792. Node: &Node{
  793. Cost: priceStr,
  794. BaseCPUPrice: baseCPUPrice,
  795. UsageType: usageType,
  796. },
  797. }
  798. }
  799. }
  800. }
  801. }
  802. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  803. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  804. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  805. zeroPrice := "0.0"
  806. for region := range regions {
  807. key := region + "," + AzureFileStandardStorageClass
  808. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  809. allPrices[key] = &AzurePricing{
  810. PV: &PV{
  811. Cost: zeroPrice,
  812. Region: region,
  813. },
  814. }
  815. }
  816. az.Pricing = allPrices
  817. az.RateCardPricingError = nil
  818. return nil
  819. }
  820. // determineCloudByRegion uses region name to pick the correct Cloud Environment for the azure provider to use
  821. func determineCloudByRegion(region string) azure.Environment {
  822. lcRegion := strings.ToLower(region)
  823. if strings.Contains(lcRegion, "china") {
  824. return azure.ChinaCloud
  825. }
  826. if strings.Contains(lcRegion, "gov") || strings.Contains(lcRegion, "dod") {
  827. return azure.USGovernmentCloud
  828. }
  829. // Default to public cloud
  830. return azure.PublicCloud
  831. }
  832. // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
  833. func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string, env azure.Environment) auth.ClientCredentialsConfig {
  834. return auth.ClientCredentialsConfig{
  835. ClientID: clientID,
  836. ClientSecret: clientSecret,
  837. TenantID: tenantID,
  838. Resource: env.ResourceManagerEndpoint,
  839. AADEndpoint: env.ActiveDirectoryEndpoint,
  840. }
  841. }
  842. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  843. if az.Pricing == nil {
  844. az.Pricing = map[string]*AzurePricing{}
  845. }
  846. az.Pricing[features] = azurePricing
  847. }
  848. // AllNodePricing returns the Azure pricing objects stored
  849. func (az *Azure) AllNodePricing() (interface{}, error) {
  850. az.DownloadPricingDataLock.RLock()
  851. defer az.DownloadPricingDataLock.RUnlock()
  852. return az.Pricing, nil
  853. }
  854. // NodePricing returns Azure pricing data for a single node
  855. func (az *Azure) NodePricing(key Key) (*Node, error) {
  856. az.DownloadPricingDataLock.RLock()
  857. defer az.DownloadPricingDataLock.RUnlock()
  858. azKey, ok := key.(*azureKey)
  859. if !ok {
  860. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  861. }
  862. config, _ := az.GetConfig()
  863. if slv, ok := azKey.Labels[config.SpotLabel]; ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  864. features := strings.Split(azKey.Features(), ",")
  865. region := features[0]
  866. instance := features[1]
  867. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  868. if n, ok := az.Pricing[spotFeatures]; ok {
  869. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  870. if azKey.isValidGPUNode() {
  871. n.Node.GPU = "1" // TODO: support multiple GPUs
  872. }
  873. return n.Node, nil
  874. }
  875. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  876. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  877. if err != nil {
  878. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  879. } else {
  880. gpu := ""
  881. if azKey.isValidGPUNode() {
  882. gpu = "1"
  883. }
  884. spotNode := &Node{
  885. Cost: spotCost,
  886. UsageType: "spot",
  887. GPU: gpu,
  888. }
  889. az.addPricing(spotFeatures, &AzurePricing{
  890. Node: spotNode,
  891. })
  892. return spotNode, nil
  893. }
  894. }
  895. if n, ok := az.Pricing[azKey.Features()]; ok {
  896. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  897. if azKey.isValidGPUNode() {
  898. n.Node.GPU = azKey.GetGPUCount()
  899. }
  900. return n.Node, nil
  901. }
  902. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", azKey.Features(), azKey)
  903. c, err := az.GetConfig()
  904. if err != nil {
  905. return nil, fmt.Errorf("No default pricing data available")
  906. }
  907. if azKey.isValidGPUNode() {
  908. return &Node{
  909. VCPUCost: c.CPU,
  910. RAMCost: c.RAM,
  911. UsesBaseCPUPrice: true,
  912. GPUCost: c.GPU,
  913. GPU: azKey.GetGPUCount(),
  914. }, nil
  915. }
  916. return &Node{
  917. VCPUCost: c.CPU,
  918. RAMCost: c.RAM,
  919. UsesBaseCPUPrice: true,
  920. }, nil
  921. }
  922. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  923. func (az *Azure) NetworkPricing() (*Network, error) {
  924. cpricing, err := az.Config.GetCustomPricingData()
  925. if err != nil {
  926. return nil, err
  927. }
  928. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  929. if err != nil {
  930. return nil, err
  931. }
  932. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  933. if err != nil {
  934. return nil, err
  935. }
  936. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  937. if err != nil {
  938. return nil, err
  939. }
  940. return &Network{
  941. ZoneNetworkEgressCost: znec,
  942. RegionNetworkEgressCost: rnec,
  943. InternetNetworkEgressCost: inec,
  944. }, nil
  945. }
  946. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  947. fffrc := 0.025
  948. afrc := 0.010
  949. lbidc := 0.008
  950. numForwardingRules := 1.0
  951. dataIngressGB := 0.0
  952. var totalCost float64
  953. if numForwardingRules < 5 {
  954. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  955. } else {
  956. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  957. }
  958. return &LoadBalancer{
  959. Cost: totalCost,
  960. }, nil
  961. }
  962. type azurePvKey struct {
  963. Labels map[string]string
  964. StorageClass string
  965. StorageClassParameters map[string]string
  966. DefaultRegion string
  967. ProviderId string
  968. }
  969. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  970. providerID := ""
  971. if pv.Spec.AzureDisk != nil {
  972. providerID = pv.Spec.AzureDisk.DiskName
  973. }
  974. return &azurePvKey{
  975. Labels: pv.Labels,
  976. StorageClass: pv.Spec.StorageClassName,
  977. StorageClassParameters: parameters,
  978. DefaultRegion: defaultRegion,
  979. ProviderId: providerID,
  980. }
  981. }
  982. func (key *azurePvKey) ID() string {
  983. return key.ProviderId
  984. }
  985. func (key *azurePvKey) GetStorageClass() string {
  986. return key.StorageClass
  987. }
  988. func (key *azurePvKey) Features() string {
  989. storageClass := key.StorageClassParameters["storageaccounttype"]
  990. storageSKU := key.StorageClassParameters["skuName"]
  991. if storageClass != "" {
  992. if strings.EqualFold(storageClass, "Premium_LRS") {
  993. storageClass = AzureDiskPremiumSSDStorageClass
  994. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  995. storageClass = AzureDiskStandardSSDStorageClass
  996. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  997. storageClass = AzureDiskStandardStorageClass
  998. }
  999. } else {
  1000. if strings.EqualFold(storageSKU, "Premium_LRS") {
  1001. storageClass = AzureFilePremiumStorageClass
  1002. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  1003. storageClass = AzureFileStandardStorageClass
  1004. }
  1005. }
  1006. if region, ok := util.GetRegion(key.Labels); ok {
  1007. return region + "," + storageClass
  1008. }
  1009. return key.DefaultRegion + "," + storageClass
  1010. }
  1011. func (*Azure) GetAddresses() ([]byte, error) {
  1012. return nil, nil
  1013. }
  1014. func (*Azure) GetDisks() ([]byte, error) {
  1015. return nil, nil
  1016. }
  1017. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1018. remoteEnabled := env.IsRemoteEnabled()
  1019. m := make(map[string]string)
  1020. m["name"] = "Azure Cluster #1"
  1021. c, err := az.GetConfig()
  1022. if err != nil {
  1023. return nil, err
  1024. }
  1025. if c.ClusterName != "" {
  1026. m["name"] = c.ClusterName
  1027. }
  1028. m["provider"] = "Azure"
  1029. m["account"] = az.clusterAccountId
  1030. m["region"] = az.clusterRegion
  1031. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1032. m["id"] = env.GetClusterID()
  1033. return m, nil
  1034. }
  1035. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  1036. return az.Config.UpdateFromMap(a)
  1037. }
  1038. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  1039. defer az.DownloadPricingData()
  1040. return az.Config.Update(func(c *CustomPricing) error {
  1041. a := make(map[string]interface{})
  1042. err := json.NewDecoder(r).Decode(&a)
  1043. if err != nil {
  1044. return err
  1045. }
  1046. for k, v := range a {
  1047. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  1048. vstr, ok := v.(string)
  1049. if ok {
  1050. err := SetCustomPricingField(c, kUpper, vstr)
  1051. if err != nil {
  1052. return err
  1053. }
  1054. } else {
  1055. return fmt.Errorf("type error while updating config for %s", kUpper)
  1056. }
  1057. }
  1058. if env.IsRemoteEnabled() {
  1059. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  1060. if err != nil {
  1061. return err
  1062. }
  1063. }
  1064. return nil
  1065. })
  1066. }
  1067. func (az *Azure) GetConfig() (*CustomPricing, error) {
  1068. c, err := az.Config.GetCustomPricingData()
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. if c.Discount == "" {
  1073. c.Discount = "0%"
  1074. }
  1075. if c.NegotiatedDiscount == "" {
  1076. c.NegotiatedDiscount = "0%"
  1077. }
  1078. if c.CurrencyCode == "" {
  1079. c.CurrencyCode = "USD"
  1080. }
  1081. if c.AzureBillingRegion == "" {
  1082. c.AzureBillingRegion = "US"
  1083. }
  1084. // Default to pay-as-you-go Durable offer id
  1085. if c.AzureOfferDurableID == "" {
  1086. c.AzureOfferDurableID = "MS-AZR-0003p"
  1087. }
  1088. if c.ShareTenancyCosts == "" {
  1089. c.ShareTenancyCosts = defaultShareTenancyCost
  1090. }
  1091. if c.SpotLabel == "" {
  1092. c.SpotLabel = defaultSpotLabel
  1093. }
  1094. if c.SpotLabelValue == "" {
  1095. c.SpotLabelValue = defaultSpotLabelValue
  1096. }
  1097. return c, nil
  1098. }
  1099. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1100. }
  1101. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1102. az.DownloadPricingDataLock.RLock()
  1103. defer az.DownloadPricingDataLock.RUnlock()
  1104. pricing, ok := az.Pricing[pvk.Features()]
  1105. if !ok {
  1106. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1107. return &PV{}, nil
  1108. }
  1109. return pricing.PV, nil
  1110. }
  1111. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1112. return ""
  1113. }
  1114. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1115. return az.serviceAccountChecks.getStatus()
  1116. }
  1117. const rateCardPricingSource = "Rate Card API"
  1118. // PricingSourceStatus returns the status of the rate card api
  1119. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1120. sources := make(map[string]*PricingSource)
  1121. errMsg := ""
  1122. if az.RateCardPricingError != nil {
  1123. errMsg = az.RateCardPricingError.Error()
  1124. }
  1125. rcps := &PricingSource{
  1126. Name: rateCardPricingSource,
  1127. Enabled: true,
  1128. Error: errMsg,
  1129. }
  1130. if rcps.Error != "" {
  1131. rcps.Available = false
  1132. } else if len(az.Pricing) == 0 {
  1133. rcps.Error = "No Pricing Data Available"
  1134. rcps.Available = false
  1135. } else {
  1136. rcps.Available = true
  1137. }
  1138. sources[rateCardPricingSource] = rcps
  1139. return sources
  1140. }
  1141. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1142. return "", 0.0, nil
  1143. }
  1144. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1145. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1146. }
  1147. func (az *Azure) Regions() []string {
  1148. return azureRegions
  1149. }
  1150. func parseAzureSubscriptionID(id string) string {
  1151. // azure:///subscriptions/0badafdf-1234-abcd-wxyz-123456789/...
  1152. // => 0badafdf-1234-abcd-wxyz-123456789
  1153. rx := regexp.MustCompile("azure:///subscriptions/([^/]*)/*")
  1154. match := rx.FindStringSubmatch(id)
  1155. if len(match) >= 2 {
  1156. return match[1]
  1157. }
  1158. // Return empty string if an account could not be parsed from provided string
  1159. return ""
  1160. }