provider.go 52 KB

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