provider.go 51 KB

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