azureprovider.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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 map[string]*ServiceAccountCheck
  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. // 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. AzureCloud string `json:"azureCloud"`
  424. }
  425. // Represents an azure app key
  426. type AzureAppKey struct {
  427. AppID string `json:"appId"`
  428. DisplayName string `json:"displayName"`
  429. Name string `json:"name"`
  430. Password string `json:"password"`
  431. Tenant string `json:"tenant"`
  432. }
  433. // Azure service key for a specific subscription
  434. type AzureServiceKey struct {
  435. SubscriptionID string `json:"subscriptionId"`
  436. ServiceKey *AzureAppKey `json:"serviceKey"`
  437. }
  438. // Validity check on service key
  439. func (ask *AzureServiceKey) IsValid() bool {
  440. return ask.SubscriptionID != "" &&
  441. ask.ServiceKey != nil &&
  442. ask.ServiceKey.AppID != "" &&
  443. ask.ServiceKey.Password != "" &&
  444. ask.ServiceKey.Tenant != ""
  445. }
  446. // Loads the azure authentication via configuration or a secret set at install time.
  447. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  448. // 1. Check config values first (set from frontend UI)
  449. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  450. subscriptionID = cp.AzureSubscriptionID
  451. clientID = cp.AzureClientID
  452. clientSecret = cp.AzureClientSecret
  453. tenantID = cp.AzureTenantID
  454. return
  455. }
  456. // 2. Check for secret
  457. s, _ := az.loadAzureAuthSecret(forceReload)
  458. if s != nil && s.IsValid() {
  459. subscriptionID = s.SubscriptionID
  460. clientID = s.ServiceKey.AppID
  461. clientSecret = s.ServiceKey.Password
  462. tenantID = s.ServiceKey.Tenant
  463. return
  464. }
  465. // 3. Empty values
  466. return "", "", "", ""
  467. }
  468. // GetAzureStorageConfig retrieves storage config from secret and sets default values
  469. func (az *Azure) GetAzureStorageConfig(forceReload bool) (*AzureStorageConfig, error) {
  470. // retrieve config for default subscription id
  471. defaultSubscriptionID := ""
  472. config, err := az.GetConfig()
  473. if err == nil {
  474. defaultSubscriptionID = config.AzureSubscriptionID
  475. }
  476. if az.ServiceAccountChecks == nil {
  477. az.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  478. }
  479. // 1. Check for secret
  480. s, err := az.loadAzureStorageConfig(forceReload)
  481. if err != nil {
  482. log.Errorf("Error, %s", err.Error())
  483. }
  484. if s != nil && s.AccessKey != "" && s.AccountName != "" && s.ContainerName != "" {
  485. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  486. Message: "Azure Storage Config exists",
  487. Status: true,
  488. }
  489. // To support already configured users, subscriptionID may not be set in secret in which case, the subscriptionID
  490. // for the rate card API is used
  491. if s.SubscriptionId == "" {
  492. s.SubscriptionId = defaultSubscriptionID
  493. }
  494. return s, nil
  495. }
  496. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  497. Message: "Azure Storage Config exists",
  498. Status: false,
  499. }
  500. return nil, fmt.Errorf("azure storage config not found")
  501. }
  502. // Load once and cache the result (even on failure). This is an install time secret, so
  503. // we don't expect the secret to change. If it does, however, we can force reload using
  504. // the input parameter.
  505. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  506. if !force && az.loadedAzureSecret {
  507. return az.azureSecret, nil
  508. }
  509. az.loadedAzureSecret = true
  510. exists, err := fileutil.FileExists(authSecretPath)
  511. if !exists || err != nil {
  512. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  513. }
  514. result, err := ioutil.ReadFile(authSecretPath)
  515. if err != nil {
  516. return nil, err
  517. }
  518. var ask AzureServiceKey
  519. err = json.Unmarshal(result, &ask)
  520. if err != nil {
  521. return nil, err
  522. }
  523. az.azureSecret = &ask
  524. return &ask, nil
  525. }
  526. // Load once and cache the result (even on failure). This is an install time secret, so
  527. // we don't expect the secret to change. If it does, however, we can force reload using
  528. // the input parameter.
  529. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  530. if !force && az.loadedAzureStorageConfigSecret {
  531. return az.azureStorageConfig, nil
  532. }
  533. az.loadedAzureStorageConfigSecret = true
  534. exists, err := fileutil.FileExists(storageConfigSecretPath)
  535. if !exists || err != nil {
  536. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  537. }
  538. result, err := ioutil.ReadFile(storageConfigSecretPath)
  539. if err != nil {
  540. return nil, err
  541. }
  542. var asc AzureStorageConfig
  543. err = json.Unmarshal(result, &asc)
  544. if err != nil {
  545. return nil, err
  546. }
  547. az.azureStorageConfig = &asc
  548. return &asc, nil
  549. }
  550. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  551. cfg, err := az.GetConfig()
  552. if err != nil {
  553. klog.Infof("Error loading azure custom pricing information")
  554. }
  555. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  556. gpuLabel := "accelerator"
  557. gpuLabelValue := "nvidia"
  558. if cfg.GpuLabel != "" {
  559. gpuLabel = cfg.GpuLabel
  560. }
  561. if cfg.GpuLabelValue != "" {
  562. gpuLabelValue = cfg.GpuLabelValue
  563. }
  564. return &azureKey{
  565. Labels: labels,
  566. GPULabel: gpuLabel,
  567. GPULabelValue: gpuLabelValue,
  568. }
  569. }
  570. // CreateString builds strings effectively
  571. func createString(keys ...string) string {
  572. var b strings.Builder
  573. for _, key := range keys {
  574. b.WriteString(key)
  575. }
  576. return b.String()
  577. }
  578. func transformMachineType(subCategory string, mt []string) []string {
  579. switch {
  580. case strings.Contains(subCategory, "Basic"):
  581. return []string{createString("Basic_", mt[0])}
  582. case len(mt) == 2:
  583. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  584. default:
  585. return []string{createString("Standard_", mt[0])}
  586. }
  587. }
  588. func addSuffix(mt string, suffixes ...string) []string {
  589. result := make([]string, len(suffixes))
  590. var suffix string
  591. parts := strings.Split(mt, "_")
  592. if len(parts) > 2 {
  593. for _, p := range parts[2:] {
  594. suffix = createString(suffix, "_", p)
  595. }
  596. }
  597. for i, s := range suffixes {
  598. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  599. }
  600. return result
  601. }
  602. func getMachineTypeVariants(mt string) []string {
  603. switch {
  604. case mtStandardB.MatchString(mt):
  605. return []string{createString(mt, "s")}
  606. case mtStandardD.MatchString(mt):
  607. var result []string
  608. result = append(result, addSuffix(mt, "s")[0])
  609. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  610. result = append(result, dsType)
  611. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  612. return result
  613. case mtStandardE.MatchString(mt):
  614. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  615. case mtStandardF.MatchString(mt):
  616. return addSuffix(mt, "s")
  617. case mtStandardG.MatchString(mt):
  618. var result []string
  619. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  620. result = append(result, gsType)
  621. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  622. case mtStandardL.MatchString(mt):
  623. return addSuffix(mt, "s")
  624. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  625. base := strings.TrimSuffix(mt, "ms")
  626. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  627. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  628. return []string{}
  629. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  630. base := strings.TrimSuffix(mt, "s")
  631. return addSuffix(base, "", "m")
  632. case mtStandardN.MatchString(mt):
  633. return addSuffix(mt, "s")
  634. }
  635. return []string{}
  636. }
  637. func (az *Azure) GetManagementPlatform() (string, error) {
  638. nodes := az.Clientset.GetAllNodes()
  639. if len(nodes) > 0 {
  640. n := nodes[0]
  641. providerID := n.Spec.ProviderID
  642. if strings.Contains(providerID, "aks") {
  643. return "aks", nil
  644. }
  645. }
  646. return "", nil
  647. }
  648. // DownloadPricingData uses provided azure "best guesses" for pricing
  649. func (az *Azure) DownloadPricingData() error {
  650. az.DownloadPricingDataLock.Lock()
  651. defer az.DownloadPricingDataLock.Unlock()
  652. config, err := az.GetConfig()
  653. if err != nil {
  654. az.RateCardPricingError = err
  655. return err
  656. }
  657. // Load the service provider keys
  658. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(true, config)
  659. config.AzureSubscriptionID = subscriptionID
  660. config.AzureClientID = clientID
  661. config.AzureClientSecret = clientSecret
  662. config.AzureTenantID = tenantID
  663. var authorizer autorest.Authorizer
  664. azureEnv := determineCloudByRegion(az.clusterRegion)
  665. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  666. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  667. a, err := credentialsConfig.Authorizer()
  668. if err != nil {
  669. az.RateCardPricingError = err
  670. return err
  671. }
  672. authorizer = a
  673. }
  674. if authorizer == nil {
  675. a, err := auth.NewAuthorizerFromEnvironment()
  676. authorizer = a
  677. if err != nil {
  678. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  679. if err != nil {
  680. az.RateCardPricingError = err
  681. return err
  682. }
  683. authorizer = a
  684. }
  685. }
  686. sClient := subscriptions.NewClientWithBaseURI(azureEnv.ResourceManagerEndpoint)
  687. sClient.Authorizer = authorizer
  688. rcClient := commerce.NewRateCardClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  689. rcClient.Authorizer = authorizer
  690. providersClient := resources.NewProvidersClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  691. providersClient.Authorizer = authorizer
  692. 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)
  693. klog.Infof("Using ratecard query %s", rateCardFilter)
  694. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  695. if err != nil {
  696. klog.Warningf("Error in pricing download query from API")
  697. az.RateCardPricingError = err
  698. return err
  699. }
  700. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  701. if err != nil {
  702. klog.Warningf("Error in pricing download regions from API")
  703. az.RateCardPricingError = err
  704. return err
  705. }
  706. baseCPUPrice := config.CPU
  707. allPrices := make(map[string]*AzurePricing)
  708. for _, v := range *result.Meters {
  709. meterName := *v.MeterName
  710. meterRegion := *v.MeterRegion
  711. meterCategory := *v.MeterCategory
  712. meterSubCategory := *v.MeterSubCategory
  713. region, err := toRegionID(meterRegion, regions)
  714. if err != nil {
  715. continue
  716. }
  717. if !strings.Contains(meterSubCategory, "Windows") {
  718. if strings.Contains(meterCategory, "Storage") {
  719. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  720. var storageClass string = ""
  721. if strings.Contains(meterName, "P4 ") {
  722. storageClass = AzureDiskPremiumSSDStorageClass
  723. } else if strings.Contains(meterName, "E4 ") {
  724. storageClass = AzureDiskStandardSSDStorageClass
  725. } else if strings.Contains(meterName, "S4 ") {
  726. storageClass = AzureDiskStandardStorageClass
  727. } else if strings.Contains(meterName, "LRS Provisioned") {
  728. storageClass = AzureFilePremiumStorageClass
  729. }
  730. if storageClass != "" {
  731. var priceInUsd float64
  732. if len(v.MeterRates) < 1 {
  733. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  734. continue
  735. }
  736. for _, rate := range v.MeterRates {
  737. priceInUsd += *rate
  738. }
  739. // rate is in disk per month, resolve price per hour, then GB per hour
  740. pricePerHour := priceInUsd / 730.0 / 32.0
  741. priceStr := fmt.Sprintf("%f", pricePerHour)
  742. key := region + "," + storageClass
  743. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  744. allPrices[key] = &AzurePricing{
  745. PV: &PV{
  746. Cost: priceStr,
  747. Region: region,
  748. },
  749. }
  750. }
  751. }
  752. }
  753. if strings.Contains(meterCategory, "Virtual Machines") {
  754. usageType := ""
  755. if !strings.Contains(meterName, "Low Priority") {
  756. usageType = "ondemand"
  757. } else {
  758. usageType = "preemptible"
  759. }
  760. var instanceTypes []string
  761. name := strings.TrimSuffix(meterName, " Low Priority")
  762. instanceType := strings.Split(name, "/")
  763. for _, it := range instanceType {
  764. if strings.Contains(meterSubCategory, "Promo") {
  765. it = it + " Promo"
  766. }
  767. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  768. }
  769. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  770. if strings.Contains(name, "Expired") {
  771. instanceTypes = []string{}
  772. }
  773. var priceInUsd float64
  774. if len(v.MeterRates) < 1 {
  775. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  776. continue
  777. }
  778. for _, rate := range v.MeterRates {
  779. priceInUsd += *rate
  780. }
  781. priceStr := fmt.Sprintf("%f", priceInUsd)
  782. for _, instanceType := range instanceTypes {
  783. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  784. allPrices[key] = &AzurePricing{
  785. Node: &Node{
  786. Cost: priceStr,
  787. BaseCPUPrice: baseCPUPrice,
  788. UsageType: usageType,
  789. },
  790. }
  791. }
  792. }
  793. }
  794. }
  795. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  796. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  797. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  798. zeroPrice := "0.0"
  799. for region := range regions {
  800. key := region + "," + AzureFileStandardStorageClass
  801. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  802. allPrices[key] = &AzurePricing{
  803. PV: &PV{
  804. Cost: zeroPrice,
  805. Region: region,
  806. },
  807. }
  808. }
  809. az.Pricing = allPrices
  810. az.RateCardPricingError = nil
  811. return nil
  812. }
  813. // determineCloudByRegion uses region name to pick the correct Cloud Environment for the azure provider to use
  814. func determineCloudByRegion(region string) azure.Environment {
  815. lcRegion := strings.ToLower(region)
  816. if strings.Contains(lcRegion, "china") {
  817. return azure.ChinaCloud
  818. }
  819. if strings.Contains(lcRegion, "gov") || strings.Contains(lcRegion, "dod") {
  820. return azure.USGovernmentCloud
  821. }
  822. // Default to public cloud
  823. return azure.PublicCloud
  824. }
  825. // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
  826. func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string, env azure.Environment) auth.ClientCredentialsConfig {
  827. return auth.ClientCredentialsConfig{
  828. ClientID: clientID,
  829. ClientSecret: clientSecret,
  830. TenantID: tenantID,
  831. Resource: env.ResourceManagerEndpoint,
  832. AADEndpoint: env.ActiveDirectoryEndpoint,
  833. }
  834. }
  835. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  836. if az.Pricing == nil {
  837. az.Pricing = map[string]*AzurePricing{}
  838. }
  839. az.Pricing[features] = azurePricing
  840. }
  841. // AllNodePricing returns the Azure pricing objects stored
  842. func (az *Azure) AllNodePricing() (interface{}, error) {
  843. az.DownloadPricingDataLock.RLock()
  844. defer az.DownloadPricingDataLock.RUnlock()
  845. return az.Pricing, nil
  846. }
  847. // NodePricing returns Azure pricing data for a single node
  848. func (az *Azure) NodePricing(key Key) (*Node, error) {
  849. az.DownloadPricingDataLock.RLock()
  850. defer az.DownloadPricingDataLock.RUnlock()
  851. azKey, ok := key.(*azureKey)
  852. if !ok {
  853. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  854. }
  855. config, _ := az.GetConfig()
  856. if slv, ok := azKey.Labels[config.SpotLabel]; ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  857. features := strings.Split(azKey.Features(), ",")
  858. region := features[0]
  859. instance := features[1]
  860. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  861. if n, ok := az.Pricing[spotFeatures]; ok {
  862. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  863. if azKey.isValidGPUNode() {
  864. n.Node.GPU = "1" // TODO: support multiple GPUs
  865. }
  866. return n.Node, nil
  867. }
  868. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  869. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  870. if err != nil {
  871. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  872. } else {
  873. gpu := ""
  874. if azKey.isValidGPUNode() {
  875. gpu = "1"
  876. }
  877. spotNode := &Node{
  878. Cost: spotCost,
  879. UsageType: "spot",
  880. GPU: gpu,
  881. }
  882. az.addPricing(spotFeatures, &AzurePricing{
  883. Node: spotNode,
  884. })
  885. return spotNode, nil
  886. }
  887. }
  888. if n, ok := az.Pricing[azKey.Features()]; ok {
  889. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  890. if azKey.isValidGPUNode() {
  891. n.Node.GPU = azKey.GetGPUCount()
  892. }
  893. return n.Node, nil
  894. }
  895. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", azKey.Features(), azKey)
  896. c, err := az.GetConfig()
  897. if err != nil {
  898. return nil, fmt.Errorf("No default pricing data available")
  899. }
  900. if azKey.isValidGPUNode() {
  901. return &Node{
  902. VCPUCost: c.CPU,
  903. RAMCost: c.RAM,
  904. UsesBaseCPUPrice: true,
  905. GPUCost: c.GPU,
  906. GPU: azKey.GetGPUCount(),
  907. }, nil
  908. }
  909. return &Node{
  910. VCPUCost: c.CPU,
  911. RAMCost: c.RAM,
  912. UsesBaseCPUPrice: true,
  913. }, nil
  914. }
  915. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  916. func (az *Azure) NetworkPricing() (*Network, error) {
  917. cpricing, err := az.Config.GetCustomPricingData()
  918. if err != nil {
  919. return nil, err
  920. }
  921. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  922. if err != nil {
  923. return nil, err
  924. }
  925. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  926. if err != nil {
  927. return nil, err
  928. }
  929. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  930. if err != nil {
  931. return nil, err
  932. }
  933. return &Network{
  934. ZoneNetworkEgressCost: znec,
  935. RegionNetworkEgressCost: rnec,
  936. InternetNetworkEgressCost: inec,
  937. }, nil
  938. }
  939. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  940. fffrc := 0.025
  941. afrc := 0.010
  942. lbidc := 0.008
  943. numForwardingRules := 1.0
  944. dataIngressGB := 0.0
  945. var totalCost float64
  946. if numForwardingRules < 5 {
  947. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  948. } else {
  949. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  950. }
  951. return &LoadBalancer{
  952. Cost: totalCost,
  953. }, nil
  954. }
  955. type azurePvKey struct {
  956. Labels map[string]string
  957. StorageClass string
  958. StorageClassParameters map[string]string
  959. DefaultRegion string
  960. ProviderId string
  961. }
  962. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  963. providerID := ""
  964. if pv.Spec.AzureDisk != nil {
  965. providerID = pv.Spec.AzureDisk.DiskName
  966. }
  967. return &azurePvKey{
  968. Labels: pv.Labels,
  969. StorageClass: pv.Spec.StorageClassName,
  970. StorageClassParameters: parameters,
  971. DefaultRegion: defaultRegion,
  972. ProviderId: providerID,
  973. }
  974. }
  975. func (key *azurePvKey) ID() string {
  976. return key.ProviderId
  977. }
  978. func (key *azurePvKey) GetStorageClass() string {
  979. return key.StorageClass
  980. }
  981. func (key *azurePvKey) Features() string {
  982. storageClass := key.StorageClassParameters["storageaccounttype"]
  983. storageSKU := key.StorageClassParameters["skuName"]
  984. if storageClass != "" {
  985. if strings.EqualFold(storageClass, "Premium_LRS") {
  986. storageClass = AzureDiskPremiumSSDStorageClass
  987. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  988. storageClass = AzureDiskStandardSSDStorageClass
  989. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  990. storageClass = AzureDiskStandardStorageClass
  991. }
  992. } else {
  993. if strings.EqualFold(storageSKU, "Premium_LRS") {
  994. storageClass = AzureFilePremiumStorageClass
  995. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  996. storageClass = AzureFileStandardStorageClass
  997. }
  998. }
  999. if region, ok := util.GetRegion(key.Labels); ok {
  1000. return region + "," + storageClass
  1001. }
  1002. return key.DefaultRegion + "," + storageClass
  1003. }
  1004. func (*Azure) GetAddresses() ([]byte, error) {
  1005. return nil, nil
  1006. }
  1007. func (*Azure) GetDisks() ([]byte, error) {
  1008. return nil, nil
  1009. }
  1010. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1011. remoteEnabled := env.IsRemoteEnabled()
  1012. m := make(map[string]string)
  1013. m["name"] = "Azure Cluster #1"
  1014. c, err := az.GetConfig()
  1015. if err != nil {
  1016. return nil, err
  1017. }
  1018. if c.ClusterName != "" {
  1019. m["name"] = c.ClusterName
  1020. }
  1021. m["provider"] = "Azure"
  1022. m["account"] = az.clusterAccountId
  1023. m["region"] = az.clusterRegion
  1024. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1025. m["id"] = env.GetClusterID()
  1026. return m, nil
  1027. }
  1028. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  1029. return az.Config.UpdateFromMap(a)
  1030. }
  1031. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  1032. defer az.DownloadPricingData()
  1033. return az.Config.Update(func(c *CustomPricing) error {
  1034. a := make(map[string]interface{})
  1035. err := json.NewDecoder(r).Decode(&a)
  1036. if err != nil {
  1037. return err
  1038. }
  1039. for k, v := range a {
  1040. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  1041. vstr, ok := v.(string)
  1042. if ok {
  1043. err := SetCustomPricingField(c, kUpper, vstr)
  1044. if err != nil {
  1045. return err
  1046. }
  1047. } else {
  1048. return fmt.Errorf("type error while updating config for %s", kUpper)
  1049. }
  1050. }
  1051. if env.IsRemoteEnabled() {
  1052. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  1053. if err != nil {
  1054. return err
  1055. }
  1056. }
  1057. return nil
  1058. })
  1059. }
  1060. func (az *Azure) GetConfig() (*CustomPricing, error) {
  1061. c, err := az.Config.GetCustomPricingData()
  1062. if err != nil {
  1063. return nil, err
  1064. }
  1065. if c.Discount == "" {
  1066. c.Discount = "0%"
  1067. }
  1068. if c.NegotiatedDiscount == "" {
  1069. c.NegotiatedDiscount = "0%"
  1070. }
  1071. if c.CurrencyCode == "" {
  1072. c.CurrencyCode = "USD"
  1073. }
  1074. if c.AzureBillingRegion == "" {
  1075. c.AzureBillingRegion = "US"
  1076. }
  1077. // Default to pay-as-you-go Durable offer id
  1078. if c.AzureOfferDurableID == "" {
  1079. c.AzureOfferDurableID = "MS-AZR-0003p"
  1080. }
  1081. if c.ShareTenancyCosts == "" {
  1082. c.ShareTenancyCosts = defaultShareTenancyCost
  1083. }
  1084. if c.SpotLabel == "" {
  1085. c.SpotLabel = defaultSpotLabel
  1086. }
  1087. if c.SpotLabelValue == "" {
  1088. c.SpotLabelValue = defaultSpotLabelValue
  1089. }
  1090. return c, nil
  1091. }
  1092. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1093. }
  1094. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1095. az.DownloadPricingDataLock.RLock()
  1096. defer az.DownloadPricingDataLock.RUnlock()
  1097. pricing, ok := az.Pricing[pvk.Features()]
  1098. if !ok {
  1099. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1100. return &PV{}, nil
  1101. }
  1102. return pricing.PV, nil
  1103. }
  1104. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1105. return ""
  1106. }
  1107. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1108. checks := []*ServiceAccountCheck{}
  1109. for _, v := range az.ServiceAccountChecks {
  1110. checks = append(checks, v)
  1111. }
  1112. return &ServiceAccountStatus{
  1113. Checks: checks,
  1114. }
  1115. }
  1116. const rateCardPricingSource = "Rate Card API"
  1117. // PricingSourceStatus returns the status of the rate card api
  1118. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1119. sources := make(map[string]*PricingSource)
  1120. errMsg := ""
  1121. if az.RateCardPricingError != nil {
  1122. errMsg = az.RateCardPricingError.Error()
  1123. }
  1124. rcps := &PricingSource{
  1125. Name: rateCardPricingSource,
  1126. Error: errMsg,
  1127. }
  1128. if rcps.Error != "" {
  1129. rcps.Available = false
  1130. } else if len(az.Pricing) == 0 {
  1131. rcps.Error = "No Pricing Data Available"
  1132. rcps.Available = false
  1133. } else {
  1134. rcps.Available = true
  1135. }
  1136. sources[rateCardPricingSource] = rcps
  1137. return sources
  1138. }
  1139. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1140. return "", 0.0, nil
  1141. }
  1142. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1143. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1144. }
  1145. func (az *Azure) Regions() []string {
  1146. return azureRegions
  1147. }
  1148. func parseAzureSubscriptionID(id string) string {
  1149. // azure:///subscriptions/0badafdf-1234-abcd-wxyz-123456789/...
  1150. // => 0badafdf-1234-abcd-wxyz-123456789
  1151. rx := regexp.MustCompile("azure:///subscriptions/([^/]*)/*")
  1152. match := rx.FindStringSubmatch(id)
  1153. if len(match) >= 2 {
  1154. return match[1]
  1155. }
  1156. // Return empty string if an account could not be parsed from provided string
  1157. return ""
  1158. }