provider.go 52 KB

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