azureprovider.go 38 KB

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