azureprovider.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. package cloud
  2. import (
  3. "context"
  4. "encoding/csv"
  5. "fmt"
  6. "github.com/kubecost/cost-model/pkg/kubecost"
  7. "io"
  8. "io/ioutil"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/kubecost/cost-model/pkg/clustercache"
  15. "github.com/kubecost/cost-model/pkg/env"
  16. "github.com/kubecost/cost-model/pkg/util"
  17. "github.com/kubecost/cost-model/pkg/util/json"
  18. "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2017-09-01/skus"
  19. "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice"
  20. "github.com/Azure/azure-sdk-for-go/services/preview/commerce/mgmt/2015-06-01-preview/commerce"
  21. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
  22. "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources"
  23. "github.com/Azure/go-autorest/autorest"
  24. "github.com/Azure/go-autorest/autorest/azure"
  25. "github.com/Azure/go-autorest/autorest/azure/auth"
  26. v1 "k8s.io/api/core/v1"
  27. "k8s.io/klog"
  28. )
  29. const (
  30. AzureFilePremiumStorageClass = "premium_smb"
  31. AzureFileStandardStorageClass = "standard_smb"
  32. AzureDiskPremiumSSDStorageClass = "premium_ssd"
  33. AzureDiskStandardSSDStorageClass = "standard_ssd"
  34. AzureDiskStandardStorageClass = "standard_hdd"
  35. )
  36. var (
  37. regionCodeMappings = map[string]string{
  38. "ap": "asia",
  39. "au": "australia",
  40. "br": "brazil",
  41. "ca": "canada",
  42. "eu": "europe",
  43. "fr": "france",
  44. "in": "india",
  45. "ja": "japan",
  46. "kr": "korea",
  47. "uk": "uk",
  48. "us": "us",
  49. "za": "southafrica",
  50. }
  51. //mtBasic, _ = regexp.Compile("^BASIC.A\\d+[_Promo]*$")
  52. //mtStandardA, _ = regexp.Compile("^A\\d+[_Promo]*$")
  53. mtStandardB, _ = regexp.Compile(`^Standard_B\d+m?[_v\d]*[_Promo]*$`)
  54. mtStandardD, _ = regexp.Compile(`^Standard_D\d[_v\d]*[_Promo]*$`)
  55. mtStandardE, _ = regexp.Compile(`^Standard_E\d+i?[_v\d]*[_Promo]*$`)
  56. mtStandardF, _ = regexp.Compile(`^Standard_F\d+[_v\d]*[_Promo]*$`)
  57. mtStandardG, _ = regexp.Compile(`^Standard_G\d+[_v\d]*[_Promo]*$`)
  58. mtStandardL, _ = regexp.Compile(`^Standard_L\d+[_v\d]*[_Promo]*$`)
  59. mtStandardM, _ = regexp.Compile(`^Standard_M\d+[m|t|l]*s[_v\d]*[_Promo]*$`)
  60. mtStandardN, _ = regexp.Compile(`^Standard_N[C|D|V]\d+r?[_v\d]*[_Promo]*$`)
  61. )
  62. const AzureLayout = "2006-01-02"
  63. var HeaderStrings = []string{"MeterCategory", "UsageDateTime", "InstanceId", "AdditionalInfo", "Tags", "PreTaxCost", "SubscriptionGuid", "ConsumedService", "ResourceGroup", "ResourceType"}
  64. var loadedAzureSecret bool = false
  65. var azureSecret *AzureServiceKey = nil
  66. var loadedAzureStorageConfigSecret bool = false
  67. var azureStorageConfig *AzureStorageConfig = nil
  68. type regionParts []string
  69. func (r regionParts) String() string {
  70. var result string
  71. for _, p := range r {
  72. result += p
  73. }
  74. return result
  75. }
  76. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  77. allLocations := make(map[string]string)
  78. supLocations := make(map[string]string)
  79. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  80. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  81. // fill up the map: DisplayName - > Name
  82. for _, loc := range *locations.Value {
  83. allLocations[*loc.DisplayName] = *loc.Name
  84. }
  85. } else {
  86. return nil, err
  87. }
  88. // identify supported locations for the namespace and resource type
  89. const (
  90. providerNamespaceForCompute = "Microsoft.Compute"
  91. resourceTypeForCompute = "locations/vmSizes"
  92. providerNamespaceForAks = "Microsoft.ContainerService"
  93. resourceTypeForAks = "managedClusters"
  94. )
  95. switch service {
  96. case "aks":
  97. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  98. for _, pr := range *providers.ResourceTypes {
  99. if *pr.ResourceType == resourceTypeForAks {
  100. for _, displName := range *pr.Locations {
  101. if loc, ok := allLocations[displName]; ok {
  102. supLocations[loc] = displName
  103. } else {
  104. klog.V(1).Infof("unsupported cloud region %s", loc)
  105. }
  106. }
  107. break
  108. }
  109. }
  110. } else {
  111. return nil, err
  112. }
  113. return supLocations, nil
  114. default:
  115. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  116. for _, pr := range *providers.ResourceTypes {
  117. if *pr.ResourceType == resourceTypeForCompute {
  118. for _, displName := range *pr.Locations {
  119. if loc, ok := allLocations[displName]; ok {
  120. supLocations[loc] = displName
  121. } else {
  122. klog.V(1).Infof("unsupported cloud region %s", loc)
  123. }
  124. }
  125. break
  126. }
  127. }
  128. } else {
  129. return nil, err
  130. }
  131. return supLocations, nil
  132. }
  133. }
  134. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  135. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  136. regionCode := regionCodeMappings[rp[0]]
  137. lastPart := rp[len(rp)-1]
  138. var regionIds []string
  139. if _, err := strconv.Atoi(lastPart); err == nil {
  140. regionIds = []string{
  141. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  142. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  143. }
  144. } else {
  145. regionIds = []string{
  146. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  147. fmt.Sprintf("%s%s", rp[1:], regionCode),
  148. }
  149. }
  150. for _, regionID := range regionIds {
  151. if checkRegionID(regionID, regions) {
  152. return regionID, nil
  153. }
  154. }
  155. return "", fmt.Errorf("Couldn't find region")
  156. }
  157. func checkRegionID(regionID string, regions map[string]string) bool {
  158. for region := range regions {
  159. if regionID == region {
  160. return true
  161. }
  162. }
  163. return false
  164. }
  165. // AzurePricing either contains a Node or PV
  166. type AzurePricing struct {
  167. Node *Node
  168. PV *PV
  169. }
  170. type Azure struct {
  171. Pricing map[string]*AzurePricing
  172. DownloadPricingDataLock sync.RWMutex
  173. Clientset clustercache.ClusterCache
  174. Config *ProviderConfig
  175. ServiceAccountChecks map[string]*ServiceAccountCheck
  176. }
  177. type azureKey struct {
  178. Labels map[string]string
  179. GPULabel string
  180. GPULabelValue string
  181. }
  182. func (k *azureKey) Features() string {
  183. r, _ := util.GetRegion(k.Labels)
  184. region := strings.ToLower(r)
  185. instance, _ := util.GetInstanceType(k.Labels)
  186. usageType := "ondemand"
  187. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  188. }
  189. // GPUType returns value of GPULabel if present
  190. func (k *azureKey) GPUType() string {
  191. if t, ok := k.Labels[k.GPULabel]; ok {
  192. return t
  193. }
  194. return ""
  195. }
  196. func (k *azureKey) isValidGPUNode() bool {
  197. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  198. }
  199. func (k *azureKey) ID() string {
  200. return ""
  201. }
  202. func (k *azureKey) GetGPUCount() string {
  203. instance, _ := util.GetInstanceType(k.Labels)
  204. // Double digits that could get matches lower in logic
  205. if strings.Contains(instance, "NC64") {
  206. return "4"
  207. }
  208. if strings.Contains(instance, "ND96") ||
  209. strings.Contains(instance, "ND40") {
  210. return "8"
  211. }
  212. // Ordered asc because of some series have different gpu counts on different versions
  213. if strings.Contains(instance, "NC6") ||
  214. strings.Contains(instance, "NC4") ||
  215. strings.Contains(instance, "NC8") ||
  216. strings.Contains(instance, "NC16") ||
  217. strings.Contains(instance, "ND6") ||
  218. strings.Contains(instance, "NV12s") ||
  219. strings.Contains(instance, "NV6") {
  220. return "1"
  221. }
  222. if strings.Contains(instance, "NC12") ||
  223. strings.Contains(instance, "ND12") ||
  224. strings.Contains(instance, "NV24s") ||
  225. strings.Contains(instance, "NV12") {
  226. return "2"
  227. }
  228. if strings.Contains(instance, "NC24") ||
  229. strings.Contains(instance, "ND24") ||
  230. strings.Contains(instance, "NV48s") ||
  231. strings.Contains(instance, "NV24") {
  232. return "4"
  233. }
  234. return "0"
  235. }
  236. // Represents an azure storage config
  237. type AzureStorageConfig struct {
  238. AccountName string `json:"azureStorageAccount"`
  239. AccessKey string `json:"azureStorageAccessKey"`
  240. ContainerName string `json:"azureStorageContainer"`
  241. }
  242. // Represents an azure app key
  243. type AzureAppKey struct {
  244. AppID string `json:"appId"`
  245. DisplayName string `json:"displayName"`
  246. Name string `json:"name"`
  247. Password string `json:"password"`
  248. Tenant string `json:"tenant"`
  249. }
  250. // Azure service key for a specific subscription
  251. type AzureServiceKey struct {
  252. SubscriptionID string `json:"subscriptionId"`
  253. ServiceKey *AzureAppKey `json:"serviceKey"`
  254. }
  255. // Validity check on service key
  256. func (ask *AzureServiceKey) IsValid() bool {
  257. return ask.SubscriptionID != "" &&
  258. ask.ServiceKey != nil &&
  259. ask.ServiceKey.AppID != "" &&
  260. ask.ServiceKey.Password != "" &&
  261. ask.ServiceKey.Tenant != ""
  262. }
  263. // Loads the azure authentication via configuration or a secret set at install time.
  264. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  265. // 1. Check config values first (set from frontend UI)
  266. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  267. subscriptionID = cp.AzureSubscriptionID
  268. clientID = cp.AzureClientID
  269. clientSecret = cp.AzureClientSecret
  270. tenantID = cp.AzureTenantID
  271. return
  272. }
  273. // 2. Check for secret
  274. s, _ := az.loadAzureAuthSecret(forceReload)
  275. if s != nil && s.IsValid() {
  276. subscriptionID = s.SubscriptionID
  277. clientID = s.ServiceKey.AppID
  278. clientSecret = s.ServiceKey.Password
  279. tenantID = s.ServiceKey.Tenant
  280. return
  281. }
  282. // 3. Empty values
  283. return "", "", "", ""
  284. }
  285. func (az *Azure) ConfigureAzureStorage() error {
  286. accessKey, accountName, containerName := az.getAzureStorageConfig(false)
  287. if accessKey != "" && accountName != "" && containerName != "" {
  288. err := env.Set(env.AzureStorageAccessKeyEnvVar, accessKey)
  289. if err != nil {
  290. return err
  291. }
  292. err = env.Set(env.AzureStorageAccountNameEnvVar, accountName)
  293. if err != nil {
  294. return err
  295. }
  296. err = env.Set(env.AzureStorageContainerNameEnvVar, containerName)
  297. if err != nil {
  298. return err
  299. }
  300. }
  301. return nil
  302. }
  303. func (az *Azure) getAzureStorageConfig(forceReload bool) (accessKey, accountName, containerName string) {
  304. if az.ServiceAccountChecks == nil {
  305. az.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  306. }
  307. // 1. Check for secret
  308. s, _ := az.loadAzureStorageConfig(forceReload)
  309. if s != nil && s.AccessKey != "" && s.AccountName != "" && s.ContainerName != "" {
  310. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  311. Message: "Azure Storage Config exists",
  312. Status: true,
  313. }
  314. accessKey = s.AccessKey
  315. accountName = s.AccountName
  316. containerName = s.ContainerName
  317. return
  318. }
  319. // 3. Fall back to env vars
  320. accessKey, accountName, containerName = env.GetAzureStorageAccessKey(), env.GetAzureStorageAccountName(), env.GetAzureStorageContainerName()
  321. if accessKey != "" && accountName != "" && containerName != "" {
  322. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  323. Message: "Azure Storage Config exists",
  324. Status: true,
  325. }
  326. } else {
  327. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  328. Message: "Azure Storage Config exists",
  329. Status: false,
  330. }
  331. }
  332. return
  333. }
  334. // Load once and cache the result (even on failure). This is an install time secret, so
  335. // we don't expect the secret to change. If it does, however, we can force reload using
  336. // the input parameter.
  337. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  338. if !force && loadedAzureSecret {
  339. return azureSecret, nil
  340. }
  341. loadedAzureSecret = true
  342. exists, err := util.FileExists(authSecretPath)
  343. if !exists || err != nil {
  344. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  345. }
  346. result, err := ioutil.ReadFile(authSecretPath)
  347. if err != nil {
  348. return nil, err
  349. }
  350. var ask AzureServiceKey
  351. err = json.Unmarshal(result, &ask)
  352. if err != nil {
  353. return nil, err
  354. }
  355. azureSecret = &ask
  356. return azureSecret, nil
  357. }
  358. // Load once and cache the result (even on failure). This is an install time secret, so
  359. // we don't expect the secret to change. If it does, however, we can force reload using
  360. // the input parameter.
  361. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  362. if !force && loadedAzureStorageConfigSecret {
  363. return azureStorageConfig, nil
  364. }
  365. loadedAzureStorageConfigSecret = true
  366. exists, err := util.FileExists(storageConfigSecretPath)
  367. if !exists || err != nil {
  368. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  369. }
  370. result, err := ioutil.ReadFile(storageConfigSecretPath)
  371. if err != nil {
  372. return nil, err
  373. }
  374. var ask AzureStorageConfig
  375. err = json.Unmarshal(result, &ask)
  376. if err != nil {
  377. return nil, err
  378. }
  379. azureStorageConfig = &ask
  380. return azureStorageConfig, nil
  381. }
  382. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  383. cfg, err := az.GetConfig()
  384. if err != nil {
  385. klog.Infof("Error loading azure custom pricing information")
  386. }
  387. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  388. gpuLabel := "accelerator"
  389. gpuLabelValue := "nvidia"
  390. if cfg.GpuLabel != "" {
  391. gpuLabel = cfg.GpuLabel
  392. }
  393. if cfg.GpuLabelValue != "" {
  394. gpuLabelValue = cfg.GpuLabelValue
  395. }
  396. return &azureKey{
  397. Labels: labels,
  398. GPULabel: gpuLabel,
  399. GPULabelValue: gpuLabelValue,
  400. }
  401. }
  402. // CreateString builds strings effectively
  403. func createString(keys ...string) string {
  404. var b strings.Builder
  405. for _, key := range keys {
  406. b.WriteString(key)
  407. }
  408. return b.String()
  409. }
  410. func transformMachineType(subCategory string, mt []string) []string {
  411. switch {
  412. case strings.Contains(subCategory, "Basic"):
  413. return []string{createString("Basic_", mt[0])}
  414. case len(mt) == 2:
  415. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  416. default:
  417. return []string{createString("Standard_", mt[0])}
  418. }
  419. }
  420. func addSuffix(mt string, suffixes ...string) []string {
  421. result := make([]string, len(suffixes))
  422. var suffix string
  423. parts := strings.Split(mt, "_")
  424. if len(parts) > 2 {
  425. for _, p := range parts[2:] {
  426. suffix = createString(suffix, "_", p)
  427. }
  428. }
  429. for i, s := range suffixes {
  430. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  431. }
  432. return result
  433. }
  434. func getMachineTypeVariants(mt string) []string {
  435. switch {
  436. case mtStandardB.MatchString(mt):
  437. return []string{createString(mt, "s")}
  438. case mtStandardD.MatchString(mt):
  439. var result []string
  440. result = append(result, addSuffix(mt, "s")[0])
  441. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  442. result = append(result, dsType)
  443. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  444. return result
  445. case mtStandardE.MatchString(mt):
  446. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  447. case mtStandardF.MatchString(mt):
  448. return addSuffix(mt, "s")
  449. case mtStandardG.MatchString(mt):
  450. var result []string
  451. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  452. result = append(result, gsType)
  453. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  454. case mtStandardL.MatchString(mt):
  455. return addSuffix(mt, "s")
  456. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  457. base := strings.TrimSuffix(mt, "ms")
  458. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  459. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  460. return []string{}
  461. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  462. base := strings.TrimSuffix(mt, "s")
  463. return addSuffix(base, "", "m")
  464. case mtStandardN.MatchString(mt):
  465. return addSuffix(mt, "s")
  466. }
  467. return []string{}
  468. }
  469. func (az *Azure) GetManagementPlatform() (string, error) {
  470. nodes := az.Clientset.GetAllNodes()
  471. if len(nodes) > 0 {
  472. n := nodes[0]
  473. providerID := n.Spec.ProviderID
  474. if strings.Contains(providerID, "aks") {
  475. return "aks", nil
  476. }
  477. }
  478. return "", nil
  479. }
  480. // DownloadPricingData uses provided azure "best guesses" for pricing
  481. func (az *Azure) DownloadPricingData() error {
  482. az.DownloadPricingDataLock.Lock()
  483. defer az.DownloadPricingDataLock.Unlock()
  484. config, err := az.GetConfig()
  485. if err != nil {
  486. return err
  487. }
  488. // Load the service provider keys
  489. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(false, config)
  490. config.AzureSubscriptionID = subscriptionID
  491. config.AzureClientID = clientID
  492. config.AzureClientSecret = clientSecret
  493. config.AzureTenantID = tenantID
  494. var authorizer autorest.Authorizer
  495. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  496. credentialsConfig := auth.NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID)
  497. a, err := credentialsConfig.Authorizer()
  498. if err != nil {
  499. return err
  500. }
  501. authorizer = a
  502. }
  503. if authorizer == nil {
  504. a, err := auth.NewAuthorizerFromEnvironment()
  505. authorizer = a
  506. if err != nil { // Failed to create authorizer from environment, try from file
  507. a, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
  508. if err != nil {
  509. return err
  510. }
  511. authorizer = a
  512. }
  513. }
  514. sClient := subscriptions.NewClient()
  515. sClient.Authorizer = authorizer
  516. rcClient := commerce.NewRateCardClient(config.AzureSubscriptionID)
  517. rcClient.Authorizer = authorizer
  518. skusClient := skus.NewResourceSkusClient(config.AzureSubscriptionID)
  519. skusClient.Authorizer = authorizer
  520. providersClient := resources.NewProvidersClient(config.AzureSubscriptionID)
  521. providersClient.Authorizer = authorizer
  522. containerServiceClient := containerservice.NewContainerServicesClient(config.AzureSubscriptionID)
  523. containerServiceClient.Authorizer = authorizer
  524. rateCardFilter := fmt.Sprintf("OfferDurableId eq 'MS-AZR-0003p' and Currency eq '%s' and Locale eq 'en-US' and RegionInfo eq '%s'", config.CurrencyCode, config.AzureBillingRegion)
  525. klog.Infof("Using ratecard query %s", rateCardFilter)
  526. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  527. if err != nil {
  528. return err
  529. }
  530. allPrices := make(map[string]*AzurePricing)
  531. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  532. if err != nil {
  533. return err
  534. }
  535. c, err := az.GetConfig()
  536. if err != nil {
  537. return err
  538. }
  539. baseCPUPrice := c.CPU
  540. for _, v := range *result.Meters {
  541. meterName := *v.MeterName
  542. meterRegion := *v.MeterRegion
  543. meterCategory := *v.MeterCategory
  544. meterSubCategory := *v.MeterSubCategory
  545. region, err := toRegionID(meterRegion, regions)
  546. if err != nil {
  547. continue
  548. }
  549. if !strings.Contains(meterSubCategory, "Windows") {
  550. if strings.Contains(meterCategory, "Storage") {
  551. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  552. var storageClass string = ""
  553. if strings.Contains(meterName, "P4 ") {
  554. storageClass = AzureDiskPremiumSSDStorageClass
  555. } else if strings.Contains(meterName, "E4 ") {
  556. storageClass = AzureDiskStandardSSDStorageClass
  557. } else if strings.Contains(meterName, "S4 ") {
  558. storageClass = AzureDiskStandardStorageClass
  559. } else if strings.Contains(meterName, "LRS Provisioned") {
  560. storageClass = AzureFilePremiumStorageClass
  561. }
  562. if storageClass != "" {
  563. var priceInUsd float64
  564. if len(v.MeterRates) < 1 {
  565. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  566. continue
  567. }
  568. for _, rate := range v.MeterRates {
  569. priceInUsd += *rate
  570. }
  571. // rate is in disk per month, resolve price per hour, then GB per hour
  572. pricePerHour := priceInUsd / 730.0 / 32.0
  573. priceStr := fmt.Sprintf("%f", pricePerHour)
  574. key := region + "," + storageClass
  575. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  576. allPrices[key] = &AzurePricing{
  577. PV: &PV{
  578. Cost: priceStr,
  579. Region: region,
  580. },
  581. }
  582. }
  583. }
  584. }
  585. if strings.Contains(meterCategory, "Virtual Machines") {
  586. usageType := ""
  587. if !strings.Contains(meterName, "Low Priority") {
  588. usageType = "ondemand"
  589. } else {
  590. usageType = "preemptible"
  591. }
  592. var instanceTypes []string
  593. name := strings.TrimSuffix(meterName, " Low Priority")
  594. instanceType := strings.Split(name, "/")
  595. for _, it := range instanceType {
  596. if strings.Contains(meterSubCategory, "Promo") {
  597. it = it + " Promo"
  598. }
  599. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  600. }
  601. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  602. if strings.Contains(name, "Expired") {
  603. instanceTypes = []string{}
  604. }
  605. var priceInUsd float64
  606. if len(v.MeterRates) < 1 {
  607. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  608. continue
  609. }
  610. for _, rate := range v.MeterRates {
  611. priceInUsd += *rate
  612. }
  613. priceStr := fmt.Sprintf("%f", priceInUsd)
  614. for _, instanceType := range instanceTypes {
  615. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  616. allPrices[key] = &AzurePricing{
  617. Node: &Node{
  618. Cost: priceStr,
  619. BaseCPUPrice: baseCPUPrice,
  620. },
  621. }
  622. }
  623. }
  624. }
  625. }
  626. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  627. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  628. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  629. zeroPrice := "0.0"
  630. for region := range regions {
  631. key := region + "," + AzureFileStandardStorageClass
  632. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  633. allPrices[key] = &AzurePricing{
  634. PV: &PV{
  635. Cost: zeroPrice,
  636. Region: region,
  637. },
  638. }
  639. }
  640. az.Pricing = allPrices
  641. return nil
  642. }
  643. // AllNodePricing returns the Azure pricing objects stored
  644. func (az *Azure) AllNodePricing() (interface{}, error) {
  645. az.DownloadPricingDataLock.RLock()
  646. defer az.DownloadPricingDataLock.RUnlock()
  647. return az.Pricing, nil
  648. }
  649. // NodePricing returns Azure pricing data for a single node
  650. func (az *Azure) NodePricing(key Key) (*Node, error) {
  651. az.DownloadPricingDataLock.RLock()
  652. defer az.DownloadPricingDataLock.RUnlock()
  653. azKey, ok := key.(*azureKey)
  654. if !ok {
  655. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  656. }
  657. if n, ok := az.Pricing[azKey.Features()]; ok {
  658. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  659. if azKey.isValidGPUNode() {
  660. n.Node.GPU = azKey.GetGPUCount()
  661. }
  662. return n.Node, nil
  663. }
  664. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", azKey.Features(), azKey)
  665. c, err := az.GetConfig()
  666. if err != nil {
  667. return nil, fmt.Errorf("No default pricing data available")
  668. }
  669. if azKey.isValidGPUNode() {
  670. return &Node{
  671. VCPUCost: c.CPU,
  672. RAMCost: c.RAM,
  673. UsesBaseCPUPrice: true,
  674. GPUCost: c.GPU,
  675. GPU: azKey.GetGPUCount(),
  676. }, nil
  677. }
  678. return &Node{
  679. VCPUCost: c.CPU,
  680. RAMCost: c.RAM,
  681. UsesBaseCPUPrice: true,
  682. }, nil
  683. }
  684. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  685. func (az *Azure) NetworkPricing() (*Network, error) {
  686. cpricing, err := az.Config.GetCustomPricingData()
  687. if err != nil {
  688. return nil, err
  689. }
  690. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  691. if err != nil {
  692. return nil, err
  693. }
  694. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  695. if err != nil {
  696. return nil, err
  697. }
  698. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  699. if err != nil {
  700. return nil, err
  701. }
  702. return &Network{
  703. ZoneNetworkEgressCost: znec,
  704. RegionNetworkEgressCost: rnec,
  705. InternetNetworkEgressCost: inec,
  706. }, nil
  707. }
  708. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  709. fffrc := 0.025
  710. afrc := 0.010
  711. lbidc := 0.008
  712. numForwardingRules := 1.0
  713. dataIngressGB := 0.0
  714. var totalCost float64
  715. if numForwardingRules < 5 {
  716. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  717. } else {
  718. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  719. }
  720. return &LoadBalancer{
  721. Cost: totalCost,
  722. }, nil
  723. }
  724. type azurePvKey struct {
  725. Labels map[string]string
  726. StorageClass string
  727. StorageClassParameters map[string]string
  728. DefaultRegion string
  729. ProviderId string
  730. }
  731. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  732. providerID := ""
  733. if pv.Spec.AzureDisk != nil {
  734. providerID = pv.Spec.AzureDisk.DiskName
  735. }
  736. return &azurePvKey{
  737. Labels: pv.Labels,
  738. StorageClass: pv.Spec.StorageClassName,
  739. StorageClassParameters: parameters,
  740. DefaultRegion: defaultRegion,
  741. ProviderId: providerID,
  742. }
  743. }
  744. func (key *azurePvKey) ID() string {
  745. return key.ProviderId
  746. }
  747. func (key *azurePvKey) GetStorageClass() string {
  748. return key.StorageClass
  749. }
  750. func (key *azurePvKey) Features() string {
  751. storageClass := key.StorageClassParameters["storageaccounttype"]
  752. storageSKU := key.StorageClassParameters["skuName"]
  753. if storageClass != "" {
  754. if strings.EqualFold(storageClass, "Premium_LRS") {
  755. storageClass = AzureDiskPremiumSSDStorageClass
  756. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  757. storageClass = AzureDiskStandardSSDStorageClass
  758. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  759. storageClass = AzureDiskStandardStorageClass
  760. }
  761. } else {
  762. if strings.EqualFold(storageSKU, "Premium_LRS") {
  763. storageClass = AzureFilePremiumStorageClass
  764. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  765. storageClass = AzureFileStandardStorageClass
  766. }
  767. }
  768. if region, ok := util.GetRegion(key.Labels); ok {
  769. return region + "," + storageClass
  770. }
  771. return key.DefaultRegion + "," + storageClass
  772. }
  773. func (*Azure) GetAddresses() ([]byte, error) {
  774. return nil, nil
  775. }
  776. func (*Azure) GetDisks() ([]byte, error) {
  777. return nil, nil
  778. }
  779. func (az *Azure) ClusterInfo() (map[string]string, error) {
  780. remoteEnabled := env.IsRemoteEnabled()
  781. m := make(map[string]string)
  782. m["name"] = "Azure Cluster #1"
  783. c, err := az.GetConfig()
  784. if err != nil {
  785. return nil, err
  786. }
  787. if c.ClusterName != "" {
  788. m["name"] = c.ClusterName
  789. }
  790. m["provider"] = "azure"
  791. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  792. m["id"] = env.GetClusterID()
  793. return m, nil
  794. }
  795. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  796. return az.Config.UpdateFromMap(a)
  797. }
  798. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  799. defer az.DownloadPricingData()
  800. return az.Config.Update(func(c *CustomPricing) error {
  801. a := make(map[string]interface{})
  802. err := json.NewDecoder(r).Decode(&a)
  803. if err != nil {
  804. return err
  805. }
  806. for k, v := range a {
  807. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  808. vstr, ok := v.(string)
  809. if ok {
  810. err := SetCustomPricingField(c, kUpper, vstr)
  811. if err != nil {
  812. return err
  813. }
  814. } else {
  815. sci := v.(map[string]interface{})
  816. sc := make(map[string]string)
  817. for k, val := range sci {
  818. sc[k] = val.(string)
  819. }
  820. c.SharedCosts = sc //todo: support reflection/multiple map fields
  821. }
  822. }
  823. if env.IsRemoteEnabled() {
  824. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  825. if err != nil {
  826. return err
  827. }
  828. }
  829. return nil
  830. })
  831. }
  832. func (az *Azure) GetConfig() (*CustomPricing, error) {
  833. c, err := az.Config.GetCustomPricingData()
  834. if c.Discount == "" {
  835. c.Discount = "0%"
  836. }
  837. if c.NegotiatedDiscount == "" {
  838. c.NegotiatedDiscount = "0%"
  839. }
  840. if c.CurrencyCode == "" {
  841. c.CurrencyCode = "USD"
  842. }
  843. if c.AzureBillingRegion == "" {
  844. c.AzureBillingRegion = "US"
  845. }
  846. if err != nil {
  847. return nil, err
  848. }
  849. return c, nil
  850. }
  851. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  852. // "start" and "end" are dates of the format YYYY-MM-DD
  853. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  854. func (az *Azure) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  855. var csvRetriever CSVRetriever = AzureCSVRetriever{}
  856. err := az.ConfigureAzureStorage() // load Azure Storage config
  857. if err != nil {
  858. return nil, err
  859. }
  860. return getExternalAllocations(start, end, aggregators, filterType, filterValue, crossCluster, csvRetriever)
  861. }
  862. func getExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool, csvRetriever CSVRetriever) ([]*OutOfClusterAllocation, error) {
  863. dateFormat := "2006-1-2"
  864. startTime, err := time.Parse(dateFormat, start)
  865. if err != nil {
  866. return nil, err
  867. }
  868. endTime, err := time.Parse(dateFormat, end)
  869. if err != nil {
  870. return nil, err
  871. }
  872. readers, err := csvRetriever.GetCSVReaders(startTime, endTime)
  873. if err != nil {
  874. return nil, err
  875. }
  876. oocAllocs := make(map[string]*OutOfClusterAllocation)
  877. for _, reader := range readers {
  878. err = parseCSV(reader, startTime, endTime, oocAllocs, aggregators, filterType, filterValue, crossCluster)
  879. if err != nil {
  880. return nil, err
  881. }
  882. }
  883. var oocAllocsArr []*OutOfClusterAllocation
  884. for _, alloc := range oocAllocs {
  885. oocAllocsArr = append(oocAllocsArr, alloc)
  886. }
  887. return oocAllocsArr, nil
  888. }
  889. func parseCSV(reader *csv.Reader, start, end time.Time, oocAllocs map[string]*OutOfClusterAllocation, aggregators []string, filterType string, filterValue string, crossCluster bool) error {
  890. headers, _ := reader.Read()
  891. headerMap := createHeaderMap(headers)
  892. for {
  893. var record, err = reader.Read()
  894. if err == io.EOF {
  895. break
  896. }
  897. if err != nil {
  898. return err
  899. }
  900. meterCategory := record[headerMap["MeterCategory"]]
  901. category := selectCategory(meterCategory)
  902. usageDateTime, err := time.Parse(AzureLayout, record[headerMap["UsageDateTime"]])
  903. if err != nil {
  904. klog.Errorf("failed to parse usage date: '%s'", record[headerMap["UsageDateTime"]])
  905. continue
  906. }
  907. // Ignore VM's and Storage Items for now
  908. if category == kubecost.ComputeCategory || category == kubecost.StorageCategory || !isValidUsageDateTime(start, end, usageDateTime) {
  909. continue
  910. }
  911. itemCost, err := strconv.ParseFloat(record[headerMap["PreTaxCost"]], 64)
  912. if err != nil {
  913. klog.Infof("failed to parse cost: '%s'", record[headerMap["PreTaxCost"]])
  914. continue
  915. }
  916. itemTags := make(map[string]string)
  917. itemTagJson := makeValidJSON(record[headerMap["Tags"]])
  918. if itemTagJson != "" {
  919. err = json.Unmarshal([]byte(itemTagJson), &itemTags)
  920. if err != nil {
  921. klog.Infof("Could not parse item tags %v", err)
  922. }
  923. }
  924. if filterType != "kubernetes_" {
  925. if value, ok := itemTags[filterType]; !ok || value != filterValue {
  926. continue
  927. }
  928. }
  929. environment := ""
  930. for _, agg := range aggregators {
  931. if tag, ok := itemTags[agg]; ok {
  932. environment = tag // just set to the first nonempty match
  933. break
  934. }
  935. }
  936. key := environment + record[headerMap["ConsumedService"]]
  937. if alloc, ok := oocAllocs[key]; ok {
  938. alloc.Cost += itemCost
  939. } else {
  940. ooc := &OutOfClusterAllocation{
  941. Aggregator: strings.Join(aggregators, ","),
  942. Environment: environment,
  943. Service: record[headerMap["ConsumedService"]],
  944. Cost: itemCost,
  945. }
  946. oocAllocs[key] = ooc
  947. }
  948. }
  949. return nil
  950. }
  951. func createHeaderMap(headers []string) map[string]int {
  952. headerMap := make(map[string]int)
  953. for i, header := range headers {
  954. for _, headerString := range HeaderStrings {
  955. if strings.Contains(header, headerString) {
  956. headerMap[headerString] = i
  957. }
  958. }
  959. }
  960. return headerMap
  961. }
  962. func makeValidJSON(jsonString string) string {
  963. if jsonString == "" || (jsonString[0] == '{' && jsonString[len(jsonString)-1] == '}') {
  964. return jsonString
  965. }
  966. return fmt.Sprintf("{%v}", jsonString)
  967. }
  968. // UsageDateTime only contains date information and not time because of this filtering usageDate time is inclusive on start and exclusive on end
  969. func isValidUsageDateTime(start, end, usageDateTime time.Time) bool {
  970. return (usageDateTime.After(start) || usageDateTime.Equal(start)) && usageDateTime.Before(end)
  971. }
  972. func getStartAndEndTimes(usageDateTime time.Time) (time.Time, time.Time) {
  973. start := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 0, 0, 0, 0, usageDateTime.Location())
  974. end := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 23, 59, 59, 999999999, usageDateTime.Location())
  975. return start, end
  976. }
  977. func selectCategory(meterCategory string) string {
  978. if meterCategory == "Virtual Machines" {
  979. return kubecost.ComputeCategory
  980. } else if meterCategory == "Storage" {
  981. return kubecost.StorageCategory
  982. } else if meterCategory == "Load Balancer" || meterCategory == "Bandwidth" {
  983. return kubecost.NetworkCategory
  984. } else {
  985. return kubecost.OtherCategory
  986. }
  987. }
  988. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  989. }
  990. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  991. az.DownloadPricingDataLock.RLock()
  992. defer az.DownloadPricingDataLock.RUnlock()
  993. pricing, ok := az.Pricing[pvk.Features()]
  994. if !ok {
  995. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  996. return &PV{}, nil
  997. }
  998. return pricing.PV, nil
  999. }
  1000. func (az *Azure) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  1001. return ""
  1002. }
  1003. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1004. checks := []*ServiceAccountCheck{}
  1005. for _, v := range az.ServiceAccountChecks {
  1006. checks = append(checks, v)
  1007. }
  1008. return &ServiceAccountStatus{
  1009. Checks: checks,
  1010. }
  1011. }
  1012. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1013. return make(map[string]*PricingSource)
  1014. }
  1015. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1016. return "", 0.0, nil
  1017. }
  1018. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1019. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1020. }
  1021. func (az *Azure) ParseID(id string) string {
  1022. return id
  1023. }
  1024. func (az *Azure) ParsePVID(id string) string {
  1025. return id
  1026. }
  1027. func (az *Azure) ParseLBID(id string) string {
  1028. return id
  1029. }