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