provider.go 49 KB

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