provider.go 49 KB

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