azureprovider.go 40 KB

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