azureprovider.go 37 KB

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