azureprovider.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. }
  686. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  687. return &azurePvKey{
  688. Labels: pv.Labels,
  689. StorageClass: pv.Spec.StorageClassName,
  690. StorageClassParameters: parameters,
  691. DefaultRegion: defaultRegion,
  692. }
  693. }
  694. func (key *azurePvKey) ID() string {
  695. return ""
  696. }
  697. func (key *azurePvKey) GetStorageClass() string {
  698. return key.StorageClass
  699. }
  700. func (key *azurePvKey) Features() string {
  701. storageClass := key.StorageClassParameters["storageaccounttype"]
  702. storageSKU := key.StorageClassParameters["skuName"]
  703. if storageClass != "" {
  704. if strings.EqualFold(storageClass, "Premium_LRS") {
  705. storageClass = AzureDiskPremiumSSDStorageClass
  706. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  707. storageClass = AzureDiskStandardSSDStorageClass
  708. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  709. storageClass = AzureDiskStandardStorageClass
  710. }
  711. } else {
  712. if strings.EqualFold(storageSKU, "Premium_LRS") {
  713. storageClass = AzureFilePremiumStorageClass
  714. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  715. storageClass = AzureFileStandardStorageClass
  716. }
  717. }
  718. if region, ok := util.GetRegion(key.Labels); ok {
  719. return region + "," + storageClass
  720. }
  721. return key.DefaultRegion + "," + storageClass
  722. }
  723. func (*Azure) GetAddresses() ([]byte, error) {
  724. return nil, nil
  725. }
  726. func (*Azure) GetDisks() ([]byte, error) {
  727. return nil, nil
  728. }
  729. func (az *Azure) ClusterInfo() (map[string]string, error) {
  730. remoteEnabled := env.IsRemoteEnabled()
  731. m := make(map[string]string)
  732. m["name"] = "Azure Cluster #1"
  733. c, err := az.GetConfig()
  734. if err != nil {
  735. return nil, err
  736. }
  737. if c.ClusterName != "" {
  738. m["name"] = c.ClusterName
  739. }
  740. m["provider"] = "azure"
  741. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  742. m["id"] = env.GetClusterID()
  743. return m, nil
  744. }
  745. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  746. return az.Config.UpdateFromMap(a)
  747. }
  748. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  749. defer az.DownloadPricingData()
  750. return az.Config.Update(func(c *CustomPricing) error {
  751. a := make(map[string]interface{})
  752. err := json.NewDecoder(r).Decode(&a)
  753. if err != nil {
  754. return err
  755. }
  756. for k, v := range a {
  757. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  758. vstr, ok := v.(string)
  759. if ok {
  760. err := SetCustomPricingField(c, kUpper, vstr)
  761. if err != nil {
  762. return err
  763. }
  764. } else {
  765. sci := v.(map[string]interface{})
  766. sc := make(map[string]string)
  767. for k, val := range sci {
  768. sc[k] = val.(string)
  769. }
  770. c.SharedCosts = sc //todo: support reflection/multiple map fields
  771. }
  772. }
  773. if env.IsRemoteEnabled() {
  774. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  775. if err != nil {
  776. return err
  777. }
  778. }
  779. return nil
  780. })
  781. }
  782. func (az *Azure) GetConfig() (*CustomPricing, error) {
  783. c, err := az.Config.GetCustomPricingData()
  784. if c.Discount == "" {
  785. c.Discount = "0%"
  786. }
  787. if c.NegotiatedDiscount == "" {
  788. c.NegotiatedDiscount = "0%"
  789. }
  790. if c.CurrencyCode == "" {
  791. c.CurrencyCode = "USD"
  792. }
  793. if c.AzureBillingRegion == "" {
  794. c.AzureBillingRegion = "US"
  795. }
  796. if err != nil {
  797. return nil, err
  798. }
  799. return c, nil
  800. }
  801. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  802. // "start" and "end" are dates of the format YYYY-MM-DD
  803. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  804. func (az *Azure) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  805. var csvRetriever CSVRetriever = AzureCSVRetriever{}
  806. err := az.ConfigureAzureStorage() // load Azure Storage config
  807. if err != nil {
  808. return nil, err
  809. }
  810. return GetExternalAllocations(start, end, aggregators, filterType, filterValue, crossCluster, csvRetriever)
  811. }
  812. func GetExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool, csvRetriever CSVRetriever) ([]*OutOfClusterAllocation, error) {
  813. dateFormat := "2006-1-2"
  814. startTime, err := time.Parse(dateFormat, start)
  815. if err != nil {
  816. return nil, err
  817. }
  818. endTime, err := time.Parse(dateFormat, end)
  819. if err != nil {
  820. return nil, err
  821. }
  822. readers, err := csvRetriever.GetCSVReaders(startTime, endTime)
  823. if err != nil {
  824. return nil, err
  825. }
  826. oocAllocs := make(map[string]*OutOfClusterAllocation)
  827. for _, reader := range readers {
  828. err = ParseCSV(reader, startTime, endTime, oocAllocs, aggregators, filterType, filterValue, crossCluster)
  829. if err != nil {
  830. return nil, err
  831. }
  832. }
  833. var oocAllocsArr []*OutOfClusterAllocation
  834. for _, alloc := range oocAllocs {
  835. oocAllocsArr = append(oocAllocsArr, alloc)
  836. }
  837. return oocAllocsArr, nil
  838. }
  839. func ParseCSV (reader *csv.Reader, start, end time.Time, oocAllocs map[string]*OutOfClusterAllocation, aggregators []string, filterType string, filterValue string, crossCluster bool) error {
  840. headers, _ := reader.Read()
  841. headerMap := map[string]int{}
  842. for i, header := range headers {
  843. headerMap[header] = i
  844. }
  845. for {
  846. var record, err = reader.Read()
  847. if err == io.EOF {
  848. break
  849. }
  850. if err != nil {
  851. return err
  852. }
  853. meterCategory := record[headerMap["MeterCategory"]]
  854. category := selectCategory(meterCategory)
  855. usageDateTime, err := time.Parse(AzureLayout, record[headerMap["UsageDateTime"]])
  856. if err != nil {
  857. klog.Errorf("failed to parse usage date: '%s'", record[headerMap["UsageDateTime"]])
  858. continue
  859. }
  860. // Ignore VM's and Storage Items for now
  861. if category == kubecost.ComputeCategory || category == kubecost.StorageCategory || !isValidUsageDateTime(start, end, usageDateTime) {
  862. continue
  863. }
  864. itemCost, err := strconv.ParseFloat(record[headerMap["PreTaxCost"]], 64)
  865. if err != nil {
  866. klog.Infof("failed to parse cost: '%s'", record[headerMap["PreTaxCost"]])
  867. continue
  868. }
  869. itemTags := make(map[string]string)
  870. itemTagJson := record[headerMap["Tags"]]
  871. if itemTagJson != "" {
  872. err = json.Unmarshal([]byte(itemTagJson), &itemTags)
  873. if err != nil {
  874. klog.Infof("Could not parse item tags %v", err)
  875. }
  876. }
  877. if filterType != "kubernetes_" {
  878. if value, ok := itemTags[filterType];!ok || value != filterValue {
  879. continue
  880. }
  881. }
  882. environment := ""
  883. for _, agg := range aggregators {
  884. if tag, ok := itemTags[agg]; ok {
  885. environment = tag // just set to the first nonempty match
  886. break
  887. }
  888. }
  889. key := environment + record[headerMap["ConsumedService"]]
  890. if alloc, ok := oocAllocs[key]; ok {
  891. alloc.Cost += itemCost
  892. } else {
  893. ooc := &OutOfClusterAllocation{
  894. Aggregator: strings.Join(aggregators, ","),
  895. Environment: environment,
  896. Service: record[headerMap["ConsumedService"]],
  897. Cost: itemCost,
  898. }
  899. oocAllocs[key] = ooc
  900. }
  901. }
  902. return nil
  903. }
  904. // UsageDateTime only contains date information and not time because of this filtering usageDate time is inclusive on start and exclusive on end
  905. func isValidUsageDateTime(start, end, usageDateTime time.Time) bool {
  906. return (usageDateTime.After(start) || usageDateTime.Equal(start)) && usageDateTime.Before(end)
  907. }
  908. func getStartAndEndTimes(usageDateTime time.Time) (time.Time, time.Time) {
  909. start := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 0, 0, 0, 0, usageDateTime.Location())
  910. end := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 23, 59, 59, 999999999, usageDateTime.Location())
  911. return start, end
  912. }
  913. func selectCategory(meterCategory string) string {
  914. if meterCategory == "Virtual Machines" {
  915. return kubecost.ComputeCategory
  916. } else if meterCategory == "Storage" {
  917. return kubecost.StorageCategory
  918. } else if meterCategory == "Load Balancer" || meterCategory == "Bandwidth" {
  919. return kubecost.NetworkCategory
  920. } else {
  921. return kubecost.OtherCategory
  922. }
  923. }
  924. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  925. }
  926. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  927. az.DownloadPricingDataLock.RLock()
  928. defer az.DownloadPricingDataLock.RUnlock()
  929. pricing, ok := az.Pricing[pvk.Features()]
  930. if !ok {
  931. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  932. return &PV{}, nil
  933. }
  934. return pricing.PV, nil
  935. }
  936. func (az *Azure) GetLocalStorageQuery(window, offset string, rate bool, used bool) string {
  937. return ""
  938. }
  939. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  940. checks := []*ServiceAccountCheck{}
  941. for _, v := range az.ServiceAccountChecks {
  942. checks = append(checks, v)
  943. }
  944. return &ServiceAccountStatus{
  945. Checks: checks,
  946. }
  947. }
  948. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  949. return make(map[string]*PricingSource)
  950. }
  951. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  952. return "", 0.0, nil
  953. }
  954. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  955. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  956. }
  957. func (az *Azure) ParseID(id string) string {
  958. return id
  959. }
  960. func (az *Azure) ParsePVID(id string) string {
  961. return id
  962. }