azureprovider.go 39 KB

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