provider.go 52 KB

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