provider.go 49 KB

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