azureprovider.go 39 KB

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