azureprovider.go 40 KB

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