azureprovider.go 52 KB

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