azureprovider.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. pricingDataExists := true
  960. if az.Pricing == nil {
  961. pricingDataExists = false
  962. log.DedupedWarningf(1, "Unable to download Azure pricing data")
  963. }
  964. azKey, ok := key.(*azureKey)
  965. if !ok {
  966. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  967. }
  968. config, _ := az.GetConfig()
  969. // Spot Node
  970. if slv, ok := azKey.Labels[config.SpotLabel]; ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  971. features := strings.Split(azKey.Features(), ",")
  972. region := features[0]
  973. instance := features[1]
  974. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  975. if n, ok := az.Pricing[spotFeatures]; ok {
  976. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  977. if azKey.isValidGPUNode() {
  978. n.Node.GPU = "1" // TODO: support multiple GPUs
  979. }
  980. return n.Node, nil
  981. }
  982. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  983. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  984. if err != nil {
  985. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  986. } else {
  987. gpu := ""
  988. if azKey.isValidGPUNode() {
  989. gpu = "1"
  990. }
  991. spotNode := &Node{
  992. Cost: spotCost,
  993. UsageType: "spot",
  994. GPU: gpu,
  995. }
  996. az.addPricing(spotFeatures, &AzurePricing{
  997. Node: spotNode,
  998. })
  999. return spotNode, nil
  1000. }
  1001. }
  1002. // Use the downloaded pricing data if possible. Otherwise, use default
  1003. // configured pricing data.
  1004. if pricingDataExists {
  1005. if n, ok := az.Pricing[azKey.Features()]; ok {
  1006. log.Debugf("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  1007. if azKey.isValidGPUNode() {
  1008. n.Node.GPU = azKey.GetGPUCount()
  1009. }
  1010. return n.Node, nil
  1011. }
  1012. log.DedupedWarningf(5, "No pricing data found for node %s from key %s", azKey, azKey.Features())
  1013. }
  1014. c, err := az.GetConfig()
  1015. if err != nil {
  1016. return nil, fmt.Errorf("No default pricing data available")
  1017. }
  1018. // GPU Node
  1019. if azKey.isValidGPUNode() {
  1020. return &Node{
  1021. VCPUCost: c.CPU,
  1022. RAMCost: c.RAM,
  1023. UsesBaseCPUPrice: true,
  1024. GPUCost: c.GPU,
  1025. GPU: azKey.GetGPUCount(),
  1026. }, nil
  1027. }
  1028. // Serverless Node. This is an Azure Container Instance, and no pods can be
  1029. // scheduled to this node. Azure does not charge for this node. Set costs to
  1030. // zero.
  1031. if azKey.Labels["kubernetes.io/hostname"] == "virtual-node-aci-linux" {
  1032. return &Node{
  1033. VCPUCost: "0",
  1034. RAMCost: "0",
  1035. }, nil
  1036. }
  1037. // Regular Node
  1038. return &Node{
  1039. VCPUCost: c.CPU,
  1040. RAMCost: c.RAM,
  1041. UsesBaseCPUPrice: true,
  1042. }, nil
  1043. }
  1044. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  1045. func (az *Azure) NetworkPricing() (*Network, error) {
  1046. cpricing, err := az.Config.GetCustomPricingData()
  1047. if err != nil {
  1048. return nil, err
  1049. }
  1050. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  1055. if err != nil {
  1056. return nil, err
  1057. }
  1058. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  1059. if err != nil {
  1060. return nil, err
  1061. }
  1062. return &Network{
  1063. ZoneNetworkEgressCost: znec,
  1064. RegionNetworkEgressCost: rnec,
  1065. InternetNetworkEgressCost: inec,
  1066. }, nil
  1067. }
  1068. // LoadBalancerPricing on Azure, LoadBalancer services correspond to public IPs. For now the pricing of LoadBalancer
  1069. // services will be that of a standard static public IP https://azure.microsoft.com/en-us/pricing/details/ip-addresses/.
  1070. // Azure still has load balancers which follow the standard pricing scheme based on rules
  1071. // https://azure.microsoft.com/en-us/pricing/details/load-balancer/, they are created on a per-cluster basis.
  1072. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  1073. return &LoadBalancer{
  1074. Cost: 0.005,
  1075. }, nil
  1076. }
  1077. type azurePvKey struct {
  1078. Labels map[string]string
  1079. StorageClass string
  1080. StorageClassParameters map[string]string
  1081. DefaultRegion string
  1082. ProviderId string
  1083. }
  1084. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  1085. providerID := ""
  1086. if pv.Spec.AzureDisk != nil {
  1087. providerID = pv.Spec.AzureDisk.DiskName
  1088. }
  1089. return &azurePvKey{
  1090. Labels: pv.Labels,
  1091. StorageClass: pv.Spec.StorageClassName,
  1092. StorageClassParameters: parameters,
  1093. DefaultRegion: defaultRegion,
  1094. ProviderId: providerID,
  1095. }
  1096. }
  1097. func (key *azurePvKey) ID() string {
  1098. return key.ProviderId
  1099. }
  1100. func (key *azurePvKey) GetStorageClass() string {
  1101. return key.StorageClass
  1102. }
  1103. func (key *azurePvKey) Features() string {
  1104. storageClass := key.StorageClassParameters["storageaccounttype"]
  1105. storageSKU := key.StorageClassParameters["skuName"]
  1106. if storageClass != "" {
  1107. if strings.EqualFold(storageClass, "Premium_LRS") {
  1108. storageClass = AzureDiskPremiumSSDStorageClass
  1109. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1110. storageClass = AzureDiskStandardSSDStorageClass
  1111. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1112. storageClass = AzureDiskStandardStorageClass
  1113. }
  1114. } else {
  1115. if strings.EqualFold(storageSKU, "Premium_LRS") {
  1116. storageClass = AzureFilePremiumStorageClass
  1117. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  1118. storageClass = AzureFileStandardStorageClass
  1119. }
  1120. }
  1121. if region, ok := util.GetRegion(key.Labels); ok {
  1122. return region + "," + storageClass
  1123. }
  1124. return key.DefaultRegion + "," + storageClass
  1125. }
  1126. func (*Azure) GetAddresses() ([]byte, error) {
  1127. return nil, nil
  1128. }
  1129. func (az *Azure) GetDisks() ([]byte, error) {
  1130. disks, err := az.getDisks()
  1131. if err != nil {
  1132. return nil, err
  1133. }
  1134. return json.Marshal(disks)
  1135. }
  1136. func (az *Azure) getDisks() ([]*compute.Disk, error) {
  1137. config, err := az.GetConfig()
  1138. if err != nil {
  1139. return nil, err
  1140. }
  1141. // Load the service provider keys
  1142. subscriptionID, clientID, clientSecret, tenantID := az.getAzureRateCardAuth(false, config)
  1143. config.AzureSubscriptionID = subscriptionID
  1144. config.AzureClientID = clientID
  1145. config.AzureClientSecret = clientSecret
  1146. config.AzureTenantID = tenantID
  1147. var authorizer autorest.Authorizer
  1148. azureEnv := determineCloudByRegion(az.clusterRegion)
  1149. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  1150. credentialsConfig := NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID, azureEnv)
  1151. a, err := credentialsConfig.Authorizer()
  1152. if err != nil {
  1153. az.rateCardPricingError = err
  1154. return nil, err
  1155. }
  1156. authorizer = a
  1157. }
  1158. if authorizer == nil {
  1159. a, err := auth.NewAuthorizerFromEnvironment()
  1160. authorizer = a
  1161. if err != nil {
  1162. a, err := auth.NewAuthorizerFromFile(azureEnv.ResourceManagerEndpoint)
  1163. if err != nil {
  1164. az.rateCardPricingError = err
  1165. return nil, err
  1166. }
  1167. authorizer = a
  1168. }
  1169. }
  1170. client := compute.NewDisksClient(config.AzureSubscriptionID)
  1171. client.Authorizer = authorizer
  1172. ctx := context.TODO()
  1173. var disks []*compute.Disk
  1174. diskPage, err := client.List(ctx)
  1175. if err != nil {
  1176. return nil, fmt.Errorf("error getting disks: %v", err)
  1177. }
  1178. for diskPage.NotDone() {
  1179. for _, d := range diskPage.Values() {
  1180. d := d
  1181. disks = append(disks, &d)
  1182. }
  1183. err := diskPage.NextWithContext(context.Background())
  1184. if err != nil {
  1185. return nil, fmt.Errorf("error getting next page: %v", err)
  1186. }
  1187. }
  1188. return disks, nil
  1189. }
  1190. func (az *Azure) isDiskOrphaned(disk *compute.Disk) bool {
  1191. //TODO: needs better algorithm
  1192. return disk.DiskState == "Unattached" || disk.DiskState == "Reserved"
  1193. }
  1194. func (az *Azure) GetOrphanedResources() ([]OrphanedResource, error) {
  1195. disks, err := az.getDisks()
  1196. if err != nil {
  1197. return nil, err
  1198. }
  1199. var orphanedResources []OrphanedResource
  1200. for _, d := range disks {
  1201. if az.isDiskOrphaned(d) {
  1202. cost, err := az.findCostForDisk(d)
  1203. if err != nil {
  1204. return nil, err
  1205. }
  1206. diskName := ""
  1207. if d.Name != nil {
  1208. diskName = *d.Name
  1209. }
  1210. diskRegion := ""
  1211. if d.Location != nil {
  1212. diskRegion = *d.Location
  1213. }
  1214. var diskSize int64
  1215. if d.DiskSizeGB != nil {
  1216. diskSize = int64(*d.DiskSizeGB)
  1217. }
  1218. desc := map[string]string{}
  1219. for k, v := range d.Tags {
  1220. if v == nil {
  1221. desc[k] = ""
  1222. } else {
  1223. desc[k] = *v
  1224. }
  1225. }
  1226. or := OrphanedResource{
  1227. Kind: "disk",
  1228. Region: diskRegion,
  1229. Description: desc,
  1230. Size: &diskSize,
  1231. DiskName: diskName,
  1232. MonthlyCost: &cost,
  1233. }
  1234. orphanedResources = append(orphanedResources, or)
  1235. }
  1236. }
  1237. return orphanedResources, nil
  1238. }
  1239. func (az *Azure) findCostForDisk(d *compute.Disk) (float64, error) {
  1240. if d == nil {
  1241. return 0.0, fmt.Errorf("disk is empty")
  1242. }
  1243. storageClass := string(d.Sku.Name)
  1244. if strings.EqualFold(storageClass, "Premium_LRS") {
  1245. storageClass = AzureDiskPremiumSSDStorageClass
  1246. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  1247. storageClass = AzureDiskStandardSSDStorageClass
  1248. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  1249. storageClass = AzureDiskStandardStorageClass
  1250. }
  1251. key := *d.Location + "," + storageClass
  1252. diskPricePerGBHour, err := strconv.ParseFloat(az.Pricing[key].PV.Cost, 64)
  1253. if err != nil {
  1254. return 0.0, fmt.Errorf("error converting to float: %s", err)
  1255. }
  1256. cost := diskPricePerGBHour * timeutil.HoursPerMonth * float64(*d.DiskSizeGB)
  1257. return cost, nil
  1258. }
  1259. func (az *Azure) ClusterInfo() (map[string]string, error) {
  1260. remoteEnabled := env.IsRemoteEnabled()
  1261. m := make(map[string]string)
  1262. m["name"] = "Azure Cluster #1"
  1263. c, err := az.GetConfig()
  1264. if err != nil {
  1265. return nil, err
  1266. }
  1267. if c.ClusterName != "" {
  1268. m["name"] = c.ClusterName
  1269. }
  1270. m["provider"] = kubecost.AzureProvider
  1271. m["account"] = az.clusterAccountID
  1272. m["region"] = az.clusterRegion
  1273. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1274. m["id"] = env.GetClusterID()
  1275. return m, nil
  1276. }
  1277. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  1278. return az.Config.UpdateFromMap(a)
  1279. }
  1280. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  1281. return az.Config.Update(func(c *CustomPricing) error {
  1282. if updateType == AzureStorageUpdateType {
  1283. asc := &AzureStorageConfig{}
  1284. err := json.NewDecoder(r).Decode(&asc)
  1285. if err != nil {
  1286. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1287. }
  1288. c.AzureStorageSubscriptionID = asc.SubscriptionId
  1289. c.AzureStorageAccount = asc.AccountName
  1290. if asc.AccessKey != "" {
  1291. c.AzureStorageAccessKey = asc.AccessKey
  1292. }
  1293. c.AzureStorageContainer = asc.ContainerName
  1294. c.AzureContainerPath = asc.ContainerPath
  1295. c.AzureCloud = asc.AzureCloud
  1296. } else {
  1297. // This will block if not in a goroutine. It calls GetConfig(), which
  1298. // in turn calls GetCustomPricingData, which acquires the same lock
  1299. // that is acquired by az.Config.Update, which is the function to
  1300. // which this function gets passed, and subsequently called. Booo.
  1301. defer func() {
  1302. go az.DownloadPricingData()
  1303. }()
  1304. a := make(map[string]interface{})
  1305. err := json.NewDecoder(r).Decode(&a)
  1306. if err != nil {
  1307. return fmt.Errorf("error decoding AzureStorageConfig: %s", err)
  1308. }
  1309. for k, v := range a {
  1310. // Just so we consistently supply / receive the same values, uppercase the first letter.
  1311. kUpper := toTitle.String(k)
  1312. vstr, ok := v.(string)
  1313. if ok {
  1314. err := SetCustomPricingField(c, kUpper, vstr)
  1315. if err != nil {
  1316. return fmt.Errorf("error setting custom pricing field on AzureStorageConfig: %s", err)
  1317. }
  1318. } else {
  1319. return fmt.Errorf("type error while updating config for %s", kUpper)
  1320. }
  1321. }
  1322. }
  1323. if env.IsRemoteEnabled() {
  1324. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  1325. if err != nil {
  1326. return fmt.Errorf("error updating cluster metadata: %s", err)
  1327. }
  1328. }
  1329. return nil
  1330. })
  1331. }
  1332. func (az *Azure) GetConfig() (*CustomPricing, error) {
  1333. c, err := az.Config.GetCustomPricingData()
  1334. if err != nil {
  1335. return nil, err
  1336. }
  1337. if c.Discount == "" {
  1338. c.Discount = "0%"
  1339. }
  1340. if c.NegotiatedDiscount == "" {
  1341. c.NegotiatedDiscount = "0%"
  1342. }
  1343. if c.CurrencyCode == "" {
  1344. c.CurrencyCode = "USD"
  1345. }
  1346. if c.AzureBillingRegion == "" {
  1347. c.AzureBillingRegion = "US"
  1348. }
  1349. // Default to pay-as-you-go Durable offer id
  1350. if c.AzureOfferDurableID == "" {
  1351. c.AzureOfferDurableID = "MS-AZR-0003p"
  1352. }
  1353. if c.ShareTenancyCosts == "" {
  1354. c.ShareTenancyCosts = defaultShareTenancyCost
  1355. }
  1356. if c.SpotLabel == "" {
  1357. c.SpotLabel = defaultSpotLabel
  1358. }
  1359. if c.SpotLabelValue == "" {
  1360. c.SpotLabelValue = defaultSpotLabelValue
  1361. }
  1362. return c, nil
  1363. }
  1364. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1365. }
  1366. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1367. az.DownloadPricingDataLock.RLock()
  1368. defer az.DownloadPricingDataLock.RUnlock()
  1369. pricing, ok := az.Pricing[pvk.Features()]
  1370. if !ok {
  1371. log.Debugf("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1372. return &PV{}, nil
  1373. }
  1374. return pricing.PV, nil
  1375. }
  1376. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1377. return ""
  1378. }
  1379. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1380. return az.serviceAccountChecks.getStatus()
  1381. }
  1382. const (
  1383. rateCardPricingSource = "Rate Card API"
  1384. priceSheetPricingSource = "Price Sheet API"
  1385. )
  1386. // PricingSourceStatus returns the status of the rate card api
  1387. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1388. az.DownloadPricingDataLock.Lock()
  1389. defer az.DownloadPricingDataLock.Unlock()
  1390. sources := make(map[string]*PricingSource)
  1391. errMsg := ""
  1392. if az.rateCardPricingError != nil {
  1393. errMsg = az.rateCardPricingError.Error()
  1394. }
  1395. rcps := &PricingSource{
  1396. Name: rateCardPricingSource,
  1397. Enabled: az.pricingSource == rateCardPricingSource,
  1398. Error: errMsg,
  1399. }
  1400. if rcps.Error != "" {
  1401. rcps.Available = false
  1402. } else if len(az.Pricing) == 0 {
  1403. rcps.Error = "No Pricing Data Available"
  1404. rcps.Available = false
  1405. } else {
  1406. rcps.Available = true
  1407. }
  1408. errMsg = ""
  1409. if az.priceSheetPricingError != nil {
  1410. errMsg = az.priceSheetPricingError.Error()
  1411. }
  1412. psps := &PricingSource{
  1413. Name: priceSheetPricingSource,
  1414. Enabled: az.pricingSource == priceSheetPricingSource,
  1415. Error: errMsg,
  1416. }
  1417. if psps.Error != "" {
  1418. psps.Available = false
  1419. } else if len(az.Pricing) == 0 {
  1420. psps.Error = "No Pricing Data Available"
  1421. psps.Available = false
  1422. } else if env.GetAzureBillingAccount() == "" {
  1423. psps.Error = "No Azure Billing Account ID"
  1424. psps.Available = false
  1425. } else {
  1426. psps.Available = true
  1427. }
  1428. sources[rateCardPricingSource] = rcps
  1429. sources[priceSheetPricingSource] = psps
  1430. return sources
  1431. }
  1432. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1433. return "", 0.0, nil
  1434. }
  1435. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1436. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1437. }
  1438. func (az *Azure) Regions() []string {
  1439. regionOverrides := env.GetRegionOverrideList()
  1440. if len(regionOverrides) > 0 {
  1441. log.Debugf("Overriding Azure regions with configured region list: %+v", regionOverrides)
  1442. return regionOverrides
  1443. }
  1444. return azureRegions
  1445. }
  1446. func parseAzureSubscriptionID(id string) string {
  1447. match := azureSubRegex.FindStringSubmatch(id)
  1448. if len(match) >= 2 {
  1449. return match[1]
  1450. }
  1451. // Return empty string if an account could not be parsed from provided string
  1452. return ""
  1453. }