2
0

provider.go 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134
  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. defer resp.Body.Close()
  291. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  292. return "", fmt.Errorf("retail price responded with error status code %d", resp.StatusCode)
  293. }
  294. linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice, err := extractAzureVMRetailAndSpotPrices(resp)
  295. if err != nil {
  296. return "", fmt.Errorf("failed to extract azure prices: %w", err)
  297. }
  298. log.DedupedInfof(5, "done parsing retail price payload from \"%s\"\n", pricingURL)
  299. return selectRetailPrice(region, skuName, linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice, spot, isWindows)
  300. }
  301. // selectRetailPrice picks the price matching the node OS and pricing model.
  302. // Windows nodes prefer the Windows-specific price; when it is absent the Linux
  303. // price is used as a best-effort estimate and the fallback is logged so the
  304. // substitution is not silent.
  305. func selectRetailPrice(region, skuName, linuxRetailPrice, windowsRetailPrice, spotPrice, windowsSpotPrice string, spot, isWindows bool) (string, error) {
  306. if spot {
  307. if isWindows && windowsSpotPrice != "" {
  308. return windowsSpotPrice, nil
  309. }
  310. if spotPrice != "" {
  311. if isWindows {
  312. log.Warnf("no Windows spot price for %q in %q region; falling back to Linux spot price", skuName, region)
  313. }
  314. return spotPrice, nil
  315. }
  316. }
  317. selectedRetail := linuxRetailPrice
  318. if isWindows && windowsRetailPrice != "" {
  319. selectedRetail = windowsRetailPrice
  320. } else if isWindows && linuxRetailPrice != "" {
  321. log.Warnf("no Windows retail price for %q in %q region; falling back to Linux retail price", skuName, region)
  322. }
  323. if selectedRetail == "" {
  324. return "", fmt.Errorf("couldn't find price for product %q in %q region", skuName, region)
  325. }
  326. return selectedRetail, nil
  327. }
  328. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  329. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  330. regionCode := regionCodeMappings[rp[0]]
  331. lastPart := rp[len(rp)-1]
  332. var regionIds []string
  333. if regionID, ok := regionIdByDisplayName[meterRegion]; ok {
  334. regionIds = []string{
  335. regionID,
  336. }
  337. } else if _, err := strconv.Atoi(lastPart); err == nil {
  338. regionIds = []string{
  339. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  340. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  341. }
  342. } else {
  343. regionIds = []string{
  344. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  345. fmt.Sprintf("%s%s", rp[1:], regionCode),
  346. }
  347. }
  348. for _, regionID := range regionIds {
  349. if checkRegionID(regionID, regions) {
  350. return regionID, nil
  351. }
  352. }
  353. return "", fmt.Errorf("Couldn't find region %q", meterRegion)
  354. }
  355. // azure has very inconsistent naming standards between display names from the rate card api and display names from the regions api
  356. // this map is to connect display names from the ratecard api to the appropriate id.
  357. var regionIdByDisplayName = map[string]string{
  358. "US Gov AZ": "usgovarizona",
  359. "US Gov TX": "usgovtexas",
  360. "US Gov": "usgovvirginia",
  361. }
  362. func checkRegionID(regionID string, regions map[string]string) bool {
  363. for region := range regions {
  364. if regionID == region {
  365. return true
  366. }
  367. }
  368. return false
  369. }
  370. // AzureRetailPricing struct for unmarshalling Azure Retail pricing api JSON response
  371. type AzureRetailPricing struct {
  372. BillingCurrency string `json:"BillingCurrency"`
  373. CustomerEntityId string `json:"CustomerEntityId"`
  374. CustomerEntityType string `json:"CustomerEntityType"`
  375. Items []AzureRetailPricingAttributes `json:"Items"`
  376. NextPageLink string `json:"NextPageLink"`
  377. Count int `json:"Count"`
  378. }
  379. // AzureRetailPricingAttributes struct for unmarshalling Azure Retail pricing api JSON response
  380. type AzureRetailPricingAttributes struct {
  381. CurrencyCode string `json:"currencyCode"`
  382. TierMinimumUnits float32 `json:"tierMinimumUnits"`
  383. RetailPrice float32 `json:"retailPrice"`
  384. UnitPrice float32 `json:"unitPrice"`
  385. ArmRegionName string `json:"armRegionName"`
  386. Location string `json:"location"`
  387. EffectiveStartDate *time.Time `json:"effectiveStartDate"`
  388. EffectiveEndDate *time.Time `json:"effectiveEndDate"`
  389. MeterId string `json:"meterId"`
  390. MeterName string `json:"meterName"`
  391. ProductId string `json:"productId"`
  392. SkuId string `json:"skuId"`
  393. ProductName string `json:"productName"`
  394. SkuName string `json:"skuName"`
  395. ServiceName string `json:"serviceName"`
  396. ServiceId string `json:"serviceId"`
  397. ServiceFamily string `json:"serviceFamily"`
  398. UnitOfMeasure string `json:"unitOfMeasure"`
  399. Type string `json:"type"`
  400. IsPrimaryMeterRegion bool `json:"isPrimaryMeterRegion"`
  401. ArmSkuName string `json:"armSkuName"`
  402. }
  403. // AzurePricing either contains a Node or PV
  404. type AzurePricing struct {
  405. Node *models.Node
  406. PV *models.PV
  407. }
  408. type Azure struct {
  409. Pricing map[string]*AzurePricing
  410. managedDiskTierHourly map[string]float64
  411. DownloadPricingDataLock sync.RWMutex
  412. Clientset clustercache.ClusterCache
  413. Config models.ProviderConfig
  414. ServiceAccountChecks *models.ServiceAccountChecks
  415. ClusterAccountID string
  416. ClusterRegion string
  417. pricingSource string
  418. rateCardPricingError error
  419. priceSheetPricingError error
  420. loadedAzureSecret bool
  421. azureSecret *AzureServiceKey
  422. loadedAzureStorageConfigSecret bool
  423. azureStorageConfig *AzureStorageConfig
  424. }
  425. // PricingSourceSummary returns the pricing source summary for the provider.
  426. // The summary represents what was _parsed_ from the pricing source, not
  427. // everything that was _available_ in the pricing source.
  428. func (az *Azure) PricingSourceSummary() interface{} {
  429. return az.Pricing
  430. }
  431. // azureWindowsOS is the node OS label value that identifies a Windows node and
  432. // the suffix used to qualify Windows-specific pricing keys.
  433. const azureWindowsOS = "windows"
  434. // isWindowsNode reports whether the node labels identify a Windows node. It
  435. // centralizes the OS detection shared by azureKey.Features and NodePricing.
  436. func isWindowsNode(labels map[string]string) bool {
  437. osLabel, ok := util.GetOperatingSystem(labels)
  438. return ok && strings.ToLower(osLabel) == azureWindowsOS
  439. }
  440. type azureKey struct {
  441. Labels map[string]string
  442. GPULabel string
  443. GPULabelValue string
  444. }
  445. func (k *azureKey) Features() string {
  446. r, _ := util.GetRegion(k.Labels)
  447. region := strings.ToLower(r)
  448. instance, _ := util.GetInstanceType(k.Labels)
  449. usageType := "ondemand"
  450. if isWindowsNode(k.Labels) {
  451. return fmt.Sprintf("%s,%s,%s,%s", region, instance, usageType, azureWindowsOS)
  452. }
  453. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  454. }
  455. func (k *azureKey) GPUCount() int {
  456. return 0
  457. }
  458. // GPUType returns value of GPULabel if present
  459. func (k *azureKey) GPUType() string {
  460. if t, ok := k.Labels[k.GPULabel]; ok {
  461. return t
  462. }
  463. return ""
  464. }
  465. func (k *azureKey) isValidGPUNode() bool {
  466. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  467. }
  468. func (k *azureKey) ID() string {
  469. return ""
  470. }
  471. func (k *azureKey) GetGPUCount() string {
  472. instance, _ := util.GetInstanceType(k.Labels)
  473. // Double digits that could get matches lower in logic
  474. if strings.Contains(instance, "NC64") {
  475. return "4"
  476. }
  477. if strings.Contains(instance, "ND96") ||
  478. strings.Contains(instance, "ND40") {
  479. return "8"
  480. }
  481. // Ordered asc because of some series have different gpu counts on different versions
  482. if strings.Contains(instance, "NC6") ||
  483. strings.Contains(instance, "NC4") ||
  484. strings.Contains(instance, "NC8") ||
  485. strings.Contains(instance, "NC16") ||
  486. strings.Contains(instance, "ND6") ||
  487. strings.Contains(instance, "NV12s") ||
  488. strings.Contains(instance, "NV6") {
  489. return "1"
  490. }
  491. if strings.Contains(instance, "NC12") ||
  492. strings.Contains(instance, "ND12") ||
  493. strings.Contains(instance, "NV24s") ||
  494. strings.Contains(instance, "NV12") {
  495. return "2"
  496. }
  497. if strings.Contains(instance, "NC24") ||
  498. strings.Contains(instance, "ND24") ||
  499. strings.Contains(instance, "NV48s") ||
  500. strings.Contains(instance, "NV24") {
  501. return "4"
  502. }
  503. return "0"
  504. }
  505. // AzureStorageConfig Represents an azure storage config
  506. // Deprecated: v1.104 Use StorageConfiguration instead
  507. type AzureStorageConfig struct {
  508. SubscriptionId string `json:"azureSubscriptionID"`
  509. AccountName string `json:"azureStorageAccount"`
  510. AccessKey string `json:"azureStorageAccessKey"`
  511. ContainerName string `json:"azureStorageContainer"`
  512. ContainerPath string `json:"azureContainerPath"`
  513. AzureCloud string `json:"azureCloud"`
  514. }
  515. // IsEmpty returns true if all fields in config are empty, false if not.
  516. func (asc *AzureStorageConfig) IsEmpty() bool {
  517. return asc.SubscriptionId == "" &&
  518. asc.AccountName == "" &&
  519. asc.AccessKey == "" &&
  520. asc.ContainerName == "" &&
  521. asc.ContainerPath == "" &&
  522. asc.AzureCloud == ""
  523. }
  524. // Represents an azure app key
  525. type AzureAppKey struct {
  526. AppID string `json:"appId"`
  527. DisplayName string `json:"displayName"`
  528. Name string `json:"name"`
  529. Password string `json:"password"`
  530. Tenant string `json:"tenant"`
  531. }
  532. // AzureServiceKey service key for a specific subscription
  533. // Deprecated: v1.104 Use ServiceKey instead
  534. type AzureServiceKey struct {
  535. SubscriptionID string `json:"subscriptionId"`
  536. ServiceKey *AzureAppKey `json:"serviceKey"`
  537. }
  538. // Validity check on service key
  539. func (ask *AzureServiceKey) IsValid() bool {
  540. return ask.SubscriptionID != "" &&
  541. ask.ServiceKey != nil &&
  542. ask.ServiceKey.AppID != "" &&
  543. ask.ServiceKey.Password != "" &&
  544. ask.ServiceKey.Tenant != ""
  545. }
  546. // Loads the azure authentication via configuration or a secret set at install time.
  547. func (az *Azure) getAzureRateCardAuth(forceReload bool, cp *models.CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  548. // 1. Check for secret (secret values will always be used if they are present)
  549. s, _ := az.loadAzureAuthSecret(forceReload)
  550. if s != nil && s.IsValid() {
  551. subscriptionID = s.SubscriptionID
  552. clientID = s.ServiceKey.AppID
  553. clientSecret = s.ServiceKey.Password
  554. tenantID = s.ServiceKey.Tenant
  555. return
  556. }
  557. // 2. Check config values (set though endpoint)
  558. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  559. subscriptionID = cp.AzureSubscriptionID
  560. clientID = cp.AzureClientID
  561. clientSecret = cp.AzureClientSecret
  562. tenantID = cp.AzureTenantID
  563. return
  564. }
  565. // 3. Check if AzureSubscriptionID is set in config (set though endpoint)
  566. // MSI credentials will be attempted if the subscription ID is set, but clientID, clientSecret and tenantID are not
  567. if cp.AzureSubscriptionID != "" {
  568. subscriptionID = cp.AzureSubscriptionID
  569. return
  570. }
  571. // 4. Empty values
  572. return "", "", "", ""
  573. }
  574. // GetAzureStorageConfig retrieves storage config from secret and sets default values
  575. func (az *Azure) GetAzureStorageConfig(forceReload bool, cp *models.CustomPricing) (*AzureStorageConfig, error) {
  576. // default subscription id
  577. defaultSubscriptionID := cp.AzureSubscriptionID
  578. // 1. Check Config for storage set up
  579. asc := &AzureStorageConfig{
  580. SubscriptionId: cp.AzureStorageSubscriptionID,
  581. AccountName: cp.AzureStorageAccount,
  582. AccessKey: cp.AzureStorageAccessKey,
  583. ContainerName: cp.AzureStorageContainer,
  584. ContainerPath: cp.AzureContainerPath,
  585. AzureCloud: cp.AzureCloud,
  586. }
  587. // check for required fields
  588. if asc != nil && asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  589. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  590. Message: "Azure Storage Config exists",
  591. Status: true,
  592. })
  593. return asc, nil
  594. }
  595. // 2. Check for secret
  596. asc, err := az.loadAzureStorageConfig(forceReload)
  597. if err != nil {
  598. log.Errorf("Error, %s", err.Error())
  599. } else if asc != nil {
  600. // To support already configured users, subscriptionID may not be set in secret in which case, the subscriptionID
  601. // for the rate card API is used
  602. if asc.SubscriptionId == "" {
  603. asc.SubscriptionId = defaultSubscriptionID
  604. }
  605. // check for required fields
  606. if asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  607. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  608. Message: "Azure Storage Config exists",
  609. Status: true,
  610. })
  611. return asc, nil
  612. }
  613. }
  614. az.ServiceAccountChecks.Set("hasStorage", &models.ServiceAccountCheck{
  615. Message: "Azure Storage Config exists",
  616. Status: false,
  617. })
  618. return nil, fmt.Errorf("azure storage config not found")
  619. }
  620. // Load once and cache the result (even on failure). This is an install time secret, so
  621. // we don't expect the secret to change. If it does, however, we can force reload using
  622. // the input parameter.
  623. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  624. if !force && az.loadedAzureSecret {
  625. return az.azureSecret, nil
  626. }
  627. az.loadedAzureSecret = true
  628. exists, err := fileutil.FileExists(models.AuthSecretPath)
  629. if !exists || err != nil {
  630. return nil, fmt.Errorf("Failed to locate service account file: %s", models.AuthSecretPath)
  631. }
  632. result, err := os.ReadFile(models.AuthSecretPath)
  633. if err != nil {
  634. return nil, err
  635. }
  636. var ask AzureServiceKey
  637. err = json.Unmarshal(result, &ask)
  638. if err != nil {
  639. return nil, err
  640. }
  641. az.azureSecret = &ask
  642. return &ask, nil
  643. }
  644. // Load once and cache the result (even on failure). This is an install time secret, so
  645. // we don't expect the secret to change. If it does, however, we can force reload using
  646. // the input parameter.
  647. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  648. if !force && az.loadedAzureStorageConfigSecret {
  649. return az.azureStorageConfig, nil
  650. }
  651. az.loadedAzureStorageConfigSecret = true
  652. exists, err := fileutil.FileExists(models.StorageConfigSecretPath)
  653. if !exists || err != nil {
  654. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", models.StorageConfigSecretPath)
  655. }
  656. result, err := os.ReadFile(models.StorageConfigSecretPath)
  657. if err != nil {
  658. return nil, err
  659. }
  660. var asc AzureStorageConfig
  661. err = json.Unmarshal(result, &asc)
  662. if err != nil {
  663. return nil, err
  664. }
  665. az.azureStorageConfig = &asc
  666. return &asc, nil
  667. }
  668. func (az *Azure) GetKey(labels map[string]string, n *clustercache.Node) models.Key {
  669. cfg, err := az.GetConfig()
  670. if err != nil {
  671. log.Infof("Error loading azure custom pricing information")
  672. }
  673. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  674. gpuLabel := "accelerator"
  675. gpuLabelValue := "nvidia"
  676. if cfg.GpuLabel != "" {
  677. gpuLabel = cfg.GpuLabel
  678. }
  679. if cfg.GpuLabelValue != "" {
  680. gpuLabelValue = cfg.GpuLabelValue
  681. }
  682. return &azureKey{
  683. Labels: labels,
  684. GPULabel: gpuLabel,
  685. GPULabelValue: gpuLabelValue,
  686. }
  687. }
  688. // CreateString builds strings effectively
  689. func createString(keys ...string) string {
  690. var b strings.Builder
  691. for _, key := range keys {
  692. b.WriteString(key)
  693. }
  694. return b.String()
  695. }
  696. // getConfigSource returns a human-readable string indicating the source of configuration
  697. func getConfigSource(envVarName, envValue, defaultSource string) string {
  698. if envValue != "" {
  699. return "env:" + envVarName
  700. }
  701. return defaultSource
  702. }
  703. func transformMachineType(subCategory string, mt []string) []string {
  704. switch {
  705. case strings.Contains(subCategory, "Basic"):
  706. return []string{createString("Basic_", mt[0])}
  707. case len(mt) == 2:
  708. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  709. default:
  710. return []string{createString("Standard_", mt[0])}
  711. }
  712. }
  713. func addSuffix(mt string, suffixes ...string) []string {
  714. result := make([]string, len(suffixes))
  715. var suffix string
  716. parts := strings.Split(mt, "_")
  717. if len(parts) > 2 {
  718. for _, p := range parts[2:] {
  719. suffix = createString(suffix, "_", p)
  720. }
  721. }
  722. for i, s := range suffixes {
  723. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  724. }
  725. return result
  726. }
  727. func getMachineTypeVariants(mt string) []string {
  728. switch {
  729. case mtStandardB.MatchString(mt):
  730. return []string{createString(mt, "s")}
  731. case mtStandardD.MatchString(mt):
  732. var result []string
  733. result = append(result, addSuffix(mt, "s")[0])
  734. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  735. result = append(result, dsType)
  736. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  737. return result
  738. case mtStandardE.MatchString(mt):
  739. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  740. case mtStandardF.MatchString(mt):
  741. return addSuffix(mt, "s")
  742. case mtStandardG.MatchString(mt):
  743. var result []string
  744. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  745. result = append(result, gsType)
  746. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  747. case mtStandardL.MatchString(mt):
  748. return addSuffix(mt, "s")
  749. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  750. base := strings.TrimSuffix(mt, "ms")
  751. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  752. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  753. return []string{}
  754. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  755. base := strings.TrimSuffix(mt, "s")
  756. return addSuffix(base, "", "m")
  757. case mtStandardN.MatchString(mt):
  758. return addSuffix(mt, "s")
  759. }
  760. return []string{}
  761. }
  762. func (az *Azure) GetManagementPlatform() (string, error) {
  763. nodes := az.Clientset.GetAllNodes()
  764. if len(nodes) > 0 {
  765. n := nodes[0]
  766. providerID := n.SpecProviderID
  767. if strings.Contains(providerID, "aks") {
  768. return "aks", nil
  769. }
  770. }
  771. return "", nil
  772. }
  773. // DownloadPricingData uses provided azure "best guesses" for pricing
  774. func (az *Azure) DownloadPricingData() error {
  775. az.DownloadPricingDataLock.Lock()
  776. defer az.DownloadPricingDataLock.Unlock()
  777. config, err := az.GetConfig()
  778. if err != nil {
  779. az.rateCardPricingError = err
  780. return err
  781. }
  782. envBillingAccount := env.GetAzureBillingAccount()
  783. if envBillingAccount != "" {
  784. config.AzureBillingAccount = envBillingAccount
  785. }
  786. envOfferID := env.GetAzureOfferID()
  787. if envOfferID != "" {
  788. config.AzureOfferDurableID = envOfferID
  789. }
  790. // Check for Azure rate card filter environment variables with backward compatibility
  791. locale := env.GetAzureLocale() // Defaults to "en-US"
  792. envCurrency := env.GetAzureCurrency()
  793. currency := config.CurrencyCode // Use config default
  794. if envCurrency != "" {
  795. currency = envCurrency // Override with environment variable if provided
  796. }
  797. envRegionInfo := env.GetAzureRegionInfo()
  798. regionInfo := config.AzureBillingRegion // Use config default
  799. if envRegionInfo != "" {
  800. regionInfo = envRegionInfo // Override with environment variable if provided
  801. }
  802. // Debug logging for rate card configuration
  803. log.Debugf("Azure rate card configuration: locale=%s (source: %s), currency=%s (source: %s), regionInfo=%s (source: %s)",
  804. locale, getConfigSource("AZURE_LOCALE", locale, "en-US"),
  805. currency, getConfigSource("AZURE_CURRENCY", envCurrency, "config"),
  806. regionInfo, getConfigSource("AZURE_REGION_INFO", envRegionInfo, "config"))
  807. // Load the service provider keys
  808. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  809. config.AzureSubscriptionID = subscriptionID
  810. config.AzureClientID = clientID
  811. config.AzureClientSecret = clientSecret
  812. config.AzureTenantID = tenantID
  813. var authorizer autorest.Authorizer
  814. azureEnv := determineCloudByRegion(az.ClusterRegion)
  815. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  816. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  817. a, err := credentialsConfig.Authorizer()
  818. if err != nil {
  819. az.rateCardPricingError = err
  820. return err
  821. }
  822. authorizer = a
  823. }
  824. if authorizer == nil {
  825. a, err := auth.NewAuthorizerFromEnvironment()
  826. authorizer = a
  827. if err != nil {
  828. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  829. if err != nil {
  830. az.rateCardPricingError = err
  831. return err
  832. }
  833. authorizer = a
  834. }
  835. }
  836. sClient := subscriptions.NewClientWithBaseURI(azureEnv.ResourceManagerEndpoint)
  837. sClient.Authorizer = authorizer
  838. rcClient := commerce.NewRateCardClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  839. rcClient.Authorizer = authorizer
  840. providersClient := resources.NewProvidersClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  841. providersClient.Authorizer = authorizer
  842. rateCardFilter := fmt.Sprintf("OfferDurableId eq '%s' and Currency eq '%s' and Locale eq '%s' and RegionInfo eq '%s'", config.AzureOfferDurableID, currency, locale, regionInfo)
  843. // create a preparer (the same way rcClient.Get() does) so that we can log the azureRateCard URL
  844. log.Infof("Using azureRateCard query %s", rateCardFilter)
  845. rcPreparer, err := rcClient.GetPreparer(context.TODO(), rateCardFilter)
  846. if err != nil {
  847. // this isn't an error that necessitates a return, as we only need the preparer for an informational log
  848. log.Infof("Failed to get azureRateCard URL: %s", err)
  849. } else {
  850. log.Infof("Using azureRateCard URL %s", rcPreparer.URL.String())
  851. }
  852. // rate-card client is old, it can hang indefinitely in some cases
  853. // this happens on the main thread, so it may block the whole app
  854. // there is can be a better way to set timeout for the client
  855. ctx, cancel := context.WithTimeout(context.TODO(), 300*time.Second)
  856. defer cancel()
  857. result, err := rcClient.Get(ctx, rateCardFilter)
  858. if err != nil {
  859. log.Warnf("Error in pricing download query from API")
  860. az.rateCardPricingError = err
  861. return err
  862. }
  863. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  864. if err != nil {
  865. log.Warnf("Error in pricing download regions from API")
  866. az.rateCardPricingError = err
  867. return err
  868. }
  869. baseCPUPrice := config.CPU
  870. allPrices := make(map[string]*AzurePricing)
  871. for _, v := range *result.Meters {
  872. pricings, err := convertMeterToPricings(v, regions, baseCPUPrice)
  873. if err != nil {
  874. log.Warnf("converting meter to pricings: %s", err.Error())
  875. continue
  876. }
  877. for key, pricing := range pricings {
  878. allPrices[key] = pricing
  879. }
  880. }
  881. addAzureFilePricing(allPrices, regions)
  882. ensureDiskClassFallbacks(allPrices)
  883. tierHourly := collectManagedDiskTierHourly(allPrices)
  884. removeManagedDiskTierEntries(allPrices)
  885. az.Pricing = allPrices
  886. az.managedDiskTierHourly = tierHourly
  887. az.pricingSource = rateCardPricingSource
  888. az.rateCardPricingError = nil
  889. // If we've got a billing account set, kick off downloading the custom pricing data.
  890. if config.AzureBillingAccount != "" {
  891. downloader := PriceSheetDownloader{
  892. TenantID: config.AzureTenantID,
  893. ClientID: config.AzureClientID,
  894. ClientSecret: config.AzureClientSecret,
  895. BillingAccount: config.AzureBillingAccount,
  896. OfferID: config.AzureOfferDurableID,
  897. ConvertMeterInfo: func(meterInfo commerce.MeterInfo) (map[string]*AzurePricing, error) {
  898. return convertMeterToPricings(meterInfo, regions, baseCPUPrice)
  899. },
  900. }
  901. // The price sheet can take 5 minutes to generate, so we don't
  902. // want to hang onto the lock while we're waiting for it.
  903. go func() {
  904. ctx := context.Background()
  905. allPrices, err := downloader.GetPricing(ctx)
  906. az.DownloadPricingDataLock.Lock()
  907. defer az.DownloadPricingDataLock.Unlock()
  908. if err != nil {
  909. log.Errorf("Error downloading Azure price sheet: %s", err)
  910. az.priceSheetPricingError = err
  911. return
  912. }
  913. addAzureFilePricing(allPrices, regions)
  914. ensureDiskClassFallbacks(allPrices)
  915. tierHourly := collectManagedDiskTierHourly(allPrices)
  916. removeManagedDiskTierEntries(allPrices)
  917. az.Pricing = allPrices
  918. az.managedDiskTierHourly = tierHourly
  919. az.pricingSource = priceSheetPricingSource
  920. az.priceSheetPricingError = nil
  921. }()
  922. }
  923. return nil
  924. }
  925. func convertMeterToPricings(info commerce.MeterInfo, regions map[string]string, baseCPUPrice string) (map[string]*AzurePricing, error) {
  926. meterName := *info.MeterName
  927. meterRegion := *info.MeterRegion
  928. meterCategory := *info.MeterCategory
  929. meterSubCategory := *info.MeterSubCategory
  930. region, err := toRegionID(meterRegion, regions)
  931. if err != nil {
  932. // Skip this meter if we don't recognize the region.
  933. return nil, nil
  934. }
  935. isWindowsMeter := strings.Contains(meterSubCategory, "Windows")
  936. if strings.Contains(meterSubCategory, "Cloud Services") || strings.Contains(meterSubCategory, "CloudServices") {
  937. // This meter doesn't correspond to any pricings.
  938. return nil, nil
  939. }
  940. if strings.Contains(meterCategory, "Storage") {
  941. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  942. if len(info.MeterRates) < 1 {
  943. return nil, fmt.Errorf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *info.MeterSubCategory, "region": region})
  944. }
  945. var priceInUsd float64
  946. for _, rate := range info.MeterRates {
  947. priceInUsd += *rate
  948. }
  949. // Shared-disk mount fees are not modeled; skip so they cannot overwrite capacity prices.
  950. if strings.Contains(meterName, "Disk Mount") {
  951. log.Debugf("Azure shared disk mount pricing is not supported; skipping meter %q in region %s", meterName, region)
  952. return nil, nil
  953. }
  954. results := make(map[string]*AzurePricing)
  955. if storageClass, redundancy, tier, ok := parseManagedDiskMeter(meterName); ok {
  956. tierKey := diskTierKey(region, storageClass, redundancy, tier)
  957. // Store whole-disk hourly cost so AllNodePricing stays in hourly units.
  958. // PVPricing converts to effective $/GiB-hour using the PV's reported size.
  959. hourly := tierHourlyFromMonthly(priceInUsd)
  960. priceStr := formatPrice(hourly)
  961. log.Debugf("Adding PV tier key: %s, HourlyCost: %s (monthly %g)", tierKey, priceStr, priceInUsd)
  962. results[tierKey] = &AzurePricing{
  963. PV: &models.PV{
  964. Cost: priceStr,
  965. Class: storageClass,
  966. Region: region,
  967. Size: tier,
  968. },
  969. }
  970. // Maintain a class-level linearized $/GiB-hour fallback from the
  971. // smallest catalog LRS tier so size-unknown PVs still resolve.
  972. if redundancy == azureDiskRedundancyLRS {
  973. if smallest, ok := smallestDiskTier(storageClass); ok && smallest.Name == tier {
  974. rate := effectiveGiBHourRateFromHourly(hourly, float64(smallest.SizeGiB))
  975. classKey := diskClassKey(region, storageClass)
  976. rateStr := formatPrice(rate)
  977. log.Debugf("Adding PV class fallback key: %s, Cost: %s", classKey, rateStr)
  978. results[classKey] = &AzurePricing{
  979. PV: &models.PV{
  980. Cost: rateStr,
  981. Class: storageClass,
  982. Region: region,
  983. },
  984. }
  985. }
  986. }
  987. return results, nil
  988. }
  989. if strings.Contains(meterName, "LRS Provisioned") {
  990. // rate is in disk per month; Premium Files uses provisioned capacity.
  991. // Keep historical linearization against 32 GiB for Azure Files Premium.
  992. pricePerHour := priceInUsd / timeutil.HoursPerMonth / 32.0
  993. priceStr := formatPrice(pricePerHour)
  994. key := diskClassKey(region, AzureFilePremiumStorageClass)
  995. log.Debugf("Adding PV.Key: %s, Cost: %s", key, priceStr)
  996. return map[string]*AzurePricing{
  997. key: {
  998. PV: &models.PV{
  999. Cost: priceStr,
  1000. Region: region,
  1001. },
  1002. },
  1003. }, nil
  1004. }
  1005. }
  1006. }
  1007. if !strings.Contains(meterCategory, "Virtual Machines") {
  1008. return nil, nil
  1009. }
  1010. usageType := ""
  1011. if !strings.Contains(meterName, "Low Priority") {
  1012. usageType = "ondemand"
  1013. } else {
  1014. usageType = "preemptible"
  1015. }
  1016. var instanceTypes []string
  1017. name := strings.TrimSuffix(meterName, " Low Priority")
  1018. instanceType := strings.Split(name, "/")
  1019. for _, it := range instanceType {
  1020. if strings.Contains(meterSubCategory, "Promo") {
  1021. it = it + " Promo"
  1022. }
  1023. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  1024. }
  1025. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  1026. if strings.Contains(name, "Expired") {
  1027. instanceTypes = []string{}
  1028. }
  1029. var priceInUsd float64
  1030. if len(info.MeterRates) < 1 {
  1031. return nil, fmt.Errorf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *info.MeterSubCategory, "region": region})
  1032. }
  1033. for _, rate := range info.MeterRates {
  1034. priceInUsd += *rate
  1035. }
  1036. priceStr := fmt.Sprintf("%f", priceInUsd)
  1037. results := make(map[string]*AzurePricing)
  1038. for _, instanceType := range instanceTypes {
  1039. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  1040. if isWindowsMeter {
  1041. key = fmt.Sprintf("%s,%s,%s,%s", region, instanceType, usageType, azureWindowsOS)
  1042. }
  1043. pricing := &AzurePricing{
  1044. Node: &models.Node{
  1045. Cost: priceStr,
  1046. BaseCPUPrice: baseCPUPrice,
  1047. UsageType: usageType,
  1048. },
  1049. }
  1050. results[key] = pricing
  1051. }
  1052. return results, nil
  1053. }
  1054. func addAzureFilePricing(prices map[string]*AzurePricing, regions map[string]string) {
  1055. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  1056. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  1057. // check https://github.com/opencost/opencost/issues/159 for more information (same problem on AWS)
  1058. zeroPrice := "0.0"
  1059. for region := range regions {
  1060. key := region + "," + AzureFileStandardStorageClass
  1061. log.Debugf("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  1062. prices[key] = &AzurePricing{
  1063. PV: &models.PV{
  1064. Cost: zeroPrice,
  1065. Region: region,
  1066. },
  1067. }
  1068. }
  1069. }
  1070. // ensureDiskClassFallbacks fills missing region,storageClass linearized $/GiB-hour
  1071. // keys from the smallest available LRS tier meter for that class. Needed when the
  1072. // Rate Card omits the absolute smallest catalog tier (e.g. P1) but includes P4.
  1073. // Tier keys store whole-disk hourly cost; class keys store $/GiB-hour.
  1074. func ensureDiskClassFallbacks(prices map[string]*AzurePricing) {
  1075. type candidate struct {
  1076. sizeGiB int
  1077. hourly float64
  1078. region string
  1079. class string
  1080. }
  1081. best := map[string]candidate{} // key: region,class
  1082. for key, pricing := range prices {
  1083. if pricing == nil || pricing.PV == nil {
  1084. continue
  1085. }
  1086. parts := strings.Split(key, ",")
  1087. if len(parts) != 4 {
  1088. continue
  1089. }
  1090. region, class, redundancy, tierName := parts[0], parts[1], parts[2], parts[3]
  1091. if redundancy != azureDiskRedundancyLRS {
  1092. continue
  1093. }
  1094. tiers := tiersForStorageClass(class)
  1095. var sizeGiB int
  1096. found := false
  1097. for _, tier := range tiers {
  1098. if tier.Name == tierName {
  1099. sizeGiB = tier.SizeGiB
  1100. found = true
  1101. break
  1102. }
  1103. }
  1104. if !found {
  1105. continue
  1106. }
  1107. hourly, err := parsePrice(pricing.PV.Cost)
  1108. if err != nil {
  1109. continue
  1110. }
  1111. ck := diskClassKey(region, class)
  1112. if existing, ok := best[ck]; ok && existing.sizeGiB <= sizeGiB {
  1113. continue
  1114. }
  1115. best[ck] = candidate{sizeGiB: sizeGiB, hourly: hourly, region: region, class: class}
  1116. }
  1117. for ck, c := range best {
  1118. if existing, ok := prices[ck]; ok && existing != nil && existing.PV != nil && existing.PV.Cost != "" {
  1119. continue
  1120. }
  1121. rate := effectiveGiBHourRateFromHourly(c.hourly, float64(c.sizeGiB))
  1122. rateStr := formatPrice(rate)
  1123. log.Debugf("Adding PV class fallback key from available tiers: %s, Cost: %s", ck, rateStr)
  1124. prices[ck] = &AzurePricing{
  1125. PV: &models.PV{
  1126. Cost: rateStr,
  1127. Class: c.class,
  1128. Region: c.region,
  1129. },
  1130. }
  1131. }
  1132. }
  1133. // collectManagedDiskTierHourly collects the hourly cost of managed disk tiers from the provided pricing data.
  1134. func collectManagedDiskTierHourly(prices map[string]*AzurePricing) map[string]float64 {
  1135. tierHourly := map[string]float64{}
  1136. for key, pricing := range prices {
  1137. if !isManagedDiskTierKey(key) || pricing == nil || pricing.PV == nil || pricing.PV.Cost == "" {
  1138. continue
  1139. }
  1140. hourly, err := parsePrice(pricing.PV.Cost)
  1141. if err != nil {
  1142. continue
  1143. }
  1144. tierHourly[key] = hourly
  1145. }
  1146. return tierHourly
  1147. }
  1148. // removeManagedDiskTierEntries removes managed disk tier entries from the provided pricing data.
  1149. func removeManagedDiskTierEntries(prices map[string]*AzurePricing) {
  1150. for key := range prices {
  1151. if isManagedDiskTierKey(key) {
  1152. delete(prices, key)
  1153. }
  1154. }
  1155. }
  1156. // determineCloudByRegion uses region name to pick the correct Cloud Environment for the azure provider to use
  1157. func determineCloudByRegion(region string) azure.Environment {
  1158. lcRegion := strings.ToLower(region)
  1159. if strings.Contains(lcRegion, "china") {
  1160. return azure.ChinaCloud
  1161. }
  1162. if strings.Contains(lcRegion, "gov") || strings.Contains(lcRegion, "dod") {
  1163. return azure.USGovernmentCloud
  1164. }
  1165. // Default to public cloud
  1166. return azure.PublicCloud
  1167. }
  1168. // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
  1169. func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string, env azure.Environment) auth.ClientCredentialsConfig {
  1170. return auth.ClientCredentialsConfig{
  1171. ClientID: clientID,
  1172. ClientSecret: clientSecret,
  1173. TenantID: tenantID,
  1174. Resource: env.ResourceManagerEndpoint,
  1175. AADEndpoint: env.ActiveDirectoryEndpoint,
  1176. }
  1177. }
  1178. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  1179. if az.Pricing == nil {
  1180. az.Pricing = map[string]*AzurePricing{}
  1181. }
  1182. az.Pricing[features] = azurePricing
  1183. }
  1184. // AllNodePricing returns the Azure pricing objects stored
  1185. func (az *Azure) AllNodePricing() (interface{}, error) {
  1186. az.DownloadPricingDataLock.RLock()
  1187. defer az.DownloadPricingDataLock.RUnlock()
  1188. return az.Pricing, nil
  1189. }
  1190. // NodePricing returns Azure pricing data for a single node
  1191. func (az *Azure) NodePricing(key models.Key) (*models.Node, models.PricingMetadata, error) {
  1192. az.DownloadPricingDataLock.RLock()
  1193. defer az.DownloadPricingDataLock.RUnlock()
  1194. meta := models.PricingMetadata{}
  1195. azKey, ok := key.(*azureKey)
  1196. if !ok {
  1197. return nil, meta, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  1198. }
  1199. config, _ := az.GetConfig()
  1200. slv, ok := azKey.Labels[config.SpotLabel]
  1201. isSpot := ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != ""
  1202. isWindows := isWindowsNode(azKey.Labels)
  1203. features := strings.Split(azKey.Features(), ",")
  1204. region := features[0]
  1205. instance := features[1]
  1206. var featureString string
  1207. if isSpot {
  1208. if isWindows {
  1209. featureString = fmt.Sprintf("%s,%s,spot,%s", region, instance, azureWindowsOS)
  1210. } else {
  1211. featureString = fmt.Sprintf("%s,%s,spot", region, instance)
  1212. }
  1213. } else {
  1214. featureString = azKey.Features()
  1215. }
  1216. if az.Pricing != nil {
  1217. if n, ok := az.Pricing[featureString]; ok {
  1218. log.Debugf("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  1219. if azKey.isValidGPUNode() {
  1220. n.Node.GPU = azKey.GetGPUCount()
  1221. }
  1222. return n.Node, meta, nil
  1223. } else {
  1224. log.Debugf("Could not find pricing for node %s from key %s", azKey, azKey.Features())
  1225. }
  1226. }
  1227. cost, err := getRetailPrice(region, instance, config.CurrencyCode, isSpot, isWindows)
  1228. if err != nil {
  1229. log.DedupedWarningf(5, "failed to retrieve retail pricing: %s", err)
  1230. } else {
  1231. gpu := ""
  1232. if azKey.isValidGPUNode() {
  1233. gpu = azKey.GetGPUCount()
  1234. }
  1235. var node *models.Node
  1236. if isSpot {
  1237. node = &models.Node{
  1238. Cost: cost,
  1239. UsageType: "spot",
  1240. GPU: gpu,
  1241. }
  1242. } else {
  1243. node = &models.Node{
  1244. Cost: cost,
  1245. GPU: gpu,
  1246. }
  1247. }
  1248. az.addPricing(featureString, &AzurePricing{
  1249. Node: node,
  1250. })
  1251. return node, meta, nil
  1252. }
  1253. log.DedupedWarningf(5, "No pricing data found for node %s from key %s", azKey, azKey.Features())
  1254. c, err := az.GetConfig()
  1255. if err != nil {
  1256. return nil, meta, fmt.Errorf("No default pricing data available")
  1257. }
  1258. var vcpuCost string
  1259. var ramCost string
  1260. var gpuCost string
  1261. if isSpot {
  1262. vcpuCost = c.SpotCPU
  1263. ramCost = c.SpotRAM
  1264. gpuCost = c.SpotGPU
  1265. } else {
  1266. vcpuCost = c.CPU
  1267. ramCost = c.RAM
  1268. gpuCost = c.GPU
  1269. }
  1270. // GPU Node
  1271. if azKey.isValidGPUNode() {
  1272. return &models.Node{
  1273. VCPUCost: vcpuCost,
  1274. RAMCost: ramCost,
  1275. UsesBaseCPUPrice: true,
  1276. GPUCost: gpuCost,
  1277. GPU: azKey.GetGPUCount(),
  1278. }, meta, nil
  1279. }
  1280. // Serverless Node. This is an Azure Container Instance, and no pods can be
  1281. // scheduled to this node. Azure does not charge for this node. Set costs to
  1282. // zero.
  1283. if azKey.Labels["kubernetes.io/hostname"] == "virtual-node-aci-linux" {
  1284. return &models.Node{
  1285. VCPUCost: "0",
  1286. RAMCost: "0",
  1287. }, meta, nil
  1288. }
  1289. // Regular Node
  1290. return &models.Node{
  1291. VCPUCost: vcpuCost,
  1292. RAMCost: ramCost,
  1293. UsesBaseCPUPrice: true,
  1294. }, meta, nil
  1295. }
  1296. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  1297. func (az *Azure) NetworkPricing() (*models.Network, error) {
  1298. cpricing, err := az.Config.GetCustomPricingData()
  1299. if err != nil {
  1300. return nil, err
  1301. }
  1302. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1303. if err != nil {
  1304. return nil, err
  1305. }
  1306. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1311. if err != nil {
  1312. return nil, err
  1313. }
  1314. nge, err := strconv.ParseFloat(cpricing.NatGatewayEgress, 64)
  1315. if err != nil {
  1316. return nil, err
  1317. }
  1318. ngi, err := strconv.ParseFloat(cpricing.NatGatewayIngress, 64)
  1319. if err != nil {
  1320. return nil, err
  1321. }
  1322. return &models.Network{
  1323. ZoneNetworkEgressCost: znec,
  1324. RegionNetworkEgressCost: rnec,
  1325. InternetNetworkEgressCost: inec,
  1326. NatGatewayEgressCost: nge,
  1327. NatGatewayIngressCost: ngi,
  1328. }, nil
  1329. }
  1330. // LoadBalancerPricing on Azure, LoadBalancer services correspond to public IPs. For now the pricing of LoadBalancer
  1331. // services will be that of a standard static public IP https://azure.microsoft.com/en-us/pricing/details/ip-addresses/.
  1332. // Azure still has load balancers which follow the standard pricing scheme based on rules
  1333. // https://azure.microsoft.com/en-us/pricing/details/load-balancer/, they are created on a per-cluster basis.
  1334. func (azr *Azure) LoadBalancerPricing() (*models.LoadBalancer, error) {
  1335. return &models.LoadBalancer{
  1336. Cost: 0.005,
  1337. }, nil
  1338. }
  1339. type azurePvKey struct {
  1340. Labels map[string]string
  1341. StorageClass string
  1342. StorageClassParameters map[string]string
  1343. DefaultRegion string
  1344. ProviderId string
  1345. SizeGiB float64
  1346. DiskStorageClass string // premium_ssd / standard_ssd / standard_hdd when managed disk
  1347. DiskRedundancy string // LRS / ZRS when managed disk
  1348. IsAzureFiles bool
  1349. }
  1350. func (az *Azure) GetPVKey(pv *clustercache.PersistentVolume, parameters map[string]string, defaultRegion string) models.PVKey {
  1351. providerID := ""
  1352. if pv.Spec.AzureDisk != nil {
  1353. providerID = pv.Spec.AzureDisk.DiskName
  1354. }
  1355. key := &azurePvKey{
  1356. Labels: pv.Labels,
  1357. StorageClass: pv.Spec.StorageClassName,
  1358. StorageClassParameters: parameters,
  1359. DefaultRegion: defaultRegion,
  1360. ProviderId: providerID,
  1361. SizeGiB: pvSizeGiB(pv),
  1362. }
  1363. key.resolveSKU()
  1364. return key
  1365. }
  1366. func (key *azurePvKey) ID() string {
  1367. return key.ProviderId
  1368. }
  1369. func (key *azurePvKey) GetStorageClass() string {
  1370. return key.StorageClass
  1371. }
  1372. // resolveSKU populates DiskStorageClass / DiskRedundancy / IsAzureFiles from
  1373. // StorageClass parameters (CSI skuname, legacy storageaccounttype, or file skuName).
  1374. func (key *azurePvKey) resolveSKU() {
  1375. if key.StorageClassParameters == nil {
  1376. return
  1377. }
  1378. diskParam := key.StorageClassParameters["storageaccounttype"]
  1379. if diskParam == "" {
  1380. diskParam = key.StorageClassParameters["skuname"]
  1381. }
  1382. if diskParam != "" {
  1383. if sku, ok := resolveDiskSKU(diskParam); ok {
  1384. key.DiskStorageClass = sku.StorageClass
  1385. key.DiskRedundancy = sku.Redundancy
  1386. return
  1387. }
  1388. }
  1389. fileSKU := key.StorageClassParameters["skuName"]
  1390. if strings.EqualFold(fileSKU, "Premium_LRS") {
  1391. key.DiskStorageClass = AzureFilePremiumStorageClass
  1392. key.IsAzureFiles = true
  1393. } else if strings.EqualFold(fileSKU, "Standard_LRS") {
  1394. key.DiskStorageClass = AzureFileStandardStorageClass
  1395. key.IsAzureFiles = true
  1396. }
  1397. }
  1398. func (key *azurePvKey) region() string {
  1399. if region, ok := util.GetRegion(key.Labels); ok {
  1400. return region
  1401. }
  1402. return key.DefaultRegion
  1403. }
  1404. func (key *azurePvKey) legacyStorageClass() string {
  1405. if key.StorageClassParameters == nil {
  1406. return ""
  1407. }
  1408. storageClass := key.StorageClassParameters["storageaccounttype"]
  1409. if storageClass == "" {
  1410. storageClass = key.StorageClassParameters["skuname"]
  1411. }
  1412. if storageClass != "" {
  1413. return storageClass
  1414. }
  1415. fileSKU := key.StorageClassParameters["skuName"]
  1416. if strings.EqualFold(fileSKU, "Premium_LRS") {
  1417. return AzureFilePremiumStorageClass
  1418. }
  1419. if strings.EqualFold(fileSKU, "Standard_LRS") {
  1420. return AzureFileStandardStorageClass
  1421. }
  1422. return ""
  1423. }
  1424. func (key *azurePvKey) Features() string {
  1425. if key.DiskStorageClass == "" {
  1426. key.resolveSKU()
  1427. }
  1428. storageClass := key.DiskStorageClass
  1429. if storageClass == "" {
  1430. storageClass = key.legacyStorageClass()
  1431. }
  1432. return diskClassKey(key.region(), storageClass)
  1433. }
  1434. func (*Azure) GetAddresses() ([]byte, error) {
  1435. return nil, nil
  1436. }
  1437. func (az *Azure) GetDisks() ([]byte, error) {
  1438. disks, err := az.getDisks()
  1439. if err != nil {
  1440. return nil, err
  1441. }
  1442. return json.Marshal(disks)
  1443. }
  1444. func (az *Azure) getDisks() ([]*compute.Disk, error) {
  1445. config, err := az.GetConfig()
  1446. if err != nil {
  1447. return nil, err
  1448. }
  1449. // Load the service provider keys
  1450. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  1451. config.AzureSubscriptionID = subscriptionID
  1452. config.AzureClientID = clientID
  1453. config.AzureClientSecret = clientSecret
  1454. config.AzureTenantID = tenantID
  1455. var authorizer autorest.Authorizer
  1456. azureEnv := determineCloudByRegion(az.ClusterRegion)
  1457. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  1458. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  1459. a, err := credentialsConfig.Authorizer()
  1460. if err != nil {
  1461. az.rateCardPricingError = err
  1462. return nil, err
  1463. }
  1464. authorizer = a
  1465. }
  1466. if authorizer == nil {
  1467. a, err := auth.NewAuthorizerFromEnvironment()
  1468. authorizer = a
  1469. if err != nil {
  1470. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  1471. if err != nil {
  1472. az.rateCardPricingError = err
  1473. return nil, err
  1474. }
  1475. authorizer = a
  1476. }
  1477. }
  1478. client := compute.NewDisksClient(config.AzureSubscriptionID)
  1479. client.Authorizer = authorizer
  1480. ctx := context.TODO()
  1481. var disks []*compute.Disk
  1482. diskPage, err := client.List(ctx)
  1483. if err != nil {
  1484. return nil, fmt.Errorf("error getting disks: %v", err)
  1485. }
  1486. for diskPage.NotDone() {
  1487. for _, d := range diskPage.Values() {
  1488. d := d
  1489. disks = append(disks, &d)
  1490. }
  1491. err := diskPage.NextWithContext(context.Background())
  1492. if err != nil {
  1493. return nil, fmt.Errorf("error getting next page: %v", err)
  1494. }
  1495. }
  1496. return disks, nil
  1497. }
  1498. func (az *Azure) isDiskOrphaned(disk *compute.Disk) bool {
  1499. //TODO: needs better algorithm
  1500. return disk.DiskState == "Unattached" || disk.DiskState == "Reserved"
  1501. }
  1502. func (az *Azure) GetOrphanedResources() ([]models.OrphanedResource, error) {
  1503. disks, err := az.getDisks()
  1504. if err != nil {
  1505. return nil, err
  1506. }
  1507. var orphanedResources []models.OrphanedResource
  1508. for _, d := range disks {
  1509. if az.isDiskOrphaned(d) {
  1510. cost, err := az.findCostForDisk(d)
  1511. if err != nil {
  1512. return nil, err
  1513. }
  1514. diskName := ""
  1515. if d.Name != nil {
  1516. diskName = *d.Name
  1517. }
  1518. diskRegion := ""
  1519. if d.Location != nil {
  1520. diskRegion = *d.Location
  1521. }
  1522. var diskSize int64
  1523. if d.DiskSizeGB != nil {
  1524. diskSize = int64(*d.DiskSizeGB)
  1525. }
  1526. desc := map[string]string{}
  1527. for k, v := range d.Tags {
  1528. if v == nil {
  1529. desc[k] = ""
  1530. } else {
  1531. desc[k] = *v
  1532. }
  1533. }
  1534. or := models.OrphanedResource{
  1535. Kind: "disk",
  1536. Region: diskRegion,
  1537. Description: desc,
  1538. Size: &diskSize,
  1539. DiskName: diskName,
  1540. MonthlyCost: &cost,
  1541. }
  1542. orphanedResources = append(orphanedResources, or)
  1543. }
  1544. }
  1545. return orphanedResources, nil
  1546. }
  1547. func (az *Azure) findCostForDisk(d *compute.Disk) (float64, error) {
  1548. az.DownloadPricingDataLock.RLock()
  1549. defer az.DownloadPricingDataLock.RUnlock()
  1550. if d == nil {
  1551. return 0.0, fmt.Errorf("disk is empty")
  1552. }
  1553. if d.Sku == nil {
  1554. return 0.0, fmt.Errorf("disk sku is nil")
  1555. }
  1556. loc := ""
  1557. if d.Location != nil {
  1558. loc = *d.Location
  1559. }
  1560. if d.DiskProperties == nil {
  1561. return 0.0, fmt.Errorf("disk properties are nil")
  1562. }
  1563. if d.DiskSizeGB == nil {
  1564. return 0.0, fmt.Errorf("disk size is nil")
  1565. }
  1566. sizeGiB := float64(*d.DiskSizeGB)
  1567. if sku, ok := resolveDiskSKU(string(d.Sku.Name)); ok {
  1568. tier, ok := selectDiskTier(sku.StorageClass, sizeGiB)
  1569. if !ok {
  1570. return 0.0, fmt.Errorf("failed to select disk tier for sku %s size %g", d.Sku.Name, sizeGiB)
  1571. }
  1572. hasPrice := func(tierName string) bool {
  1573. _, ok := az.managedDiskTierHourly[diskTierKey(loc, sku.StorageClass, sku.Redundancy, tierName)]
  1574. return ok
  1575. }
  1576. pricedTier, ok := pickSizedOrLargerAvailableTier(sku.StorageClass, tier.Name, hasPrice)
  1577. if ok {
  1578. if pricedTier.Name != tier.Name {
  1579. log.Warnf("Azure disk tier meter %s missing for %s %s; using next available larger tier %s",
  1580. tier.Name, sku.StorageClass, sku.Redundancy, pricedTier.Name)
  1581. }
  1582. tierKey := diskTierKey(loc, sku.StorageClass, sku.Redundancy, pricedTier.Name)
  1583. hourly, ok := az.managedDiskTierHourly[tierKey]
  1584. if !ok {
  1585. return 0.0, fmt.Errorf("failed to find pricing for key: %s", tierKey)
  1586. }
  1587. return hourly * timeutil.HoursPerMonth, nil
  1588. }
  1589. if sku.Redundancy == azureDiskRedundancyZRS {
  1590. log.Warnf("Azure ZRS disk pricing unavailable for %s size %g; falling back to LRS class rate", loc, sizeGiB)
  1591. } else {
  1592. log.Warnf("Azure disk tier pricing unavailable for %s; falling back to linearized class rate",
  1593. diskTierKey(loc, sku.StorageClass, sku.Redundancy, tier.Name))
  1594. }
  1595. // Fall back to linearized class rate × size when no tier meter is available.
  1596. classKey := diskClassKey(loc, sku.StorageClass)
  1597. if p, ok := az.Pricing[classKey]; ok && p != nil && p.PV != nil {
  1598. diskPricePerGBHour, err := parsePrice(p.PV.Cost)
  1599. if err != nil {
  1600. return 0.0, fmt.Errorf("error converting to float: %s", err)
  1601. }
  1602. return diskPricePerGBHour * timeutil.HoursPerMonth * sizeGiB, nil
  1603. }
  1604. return 0.0, fmt.Errorf("failed to find pricing for key: %s", diskTierKey(loc, sku.StorageClass, sku.Redundancy, tier.Name))
  1605. }
  1606. // Unknown / custom SKU names: preserve legacy class-key lookup.
  1607. storageClass := string(d.Sku.Name)
  1608. key := loc + "," + storageClass
  1609. if p, ok := az.Pricing[key]; !ok || p == nil {
  1610. return 0.0, fmt.Errorf("failed to find pricing for key: %s", key)
  1611. }
  1612. if az.Pricing[key].PV == nil {
  1613. return 0.0, fmt.Errorf("pricing for key '%s' has nil PV", key)
  1614. }
  1615. diskPricePerGBHour, err := parsePrice(az.Pricing[key].PV.Cost)
  1616. if err != nil {
  1617. return 0.0, fmt.Errorf("error converting to float: %s", err)
  1618. }
  1619. return diskPricePerGBHour * timeutil.HoursPerMonth * sizeGiB, nil
  1620. }
  1621. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1622. remoteEnabled := env.IsRemoteEnabled()
  1623. m := make(map[string]string)
  1624. m["name"] = "Azure Cluster #1"
  1625. c, err := az.GetConfig()
  1626. if err != nil {
  1627. return nil, err
  1628. }
  1629. if c.ClusterName != "" {
  1630. m["name"] = c.ClusterName
  1631. }
  1632. m["provider"] = opencost.AzureProvider
  1633. m["account"] = az.ClusterAccountID
  1634. m["region"] = az.ClusterRegion
  1635. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1636. m["id"] = coreenv.GetClusterID()
  1637. return m, nil
  1638. }
  1639. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*models.CustomPricing, error) {
  1640. return az.Config.UpdateFromMap(a)
  1641. }
  1642. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*models.CustomPricing, error) {
  1643. return az.Config.Update(func(c *models.CustomPricing) error {
  1644. if updateType == AzureStorageUpdateType {
  1645. asc := &AzureStorageConfig{}
  1646. err := json.NewDecoder(r).Decode(&asc)
  1647. if err != nil {
  1648. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1649. }
  1650. c.AzureStorageSubscriptionID = asc.SubscriptionId
  1651. c.AzureStorageAccount = asc.AccountName
  1652. if asc.AccessKey != "" {
  1653. c.AzureStorageAccessKey = asc.AccessKey
  1654. }
  1655. c.AzureStorageContainer = asc.ContainerName
  1656. c.AzureContainerPath = asc.ContainerPath
  1657. c.AzureCloud = asc.AzureCloud
  1658. } else {
  1659. // This will block if not in a goroutine. It calls GetConfig(), which
  1660. // in turn calls GetCustomPricingData, which acquires the same lock
  1661. // that is acquired by az.Config.Update, which is the function to
  1662. // which this function gets passed, and subsequently called. Booo.
  1663. defer func() {
  1664. go az.DownloadPricingData()
  1665. }()
  1666. a := make(map[string]interface{})
  1667. err := json.NewDecoder(r).Decode(&a)
  1668. if err != nil {
  1669. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1670. }
  1671. for k, v := range a {
  1672. // Just so we consistently supply / receive the same values, uppercase the first letter.
  1673. kUpper := utils.ToTitle.String(k)
  1674. vstr, ok := v.(string)
  1675. if ok {
  1676. err := models.SetCustomPricingField(c, kUpper, vstr)
  1677. if err != nil {
  1678. return fmt.Errorf("error setting custom pricing field on AzureStorageConfig: %s", err)
  1679. }
  1680. } else {
  1681. return fmt.Errorf("type error while updating config for %s", kUpper)
  1682. }
  1683. }
  1684. }
  1685. if env.IsRemoteEnabled() {
  1686. err := utils.UpdateClusterMeta(coreenv.GetClusterID(), c.ClusterName)
  1687. if err != nil {
  1688. return fmt.Errorf("error updating cluster metadata: %s", err)
  1689. }
  1690. }
  1691. return nil
  1692. })
  1693. }
  1694. func (az *Azure) GetConfig() (*models.CustomPricing, error) {
  1695. c, err := az.Config.GetCustomPricingData()
  1696. if err != nil {
  1697. return nil, err
  1698. }
  1699. if c.Discount == "" {
  1700. c.Discount = "0%"
  1701. }
  1702. if c.NegotiatedDiscount == "" {
  1703. c.NegotiatedDiscount = "0%"
  1704. }
  1705. if c.CurrencyCode == "" {
  1706. c.CurrencyCode = "USD"
  1707. }
  1708. if c.AzureBillingRegion == "" {
  1709. c.AzureBillingRegion = "US"
  1710. }
  1711. // Default to pay-as-you-go Durable offer id
  1712. if c.AzureOfferDurableID == "" {
  1713. c.AzureOfferDurableID = "MS-AZR-0003p"
  1714. }
  1715. if c.SpotLabel == "" {
  1716. c.SpotLabel = defaultSpotLabel
  1717. }
  1718. if c.SpotLabelValue == "" {
  1719. c.SpotLabelValue = defaultSpotLabelValue
  1720. }
  1721. return c, nil
  1722. }
  1723. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*models.Node) {
  1724. }
  1725. func (az *Azure) GpuPricing(nodeLabels map[string]string) (string, error) {
  1726. return "", nil
  1727. }
  1728. func (az *Azure) PVPricing(pvk models.PVKey) (*models.PV, error) {
  1729. az.DownloadPricingDataLock.RLock()
  1730. defer az.DownloadPricingDataLock.RUnlock()
  1731. if key, ok := pvk.(*azurePvKey); ok {
  1732. return az.pvPricingFromAzureKey(key)
  1733. }
  1734. pricing, ok := az.Pricing[pvk.Features()]
  1735. if !ok {
  1736. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1737. return &models.PV{}, nil
  1738. }
  1739. return pricing.PV, nil
  1740. }
  1741. // pvPricingFromAzureKey returns an effective $/GiB-hour rate for the PV.
  1742. // Managed disks use Azure size-tier meters; the rate is chosen so that
  1743. // rate × reportedSizeGiB × hours equals the tier's hourly cost.
  1744. func (az *Azure) pvPricingFromAzureKey(key *azurePvKey) (*models.PV, error) {
  1745. if key.DiskStorageClass == "" {
  1746. key.resolveSKU()
  1747. }
  1748. region := key.region()
  1749. if key.IsAzureFiles || key.DiskStorageClass == AzureFilePremiumStorageClass || key.DiskStorageClass == AzureFileStandardStorageClass {
  1750. pricing, ok := az.Pricing[diskClassKey(region, key.DiskStorageClass)]
  1751. if !ok || pricing == nil || pricing.PV == nil {
  1752. log.Debugf("Persistent Volume pricing not found for %s: %s", key.GetStorageClass(), key.Features())
  1753. return &models.PV{}, nil
  1754. }
  1755. return pricing.PV, nil
  1756. }
  1757. if key.DiskStorageClass == "" {
  1758. legacyStorageClass := key.legacyStorageClass()
  1759. if legacyStorageClass != "" {
  1760. pricing, ok := az.Pricing[diskClassKey(region, legacyStorageClass)]
  1761. if ok && pricing != nil && pricing.PV != nil {
  1762. return pricing.PV, nil
  1763. }
  1764. }
  1765. log.Debugf("Persistent Volume pricing not found for %s: %s", key.GetStorageClass(), key.Features())
  1766. return &models.PV{}, nil
  1767. }
  1768. redundancy := key.DiskRedundancy
  1769. if redundancy == "" {
  1770. redundancy = azureDiskRedundancyLRS
  1771. }
  1772. if key.SizeGiB > 0 {
  1773. tier, ok := selectDiskTier(key.DiskStorageClass, key.SizeGiB)
  1774. if !ok {
  1775. log.Warnf("No disk tier for storage class %s size %g; falling back to class rate", key.DiskStorageClass, key.SizeGiB)
  1776. return az.pvClassFallback(region, key.DiskStorageClass, redundancy)
  1777. }
  1778. hasPrice := func(tierName string) bool {
  1779. _, ok := az.managedDiskTierHourly[diskTierKey(region, key.DiskStorageClass, redundancy, tierName)]
  1780. return ok
  1781. }
  1782. pricedTier, ok := pickSizedOrLargerAvailableTier(key.DiskStorageClass, tier.Name, hasPrice)
  1783. if !ok {
  1784. log.Warnf("Persistent Volume tier pricing not found for %s size %g (%s); falling back to class rate",
  1785. diskTierKey(region, key.DiskStorageClass, redundancy, tier.Name), key.SizeGiB, redundancy)
  1786. return az.pvClassFallback(region, key.DiskStorageClass, redundancy)
  1787. }
  1788. if pricedTier.Name != tier.Name {
  1789. log.Warnf("Azure disk tier meter %s missing for %s; using next available larger tier %s",
  1790. tier.Name, diskClassKey(region, key.DiskStorageClass), pricedTier.Name)
  1791. }
  1792. tierKey := diskTierKey(region, key.DiskStorageClass, redundancy, pricedTier.Name)
  1793. hourly, ok := az.managedDiskTierHourly[tierKey]
  1794. if !ok {
  1795. log.Warnf("Persistent Volume tier pricing not found for %s size %g (%s); falling back to class rate",
  1796. tierKey, key.SizeGiB, redundancy)
  1797. return az.pvClassFallback(region, key.DiskStorageClass, redundancy)
  1798. }
  1799. rate := effectiveGiBHourRateFromHourly(hourly, key.SizeGiB)
  1800. return &models.PV{
  1801. Cost: formatPrice(rate),
  1802. Class: key.DiskStorageClass,
  1803. Region: region,
  1804. Size: strconv.FormatFloat(key.SizeGiB, 'f', -1, 64),
  1805. }, nil
  1806. }
  1807. if redundancy == azureDiskRedundancyZRS {
  1808. log.Warnf("Persistent Volume size unknown for ZRS volume %s; using LRS linearized class rate", key.Features())
  1809. } else {
  1810. log.Debugf("Persistent Volume size unknown for %s; using linearized class rate", key.Features())
  1811. }
  1812. return az.pvClassFallback(region, key.DiskStorageClass, redundancy)
  1813. }
  1814. func (az *Azure) pvClassFallback(region, storageClass, redundancy string) (*models.PV, error) {
  1815. if redundancy == azureDiskRedundancyZRS {
  1816. log.Warnf("Azure ZRS class-level pricing is unavailable; using LRS linearized rate for %s,%s", region, storageClass)
  1817. }
  1818. pricing, ok := az.Pricing[diskClassKey(region, storageClass)]
  1819. if !ok || pricing == nil || pricing.PV == nil {
  1820. log.Debugf("Persistent Volume pricing not found for %s,%s", region, storageClass)
  1821. return &models.PV{}, nil
  1822. }
  1823. return pricing.PV, nil
  1824. }
  1825. func (az *Azure) ServiceAccountStatus() *models.ServiceAccountStatus {
  1826. return az.ServiceAccountChecks.GetStatus()
  1827. }
  1828. const (
  1829. rateCardPricingSource = "Rate Card API"
  1830. priceSheetPricingSource = "Price Sheet API"
  1831. )
  1832. // PricingSourceStatus returns the status of the rate card api
  1833. func (az *Azure) PricingSourceStatus() map[string]*models.PricingSource {
  1834. az.DownloadPricingDataLock.Lock()
  1835. defer az.DownloadPricingDataLock.Unlock()
  1836. sources := make(map[string]*models.PricingSource)
  1837. errMsg := ""
  1838. if az.rateCardPricingError != nil {
  1839. errMsg = az.rateCardPricingError.Error()
  1840. }
  1841. rcps := &models.PricingSource{
  1842. Name: rateCardPricingSource,
  1843. Enabled: az.pricingSource == rateCardPricingSource,
  1844. Error: errMsg,
  1845. }
  1846. if rcps.Error != "" {
  1847. rcps.Available = false
  1848. } else if len(az.Pricing) == 0 {
  1849. rcps.Error = "No Pricing Data Available"
  1850. rcps.Available = false
  1851. } else {
  1852. rcps.Available = true
  1853. }
  1854. errMsg = ""
  1855. if az.priceSheetPricingError != nil {
  1856. errMsg = az.priceSheetPricingError.Error()
  1857. }
  1858. psps := &models.PricingSource{
  1859. Name: priceSheetPricingSource,
  1860. Enabled: az.pricingSource == priceSheetPricingSource,
  1861. Error: errMsg,
  1862. }
  1863. if psps.Error != "" {
  1864. psps.Available = false
  1865. } else if len(az.Pricing) == 0 {
  1866. psps.Error = "No Pricing Data Available"
  1867. psps.Available = false
  1868. } else if env.GetAzureBillingAccount() == "" {
  1869. psps.Error = "No Azure Billing Account ID"
  1870. psps.Available = false
  1871. } else {
  1872. psps.Available = true
  1873. }
  1874. sources[rateCardPricingSource] = rcps
  1875. sources[priceSheetPricingSource] = psps
  1876. return sources
  1877. }
  1878. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1879. return "", 0.0, nil
  1880. }
  1881. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1882. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1883. }
  1884. func (az *Azure) Regions() []string {
  1885. regionOverrides := env.GetRegionOverrideList()
  1886. if len(regionOverrides) > 0 {
  1887. log.Debugf("Overriding Azure regions with configured region list: %+v", regionOverrides)
  1888. return regionOverrides
  1889. }
  1890. return azureRegions
  1891. }
  1892. func ParseAzureSubscriptionID(id string) string {
  1893. match := azureSubRegex.FindStringSubmatch(id)
  1894. if len(match) >= 2 {
  1895. return match[1]
  1896. }
  1897. // Return empty string if an account could not be parsed from provided string
  1898. return ""
  1899. }