azureprovider.go 40 KB

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