azureprovider.go 31 KB

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