provider.go 49 KB

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