azureprovider.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. package cloud
  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/opencost/opencost/pkg/clustercache"
  15. "github.com/opencost/opencost/pkg/env"
  16. "github.com/opencost/opencost/pkg/log"
  17. "github.com/opencost/opencost/pkg/util"
  18. "github.com/opencost/opencost/pkg/util/fileutil"
  19. "github.com/opencost/opencost/pkg/util/json"
  20. "github.com/opencost/opencost/pkg/util/timeutil"
  21. "golang.org/x/text/cases"
  22. "golang.org/x/text/language"
  23. "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-11-01/compute"
  24. "github.com/Azure/azure-sdk-for-go/services/preview/commerce/mgmt/2015-06-01-preview/commerce"
  25. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
  26. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
  27. "github.com/Azure/go-autorest/autorest"
  28. "github.com/Azure/go-autorest/autorest/azure"
  29. "github.com/Azure/go-autorest/autorest/azure/auth"
  30. v1 "k8s.io/api/core/v1"
  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 toTitle = cases.Title(language.Und, cases.NoLower)
  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 %s", loc)
  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 %s", loc)
  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")
  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 *Node
  353. PV *PV
  354. }
  355. type Azure struct {
  356. Pricing map[string]*AzurePricing
  357. DownloadPricingDataLock sync.RWMutex
  358. Clientset clustercache.ClusterCache
  359. Config *ProviderConfig
  360. serviceAccountChecks *ServiceAccountChecks
  361. RateCardPricingError error
  362. clusterAccountId string
  363. clusterRegion string
  364. loadedAzureSecret bool
  365. azureSecret *AzureServiceKey
  366. loadedAzureStorageConfigSecret bool
  367. azureStorageConfig *AzureStorageConfig
  368. }
  369. type azureKey struct {
  370. Labels map[string]string
  371. GPULabel string
  372. GPULabelValue string
  373. }
  374. func (k *azureKey) Features() string {
  375. r, _ := util.GetRegion(k.Labels)
  376. region := strings.ToLower(r)
  377. instance, _ := util.GetInstanceType(k.Labels)
  378. usageType := "ondemand"
  379. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  380. }
  381. func (k *azureKey) GPUCount() int {
  382. return 0
  383. }
  384. // GPUType returns value of GPULabel if present
  385. func (k *azureKey) GPUType() string {
  386. if t, ok := k.Labels[k.GPULabel]; ok {
  387. return t
  388. }
  389. return ""
  390. }
  391. func (k *azureKey) isValidGPUNode() bool {
  392. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  393. }
  394. func (k *azureKey) ID() string {
  395. return ""
  396. }
  397. func (k *azureKey) GetGPUCount() string {
  398. instance, _ := util.GetInstanceType(k.Labels)
  399. // Double digits that could get matches lower in logic
  400. if strings.Contains(instance, "NC64") {
  401. return "4"
  402. }
  403. if strings.Contains(instance, "ND96") ||
  404. strings.Contains(instance, "ND40") {
  405. return "8"
  406. }
  407. // Ordered asc because of some series have different gpu counts on different versions
  408. if strings.Contains(instance, "NC6") ||
  409. strings.Contains(instance, "NC4") ||
  410. strings.Contains(instance, "NC8") ||
  411. strings.Contains(instance, "NC16") ||
  412. strings.Contains(instance, "ND6") ||
  413. strings.Contains(instance, "NV12s") ||
  414. strings.Contains(instance, "NV6") {
  415. return "1"
  416. }
  417. if strings.Contains(instance, "NC12") ||
  418. strings.Contains(instance, "ND12") ||
  419. strings.Contains(instance, "NV24s") ||
  420. strings.Contains(instance, "NV12") {
  421. return "2"
  422. }
  423. if strings.Contains(instance, "NC24") ||
  424. strings.Contains(instance, "ND24") ||
  425. strings.Contains(instance, "NV48s") ||
  426. strings.Contains(instance, "NV24") {
  427. return "4"
  428. }
  429. return "0"
  430. }
  431. // AzureStorageConfig Represents an azure storage config
  432. type AzureStorageConfig struct {
  433. SubscriptionId string `json:"azureSubscriptionID"`
  434. AccountName string `json:"azureStorageAccount"`
  435. AccessKey string `json:"azureStorageAccessKey"`
  436. ContainerName string `json:"azureStorageContainer"`
  437. ContainerPath string `json:"azureContainerPath"`
  438. AzureCloud string `json:"azureCloud"`
  439. }
  440. // IsEmpty returns true if all fields in config are empty, false if not.
  441. func (asc *AzureStorageConfig) IsEmpty() bool {
  442. return asc.SubscriptionId == "" &&
  443. asc.AccountName == "" &&
  444. asc.AccessKey == "" &&
  445. asc.ContainerName == "" &&
  446. asc.ContainerPath == "" &&
  447. asc.AzureCloud == ""
  448. }
  449. // Represents an azure app key
  450. type AzureAppKey struct {
  451. AppID string `json:"appId"`
  452. DisplayName string `json:"displayName"`
  453. Name string `json:"name"`
  454. Password string `json:"password"`
  455. Tenant string `json:"tenant"`
  456. }
  457. // Azure service key for a specific subscription
  458. type AzureServiceKey struct {
  459. SubscriptionID string `json:"subscriptionId"`
  460. ServiceKey *AzureAppKey `json:"serviceKey"`
  461. }
  462. // Validity check on service key
  463. func (ask *AzureServiceKey) IsValid() bool {
  464. return ask.SubscriptionID != "" &&
  465. ask.ServiceKey != nil &&
  466. ask.ServiceKey.AppID != "" &&
  467. ask.ServiceKey.Password != "" &&
  468. ask.ServiceKey.Tenant != ""
  469. }
  470. // Loads the azure authentication via configuration or a secret set at install time.
  471. func (az *Azure) getAzureRateCardAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  472. // 1. Check for secret (secret values will always be used if they are present)
  473. s, _ := az.loadAzureAuthSecret(forceReload)
  474. if s != nil && s.IsValid() {
  475. subscriptionID = s.SubscriptionID
  476. clientID = s.ServiceKey.AppID
  477. clientSecret = s.ServiceKey.Password
  478. tenantID = s.ServiceKey.Tenant
  479. return
  480. }
  481. // 2. Check config values (set though endpoint)
  482. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  483. subscriptionID = cp.AzureSubscriptionID
  484. clientID = cp.AzureClientID
  485. clientSecret = cp.AzureClientSecret
  486. tenantID = cp.AzureTenantID
  487. return
  488. }
  489. // 3. Check if AzureSubscriptionID is set in config (set though endpoint)
  490. // MSI credentials will be attempted if the subscription ID is set, but clientID, clientSecret and tenantID are not
  491. if cp.AzureSubscriptionID != "" {
  492. subscriptionID = cp.AzureSubscriptionID
  493. return
  494. }
  495. // 4. Empty values
  496. return "", "", "", ""
  497. }
  498. // GetAzureStorageConfig retrieves storage config from secret and sets default values
  499. func (az *Azure) GetAzureStorageConfig(forceReload bool, cp *CustomPricing) (*AzureStorageConfig, error) {
  500. // default subscription id
  501. defaultSubscriptionID := cp.AzureSubscriptionID
  502. // 1. Check Config for storage set up
  503. asc := &AzureStorageConfig{
  504. SubscriptionId: cp.AzureStorageSubscriptionID,
  505. AccountName: cp.AzureStorageAccount,
  506. AccessKey: cp.AzureStorageAccessKey,
  507. ContainerName: cp.AzureStorageContainer,
  508. ContainerPath: cp.AzureContainerPath,
  509. AzureCloud: cp.AzureCloud,
  510. }
  511. // check for required fields
  512. if asc != nil && asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  513. az.serviceAccountChecks.set("hasStorage", &ServiceAccountCheck{
  514. Message: "Azure Storage Config exists",
  515. Status: true,
  516. })
  517. return asc, nil
  518. }
  519. // 2. Check for secret
  520. asc, err := az.loadAzureStorageConfig(forceReload)
  521. if err != nil {
  522. log.Errorf("Error, %s", err.Error())
  523. } else if asc != nil {
  524. // To support already configured users, subscriptionID may not be set in secret in which case, the subscriptionID
  525. // for the rate card API is used
  526. if asc.SubscriptionId == "" {
  527. asc.SubscriptionId = defaultSubscriptionID
  528. }
  529. // check for required fields
  530. if asc.AccessKey != "" && asc.AccountName != "" && asc.ContainerName != "" && asc.SubscriptionId != "" {
  531. az.serviceAccountChecks.set("hasStorage", &ServiceAccountCheck{
  532. Message: "Azure Storage Config exists",
  533. Status: true,
  534. })
  535. return asc, nil
  536. }
  537. }
  538. az.serviceAccountChecks.set("hasStorage", &ServiceAccountCheck{
  539. Message: "Azure Storage Config exists",
  540. Status: false,
  541. })
  542. return nil, fmt.Errorf("azure storage config not found")
  543. }
  544. // Load once and cache the result (even on failure). This is an install time secret, so
  545. // we don't expect the secret to change. If it does, however, we can force reload using
  546. // the input parameter.
  547. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  548. if !force && az.loadedAzureSecret {
  549. return az.azureSecret, nil
  550. }
  551. az.loadedAzureSecret = true
  552. exists, err := fileutil.FileExists(authSecretPath)
  553. if !exists || err != nil {
  554. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  555. }
  556. result, err := os.ReadFile(authSecretPath)
  557. if err != nil {
  558. return nil, err
  559. }
  560. var ask AzureServiceKey
  561. err = json.Unmarshal(result, &ask)
  562. if err != nil {
  563. return nil, err
  564. }
  565. az.azureSecret = &ask
  566. return &ask, nil
  567. }
  568. // Load once and cache the result (even on failure). This is an install time secret, so
  569. // we don't expect the secret to change. If it does, however, we can force reload using
  570. // the input parameter.
  571. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  572. if !force && az.loadedAzureStorageConfigSecret {
  573. return az.azureStorageConfig, nil
  574. }
  575. az.loadedAzureStorageConfigSecret = true
  576. exists, err := fileutil.FileExists(storageConfigSecretPath)
  577. if !exists || err != nil {
  578. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  579. }
  580. result, err := os.ReadFile(storageConfigSecretPath)
  581. if err != nil {
  582. return nil, err
  583. }
  584. var asc AzureStorageConfig
  585. err = json.Unmarshal(result, &asc)
  586. if err != nil {
  587. return nil, err
  588. }
  589. az.azureStorageConfig = &asc
  590. return &asc, nil
  591. }
  592. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  593. cfg, err := az.GetConfig()
  594. if err != nil {
  595. log.Infof("Error loading azure custom pricing information")
  596. }
  597. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  598. gpuLabel := "accelerator"
  599. gpuLabelValue := "nvidia"
  600. if cfg.GpuLabel != "" {
  601. gpuLabel = cfg.GpuLabel
  602. }
  603. if cfg.GpuLabelValue != "" {
  604. gpuLabelValue = cfg.GpuLabelValue
  605. }
  606. return &azureKey{
  607. Labels: labels,
  608. GPULabel: gpuLabel,
  609. GPULabelValue: gpuLabelValue,
  610. }
  611. }
  612. // CreateString builds strings effectively
  613. func createString(keys ...string) string {
  614. var b strings.Builder
  615. for _, key := range keys {
  616. b.WriteString(key)
  617. }
  618. return b.String()
  619. }
  620. func transformMachineType(subCategory string, mt []string) []string {
  621. switch {
  622. case strings.Contains(subCategory, "Basic"):
  623. return []string{createString("Basic_", mt[0])}
  624. case len(mt) == 2:
  625. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  626. default:
  627. return []string{createString("Standard_", mt[0])}
  628. }
  629. }
  630. func addSuffix(mt string, suffixes ...string) []string {
  631. result := make([]string, len(suffixes))
  632. var suffix string
  633. parts := strings.Split(mt, "_")
  634. if len(parts) > 2 {
  635. for _, p := range parts[2:] {
  636. suffix = createString(suffix, "_", p)
  637. }
  638. }
  639. for i, s := range suffixes {
  640. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  641. }
  642. return result
  643. }
  644. func getMachineTypeVariants(mt string) []string {
  645. switch {
  646. case mtStandardB.MatchString(mt):
  647. return []string{createString(mt, "s")}
  648. case mtStandardD.MatchString(mt):
  649. var result []string
  650. result = append(result, addSuffix(mt, "s")[0])
  651. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  652. result = append(result, dsType)
  653. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  654. return result
  655. case mtStandardE.MatchString(mt):
  656. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  657. case mtStandardF.MatchString(mt):
  658. return addSuffix(mt, "s")
  659. case mtStandardG.MatchString(mt):
  660. var result []string
  661. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  662. result = append(result, gsType)
  663. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  664. case mtStandardL.MatchString(mt):
  665. return addSuffix(mt, "s")
  666. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  667. base := strings.TrimSuffix(mt, "ms")
  668. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  669. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  670. return []string{}
  671. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  672. base := strings.TrimSuffix(mt, "s")
  673. return addSuffix(base, "", "m")
  674. case mtStandardN.MatchString(mt):
  675. return addSuffix(mt, "s")
  676. }
  677. return []string{}
  678. }
  679. func (az *Azure) GetManagementPlatform() (string, error) {
  680. nodes := az.Clientset.GetAllNodes()
  681. if len(nodes) > 0 {
  682. n := nodes[0]
  683. providerID := n.Spec.ProviderID
  684. if strings.Contains(providerID, "aks") {
  685. return "aks", nil
  686. }
  687. }
  688. return "", nil
  689. }
  690. // DownloadPricingData uses provided azure "best guesses" for pricing
  691. func (az *Azure) DownloadPricingData() error {
  692. az.DownloadPricingDataLock.Lock()
  693. defer az.DownloadPricingDataLock.Unlock()
  694. config, err := az.GetConfig()
  695. if err != nil {
  696. az.RateCardPricingError = err
  697. return err
  698. }
  699. // Load the service provider keys
  700. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  701. config.AzureSubscriptionID = subscriptionID
  702. config.AzureClientID = clientID
  703. config.AzureClientSecret = clientSecret
  704. config.AzureTenantID = tenantID
  705. var authorizer autorest.Authorizer
  706. azureEnv := determineCloudByRegion(az.clusterRegion)
  707. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  708. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  709. a, err := credentialsConfig.Authorizer()
  710. if err != nil {
  711. az.RateCardPricingError = err
  712. return err
  713. }
  714. authorizer = a
  715. }
  716. if authorizer == nil {
  717. a, err := auth.NewAuthorizerFromEnvironment()
  718. authorizer = a
  719. if err != nil {
  720. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  721. if err != nil {
  722. az.RateCardPricingError = err
  723. return err
  724. }
  725. authorizer = a
  726. }
  727. }
  728. sClient := subscriptions.NewClientWithBaseURI(azureEnv.ResourceManagerEndpoint)
  729. sClient.Authorizer = authorizer
  730. rcClient := commerce.NewRateCardClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  731. rcClient.Authorizer = authorizer
  732. providersClient := resources.NewProvidersClientWithBaseURI(azureEnv.ResourceManagerEndpoint, config.AzureSubscriptionID)
  733. providersClient.Authorizer = authorizer
  734. 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)
  735. log.Infof("Using ratecard query %s", rateCardFilter)
  736. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  737. if err != nil {
  738. log.Warnf("Error in pricing download query from API")
  739. az.RateCardPricingError = err
  740. return err
  741. }
  742. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  743. if err != nil {
  744. log.Warnf("Error in pricing download regions from API")
  745. az.RateCardPricingError = err
  746. return err
  747. }
  748. baseCPUPrice := config.CPU
  749. allPrices := make(map[string]*AzurePricing)
  750. for _, v := range *result.Meters {
  751. meterName := *v.MeterName
  752. meterRegion := *v.MeterRegion
  753. meterCategory := *v.MeterCategory
  754. meterSubCategory := *v.MeterSubCategory
  755. region, err := toRegionID(meterRegion, regions)
  756. if err != nil {
  757. continue
  758. }
  759. if !strings.Contains(meterSubCategory, "Windows") {
  760. if strings.Contains(meterCategory, "Storage") {
  761. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  762. var storageClass string = ""
  763. if strings.Contains(meterName, "P4 ") {
  764. storageClass = AzureDiskPremiumSSDStorageClass
  765. } else if strings.Contains(meterName, "E4 ") {
  766. storageClass = AzureDiskStandardSSDStorageClass
  767. } else if strings.Contains(meterName, "S4 ") {
  768. storageClass = AzureDiskStandardStorageClass
  769. } else if strings.Contains(meterName, "LRS Provisioned") {
  770. storageClass = AzureFilePremiumStorageClass
  771. }
  772. if storageClass != "" {
  773. var priceInUsd float64
  774. if len(v.MeterRates) < 1 {
  775. log.Warnf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  776. continue
  777. }
  778. for _, rate := range v.MeterRates {
  779. priceInUsd += *rate
  780. }
  781. // rate is in disk per month, resolve price per hour, then GB per hour
  782. pricePerHour := priceInUsd / 730.0 / 32.0
  783. priceStr := fmt.Sprintf("%f", pricePerHour)
  784. key := region + "," + storageClass
  785. log.Debugf("Adding PV.Key: %s, Cost: %s", key, priceStr)
  786. allPrices[key] = &AzurePricing{
  787. PV: &PV{
  788. Cost: priceStr,
  789. Region: region,
  790. },
  791. }
  792. }
  793. }
  794. }
  795. if strings.Contains(meterCategory, "Virtual Machines") {
  796. usageType := ""
  797. if !strings.Contains(meterName, "Low Priority") {
  798. usageType = "ondemand"
  799. } else {
  800. usageType = "preemptible"
  801. }
  802. var instanceTypes []string
  803. name := strings.TrimSuffix(meterName, " Low Priority")
  804. instanceType := strings.Split(name, "/")
  805. for _, it := range instanceType {
  806. if strings.Contains(meterSubCategory, "Promo") {
  807. it = it + " Promo"
  808. }
  809. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  810. }
  811. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  812. if strings.Contains(name, "Expired") {
  813. instanceTypes = []string{}
  814. }
  815. var priceInUsd float64
  816. if len(v.MeterRates) < 1 {
  817. log.Warnf("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  818. continue
  819. }
  820. for _, rate := range v.MeterRates {
  821. priceInUsd += *rate
  822. }
  823. priceStr := fmt.Sprintf("%f", priceInUsd)
  824. for _, instanceType := range instanceTypes {
  825. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  826. allPrices[key] = &AzurePricing{
  827. Node: &Node{
  828. Cost: priceStr,
  829. BaseCPUPrice: baseCPUPrice,
  830. UsageType: usageType,
  831. },
  832. }
  833. }
  834. }
  835. }
  836. }
  837. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  838. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  839. // check https://github.com/opencost/opencost/issues/159 for more information (same problem on AWS)
  840. zeroPrice := "0.0"
  841. for region := range regions {
  842. key := region + "," + AzureFileStandardStorageClass
  843. log.Debugf("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  844. allPrices[key] = &AzurePricing{
  845. PV: &PV{
  846. Cost: zeroPrice,
  847. Region: region,
  848. },
  849. }
  850. }
  851. az.Pricing = allPrices
  852. az.RateCardPricingError = nil
  853. return nil
  854. }
  855. // determineCloudByRegion uses region name to pick the correct Cloud Environment for the azure provider to use
  856. func determineCloudByRegion(region string) azure.Environment {
  857. lcRegion := strings.ToLower(region)
  858. if strings.Contains(lcRegion, "china") {
  859. return azure.ChinaCloud
  860. }
  861. if strings.Contains(lcRegion, "gov") || strings.Contains(lcRegion, "dod") {
  862. return azure.USGovernmentCloud
  863. }
  864. // Default to public cloud
  865. return azure.PublicCloud
  866. }
  867. // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
  868. func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string, env azure.Environment) auth.ClientCredentialsConfig {
  869. return auth.ClientCredentialsConfig{
  870. ClientID: clientID,
  871. ClientSecret: clientSecret,
  872. TenantID: tenantID,
  873. Resource: env.ResourceManagerEndpoint,
  874. AADEndpoint: env.ActiveDirectoryEndpoint,
  875. }
  876. }
  877. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  878. if az.Pricing == nil {
  879. az.Pricing = map[string]*AzurePricing{}
  880. }
  881. az.Pricing[features] = azurePricing
  882. }
  883. // AllNodePricing returns the Azure pricing objects stored
  884. func (az *Azure) AllNodePricing() (interface{}, error) {
  885. az.DownloadPricingDataLock.RLock()
  886. defer az.DownloadPricingDataLock.RUnlock()
  887. return az.Pricing, nil
  888. }
  889. // NodePricing returns Azure pricing data for a single node
  890. func (az *Azure) NodePricing(key Key) (*Node, error) {
  891. az.DownloadPricingDataLock.RLock()
  892. defer az.DownloadPricingDataLock.RUnlock()
  893. azKey, ok := key.(*azureKey)
  894. if !ok {
  895. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  896. }
  897. config, _ := az.GetConfig()
  898. if slv, ok := azKey.Labels[config.SpotLabel]; ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  899. features := strings.Split(azKey.Features(), ",")
  900. region := features[0]
  901. instance := features[1]
  902. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  903. if n, ok := az.Pricing[spotFeatures]; ok {
  904. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  905. if azKey.isValidGPUNode() {
  906. n.Node.GPU = "1" // TODO: support multiple GPUs
  907. }
  908. return n.Node, nil
  909. }
  910. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  911. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  912. if err != nil {
  913. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  914. } else {
  915. gpu := ""
  916. if azKey.isValidGPUNode() {
  917. gpu = "1"
  918. }
  919. spotNode := &Node{
  920. Cost: spotCost,
  921. UsageType: "spot",
  922. GPU: gpu,
  923. }
  924. az.addPricing(spotFeatures, &AzurePricing{
  925. Node: spotNode,
  926. })
  927. return spotNode, nil
  928. }
  929. }
  930. if n, ok := az.Pricing[azKey.Features()]; ok {
  931. log.Debugf("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  932. if azKey.isValidGPUNode() {
  933. n.Node.GPU = azKey.GetGPUCount()
  934. }
  935. return n.Node, nil
  936. }
  937. log.Warnf("no pricing data found for %s: %s", azKey.Features(), azKey)
  938. c, err := az.GetConfig()
  939. if err != nil {
  940. return nil, fmt.Errorf("No default pricing data available")
  941. }
  942. if azKey.isValidGPUNode() {
  943. return &Node{
  944. VCPUCost: c.CPU,
  945. RAMCost: c.RAM,
  946. UsesBaseCPUPrice: true,
  947. GPUCost: c.GPU,
  948. GPU: azKey.GetGPUCount(),
  949. }, nil
  950. }
  951. return &Node{
  952. VCPUCost: c.CPU,
  953. RAMCost: c.RAM,
  954. UsesBaseCPUPrice: true,
  955. }, nil
  956. }
  957. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  958. func (az *Azure) NetworkPricing() (*Network, error) {
  959. cpricing, err := az.Config.GetCustomPricingData()
  960. if err != nil {
  961. return nil, err
  962. }
  963. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  964. if err != nil {
  965. return nil, err
  966. }
  967. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  968. if err != nil {
  969. return nil, err
  970. }
  971. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  972. if err != nil {
  973. return nil, err
  974. }
  975. return &Network{
  976. ZoneNetworkEgressCost: znec,
  977. RegionNetworkEgressCost: rnec,
  978. InternetNetworkEgressCost: inec,
  979. }, nil
  980. }
  981. // LoadBalancerPricing on Azure, LoadBalancer services correspond to public IPs. For now the pricing of LoadBalancer
  982. // services will be that of a standard static public IP https://azure.microsoft.com/en-us/pricing/details/ip-addresses/.
  983. // Azure still has load balancers which follow the standard pricing scheme based on rules
  984. // https://azure.microsoft.com/en-us/pricing/details/load-balancer/, they are created on a per-cluster basis.
  985. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  986. return &LoadBalancer{
  987. Cost: 0.005,
  988. }, nil
  989. }
  990. type azurePvKey struct {
  991. Labels map[string]string
  992. StorageClass string
  993. StorageClassParameters map[string]string
  994. DefaultRegion string
  995. ProviderId string
  996. }
  997. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  998. providerID := ""
  999. if pv.Spec.AzureDisk != nil {
  1000. providerID = pv.Spec.AzureDisk.DiskName
  1001. }
  1002. return &azurePvKey{
  1003. Labels: pv.Labels,
  1004. StorageClass: pv.Spec.StorageClassName,
  1005. StorageClassParameters: parameters,
  1006. DefaultRegion: defaultRegion,
  1007. ProviderId: providerID,
  1008. }
  1009. }
  1010. func (key *azurePvKey) ID() string {
  1011. return key.ProviderId
  1012. }
  1013. func (key *azurePvKey) GetStorageClass() string {
  1014. return key.StorageClass
  1015. }
  1016. func (key *azurePvKey) Features() string {
  1017. storageClass := key.StorageClassParameters["storageaccounttype"]
  1018. storageSKU := key.StorageClassParameters["skuName"]
  1019. if storageClass != "" {
  1020. if strings.EqualFold(storageClass, "Premium_LRS") {
  1021. storageClass = AzureDiskPremiumSSDStorageClass
  1022. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1023. storageClass = AzureDiskStandardSSDStorageClass
  1024. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1025. storageClass = AzureDiskStandardStorageClass
  1026. }
  1027. } else {
  1028. if strings.EqualFold(storageSKU, "Premium_LRS") {
  1029. storageClass = AzureFilePremiumStorageClass
  1030. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  1031. storageClass = AzureFileStandardStorageClass
  1032. }
  1033. }
  1034. if region, ok := util.GetRegion(key.Labels); ok {
  1035. return region + "," + storageClass
  1036. }
  1037. return key.DefaultRegion + "," + storageClass
  1038. }
  1039. func (*Azure) GetAddresses() ([]byte, error) {
  1040. return nil, nil
  1041. }
  1042. func (az *Azure) GetDisks() ([]byte, error) {
  1043. disks, err := az.getDisks()
  1044. if err != nil {
  1045. return nil, err
  1046. }
  1047. return json.Marshal(disks)
  1048. }
  1049. func (az *Azure) getDisks() ([]*compute.Disk, error) {
  1050. config, err := az.GetConfig()
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. // Load the service provider keys
  1055. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  1056. config.AzureSubscriptionID = subscriptionID
  1057. config.AzureClientID = clientID
  1058. config.AzureClientSecret = clientSecret
  1059. config.AzureTenantID = tenantID
  1060. var authorizer autorest.Authorizer
  1061. azureEnv := determineCloudByRegion(az.clusterRegion)
  1062. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  1063. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  1064. a, err := credentialsConfig.Authorizer()
  1065. if err != nil {
  1066. az.RateCardPricingError = err
  1067. return nil, err
  1068. }
  1069. authorizer = a
  1070. }
  1071. if authorizer == nil {
  1072. a, err := auth.NewAuthorizerFromEnvironment()
  1073. authorizer = a
  1074. if err != nil {
  1075. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  1076. if err != nil {
  1077. az.RateCardPricingError = err
  1078. return nil, err
  1079. }
  1080. authorizer = a
  1081. }
  1082. }
  1083. client := compute.NewDisksClient(config.AzureSubscriptionID)
  1084. client.Authorizer = authorizer
  1085. ctx := context.TODO()
  1086. var disks []*compute.Disk
  1087. diskPage, err := client.List(ctx)
  1088. if err != nil {
  1089. return nil, fmt.Errorf("error getting disks: %v", err)
  1090. }
  1091. for diskPage.NotDone() {
  1092. for _, d := range diskPage.Values() {
  1093. d := d
  1094. disks = append(disks, &d)
  1095. }
  1096. err := diskPage.Next()
  1097. if err != nil {
  1098. return nil, fmt.Errorf("error getting next page: %v", err)
  1099. }
  1100. }
  1101. return disks, nil
  1102. }
  1103. func isDiskOrphaned(disk *compute.Disk) bool {
  1104. //TODO: needs better algorithm
  1105. return disk.DiskState == "Unattached" || disk.DiskState == "Reserved"
  1106. }
  1107. func (az *Azure) GetOrphanedResources() ([]OrphanedResource, error) {
  1108. disks, err := az.getDisks()
  1109. if err != nil {
  1110. return nil, err
  1111. }
  1112. var orphanedResources []OrphanedResource
  1113. for _, d := range disks {
  1114. if isDiskOrphaned(d) {
  1115. cost, err := az.findCostForDisk(d)
  1116. if err != nil {
  1117. return nil, err
  1118. }
  1119. or := OrphanedResource{
  1120. Kind: "disk",
  1121. Region: *d.Location,
  1122. Description: map[string]string{
  1123. "diskState": string(d.DiskState),
  1124. "timeCreated": d.TimeCreated.String(),
  1125. },
  1126. Size: d.DiskSizeGB,
  1127. MonthlyCost: &cost,
  1128. }
  1129. orphanedResources = append(orphanedResources, or)
  1130. }
  1131. }
  1132. return orphanedResources, nil
  1133. }
  1134. func (az *Azure) findCostForDisk(d *compute.Disk) (float64, error) {
  1135. if d == nil {
  1136. return 0.0, fmt.Errorf("disk is empty")
  1137. }
  1138. storageClass := string(d.Sku.Name)
  1139. if strings.EqualFold(storageClass, "Premium_LRS") {
  1140. storageClass = AzureDiskPremiumSSDStorageClass
  1141. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1142. storageClass = AzureDiskStandardSSDStorageClass
  1143. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1144. storageClass = AzureDiskStandardStorageClass
  1145. }
  1146. key := *d.Location + "," + storageClass
  1147. diskPricePerGBHour, err := strconv.ParseFloat(az.Pricing[key].PV.Cost, 64)
  1148. if err != nil {
  1149. return 0.0, fmt.Errorf("error converting to float: %s", err)
  1150. }
  1151. cost := diskPricePerGBHour * timeutil.HoursPerMonth * float64(*d.DiskSizeGB)
  1152. return cost, nil
  1153. }
  1154. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1155. remoteEnabled := env.IsRemoteEnabled()
  1156. m := make(map[string]string)
  1157. m["name"] = "Azure Cluster #1"
  1158. c, err := az.GetConfig()
  1159. if err != nil {
  1160. return nil, err
  1161. }
  1162. if c.ClusterName != "" {
  1163. m["name"] = c.ClusterName
  1164. }
  1165. m["provider"] = "Azure"
  1166. m["account"] = az.clusterAccountId
  1167. m["region"] = az.clusterRegion
  1168. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1169. m["id"] = env.GetClusterID()
  1170. return m, nil
  1171. }
  1172. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  1173. return az.Config.UpdateFromMap(a)
  1174. }
  1175. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  1176. return az.Config.Update(func(c *CustomPricing) error {
  1177. if updateType == AzureStorageUpdateType {
  1178. asc := &AzureStorageConfig{}
  1179. err := json.NewDecoder(r).Decode(&asc)
  1180. if err != nil {
  1181. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1182. }
  1183. c.AzureStorageSubscriptionID = asc.SubscriptionId
  1184. c.AzureStorageAccount = asc.AccountName
  1185. if asc.AccessKey != "" {
  1186. c.AzureStorageAccessKey = asc.AccessKey
  1187. }
  1188. c.AzureStorageContainer = asc.ContainerName
  1189. c.AzureContainerPath = asc.ContainerPath
  1190. c.AzureCloud = asc.AzureCloud
  1191. } else {
  1192. // This will block if not in a goroutine. It calls GetConfig(), which
  1193. // in turn calls GetCustomPricingData, which acquires the same lock
  1194. // that is acquired by az.Config.Update, which is the function to
  1195. // which this function gets passed, and subsequently called. Booo.
  1196. defer func() {
  1197. go az.DownloadPricingData()
  1198. }()
  1199. a := make(map[string]interface{})
  1200. err := json.NewDecoder(r).Decode(&a)
  1201. if err != nil {
  1202. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1203. }
  1204. for k, v := range a {
  1205. // Just so we consistently supply / receive the same values, uppercase the first letter.
  1206. kUpper := toTitle.String(k)
  1207. vstr, ok := v.(string)
  1208. if ok {
  1209. err := SetCustomPricingField(c, kUpper, vstr)
  1210. if err != nil {
  1211. return fmt.Errorf("error setting custom pricing field on AzureStorageConfig: %s", err)
  1212. }
  1213. } else {
  1214. return fmt.Errorf("type error while updating config for %s", kUpper)
  1215. }
  1216. }
  1217. }
  1218. if env.IsRemoteEnabled() {
  1219. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  1220. if err != nil {
  1221. return fmt.Errorf("error updating cluster metadata: %s", err)
  1222. }
  1223. }
  1224. return nil
  1225. })
  1226. }
  1227. func (az *Azure) GetConfig() (*CustomPricing, error) {
  1228. c, err := az.Config.GetCustomPricingData()
  1229. if err != nil {
  1230. return nil, err
  1231. }
  1232. if c.Discount == "" {
  1233. c.Discount = "0%"
  1234. }
  1235. if c.NegotiatedDiscount == "" {
  1236. c.NegotiatedDiscount = "0%"
  1237. }
  1238. if c.CurrencyCode == "" {
  1239. c.CurrencyCode = "USD"
  1240. }
  1241. if c.AzureBillingRegion == "" {
  1242. c.AzureBillingRegion = "US"
  1243. }
  1244. // Default to pay-as-you-go Durable offer id
  1245. if c.AzureOfferDurableID == "" {
  1246. c.AzureOfferDurableID = "MS-AZR-0003p"
  1247. }
  1248. if c.ShareTenancyCosts == "" {
  1249. c.ShareTenancyCosts = defaultShareTenancyCost
  1250. }
  1251. if c.SpotLabel == "" {
  1252. c.SpotLabel = defaultSpotLabel
  1253. }
  1254. if c.SpotLabelValue == "" {
  1255. c.SpotLabelValue = defaultSpotLabelValue
  1256. }
  1257. return c, nil
  1258. }
  1259. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1260. }
  1261. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1262. az.DownloadPricingDataLock.RLock()
  1263. defer az.DownloadPricingDataLock.RUnlock()
  1264. pricing, ok := az.Pricing[pvk.Features()]
  1265. if !ok {
  1266. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1267. return &PV{}, nil
  1268. }
  1269. return pricing.PV, nil
  1270. }
  1271. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1272. return ""
  1273. }
  1274. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1275. return az.serviceAccountChecks.getStatus()
  1276. }
  1277. const rateCardPricingSource = "Rate Card API"
  1278. // PricingSourceStatus returns the status of the rate card api
  1279. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1280. sources := make(map[string]*PricingSource)
  1281. errMsg := ""
  1282. if az.RateCardPricingError != nil {
  1283. errMsg = az.RateCardPricingError.Error()
  1284. }
  1285. rcps := &PricingSource{
  1286. Name: rateCardPricingSource,
  1287. Enabled: true,
  1288. Error: errMsg,
  1289. }
  1290. if rcps.Error != "" {
  1291. rcps.Available = false
  1292. } else if len(az.Pricing) == 0 {
  1293. rcps.Error = "No Pricing Data Available"
  1294. rcps.Available = false
  1295. } else {
  1296. rcps.Available = true
  1297. }
  1298. sources[rateCardPricingSource] = rcps
  1299. return sources
  1300. }
  1301. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1302. return "", 0.0, nil
  1303. }
  1304. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1305. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1306. }
  1307. func (az *Azure) Regions() []string {
  1308. return azureRegions
  1309. }
  1310. func parseAzureSubscriptionID(id string) string {
  1311. match := azureSubRegex.FindStringSubmatch(id)
  1312. if len(match) >= 2 {
  1313. return match[1]
  1314. }
  1315. // Return empty string if an account could not be parsed from provided string
  1316. return ""
  1317. }