2
0

provider.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute"
  15. "github.com/Azure/azure-sdk-for-go/services/preview/commerce/mgmt/2015-06-01-preview/commerce"
  16. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
  17. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
  18. "github.com/Azure/go-autorest/autorest"
  19. "github.com/Azure/go-autorest/autorest/azure"
  20. "github.com/Azure/go-autorest/autorest/azure/auth"
  21. coreenv "github.com/opencost/opencost/core/pkg/env"
  22. "github.com/opencost/opencost/core/pkg/clustercache"
  23. "github.com/opencost/opencost/core/pkg/log"
  24. "github.com/opencost/opencost/core/pkg/opencost"
  25. "github.com/opencost/opencost/core/pkg/util"
  26. "github.com/opencost/opencost/core/pkg/util/fileutil"
  27. "github.com/opencost/opencost/core/pkg/util/json"
  28. "github.com/opencost/opencost/core/pkg/util/timeutil"
  29. "github.com/opencost/opencost/pkg/cloud/httputil"
  30. "github.com/opencost/opencost/pkg/cloud/models"
  31. "github.com/opencost/opencost/pkg/cloud/utils"
  32. "github.com/opencost/opencost/pkg/env"
  33. )
  34. const (
  35. AzureFilePremiumStorageClass = "premium_smb"
  36. AzureFileStandardStorageClass = "standard_smb"
  37. AzureDiskPremiumSSDStorageClass = "premium_ssd"
  38. AzureDiskStandardSSDStorageClass = "standard_ssd"
  39. AzureDiskStandardStorageClass = "standard_hdd"
  40. defaultSpotLabel = "kubernetes.azure.com/scalesetpriority"
  41. defaultSpotLabelValue = "spot"
  42. AzureStorageUpdateType = "AzureStorage"
  43. )
  44. var (
  45. regionCodeMappings = map[string]string{
  46. "ap": "asia",
  47. "au": "australia",
  48. "br": "brazil",
  49. "ca": "canada",
  50. "eu": "europe",
  51. "fr": "france",
  52. "in": "india",
  53. "ja": "japan",
  54. "kr": "korea",
  55. "uk": "uk",
  56. "us": "us",
  57. "za": "southafrica",
  58. "no": "norway",
  59. "ch": "switzerland",
  60. "de": "germany",
  61. "ue": "uae",
  62. }
  63. //mtBasic, _ = regexp.Compile("^BASIC.A\\d+[_Promo]*$")
  64. //mtStandardA, _ = regexp.Compile("^A\\d+[_Promo]*$")
  65. mtStandardB, _ = regexp.Compile(`^Standard_B\d+m?[_v\d]*[_Promo]*$`)
  66. mtStandardD, _ = regexp.Compile(`^Standard_D\d[_v\d]*[_Promo]*$`)
  67. mtStandardE, _ = regexp.Compile(`^Standard_E\d+i?[_v\d]*[_Promo]*$`)
  68. mtStandardF, _ = regexp.Compile(`^Standard_F\d+[_v\d]*[_Promo]*$`)
  69. mtStandardG, _ = regexp.Compile(`^Standard_G\d+[_v\d]*[_Promo]*$`)
  70. mtStandardL, _ = regexp.Compile(`^Standard_L\d+[_v\d]*[_Promo]*$`)
  71. mtStandardM, _ = regexp.Compile(`^Standard_M\d+[m|t|l]*s[_v\d]*[_Promo]*$`)
  72. mtStandardN, _ = regexp.Compile(`^Standard_N[C|D|V]\d+r?[_v\d]*[_Promo]*$`)
  73. // azure:///subscriptions/0badafdf-1234-abcd-wxyz-123456789/...
  74. // => 0badafdf-1234-abcd-wxyz-123456789
  75. azureSubRegex = regexp.MustCompile("azure:///subscriptions/([^/]*)/*")
  76. )
  77. // List obtained by installing the Azure CLI tool "az", described here:
  78. // https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt
  79. // logging into an Azure account, and running command `az account list-locations`
  80. var azureRegions = []string{
  81. "eastus",
  82. "eastus2",
  83. "southcentralus",
  84. "westus2",
  85. "westus3",
  86. "australiaeast",
  87. "southeastasia",
  88. "northeurope",
  89. "swedencentral",
  90. "uksouth",
  91. "westeurope",
  92. "centralus",
  93. "northcentralus",
  94. "westus",
  95. "southafricanorth",
  96. "centralindia",
  97. "eastasia",
  98. "japaneast",
  99. "jioindiawest",
  100. "koreacentral",
  101. "canadacentral",
  102. "francecentral",
  103. "germanywestcentral",
  104. "norwayeast",
  105. "switzerlandnorth",
  106. "uaenorth",
  107. "brazilsouth",
  108. "centralusstage",
  109. "eastusstage",
  110. "eastus2stage",
  111. "northcentralusstage",
  112. "southcentralusstage",
  113. "westusstage",
  114. "westus2stage",
  115. "asia",
  116. "asiapacific",
  117. "australia",
  118. "brazil",
  119. "canada",
  120. "europe",
  121. "france",
  122. "germany",
  123. "global",
  124. "india",
  125. "japan",
  126. "korea",
  127. "norway",
  128. "southafrica",
  129. "switzerland",
  130. "uae",
  131. "uk",
  132. "unitedstates",
  133. "eastasiastage",
  134. "southeastasiastage",
  135. "centraluseuap",
  136. "eastus2euap",
  137. "westcentralus",
  138. "southafricawest",
  139. "australiacentral",
  140. "australiacentral2",
  141. "australiasoutheast",
  142. "japanwest",
  143. "jioindiacentral",
  144. "koreasouth",
  145. "southindia",
  146. "westindia",
  147. "canadaeast",
  148. "francesouth",
  149. "germanynorth",
  150. "norwaywest",
  151. "switzerlandwest",
  152. "ukwest",
  153. "uaecentral",
  154. "brazilsoutheast",
  155. "usgovarizona",
  156. "usgoviowa",
  157. "usgovvirginia",
  158. "usgovtexas",
  159. }
  160. type regionParts []string
  161. func (r regionParts) String() string {
  162. var result string
  163. for _, p := range r {
  164. result += p
  165. }
  166. return result
  167. }
  168. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  169. allLocations := make(map[string]string)
  170. supLocations := make(map[string]string)
  171. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  172. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  173. // fill up the map: DisplayName - > Name
  174. for _, loc := range *locations.Value {
  175. allLocations[*loc.DisplayName] = *loc.Name
  176. }
  177. } else {
  178. return nil, err
  179. }
  180. // identify supported locations for the namespace and resource type
  181. const (
  182. providerNamespaceForCompute = "Microsoft.Compute"
  183. resourceTypeForCompute = "locations/vmSizes"
  184. providerNamespaceForAks = "Microsoft.ContainerService"
  185. resourceTypeForAks = "managedClusters"
  186. )
  187. switch service {
  188. case "aks":
  189. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  190. for _, pr := range *providers.ResourceTypes {
  191. if *pr.ResourceType == resourceTypeForAks {
  192. for _, displName := range *pr.Locations {
  193. if loc, ok := allLocations[displName]; ok {
  194. supLocations[loc] = displName
  195. } else {
  196. log.Warnf("unsupported cloud region %q", displName)
  197. }
  198. }
  199. break
  200. }
  201. }
  202. } else {
  203. return nil, err
  204. }
  205. return supLocations, nil
  206. default:
  207. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  208. for _, pr := range *providers.ResourceTypes {
  209. if *pr.ResourceType == resourceTypeForCompute {
  210. for _, displName := range *pr.Locations {
  211. if loc, ok := allLocations[displName]; ok {
  212. supLocations[loc] = displName
  213. } else {
  214. log.Warnf("unsupported cloud region %q", displName)
  215. }
  216. }
  217. break
  218. }
  219. }
  220. } else {
  221. return nil, err
  222. }
  223. return supLocations, nil
  224. }
  225. }
  226. func buildAzureRetailPricesURL(region string, skuName string, currencyCode string) string {
  227. pricingURL := "https://prices.azure.com/api/retail/prices?$skip=0"
  228. if currencyCode != "" {
  229. pricingURL += fmt.Sprintf("&currencyCode='%s'", currencyCode)
  230. }
  231. var filterParams []string
  232. if region != "" {
  233. regionParam := fmt.Sprintf("armRegionName eq '%s'", region)
  234. filterParams = append(filterParams, regionParam)
  235. }
  236. if skuName != "" {
  237. skuNameParam := fmt.Sprintf("armSkuName eq '%s'", skuName)
  238. filterParams = append(filterParams, skuNameParam)
  239. }
  240. // Make sure only service name with Virtual Machines are parsed with skuName
  241. filterParams = append(filterParams, "serviceFamily eq 'Compute'")
  242. // Add type eq 'Consumption' to the filter to avoid reservation cost
  243. filterParams = append(filterParams, "type eq 'Consumption'")
  244. // Exclude Low Priority instances[Azure has special computes that let you run workloads on spare capacity at a deeply discounted price in exchange for no SLA and the possibility of being evicted]
  245. filterParams = append(filterParams, "contains(meterName,'Low Priority') eq false")
  246. filterParamsEscaped := url.QueryEscape(strings.Join(filterParams[:], " and "))
  247. pricingURL += fmt.Sprintf("&$filter=%s", filterParamsEscaped)
  248. return pricingURL
  249. }
  250. func extractAzureVMRetailAndSpotPrices(resp *http.Response) (linuxRetailPrice string, windowsRetailPrice string, spotPrice string, windowsSpotPrice string, err error) {
  251. body, err := io.ReadAll(resp.Body)
  252. if err != nil {
  253. return "", "", "", "", fmt.Errorf("error getting response: %w", err)
  254. }
  255. pricingPayload := AzureRetailPricing{}
  256. jsonErr := json.Unmarshal(body, &pricingPayload)
  257. if jsonErr != nil {
  258. return "", "", "", "", fmt.Errorf("error unmarshalling data: %w", jsonErr)
  259. }
  260. for _, item := range pricingPayload.Items {
  261. skuLower := strings.ToLower(item.SkuName)
  262. productLower := strings.ToLower(item.ProductName)
  263. isWindowsProduct := strings.Contains(productLower, "windows")
  264. if strings.Contains(skuLower, " spot") {
  265. if isWindowsProduct {
  266. windowsSpotPrice = fmt.Sprintf("%f", item.RetailPrice)
  267. } else {
  268. spotPrice = fmt.Sprintf("%f", item.RetailPrice)
  269. }
  270. } else if !(strings.Contains(skuLower, "low priority") || strings.Contains(productLower, "cloud services") || strings.Contains(productLower, "cloudservices")) {
  271. if isWindowsProduct {
  272. windowsRetailPrice = fmt.Sprintf("%f", item.RetailPrice)
  273. } else {
  274. linuxRetailPrice = fmt.Sprintf("%f", item.RetailPrice)
  275. }
  276. }
  277. }
  278. return linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice, nil
  279. }
  280. func getRetailPrice(region string, skuName string, currencyCode string, spot bool, isWindows bool) (string, error) {
  281. pricingURL := buildAzureRetailPricesURL(region, skuName, currencyCode)
  282. log.Infof("starting download retail price payload from \"%s\"", pricingURL)
  283. // Single SKU lookup returns a small payload, so the shared bounded client
  284. // keeps a hung endpoint from blocking pricing without risking truncation.
  285. client := httputil.BoundedClient()
  286. resp, err := client.Get(pricingURL)
  287. if err != nil {
  288. return "", fmt.Errorf("failed to fetch retail price with URL \"%s\": %w", pricingURL, err)
  289. }
  290. if resp.StatusCode < 200 && resp.StatusCode > 299 {
  291. return "", fmt.Errorf("retail price responded with error status code %d", resp.StatusCode)
  292. }
  293. linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice, err := extractAzureVMRetailAndSpotPrices(resp)
  294. if err != nil {
  295. return "", fmt.Errorf("failed to extract azure prices: %w", err)
  296. }
  297. log.DedupedInfof(5, "done parsing retail price payload from \"%s\"\n", pricingURL)
  298. return selectRetailPrice(region, skuName, linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice, spot, isWindows)
  299. }
  300. // selectRetailPrice picks the price matching the node OS and pricing model.
  301. // Windows nodes prefer the Windows-specific price; when it is absent the Linux
  302. // price is used as a best-effort estimate and the fallback is logged so the
  303. // substitution is not silent.
  304. func selectRetailPrice(region, skuName, linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice string, spot, isWindows bool) (string, error) {
  305. if spot {
  306. if isWindows && windowsSpotPrice != "" {
  307. return windowsSpotPrice, nil
  308. }
  309. if spotPrice != "" {
  310. if isWindows {
  311. log.Warnf("no Windows spot price for %q in %q region; falling back to Linux spot price", skuName, region)
  312. }
  313. return spotPrice, nil
  314. }
  315. }
  316. selectedRetail := linuxRetailPrice
  317. if isWindows && windowsRetailPrice != "" {
  318. selectedRetail = windowsRetailPrice
  319. } else if isWindows && linuxRetailPrice != "" {
  320. log.Warnf("no Windows retail price for %q in %q region; falling back to Linux retail price", skuName, region)
  321. }
  322. if selectedRetail == "" {
  323. return "", fmt.Errorf("couldn't find price for product %q in %q region", skuName, region)
  324. }
  325. return selectedRetail, nil
  326. }
  327. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  328. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  329. regionCode := regionCodeMappings[rp[0]]
  330. lastPart := rp[len(rp)-1]
  331. var regionIds []string
  332. if regionID, ok := regionIdByDisplayName[meterRegion]; ok {
  333. regionIds = []string{
  334. regionID,
  335. }
  336. } else if _, err := strconv.Atoi(lastPart); err == nil {
  337. regionIds = []string{
  338. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  339. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  340. }
  341. } else {
  342. regionIds = []string{
  343. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  344. fmt.Sprintf("%s%s", rp[1:], regionCode),
  345. }
  346. }
  347. for _, regionID := range regionIds {
  348. if checkRegionID(regionID, regions) {
  349. return regionID, nil
  350. }
  351. }
  352. return "", fmt.Errorf("Couldn't find region %q", meterRegion)
  353. }
  354. // azure has very inconsistent naming standards between display names from the rate card api and display names from the regions api
  355. // this map is to connect display names from the ratecard api to the appropriate id.
  356. var regionIdByDisplayName = map[string]string{
  357. "US Gov AZ": "usgovarizona",
  358. "US Gov TX": "usgovtexas",
  359. "US Gov": "usgovvirginia",
  360. }
  361. func checkRegionID(regionID string, regions map[string]string) bool {
  362. for region := range regions {
  363. if regionID == region {
  364. return true
  365. }
  366. }
  367. return false
  368. }
  369. // AzureRetailPricing struct for unmarshalling Azure Retail pricing api JSON response
  370. type AzureRetailPricing struct {
  371. BillingCurrency string `json:"BillingCurrency"`
  372. CustomerEntityId string `json:"CustomerEntityId"`
  373. CustomerEntityType string `json:"CustomerEntityType"`
  374. Items []AzureRetailPricingAttributes `json:"Items"`
  375. NextPageLink string `json:"NextPageLink"`
  376. Count int `json:"Count"`
  377. }
  378. // AzureRetailPricingAttributes struct for unmarshalling Azure Retail pricing api JSON response
  379. type AzureRetailPricingAttributes struct {
  380. CurrencyCode string `json:"currencyCode"`
  381. TierMinimumUnits float32 `json:"tierMinimumUnits"`
  382. RetailPrice float32 `json:"retailPrice"`
  383. UnitPrice float32 `json:"unitPrice"`
  384. ArmRegionName string `json:"armRegionName"`
  385. Location string `json:"location"`
  386. EffectiveStartDate *time.Time `json:"effectiveStartDate"`
  387. EffectiveEndDate *time.Time `json:"effectiveEndDate"`
  388. MeterId string `json:"meterId"`
  389. MeterName string `json:"meterName"`
  390. ProductId string `json:"productId"`
  391. SkuId string `json:"skuId"`
  392. ProductName string `json:"productName"`
  393. SkuName string `json:"skuName"`
  394. ServiceName string `json:"serviceName"`
  395. ServiceId string `json:"serviceId"`
  396. ServiceFamily string `json:"serviceFamily"`
  397. UnitOfMeasure string `json:"unitOfMeasure"`
  398. Type string `json:"type"`
  399. IsPrimaryMeterRegion bool `json:"isPrimaryMeterRegion"`
  400. ArmSkuName string `json:"armSkuName"`
  401. }
  402. // AzurePricing either contains a Node or PV
  403. type AzurePricing struct {
  404. Node *models.Node
  405. PV *models.PV
  406. }
  407. type Azure struct {
  408. Pricing map[string]*AzurePricing
  409. DownloadPricingDataLock sync.RWMutex
  410. Clientset clustercache.ClusterCache
  411. Config models.ProviderConfig
  412. ServiceAccountChecks *models.ServiceAccountChecks
  413. ClusterAccountID string
  414. ClusterRegion string
  415. pricingSource string
  416. rateCardPricingError error
  417. priceSheetPricingError error
  418. loadedAzureSecret bool
  419. azureSecret *AzureServiceKey
  420. loadedAzureStorageConfigSecret bool
  421. azureStorageConfig *AzureStorageConfig
  422. }
  423. // PricingSourceSummary returns the pricing source summary for the provider.
  424. // The summary represents what was _parsed_ from the pricing source, not
  425. // everything that was _available_ in the pricing source.
  426. func (az *Azure) PricingSourceSummary() interface{} {
  427. return az.Pricing
  428. }
  429. // azureWindowsOS is the node OS label value that identifies a Windows node and
  430. // the suffix used to qualify Windows-specific pricing keys.
  431. const azureWindowsOS = "windows"
  432. // isWindowsNode reports whether the node labels identify a Windows node. It
  433. // centralizes the OS detection shared by azureKey.Features and NodePricing.
  434. func isWindowsNode(labels map[string]string) bool {
  435. osLabel, ok := util.GetOperatingSystem(labels)
  436. return ok && strings.ToLower(osLabel) == azureWindowsOS
  437. }
  438. type azureKey struct {
  439. Labels map[string]string
  440. GPULabel string
  441. GPULabelValue string
  442. }
  443. func (k *azureKey) Features() string {
  444. r, _ := util.GetRegion(k.Labels)
  445. region := strings.ToLower(r)
  446. instance, _ := util.GetInstanceType(k.Labels)
  447. usageType := "ondemand"
  448. if isWindowsNode(k.Labels) {
  449. return fmt.Sprintf("%s,%s,%s,%s", region, instance, usageType, azureWindowsOS)
  450. }
  451. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  452. }
  453. func (k *azureKey) GPUCount() int {
  454. return 0
  455. }
  456. // GPUType returns value of GPULabel if present
  457. func (k *azureKey) GPUType() string {
  458. if t, ok := k.Labels[k.GPULabel]; ok {
  459. return t
  460. }
  461. return ""
  462. }
  463. func (k *azureKey) isValidGPUNode() bool {
  464. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  465. }
  466. func (k *azureKey) ID() string {
  467. return ""
  468. }
  469. func (k *azureKey) GetGPUCount() string {
  470. instance, _ := util.GetInstanceType(k.Labels)
  471. // Double digits that could get matches lower in logic
  472. if strings.Contains(instance, "NC64") {
  473. return "4"
  474. }
  475. if strings.Contains(instance, "ND96") ||
  476. strings.Contains(instance, "ND40") {
  477. return "8"
  478. }
  479. // Ordered asc because of some series have different gpu counts on different versions
  480. if strings.Contains(instance, "NC6") ||
  481. strings.Contains(instance, "NC4") ||
  482. strings.Contains(instance, "NC8") ||
  483. strings.Contains(instance, "NC16") ||
  484. strings.Contains(instance, "ND6") ||
  485. strings.Contains(instance, "NV12s") ||
  486. strings.Contains(instance, "NV6") {
  487. return "1"
  488. }
  489. if strings.Contains(instance, "NC12") ||
  490. strings.Contains(instance, "ND12") ||
  491. strings.Contains(instance, "NV24s") ||
  492. strings.Contains(instance, "NV12") {
  493. return "2"
  494. }
  495. if strings.Contains(instance, "NC24") ||
  496. strings.Contains(instance, "ND24") ||
  497. strings.Contains(instance, "NV48s") ||
  498. strings.Contains(instance, "NV24") {
  499. return "4"
  500. }
  501. return "0"
  502. }
  503. // AzureStorageConfig Represents an azure storage config
  504. // Deprecated: v1.104 Use StorageConfiguration instead
  505. type AzureStorageConfig struct {
  506. SubscriptionId string `json:"azureSubscriptionID"`
  507. AccountName string `json:"azureStorageAccount"`
  508. AccessKey string `json:"azureStorageAccessKey"`
  509. ContainerName string `json:"azureStorageContainer"`
  510. ContainerPath string `json:"azureContainerPath"`
  511. AzureCloud string `json:"azureCloud"`
  512. }
  513. // IsEmpty returns true if all fields in config are empty, false if not.
  514. func (asc *AzureStorageConfig) IsEmpty() bool {
  515. return asc.SubscriptionId == "" &&
  516. asc.AccountName == "" &&
  517. asc.AccessKey == "" &&
  518. asc.ContainerName == "" &&
  519. asc.ContainerPath == "" &&
  520. asc.AzureCloud == ""
  521. }
  522. // Represents an azure app key
  523. type AzureAppKey struct {
  524. AppID string `json:"appId"`
  525. DisplayName string `json:"displayName"`
  526. Name string `json:"name"`
  527. Password string `json:"password"`
  528. Tenant string `json:"tenant"`
  529. }
  530. // AzureServiceKey service key for a specific subscription
  531. // Deprecated: v1.104 Use ServiceKey instead
  532. type AzureServiceKey struct {
  533. SubscriptionID string `json:"subscriptionId"`
  534. ServiceKey *AzureAppKey `json:"serviceKey"`
  535. }
  536. // Validity check on service key
  537. func (ask *AzureServiceKey) IsValid() bool {
  538. return ask.SubscriptionID != "" &&
  539. ask.ServiceKey != nil &&
  540. ask.ServiceKey.AppID != "" &&
  541. ask.ServiceKey.Password != "" &&
  542. ask.ServiceKey.Tenant != ""
  543. }
  544. // Loads the azure authentication via configuration or a secret set at install time.
  545. func (az *Azure) getAzureRateCardAuth(forceReload bool, cp *models.CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  546. // 1. Check for secret (secret values will always be used if they are present)
  547. s, _ := az.loadAzureAuthSecret(forceReload)
  548. if s != nil && s.IsValid() {
  549. subscriptionID = s.SubscriptionID
  550. clientID = s.ServiceKey.AppID
  551. clientSecret = s.ServiceKey.Password
  552. tenantID = s.ServiceKey.Tenant
  553. return
  554. }
  555. // 2. Check config values (set though endpoint)
  556. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  557. subscriptionID = cp.AzureSubscriptionID
  558. clientID = cp.AzureClientID
  559. clientSecret = cp.AzureClientSecret
  560. tenantID = cp.AzureTenantID
  561. return
  562. }
  563. // 3. Check if AzureSubscriptionID is set in config (set though endpoint)
  564. // MSI credentials will be attempted if the subscription ID is set, but clientID, clientSecret and tenantID are not
  565. if cp.AzureSubscriptionID != "" {
  566. subscriptionID = cp.AzureSubscriptionID
  567. return
  568. }
  569. // 4. Empty values
  570. return "", "", "", ""
  571. }
  572. // GetAzureStorageConfig retrieves storage config from secret and sets default values
  573. func (az *Azure) GetAzureStorageConfig(forceReload bool, cp *models.CustomPricing) (*AzureStorageConfig, error) {
  574. // default subscription id
  575. defaultSubscriptionID := cp.AzureSubscriptionID
  576. // 1. Check Config for storage set up
  577. asc := &AzureStorageConfig{
  578. SubscriptionId: cp.AzureStorageSubscriptionID,
  579. AccountName: cp.AzureStorageAccount,
  580. AccessKey: cp.AzureStorageAccessKey,
  581. ContainerName: cp.AzureStorageContainer,
  582. ContainerPath: cp.AzureContainerPath,
  583. AzureCloud: cp.AzureCloud,
  584. }
  585. // check for required fields
  586. if asc != nil && asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  587. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  588. Message: "Azure Storage Config exists",
  589. Status: true,
  590. })
  591. return asc, nil
  592. }
  593. // 2. Check for secret
  594. asc, err := az.loadAzureStorageConfig(forceReload)
  595. if err != nil {
  596. log.Errorf("Error, %s", err.Error())
  597. } else if asc != nil {
  598. // To support already configured users, subscriptionID may not be set in secret in which case, the subscriptionID
  599. // for the rate card API is used
  600. if asc.SubscriptionId == "" {
  601. asc.SubscriptionId = defaultSubscriptionID
  602. }
  603. // check for required fields
  604. if asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  605. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  606. Message: "Azure Storage Config exists",
  607. Status: true,
  608. })
  609. return asc, nil
  610. }
  611. }
  612. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  613. Message: "Azure Storage Config exists",
  614. Status: false,
  615. })
  616. return nil, fmt.Errorf("azure storage config not found")
  617. }
  618. // Load once and cache the result (even on failure). This is an install time secret, so
  619. // we don't expect the secret to change. If it does, however, we can force reload using
  620. // the input parameter.
  621. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  622. if !force && az.loadedAzureSecret {
  623. return az.azureSecret, nil
  624. }
  625. az.loadedAzureSecret = true
  626. exists, err := fileutil.FileExists(models.AuthSecretPath)
  627. if !exists || err != nil {
  628. return nil, fmt.Errorf("Failed to locate service account file: %s", models.AuthSecretPath)
  629. }
  630. result, err := os.ReadFile(models.AuthSecretPath)
  631. if err != nil {
  632. return nil, err
  633. }
  634. var ask AzureServiceKey
  635. err = json.Unmarshal(result, &ask)
  636. if err != nil {
  637. return nil, err
  638. }
  639. az.azureSecret = &ask
  640. return &ask, nil
  641. }
  642. // Load once and cache the result (even on failure). This is an install time secret, so
  643. // we don't expect the secret to change. If it does, however, we can force reload using
  644. // the input parameter.
  645. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  646. if !force && az.loadedAzureStorageConfigSecret {
  647. return az.azureStorageConfig, nil
  648. }
  649. az.loadedAzureStorageConfigSecret = true
  650. exists, err := fileutil.FileExists(models.StorageConfigSecretPath)
  651. if !exists || err != nil {
  652. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", models.StorageConfigSecretPath)
  653. }
  654. result, err := os.ReadFile(models.StorageConfigSecretPath)
  655. if err != nil {
  656. return nil, err
  657. }
  658. var asc AzureStorageConfig
  659. err = json.Unmarshal(result, &asc)
  660. if err != nil {
  661. return nil, err
  662. }
  663. az.azureStorageConfig = &asc
  664. return &asc, nil
  665. }
  666. func (az *Azure) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  667. cfg, err := az.GetConfig()
  668. if err != nil {
  669. log.Infof("Error loading azure custom pricing information")
  670. }
  671. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  672. gpuLabel := "accelerator"
  673. gpuLabelValue := "nvidia"
  674. if cfg.GpuLabel != "" {
  675. gpuLabel = cfg.GpuLabel
  676. }
  677. if cfg.GpuLabelValue != "" {
  678. gpuLabelValue = cfg.GpuLabelValue
  679. }
  680. return &azureKey{
  681. Labels: labels,
  682. GPULabel: gpuLabel,
  683. GPULabelValue: gpuLabelValue,
  684. }
  685. }
  686. // CreateString builds strings effectively
  687. func createString(keys ...string) string {
  688. var b strings.Builder
  689. for _, key := range keys {
  690. b.WriteString(key)
  691. }
  692. return b.String()
  693. }
  694. // getConfigSource returns a human-readable string indicating the source of configuration
  695. func getConfigSource(envVarName, envValue, defaultSource string) string {
  696. if envValue != "" {
  697. return "env:" + envVarName
  698. }
  699. return defaultSource
  700. }
  701. func transformMachineType(subCategory string, mt []string) []string {
  702. switch {
  703. case strings.Contains(subCategory, "Basic"):
  704. return []string{createString("Basic_", mt[0])}
  705. case len(mt) == 2:
  706. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  707. default:
  708. return []string{createString("Standard_", mt[0])}
  709. }
  710. }
  711. func addSuffix(mt string, suffixes ...string) []string {
  712. result := make([]string, len(suffixes))
  713. var suffix string
  714. parts := strings.Split(mt, "_")
  715. if len(parts) > 2 {
  716. for _, p := range parts[2:] {
  717. suffix = createString(suffix, "_", p)
  718. }
  719. }
  720. for i, s := range suffixes {
  721. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  722. }
  723. return result
  724. }
  725. func getMachineTypeVariants(mt string) []string {
  726. switch {
  727. case mtStandardB.MatchString(mt):
  728. return []string{createString(mt, "s")}
  729. case mtStandardD.MatchString(mt):
  730. var result []string
  731. result = append(result, addSuffix(mt, "s")[0])
  732. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  733. result = append(result, dsType)
  734. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  735. return result
  736. case mtStandardE.MatchString(mt):
  737. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  738. case mtStandardF.MatchString(mt):
  739. return addSuffix(mt, "s")
  740. case mtStandardG.MatchString(mt):
  741. var result []string
  742. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  743. result = append(result, gsType)
  744. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  745. case mtStandardL.MatchString(mt):
  746. return addSuffix(mt, "s")
  747. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  748. base := strings.TrimSuffix(mt, "ms")
  749. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  750. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  751. return []string{}
  752. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  753. base := strings.TrimSuffix(mt, "s")
  754. return addSuffix(base, "", "m")
  755. case mtStandardN.MatchString(mt):
  756. return addSuffix(mt, "s")
  757. }
  758. return []string{}
  759. }
  760. func (az *Azure) GetManagementPlatform() (string, error) {
  761. nodes := az.Clientset.GetAllNodes()
  762. if len(nodes) > 0 {
  763. n := nodes[0]
  764. providerID := n.SpecProviderID
  765. if strings.Contains(providerID, "aks") {
  766. return "aks", nil
  767. }
  768. }
  769. return "", nil
  770. }
  771. // DownloadPricingData uses provided azure "best guesses" for pricing
  772. func (az *Azure) DownloadPricingData() error {
  773. az.DownloadPricingDataLock.Lock()
  774. defer az.DownloadPricingDataLock.Unlock()
  775. config, err := az.GetConfig()
  776. if err != nil {
  777. az.rateCardPricingError = err
  778. return err
  779. }
  780. envBillingAccount := env.GetAzureBillingAccount()
  781. if envBillingAccount != "" {
  782. config.AzureBillingAccount = envBillingAccount
  783. }
  784. envOfferID := env.GetAzureOfferID()
  785. if envOfferID != "" {
  786. config.AzureOfferDurableID = envOfferID
  787. }
  788. // Check for Azure rate card filter environment variables with backward compatibility
  789. locale := env.GetAzureLocale() // Defaults to "en-US"
  790. envCurrency := env.GetAzureCurrency()
  791. currency := config.CurrencyCode // Use config default
  792. if envCurrency != "" {
  793. currency = envCurrency // Override with environment variable if provided
  794. }
  795. envRegionInfo := env.GetAzureRegionInfo()
  796. regionInfo := config.AzureBillingRegion // Use config default
  797. if envRegionInfo != "" {
  798. regionInfo = envRegionInfo // Override with environment variable if provided
  799. }
  800. // Debug logging for rate card configuration
  801. log.Debugf("Azure rate card configuration: locale=%s (source: %s), currency=%s (source: %s), regionInfo=%s (source: %s)",
  802. locale, getConfigSource("AZURE_LOCALE", locale, "en-US"),
  803. currency, getConfigSource("AZURE_CURRENCY", envCurrency, "config"),
  804. regionInfo, getConfigSource("AZURE_REGION_INFO", envRegionInfo, "config"))
  805. // Load the service provider keys
  806. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  807. config.AzureSubscriptionID = subscriptionID
  808. config.AzureClientID = clientID
  809. config.AzureClientSecret = clientSecret
  810. config.AzureTenantID = tenantID
  811. var authorizer autorest.Authorizer
  812. azureEnv := determineCloudByRegion(az.ClusterRegion)
  813. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  814. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  815. a, err := credentialsConfig.Authorizer()
  816. if err != nil {
  817. az.rateCardPricingError = err
  818. return err
  819. }
  820. authorizer = a
  821. }
  822. if authorizer == nil {
  823. a, err := auth.NewAuthorizerFromEnvironment()
  824. authorizer = a
  825. if err != nil {
  826. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  827. if err != nil {
  828. az.rateCardPricingError = err
  829. return err
  830. }
  831. authorizer = a
  832. }
  833. }
  834. sClient := subscriptions.NewClientWithBaseURI(azureEnv.ResourceManagerEndpoint)
  835. sClient.Authorizer = authorizer
  836. rcClient := commerce.NewRateCardClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  837. rcClient.Authorizer = authorizer
  838. providersClient := resources.NewProvidersClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  839. providersClient.Authorizer = authorizer
  840. rateCardFilter := fmt.Sprintf("OfferDurableId eq '%s' and Currency eq '%s' and Locale eq '%s' and RegionInfo eq '%s'", config.AzureOfferDurableID, currency, locale, regionInfo)
  841. // create a preparer (the same way rcClient.Get() does) so that we can log the azureRateCard URL
  842. log.Infof("Using azureRateCard query %s", rateCardFilter)
  843. rcPreparer, err := rcClient.GetPreparer(context.TODO(), rateCardFilter)
  844. if err != nil {
  845. // this isn't an error that necessitates a return, as we only need the preparer for an informational log
  846. log.Infof("Failed to get azureRateCard URL: %s", err)
  847. } else {
  848. log.Infof("Using azureRateCard URL %s", rcPreparer.URL.String())
  849. }
  850. // rate-card client is old, it can hang indefinitely in some cases
  851. // this happens on the main thread, so it may block the whole app
  852. // there is can be a better way to set timeout for the client
  853. ctx, cancel := context.WithTimeout(context.TODO(), 300*time.Second)
  854. defer cancel()
  855. result, err := rcClient.Get(ctx, rateCardFilter)
  856. if err != nil {
  857. log.Warnf("Error in pricing download query from API")
  858. az.rateCardPricingError = err
  859. return err
  860. }
  861. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  862. if err != nil {
  863. log.Warnf("Error in pricing download regions from API")
  864. az.rateCardPricingError = err
  865. return err
  866. }
  867. baseCPUPrice := config.CPU
  868. allPrices := make(map[string]*AzurePricing)
  869. for _, v := range *result.Meters {
  870. pricings, err := convertMeterToPricings(v, regions, baseCPUPrice)
  871. if err != nil {
  872. log.Warnf("converting meter to pricings: %s", err.Error())
  873. continue
  874. }
  875. for key, pricing := range pricings {
  876. allPrices[key] = pricing
  877. }
  878. }
  879. addAzureFilePricing(allPrices, regions)
  880. az.Pricing = allPrices
  881. az.pricingSource = rateCardPricingSource
  882. az.rateCardPricingError = nil
  883. // If we've got a billing account set, kick off downloading the custom pricing data.
  884. if config.AzureBillingAccount != "" {
  885. downloader := PriceSheetDownloader{
  886. TenantID: config.AzureTenantID,
  887. ClientID: config.AzureClientID,
  888. ClientSecret: config.AzureClientSecret,
  889. BillingAccount: config.AzureBillingAccount,
  890. OfferID: config.AzureOfferDurableID,
  891. ConvertMeterInfo: func(meterInfo commerce.MeterInfo) (map[string]*AzurePricing, error) {
  892. return convertMeterToPricings(meterInfo, regions, baseCPUPrice)
  893. },
  894. }
  895. // The price sheet can take 5 minutes to generate, so we don't
  896. // want to hang onto the lock while we're waiting for it.
  897. go func() {
  898. ctx := context.Background()
  899. allPrices, err := downloader.GetPricing(ctx)
  900. az.DownloadPricingDataLock.Lock()
  901. defer az.DownloadPricingDataLock.Unlock()
  902. if err != nil {
  903. log.Errorf("Error downloading Azure price sheet: %s", err)
  904. az.priceSheetPricingError = err
  905. return
  906. }
  907. addAzureFilePricing(allPrices, regions)
  908. az.Pricing = allPrices
  909. az.pricingSource = priceSheetPricingSource
  910. az.priceSheetPricingError = nil
  911. }()
  912. }
  913. return nil
  914. }
  915. func convertMeterToPricings(info commerce.MeterInfo, regions map[string]string, baseCPUPrice string) (map[string]*AzurePricing, error) {
  916. meterName := *info.MeterName
  917. meterRegion := *info.MeterRegion
  918. meterCategory := *info.MeterCategory
  919. meterSubCategory := *info.MeterSubCategory
  920. region, err := toRegionID(meterRegion, regions)
  921. if err != nil {
  922. // Skip this meter if we don't recognize the region.
  923. return nil, nil
  924. }
  925. isWindowsMeter := strings.Contains(meterSubCategory, "Windows")
  926. if strings.Contains(meterSubCategory, "Cloud Services") || strings.Contains(meterSubCategory, "CloudServices") {
  927. // This meter doesn't correspond to any pricings.
  928. return nil, nil
  929. }
  930. if strings.Contains(meterCategory, "Storage") {
  931. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  932. var storageClass string = ""
  933. if strings.Contains(meterName, "P4 ") {
  934. storageClass = AzureDiskPremiumSSDStorageClass
  935. } else if strings.Contains(meterName, "E4 ") {
  936. storageClass = AzureDiskStandardSSDStorageClass
  937. } else if strings.Contains(meterName, "S4 ") {
  938. storageClass = AzureDiskStandardStorageClass
  939. } else if strings.Contains(meterName, "LRS Provisioned") {
  940. storageClass = AzureFilePremiumStorageClass
  941. }
  942. if storageClass != "" {
  943. var priceInUsd float64
  944. if len(info.MeterRates) < 1 {
  945. return nil, fmt.Errorf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *info.MeterSubCategory, "region": region})
  946. }
  947. for _, rate := range info.MeterRates {
  948. priceInUsd += *rate
  949. }
  950. // rate is in disk per month, resolve price per hour, then GB per hour
  951. pricePerHour := priceInUsd / 730.0 / 32.0
  952. priceStr := fmt.Sprintf("%f", pricePerHour)
  953. key := region + "," + storageClass
  954. log.Debugf("Adding PV.Key: %s, Cost: %s", key, priceStr)
  955. return map[string]*AzurePricing{
  956. key: {
  957. PV: &models.PV{
  958. Cost: priceStr,
  959. Region: region,
  960. },
  961. },
  962. }, nil
  963. }
  964. }
  965. }
  966. if !strings.Contains(meterCategory, "Virtual Machines") {
  967. return nil, nil
  968. }
  969. usageType := ""
  970. if !strings.Contains(meterName, "Low Priority") {
  971. usageType = "ondemand"
  972. } else {
  973. usageType = "preemptible"
  974. }
  975. var instanceTypes []string
  976. name := strings.TrimSuffix(meterName, " Low Priority")
  977. instanceType := strings.Split(name, "/")
  978. for _, it := range instanceType {
  979. if strings.Contains(meterSubCategory, "Promo") {
  980. it = it + " Promo"
  981. }
  982. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  983. }
  984. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  985. if strings.Contains(name, "Expired") {
  986. instanceTypes = []string{}
  987. }
  988. var priceInUsd float64
  989. if len(info.MeterRates) < 1 {
  990. return nil, fmt.Errorf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *info.MeterSubCategory, "region": region})
  991. }
  992. for _, rate := range info.MeterRates {
  993. priceInUsd += *rate
  994. }
  995. priceStr := fmt.Sprintf("%f", priceInUsd)
  996. results := make(map[string]*AzurePricing)
  997. for _, instanceType := range instanceTypes {
  998. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  999. if isWindowsMeter {
  1000. key = fmt.Sprintf("%s,%s,%s,%s", region, instanceType, usageType, azureWindowsOS)
  1001. }
  1002. pricing := &AzurePricing{
  1003. Node: &models.Node{
  1004. Cost: priceStr,
  1005. BaseCPUPrice: baseCPUPrice,
  1006. UsageType: usageType,
  1007. },
  1008. }
  1009. results[key] = pricing
  1010. }
  1011. return results, nil
  1012. }
  1013. func addAzureFilePricing(prices map[string]*AzurePricing, regions map[string]string) {
  1014. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  1015. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  1016. // check https://github.com/opencost/opencost/issues/159 for more information (same problem on AWS)
  1017. zeroPrice := "0.0"
  1018. for region := range regions {
  1019. key := region + "," + AzureFileStandardStorageClass
  1020. log.Debugf("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  1021. prices[key] = &AzurePricing{
  1022. PV: &models.PV{
  1023. Cost: zeroPrice,
  1024. Region: region,
  1025. },
  1026. }
  1027. }
  1028. }
  1029. // determineCloudByRegion uses region name to pick the correct Cloud Environment for the azure provider to use
  1030. func determineCloudByRegion(region string) azure.Environment {
  1031. lcRegion := strings.ToLower(region)
  1032. if strings.Contains(lcRegion, "china") {
  1033. return azure.ChinaCloud
  1034. }
  1035. if strings.Contains(lcRegion, "gov") || strings.Contains(lcRegion, "dod") {
  1036. return azure.USGovernmentCloud
  1037. }
  1038. // Default to public cloud
  1039. return azure.PublicCloud
  1040. }
  1041. // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
  1042. func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string, env azure.Environment) auth.ClientCredentialsConfig {
  1043. return auth.ClientCredentialsConfig{
  1044. ClientID: clientID,
  1045. ClientSecret: clientSecret,
  1046. TenantID: tenantID,
  1047. Resource: env.ResourceManagerEndpoint,
  1048. AADEndpoint: env.ActiveDirectoryEndpoint,
  1049. }
  1050. }
  1051. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  1052. if az.Pricing == nil {
  1053. az.Pricing = map[string]*AzurePricing{}
  1054. }
  1055. az.Pricing[features] = azurePricing
  1056. }
  1057. // AllNodePricing returns the Azure pricing objects stored
  1058. func (az *Azure) AllNodePricing() (interface{}, error) {
  1059. az.DownloadPricingDataLock.RLock()
  1060. defer az.DownloadPricingDataLock.RUnlock()
  1061. return az.Pricing, nil
  1062. }
  1063. // NodePricing returns Azure pricing data for a single node
  1064. func (az *Azure) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  1065. az.DownloadPricingDataLock.RLock()
  1066. defer az.DownloadPricingDataLock.RUnlock()
  1067. meta := models.PricingMetadata{}
  1068. azKey, ok := key.(*azureKey)
  1069. if !ok {
  1070. return nil, meta, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  1071. }
  1072. config, _ := az.GetConfig()
  1073. slv, ok := azKey.Labels[config.SpotLabel]
  1074. isSpot := ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != ""
  1075. isWindows := isWindowsNode(azKey.Labels)
  1076. features := strings.Split(azKey.Features(), ",")
  1077. region := features[0]
  1078. instance := features[1]
  1079. var featureString string
  1080. if isSpot {
  1081. if isWindows {
  1082. featureString = fmt.Sprintf("%s,%s,spot,%s", region, instance, azureWindowsOS)
  1083. } else {
  1084. featureString = fmt.Sprintf("%s,%s,spot", region, instance)
  1085. }
  1086. } else {
  1087. featureString = azKey.Features()
  1088. }
  1089. if az.Pricing != nil {
  1090. if n, ok := az.Pricing[featureString]; ok {
  1091. log.Debugf("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  1092. if azKey.isValidGPUNode() {
  1093. n.Node.GPU = azKey.GetGPUCount()
  1094. }
  1095. return n.Node, meta, nil
  1096. } else {
  1097. log.Debugf("Could not find pricing for node %s from key %s", azKey, azKey.Features())
  1098. }
  1099. }
  1100. cost, err := getRetailPrice(region, instance, config.CurrencyCode, isSpot, isWindows)
  1101. if err != nil {
  1102. log.DedupedWarningf(5, "failed to retrieve retail pricing: %s", err)
  1103. } else {
  1104. gpu := ""
  1105. if azKey.isValidGPUNode() {
  1106. gpu = azKey.GetGPUCount()
  1107. }
  1108. var node *models.Node
  1109. if isSpot {
  1110. node = &models.Node{
  1111. Cost: cost,
  1112. UsageType: "spot",
  1113. GPU: gpu,
  1114. }
  1115. } else {
  1116. node = &models.Node{
  1117. Cost: cost,
  1118. GPU: gpu,
  1119. }
  1120. }
  1121. az.addPricing(featureString, &AzurePricing{
  1122. Node: node,
  1123. })
  1124. return node, meta, nil
  1125. }
  1126. log.DedupedWarningf(5, "No pricing data found for node %s from key %s", azKey, azKey.Features())
  1127. c, err := az.GetConfig()
  1128. if err != nil {
  1129. return nil, meta, fmt.Errorf("No default pricing data available")
  1130. }
  1131. var vcpuCost string
  1132. var ramCost string
  1133. var gpuCost string
  1134. if isSpot {
  1135. vcpuCost = c.SpotCPU
  1136. ramCost = c.SpotRAM
  1137. gpuCost = c.SpotGPU
  1138. } else {
  1139. vcpuCost = c.CPU
  1140. ramCost = c.RAM
  1141. gpuCost = c.GPU
  1142. }
  1143. // GPU Node
  1144. if azKey.isValidGPUNode() {
  1145. return &models.Node{
  1146. VCPUCost: vcpuCost,
  1147. RAMCost: ramCost,
  1148. UsesBaseCPUPrice: true,
  1149. GPUCost: gpuCost,
  1150. GPU: azKey.GetGPUCount(),
  1151. }, meta, nil
  1152. }
  1153. // Serverless Node. This is an Azure Container Instance, and no pods can be
  1154. // scheduled to this node. Azure does not charge for this node. Set costs to
  1155. // zero.
  1156. if azKey.Labels["kubernetes.io/hostname"] == "virtual-node-aci-linux" {
  1157. return &models.Node{
  1158. VCPUCost: "0",
  1159. RAMCost: "0",
  1160. }, meta, nil
  1161. }
  1162. // Regular Node
  1163. return &models.Node{
  1164. VCPUCost: vcpuCost,
  1165. RAMCost: ramCost,
  1166. UsesBaseCPUPrice: true,
  1167. }, meta, nil
  1168. }
  1169. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  1170. func (az *Azure) NetworkPricing() (*models.Network, error) {
  1171. cpricing, err := az.Config.GetCustomPricingData()
  1172. if err != nil {
  1173. return nil, err
  1174. }
  1175. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1180. if err != nil {
  1181. return nil, err
  1182. }
  1183. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1184. if err != nil {
  1185. return nil, err
  1186. }
  1187. nge, err := strconv.ParseFloat(cpricing.NatGatewayEgress, 64)
  1188. if err != nil {
  1189. return nil, err
  1190. }
  1191. ngi, err := strconv.ParseFloat(cpricing.NatGatewayIngress, 64)
  1192. if err != nil {
  1193. return nil, err
  1194. }
  1195. return &models.Network{
  1196. ZoneNetworkEgressCost: znec,
  1197. RegionNetworkEgressCost: rnec,
  1198. InternetNetworkEgressCost: inec,
  1199. NatGatewayEgressCost: nge,
  1200. NatGatewayIngressCost: ngi,
  1201. }, nil
  1202. }
  1203. // LoadBalancerPricing on Azure, LoadBalancer services correspond to public IPs. For now the pricing of LoadBalancer
  1204. // services will be that of a standard static public IP https://azure.microsoft.com/en-us/pricing/details/ip-addresses/.
  1205. // Azure still has load balancers which follow the standard pricing scheme based on rules
  1206. // https://azure.microsoft.com/en-us/pricing/details/load-balancer/, they are created on a per-cluster basis.
  1207. func (azr *Azure) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1208. return &models.LoadBalancer{
  1209. Cost: 0.005,
  1210. }, nil
  1211. }
  1212. type azurePvKey struct {
  1213. Labels map[string]string
  1214. StorageClass string
  1215. StorageClassParameters map[string]string
  1216. DefaultRegion string
  1217. ProviderId string
  1218. }
  1219. func (az *Azure) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  1220. providerID := ""
  1221. if pv.Spec.AzureDisk != nil {
  1222. providerID = pv.Spec.AzureDisk.DiskName
  1223. }
  1224. return &azurePvKey{
  1225. Labels: pv.Labels,
  1226. StorageClass: pv.Spec.StorageClassName,
  1227. StorageClassParameters: parameters,
  1228. DefaultRegion: defaultRegion,
  1229. ProviderId: providerID,
  1230. }
  1231. }
  1232. func (key *azurePvKey) ID() string {
  1233. return key.ProviderId
  1234. }
  1235. func (key *azurePvKey) GetStorageClass() string {
  1236. return key.StorageClass
  1237. }
  1238. func (key *azurePvKey) Features() string {
  1239. storageClass := key.StorageClassParameters["storageaccounttype"]
  1240. diskSKU := key.StorageClassParameters["skuname"]
  1241. fileSKU := key.StorageClassParameters["skuName"]
  1242. if storageClass == "" {
  1243. storageClass = diskSKU
  1244. }
  1245. if storageClass != "" {
  1246. if strings.EqualFold(storageClass, "Premium_LRS") {
  1247. storageClass = AzureDiskPremiumSSDStorageClass
  1248. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1249. storageClass = AzureDiskStandardSSDStorageClass
  1250. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1251. storageClass = AzureDiskStandardStorageClass
  1252. }
  1253. } else {
  1254. if strings.EqualFold(fileSKU, "Premium_LRS") {
  1255. storageClass = AzureFilePremiumStorageClass
  1256. } else if strings.EqualFold(fileSKU, "Standard_LRS") {
  1257. storageClass = AzureFileStandardStorageClass
  1258. }
  1259. }
  1260. if region, ok := util.GetRegion(key.Labels); ok {
  1261. return region + "," + storageClass
  1262. }
  1263. return key.DefaultRegion + "," + storageClass
  1264. }
  1265. func (*Azure) GetAddresses() ([]byte, error) {
  1266. return nil, nil
  1267. }
  1268. func (az *Azure) GetDisks() ([]byte, error) {
  1269. disks, err := az.getDisks()
  1270. if err != nil {
  1271. return nil, err
  1272. }
  1273. return json.Marshal(disks)
  1274. }
  1275. func (az *Azure) getDisks() ([]*compute.Disk, error) {
  1276. config, err := az.GetConfig()
  1277. if err != nil {
  1278. return nil, err
  1279. }
  1280. // Load the service provider keys
  1281. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  1282. config.AzureSubscriptionID = subscriptionID
  1283. config.AzureClientID = clientID
  1284. config.AzureClientSecret = clientSecret
  1285. config.AzureTenantID = tenantID
  1286. var authorizer autorest.Authorizer
  1287. azureEnv := determineCloudByRegion(az.ClusterRegion)
  1288. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  1289. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  1290. a, err := credentialsConfig.Authorizer()
  1291. if err != nil {
  1292. az.rateCardPricingError = err
  1293. return nil, err
  1294. }
  1295. authorizer = a
  1296. }
  1297. if authorizer == nil {
  1298. a, err := auth.NewAuthorizerFromEnvironment()
  1299. authorizer = a
  1300. if err != nil {
  1301. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  1302. if err != nil {
  1303. az.rateCardPricingError = err
  1304. return nil, err
  1305. }
  1306. authorizer = a
  1307. }
  1308. }
  1309. client := compute.NewDisksClient(config.AzureSubscriptionID)
  1310. client.Authorizer = authorizer
  1311. ctx := context.TODO()
  1312. var disks []*compute.Disk
  1313. diskPage, err := client.List(ctx)
  1314. if err != nil {
  1315. return nil, fmt.Errorf("error getting disks: %v", err)
  1316. }
  1317. for diskPage.NotDone() {
  1318. for _, d := range diskPage.Values() {
  1319. d := d
  1320. disks = append(disks, &d)
  1321. }
  1322. err := diskPage.NextWithContext(context.Background())
  1323. if err != nil {
  1324. return nil, fmt.Errorf("error getting next page: %v", err)
  1325. }
  1326. }
  1327. return disks, nil
  1328. }
  1329. func (az *Azure) isDiskOrphaned(disk *compute.Disk) bool {
  1330. //TODO: needs better algorithm
  1331. return disk.DiskState == "Unattached" || disk.DiskState == "Reserved"
  1332. }
  1333. func (az *Azure) GetOrphanedResources() ([]models.OrphanedResource, error) {
  1334. disks, err := az.getDisks()
  1335. if err != nil {
  1336. return nil, err
  1337. }
  1338. var orphanedResources []models.OrphanedResource
  1339. for _, d := range disks {
  1340. if az.isDiskOrphaned(d) {
  1341. cost, err := az.findCostForDisk(d)
  1342. if err != nil {
  1343. return nil, err
  1344. }
  1345. diskName := ""
  1346. if d.Name != nil {
  1347. diskName = *d.Name
  1348. }
  1349. diskRegion := ""
  1350. if d.Location != nil {
  1351. diskRegion = *d.Location
  1352. }
  1353. var diskSize int64
  1354. if d.DiskSizeGB != nil {
  1355. diskSize = int64(*d.DiskSizeGB)
  1356. }
  1357. desc := map[string]string{}
  1358. for k, v := range d.Tags {
  1359. if v == nil {
  1360. desc[k] = ""
  1361. } else {
  1362. desc[k] = *v
  1363. }
  1364. }
  1365. or := models.OrphanedResource{
  1366. Kind: "disk",
  1367. Region: diskRegion,
  1368. Description: desc,
  1369. Size: &diskSize,
  1370. DiskName: diskName,
  1371. MonthlyCost: &cost,
  1372. }
  1373. orphanedResources = append(orphanedResources, or)
  1374. }
  1375. }
  1376. return orphanedResources, nil
  1377. }
  1378. func (az *Azure) findCostForDisk(d *compute.Disk) (float64, error) {
  1379. if d == nil {
  1380. return 0.0, fmt.Errorf("disk is empty")
  1381. }
  1382. if d.Sku == nil {
  1383. return 0.0, fmt.Errorf("disk sku is nil")
  1384. }
  1385. storageClass := string(d.Sku.Name)
  1386. if strings.EqualFold(storageClass, "Premium_LRS") {
  1387. storageClass = AzureDiskPremiumSSDStorageClass
  1388. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1389. storageClass = AzureDiskStandardSSDStorageClass
  1390. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1391. storageClass = AzureDiskStandardStorageClass
  1392. }
  1393. loc := ""
  1394. if d.Location != nil {
  1395. loc = *d.Location
  1396. }
  1397. key := loc + "," + storageClass
  1398. if p, ok := az.Pricing[key]; !ok || p == nil {
  1399. return 0.0, fmt.Errorf("failed to find pricing for key: %s", key)
  1400. }
  1401. if az.Pricing[key].PV == nil {
  1402. return 0.0, fmt.Errorf("pricing for key '%s' has nil PV", key)
  1403. }
  1404. diskPricePerGBHour, err := strconv.ParseFloat(az.Pricing[key].PV.Cost, 64)
  1405. if err != nil {
  1406. return 0.0, fmt.Errorf("error converting to float: %s", err)
  1407. }
  1408. if d.DiskProperties == nil {
  1409. return 0.0, fmt.Errorf("disk properties are nil")
  1410. }
  1411. if d.DiskSizeGB == nil {
  1412. return 0.0, fmt.Errorf("disk size is nil")
  1413. }
  1414. cost := diskPricePerGBHour * timeutil.HoursPerMonth * float64(*d.DiskSizeGB)
  1415. return cost, nil
  1416. }
  1417. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1418. remoteEnabled := env.IsRemoteEnabled()
  1419. m := make(map[string]string)
  1420. m["name"] = "Azure Cluster #1"
  1421. c, err := az.GetConfig()
  1422. if err != nil {
  1423. return nil, err
  1424. }
  1425. if c.ClusterName != "" {
  1426. m["name"] = c.ClusterName
  1427. }
  1428. m["provider"] = opencost.AzureProvider
  1429. m["account"] = az.ClusterAccountID
  1430. m["region"] = az.ClusterRegion
  1431. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1432. m["id"] = coreenv.GetClusterID()
  1433. return m, nil
  1434. }
  1435. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  1436. return az.Config.UpdateFromMap(a)
  1437. }
  1438. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  1439. return az.Config.Update(func(c *models.CustomPricing) error {
  1440. if updateType == AzureStorageUpdateType {
  1441. asc := &AzureStorageConfig{}
  1442. err := json.NewDecoder(r).Decode(&asc)
  1443. if err != nil {
  1444. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1445. }
  1446. c.AzureStorageSubscriptionID = asc.SubscriptionId
  1447. c.AzureStorageAccount = asc.AccountName
  1448. if asc.AccessKey != "" {
  1449. c.AzureStorageAccessKey = asc.AccessKey
  1450. }
  1451. c.AzureStorageContainer = asc.ContainerName
  1452. c.AzureContainerPath = asc.ContainerPath
  1453. c.AzureCloud = asc.AzureCloud
  1454. } else {
  1455. // This will block if not in a goroutine. It calls GetConfig(), which
  1456. // in turn calls GetCustomPricingData, which acquires the same lock
  1457. // that is acquired by az.Config.Update, which is the function to
  1458. // which this function gets passed, and subsequently called. Booo.
  1459. defer func() {
  1460. go az.DownloadPricingData()
  1461. }()
  1462. a := make(map[string]interface{})
  1463. err := json.NewDecoder(r).Decode(&a)
  1464. if err != nil {
  1465. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1466. }
  1467. for k, v := range a {
  1468. // Just so we consistently supply / receive the same values, uppercase the first letter.
  1469. kUpper := utils.ToTitle.String(k)
  1470. vstr, ok := v.(string)
  1471. if ok {
  1472. err := models.SetCustomPricingField(c, kUpper, vstr)
  1473. if err != nil {
  1474. return fmt.Errorf("error setting custom pricing field on AzureStorageConfig: %s", err)
  1475. }
  1476. } else {
  1477. return fmt.Errorf("type error while updating config for %s", kUpper)
  1478. }
  1479. }
  1480. }
  1481. if env.IsRemoteEnabled() {
  1482. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  1483. if err != nil {
  1484. return fmt.Errorf("error updating cluster metadata: %s", err)
  1485. }
  1486. }
  1487. return nil
  1488. })
  1489. }
  1490. func (az *Azure) GetConfig() (*models.CustomPricing, error) {
  1491. c, err := az.Config.GetCustomPricingData()
  1492. if err != nil {
  1493. return nil, err
  1494. }
  1495. if c.Discount == "" {
  1496. c.Discount = "0%"
  1497. }
  1498. if c.NegotiatedDiscount == "" {
  1499. c.NegotiatedDiscount = "0%"
  1500. }
  1501. if c.CurrencyCode == "" {
  1502. c.CurrencyCode = "USD"
  1503. }
  1504. if c.AzureBillingRegion == "" {
  1505. c.AzureBillingRegion = "US"
  1506. }
  1507. // Default to pay-as-you-go Durable offer id
  1508. if c.AzureOfferDurableID == "" {
  1509. c.AzureOfferDurableID = "MS-AZR-0003p"
  1510. }
  1511. if c.SpotLabel == "" {
  1512. c.SpotLabel = defaultSpotLabel
  1513. }
  1514. if c.SpotLabelValue == "" {
  1515. c.SpotLabelValue = defaultSpotLabelValue
  1516. }
  1517. return c, nil
  1518. }
  1519. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  1520. }
  1521. func (az *Azure) GpuPricing(nodeLabels map[string]string) (string, error) {
  1522. return "", nil
  1523. }
  1524. func (az *Azure) PVPricing(pvk models.PVKey) (*models.PV, error) {
  1525. az.DownloadPricingDataLock.RLock()
  1526. defer az.DownloadPricingDataLock.RUnlock()
  1527. pricing, ok := az.Pricing[pvk.Features()]
  1528. if !ok {
  1529. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1530. return &models.PV{}, nil
  1531. }
  1532. return pricing.PV, nil
  1533. }
  1534. func (az *Azure) ServiceAccountStatus() *models.ServiceAccountStatus {
  1535. return az.ServiceAccountChecks.GetStatus()
  1536. }
  1537. const (
  1538. rateCardPricingSource = "Rate Card API"
  1539. priceSheetPricingSource = "Price Sheet API"
  1540. )
  1541. // PricingSourceStatus returns the status of the rate card api
  1542. func (az *Azure) PricingSourceStatus() map[string]*models.PricingSource {
  1543. az.DownloadPricingDataLock.Lock()
  1544. defer az.DownloadPricingDataLock.Unlock()
  1545. sources := make(map[string]*models.PricingSource)
  1546. errMsg := ""
  1547. if az.rateCardPricingError != nil {
  1548. errMsg = az.rateCardPricingError.Error()
  1549. }
  1550. rcps := &models.PricingSource{
  1551. Name: rateCardPricingSource,
  1552. Enabled: az.pricingSource == rateCardPricingSource,
  1553. Error: errMsg,
  1554. }
  1555. if rcps.Error != "" {
  1556. rcps.Available = false
  1557. } else if len(az.Pricing) == 0 {
  1558. rcps.Error = "No Pricing Data Available"
  1559. rcps.Available = false
  1560. } else {
  1561. rcps.Available = true
  1562. }
  1563. errMsg = ""
  1564. if az.priceSheetPricingError != nil {
  1565. errMsg = az.priceSheetPricingError.Error()
  1566. }
  1567. psps := &models.PricingSource{
  1568. Name: priceSheetPricingSource,
  1569. Enabled: az.pricingSource == priceSheetPricingSource,
  1570. Error: errMsg,
  1571. }
  1572. if psps.Error != "" {
  1573. psps.Available = false
  1574. } else if len(az.Pricing) == 0 {
  1575. psps.Error = "No Pricing Data Available"
  1576. psps.Available = false
  1577. } else if env.GetAzureBillingAccount() == "" {
  1578. psps.Error = "No Azure Billing Account ID"
  1579. psps.Available = false
  1580. } else {
  1581. psps.Available = true
  1582. }
  1583. sources[rateCardPricingSource] = rcps
  1584. sources[priceSheetPricingSource] = psps
  1585. return sources
  1586. }
  1587. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1588. return "", 0.0, nil
  1589. }
  1590. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1591. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1592. }
  1593. func (az *Azure) Regions() []string {
  1594. regionOverrides := env.GetRegionOverrideList()
  1595. if len(regionOverrides) > 0 {
  1596. log.Debugf("Overriding Azure regions with configured region list: %+v", regionOverrides)
  1597. return regionOverrides
  1598. }
  1599. return azureRegions
  1600. }
  1601. func ParseAzureSubscriptionID(id string) string {
  1602. match := azureSubRegex.FindStringSubmatch(id)
  1603. if len(match) >= 2 {
  1604. return match[1]
  1605. }
  1606. // Return empty string if an account could not be parsed from provided string
  1607. return ""
  1608. }