azureprovider.go 47 KB

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