azureprovider.go 37 KB

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