azureprovider.go 32 KB

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