provider.go 49 KB

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