azureprovider.go 33 KB

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