azureprovider.go 39 KB

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