provider.go 50 KB

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