provider.go 49 KB

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