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