provider.go 49 KB

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