azureprovider.go 43 KB

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