azureprovider.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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. RateCardPricingError error
  345. }
  346. type azureKey struct {
  347. Labels map[string]string
  348. GPULabel string
  349. GPULabelValue string
  350. }
  351. func (k *azureKey) Features() string {
  352. r, _ := util.GetRegion(k.Labels)
  353. region := strings.ToLower(r)
  354. instance, _ := util.GetInstanceType(k.Labels)
  355. usageType := "ondemand"
  356. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  357. }
  358. // GPUType returns value of GPULabel if present
  359. func (k *azureKey) GPUType() string {
  360. if t, ok := k.Labels[k.GPULabel]; ok {
  361. return t
  362. }
  363. return ""
  364. }
  365. func (k *azureKey) isValidGPUNode() bool {
  366. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  367. }
  368. func (k *azureKey) ID() string {
  369. return ""
  370. }
  371. func (k *azureKey) GetGPUCount() string {
  372. instance, _ := util.GetInstanceType(k.Labels)
  373. // Double digits that could get matches lower in logic
  374. if strings.Contains(instance, "NC64") {
  375. return "4"
  376. }
  377. if strings.Contains(instance, "ND96") ||
  378. strings.Contains(instance, "ND40") {
  379. return "8"
  380. }
  381. // Ordered asc because of some series have different gpu counts on different versions
  382. if strings.Contains(instance, "NC6") ||
  383. strings.Contains(instance, "NC4") ||
  384. strings.Contains(instance, "NC8") ||
  385. strings.Contains(instance, "NC16") ||
  386. strings.Contains(instance, "ND6") ||
  387. strings.Contains(instance, "NV12s") ||
  388. strings.Contains(instance, "NV6") {
  389. return "1"
  390. }
  391. if strings.Contains(instance, "NC12") ||
  392. strings.Contains(instance, "ND12") ||
  393. strings.Contains(instance, "NV24s") ||
  394. strings.Contains(instance, "NV12") {
  395. return "2"
  396. }
  397. if strings.Contains(instance, "NC24") ||
  398. strings.Contains(instance, "ND24") ||
  399. strings.Contains(instance, "NV48s") ||
  400. strings.Contains(instance, "NV24") {
  401. return "4"
  402. }
  403. return "0"
  404. }
  405. // Represents an azure storage config
  406. type AzureStorageConfig struct {
  407. SubscriptionId string `json:"azureSubscriptionID"`
  408. AccountName string `json:"azureStorageAccount"`
  409. AccessKey string `json:"azureStorageAccessKey"`
  410. ContainerName string `json:"azureStorageContainer"`
  411. }
  412. // Represents an azure app key
  413. type AzureAppKey struct {
  414. AppID string `json:"appId"`
  415. DisplayName string `json:"displayName"`
  416. Name string `json:"name"`
  417. Password string `json:"password"`
  418. Tenant string `json:"tenant"`
  419. }
  420. // Azure service key for a specific subscription
  421. type AzureServiceKey struct {
  422. SubscriptionID string `json:"subscriptionId"`
  423. ServiceKey *AzureAppKey `json:"serviceKey"`
  424. }
  425. // Validity check on service key
  426. func (ask *AzureServiceKey) IsValid() bool {
  427. return ask.SubscriptionID != "" &&
  428. ask.ServiceKey != nil &&
  429. ask.ServiceKey.AppID != "" &&
  430. ask.ServiceKey.Password != "" &&
  431. ask.ServiceKey.Tenant != ""
  432. }
  433. // Loads the azure authentication via configuration or a secret set at install time.
  434. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  435. // 1. Check config values first (set from frontend UI)
  436. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  437. subscriptionID = cp.AzureSubscriptionID
  438. clientID = cp.AzureClientID
  439. clientSecret = cp.AzureClientSecret
  440. tenantID = cp.AzureTenantID
  441. return
  442. }
  443. // 2. Check for secret
  444. s, _ := az.loadAzureAuthSecret(forceReload)
  445. if s != nil && s.IsValid() {
  446. subscriptionID = s.SubscriptionID
  447. clientID = s.ServiceKey.AppID
  448. clientSecret = s.ServiceKey.Password
  449. tenantID = s.ServiceKey.Tenant
  450. return
  451. }
  452. // 3. Empty values
  453. return "", "", "", ""
  454. }
  455. func (az *Azure) ConfigureAzureStorage() error {
  456. accessKey, accountName, containerName := az.getAzureStorageConfig(false)
  457. if accessKey != "" && accountName != "" && containerName != "" {
  458. err := env.Set(env.AzureStorageAccessKeyEnvVar, accessKey)
  459. if err != nil {
  460. return err
  461. }
  462. err = env.Set(env.AzureStorageAccountNameEnvVar, accountName)
  463. if err != nil {
  464. return err
  465. }
  466. err = env.Set(env.AzureStorageContainerNameEnvVar, containerName)
  467. if err != nil {
  468. return err
  469. }
  470. }
  471. return nil
  472. }
  473. func (az *Azure) getAzureStorageConfig(forceReload bool) (accessKey, accountName, containerName string) {
  474. if az.ServiceAccountChecks == nil {
  475. az.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  476. }
  477. // 1. Check for secret
  478. s, _ := az.loadAzureStorageConfig(forceReload)
  479. if s != nil && s.AccessKey != "" && s.AccountName != "" && s.ContainerName != "" {
  480. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  481. Message: "Azure Storage Config exists",
  482. Status: true,
  483. }
  484. accessKey = s.AccessKey
  485. accountName = s.AccountName
  486. containerName = s.ContainerName
  487. return
  488. }
  489. // 3. Fall back to env vars
  490. accessKey, accountName, containerName = env.GetAzureStorageAccessKey(), env.GetAzureStorageAccountName(), env.GetAzureStorageContainerName()
  491. if accessKey != "" && accountName != "" && containerName != "" {
  492. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  493. Message: "Azure Storage Config exists",
  494. Status: true,
  495. }
  496. } else {
  497. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  498. Message: "Azure Storage Config exists",
  499. Status: false,
  500. }
  501. }
  502. return
  503. }
  504. // Load once and cache the result (even on failure). This is an install time secret, so
  505. // we don't expect the secret to change. If it does, however, we can force reload using
  506. // the input parameter.
  507. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  508. if !force && loadedAzureSecret {
  509. return azureSecret, nil
  510. }
  511. loadedAzureSecret = true
  512. exists, err := fileutil.FileExists(authSecretPath)
  513. if !exists || err != nil {
  514. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  515. }
  516. result, err := ioutil.ReadFile(authSecretPath)
  517. if err != nil {
  518. return nil, err
  519. }
  520. var ask AzureServiceKey
  521. err = json.Unmarshal(result, &ask)
  522. if err != nil {
  523. return nil, err
  524. }
  525. azureSecret = &ask
  526. return azureSecret, nil
  527. }
  528. // Load once and cache the result (even on failure). This is an install time secret, so
  529. // we don't expect the secret to change. If it does, however, we can force reload using
  530. // the input parameter.
  531. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  532. if !force && loadedAzureStorageConfigSecret {
  533. return azureStorageConfig, nil
  534. }
  535. loadedAzureStorageConfigSecret = true
  536. exists, err := fileutil.FileExists(storageConfigSecretPath)
  537. if !exists || err != nil {
  538. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  539. }
  540. result, err := ioutil.ReadFile(storageConfigSecretPath)
  541. if err != nil {
  542. return nil, err
  543. }
  544. var ask AzureStorageConfig
  545. err = json.Unmarshal(result, &ask)
  546. if err != nil {
  547. return nil, err
  548. }
  549. azureStorageConfig = &ask
  550. return azureStorageConfig, nil
  551. }
  552. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  553. cfg, err := az.GetConfig()
  554. if err != nil {
  555. klog.Infof("Error loading azure custom pricing information")
  556. }
  557. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  558. gpuLabel := "accelerator"
  559. gpuLabelValue := "nvidia"
  560. if cfg.GpuLabel != "" {
  561. gpuLabel = cfg.GpuLabel
  562. }
  563. if cfg.GpuLabelValue != "" {
  564. gpuLabelValue = cfg.GpuLabelValue
  565. }
  566. return &azureKey{
  567. Labels: labels,
  568. GPULabel: gpuLabel,
  569. GPULabelValue: gpuLabelValue,
  570. }
  571. }
  572. // CreateString builds strings effectively
  573. func createString(keys ...string) string {
  574. var b strings.Builder
  575. for _, key := range keys {
  576. b.WriteString(key)
  577. }
  578. return b.String()
  579. }
  580. func transformMachineType(subCategory string, mt []string) []string {
  581. switch {
  582. case strings.Contains(subCategory, "Basic"):
  583. return []string{createString("Basic_", mt[0])}
  584. case len(mt) == 2:
  585. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  586. default:
  587. return []string{createString("Standard_", mt[0])}
  588. }
  589. }
  590. func addSuffix(mt string, suffixes ...string) []string {
  591. result := make([]string, len(suffixes))
  592. var suffix string
  593. parts := strings.Split(mt, "_")
  594. if len(parts) > 2 {
  595. for _, p := range parts[2:] {
  596. suffix = createString(suffix, "_", p)
  597. }
  598. }
  599. for i, s := range suffixes {
  600. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  601. }
  602. return result
  603. }
  604. func getMachineTypeVariants(mt string) []string {
  605. switch {
  606. case mtStandardB.MatchString(mt):
  607. return []string{createString(mt, "s")}
  608. case mtStandardD.MatchString(mt):
  609. var result []string
  610. result = append(result, addSuffix(mt, "s")[0])
  611. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  612. result = append(result, dsType)
  613. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  614. return result
  615. case mtStandardE.MatchString(mt):
  616. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  617. case mtStandardF.MatchString(mt):
  618. return addSuffix(mt, "s")
  619. case mtStandardG.MatchString(mt):
  620. var result []string
  621. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  622. result = append(result, gsType)
  623. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  624. case mtStandardL.MatchString(mt):
  625. return addSuffix(mt, "s")
  626. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  627. base := strings.TrimSuffix(mt, "ms")
  628. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  629. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  630. return []string{}
  631. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  632. base := strings.TrimSuffix(mt, "s")
  633. return addSuffix(base, "", "m")
  634. case mtStandardN.MatchString(mt):
  635. return addSuffix(mt, "s")
  636. }
  637. return []string{}
  638. }
  639. func (az *Azure) GetManagementPlatform() (string, error) {
  640. nodes := az.Clientset.GetAllNodes()
  641. if len(nodes) > 0 {
  642. n := nodes[0]
  643. providerID := n.Spec.ProviderID
  644. if strings.Contains(providerID, "aks") {
  645. return "aks", nil
  646. }
  647. }
  648. return "", nil
  649. }
  650. // DownloadPricingData uses provided azure "best guesses" for pricing
  651. func (az *Azure) DownloadPricingData() error {
  652. az.DownloadPricingDataLock.Lock()
  653. defer az.DownloadPricingDataLock.Unlock()
  654. config, err := az.GetConfig()
  655. if err != nil {
  656. az.RateCardPricingError = err
  657. return err
  658. }
  659. // Load the service provider keys
  660. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(false, config)
  661. config.AzureSubscriptionID = subscriptionID
  662. config.AzureClientID = clientID
  663. config.AzureClientSecret = clientSecret
  664. config.AzureTenantID = tenantID
  665. var authorizer autorest.Authorizer
  666. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  667. credentialsConfig := auth.NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID)
  668. a, err := credentialsConfig.Authorizer()
  669. if err != nil {
  670. az.RateCardPricingError = err
  671. return err
  672. }
  673. authorizer = a
  674. }
  675. if authorizer == nil {
  676. a, err := auth.NewAuthorizerFromEnvironment()
  677. authorizer = a
  678. if err != nil { // Failed to create authorizer from environment, try from file
  679. a, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
  680. if err != nil {
  681. az.RateCardPricingError = err
  682. return err
  683. }
  684. authorizer = a
  685. }
  686. }
  687. sClient := subscriptions.NewClient()
  688. sClient.Authorizer = authorizer
  689. rcClient := commerce.NewRateCardClient(config.AzureSubscriptionID)
  690. rcClient.Authorizer = authorizer
  691. skusClient := skus.NewResourceSkusClient(config.AzureSubscriptionID)
  692. skusClient.Authorizer = authorizer
  693. providersClient := resources.NewProvidersClient(config.AzureSubscriptionID)
  694. providersClient.Authorizer = authorizer
  695. containerServiceClient := containerservice.NewContainerServicesClient(config.AzureSubscriptionID)
  696. containerServiceClient.Authorizer = authorizer
  697. 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)
  698. klog.Infof("Using ratecard query %s", rateCardFilter)
  699. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  700. if err != nil {
  701. az.RateCardPricingError = err
  702. return err
  703. }
  704. allPrices := make(map[string]*AzurePricing)
  705. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  706. if err != nil {
  707. az.RateCardPricingError = err
  708. return err
  709. }
  710. baseCPUPrice := config.CPU
  711. for _, v := range *result.Meters {
  712. meterName := *v.MeterName
  713. meterRegion := *v.MeterRegion
  714. meterCategory := *v.MeterCategory
  715. meterSubCategory := *v.MeterSubCategory
  716. region, err := toRegionID(meterRegion, regions)
  717. if err != nil {
  718. continue
  719. }
  720. if !strings.Contains(meterSubCategory, "Windows") {
  721. if strings.Contains(meterCategory, "Storage") {
  722. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  723. var storageClass string = ""
  724. if strings.Contains(meterName, "P4 ") {
  725. storageClass = AzureDiskPremiumSSDStorageClass
  726. } else if strings.Contains(meterName, "E4 ") {
  727. storageClass = AzureDiskStandardSSDStorageClass
  728. } else if strings.Contains(meterName, "S4 ") {
  729. storageClass = AzureDiskStandardStorageClass
  730. } else if strings.Contains(meterName, "LRS Provisioned") {
  731. storageClass = AzureFilePremiumStorageClass
  732. }
  733. if storageClass != "" {
  734. var priceInUsd float64
  735. if len(v.MeterRates) < 1 {
  736. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  737. continue
  738. }
  739. for _, rate := range v.MeterRates {
  740. priceInUsd += *rate
  741. }
  742. // rate is in disk per month, resolve price per hour, then GB per hour
  743. pricePerHour := priceInUsd / 730.0 / 32.0
  744. priceStr := fmt.Sprintf("%f", pricePerHour)
  745. key := region + "," + storageClass
  746. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  747. allPrices[key] = &AzurePricing{
  748. PV: &PV{
  749. Cost: priceStr,
  750. Region: region,
  751. },
  752. }
  753. }
  754. }
  755. }
  756. if strings.Contains(meterCategory, "Virtual Machines") {
  757. usageType := ""
  758. if !strings.Contains(meterName, "Low Priority") {
  759. usageType = "ondemand"
  760. } else {
  761. usageType = "preemptible"
  762. }
  763. var instanceTypes []string
  764. name := strings.TrimSuffix(meterName, " Low Priority")
  765. instanceType := strings.Split(name, "/")
  766. for _, it := range instanceType {
  767. if strings.Contains(meterSubCategory, "Promo") {
  768. it = it + " Promo"
  769. }
  770. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  771. }
  772. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  773. if strings.Contains(name, "Expired") {
  774. instanceTypes = []string{}
  775. }
  776. var priceInUsd float64
  777. if len(v.MeterRates) < 1 {
  778. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  779. continue
  780. }
  781. for _, rate := range v.MeterRates {
  782. priceInUsd += *rate
  783. }
  784. priceStr := fmt.Sprintf("%f", priceInUsd)
  785. for _, instanceType := range instanceTypes {
  786. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  787. allPrices[key] = &AzurePricing{
  788. Node: &Node{
  789. Cost: priceStr,
  790. BaseCPUPrice: baseCPUPrice,
  791. UsageType: usageType,
  792. },
  793. }
  794. }
  795. }
  796. }
  797. }
  798. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  799. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  800. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  801. zeroPrice := "0.0"
  802. for region := range regions {
  803. key := region + "," + AzureFileStandardStorageClass
  804. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  805. allPrices[key] = &AzurePricing{
  806. PV: &PV{
  807. Cost: zeroPrice,
  808. Region: region,
  809. },
  810. }
  811. }
  812. az.Pricing = allPrices
  813. az.RateCardPricingError = nil
  814. return nil
  815. }
  816. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  817. if az.Pricing == nil {
  818. az.Pricing = map[string]*AzurePricing{}
  819. }
  820. az.Pricing[features] = azurePricing
  821. }
  822. // AllNodePricing returns the Azure pricing objects stored
  823. func (az *Azure) AllNodePricing() (interface{}, error) {
  824. az.DownloadPricingDataLock.RLock()
  825. defer az.DownloadPricingDataLock.RUnlock()
  826. return az.Pricing, nil
  827. }
  828. // NodePricing returns Azure pricing data for a single node
  829. func (az *Azure) NodePricing(key Key) (*Node, error) {
  830. az.DownloadPricingDataLock.RLock()
  831. defer az.DownloadPricingDataLock.RUnlock()
  832. azKey, ok := key.(*azureKey)
  833. if !ok {
  834. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  835. }
  836. config, _ := az.GetConfig()
  837. if slv, ok := azKey.Labels[config.SpotLabel]; ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  838. features := strings.Split(azKey.Features(), ",")
  839. region := features[0]
  840. instance := features[1]
  841. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  842. if n, ok := az.Pricing[spotFeatures]; ok {
  843. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  844. if azKey.isValidGPUNode() {
  845. n.Node.GPU = "1" // TODO: support multiple GPUs
  846. }
  847. return n.Node, nil
  848. }
  849. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  850. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  851. if err != nil {
  852. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  853. } else {
  854. gpu := ""
  855. if azKey.isValidGPUNode() {
  856. gpu = "1"
  857. }
  858. spotNode := &Node{
  859. Cost: spotCost,
  860. UsageType: "spot",
  861. GPU: gpu,
  862. }
  863. az.addPricing(spotFeatures, &AzurePricing{
  864. Node: spotNode,
  865. })
  866. return spotNode, nil
  867. }
  868. }
  869. if n, ok := az.Pricing[azKey.Features()]; ok {
  870. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  871. if azKey.isValidGPUNode() {
  872. n.Node.GPU = azKey.GetGPUCount()
  873. }
  874. return n.Node, nil
  875. }
  876. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", azKey.Features(), azKey)
  877. c, err := az.GetConfig()
  878. if err != nil {
  879. return nil, fmt.Errorf("No default pricing data available")
  880. }
  881. if azKey.isValidGPUNode() {
  882. return &Node{
  883. VCPUCost: c.CPU,
  884. RAMCost: c.RAM,
  885. UsesBaseCPUPrice: true,
  886. GPUCost: c.GPU,
  887. GPU: azKey.GetGPUCount(),
  888. }, nil
  889. }
  890. return &Node{
  891. VCPUCost: c.CPU,
  892. RAMCost: c.RAM,
  893. UsesBaseCPUPrice: true,
  894. }, nil
  895. }
  896. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  897. func (az *Azure) NetworkPricing() (*Network, error) {
  898. cpricing, err := az.Config.GetCustomPricingData()
  899. if err != nil {
  900. return nil, err
  901. }
  902. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  903. if err != nil {
  904. return nil, err
  905. }
  906. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  907. if err != nil {
  908. return nil, err
  909. }
  910. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  911. if err != nil {
  912. return nil, err
  913. }
  914. return &Network{
  915. ZoneNetworkEgressCost: znec,
  916. RegionNetworkEgressCost: rnec,
  917. InternetNetworkEgressCost: inec,
  918. }, nil
  919. }
  920. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  921. fffrc := 0.025
  922. afrc := 0.010
  923. lbidc := 0.008
  924. numForwardingRules := 1.0
  925. dataIngressGB := 0.0
  926. var totalCost float64
  927. if numForwardingRules < 5 {
  928. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  929. } else {
  930. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  931. }
  932. return &LoadBalancer{
  933. Cost: totalCost,
  934. }, nil
  935. }
  936. type azurePvKey struct {
  937. Labels map[string]string
  938. StorageClass string
  939. StorageClassParameters map[string]string
  940. DefaultRegion string
  941. ProviderId string
  942. }
  943. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  944. providerID := ""
  945. if pv.Spec.AzureDisk != nil {
  946. providerID = pv.Spec.AzureDisk.DiskName
  947. }
  948. return &azurePvKey{
  949. Labels: pv.Labels,
  950. StorageClass: pv.Spec.StorageClassName,
  951. StorageClassParameters: parameters,
  952. DefaultRegion: defaultRegion,
  953. ProviderId: providerID,
  954. }
  955. }
  956. func (key *azurePvKey) ID() string {
  957. return key.ProviderId
  958. }
  959. func (key *azurePvKey) GetStorageClass() string {
  960. return key.StorageClass
  961. }
  962. func (key *azurePvKey) Features() string {
  963. storageClass := key.StorageClassParameters["storageaccounttype"]
  964. storageSKU := key.StorageClassParameters["skuName"]
  965. if storageClass != "" {
  966. if strings.EqualFold(storageClass, "Premium_LRS") {
  967. storageClass = AzureDiskPremiumSSDStorageClass
  968. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  969. storageClass = AzureDiskStandardSSDStorageClass
  970. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  971. storageClass = AzureDiskStandardStorageClass
  972. }
  973. } else {
  974. if strings.EqualFold(storageSKU, "Premium_LRS") {
  975. storageClass = AzureFilePremiumStorageClass
  976. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  977. storageClass = AzureFileStandardStorageClass
  978. }
  979. }
  980. if region, ok := util.GetRegion(key.Labels); ok {
  981. return region + "," + storageClass
  982. }
  983. return key.DefaultRegion + "," + storageClass
  984. }
  985. func (*Azure) GetAddresses() ([]byte, error) {
  986. return nil, nil
  987. }
  988. func (*Azure) GetDisks() ([]byte, error) {
  989. return nil, nil
  990. }
  991. func (az *Azure) ClusterInfo() (map[string]string, error) {
  992. remoteEnabled := env.IsRemoteEnabled()
  993. m := make(map[string]string)
  994. m["name"] = "Azure Cluster #1"
  995. c, err := az.GetConfig()
  996. if err != nil {
  997. return nil, err
  998. }
  999. if c.ClusterName != "" {
  1000. m["name"] = c.ClusterName
  1001. }
  1002. m["provider"] = "azure"
  1003. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  1004. m["id"] = env.GetClusterID()
  1005. return m, nil
  1006. }
  1007. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  1008. return az.Config.UpdateFromMap(a)
  1009. }
  1010. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  1011. defer az.DownloadPricingData()
  1012. return az.Config.Update(func(c *CustomPricing) error {
  1013. a := make(map[string]interface{})
  1014. err := json.NewDecoder(r).Decode(&a)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. for k, v := range a {
  1019. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  1020. vstr, ok := v.(string)
  1021. if ok {
  1022. err := SetCustomPricingField(c, kUpper, vstr)
  1023. if err != nil {
  1024. return err
  1025. }
  1026. } else {
  1027. return fmt.Errorf("type error while updating config for %s", kUpper)
  1028. }
  1029. }
  1030. if env.IsRemoteEnabled() {
  1031. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  1032. if err != nil {
  1033. return err
  1034. }
  1035. }
  1036. return nil
  1037. })
  1038. }
  1039. func (az *Azure) GetConfig() (*CustomPricing, error) {
  1040. c, err := az.Config.GetCustomPricingData()
  1041. if err != nil {
  1042. return nil, err
  1043. }
  1044. if c.Discount == "" {
  1045. c.Discount = "0%"
  1046. }
  1047. if c.NegotiatedDiscount == "" {
  1048. c.NegotiatedDiscount = "0%"
  1049. }
  1050. if c.CurrencyCode == "" {
  1051. c.CurrencyCode = "USD"
  1052. }
  1053. if c.AzureBillingRegion == "" {
  1054. c.AzureBillingRegion = "US"
  1055. }
  1056. if c.ShareTenancyCosts == "" {
  1057. c.ShareTenancyCosts = defaultShareTenancyCost
  1058. }
  1059. if c.SpotLabel == "" {
  1060. c.SpotLabel = defaultSpotLabel
  1061. }
  1062. if c.SpotLabelValue == "" {
  1063. c.SpotLabelValue = defaultSpotLabelValue
  1064. }
  1065. return c, nil
  1066. }
  1067. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  1068. // "start" and "end" are dates of the format YYYY-MM-DD
  1069. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  1070. func (az *Azure) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  1071. var csvRetriever CSVRetriever = AzureCSVRetriever{}
  1072. err := az.ConfigureAzureStorage() // load Azure Storage config
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. return getExternalAllocations(start, end, aggregators, filterType, filterValue, crossCluster, csvRetriever)
  1077. }
  1078. func getExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool, csvRetriever CSVRetriever) ([]*OutOfClusterAllocation, error) {
  1079. dateFormat := "2006-1-2"
  1080. startTime, err := time.Parse(dateFormat, start)
  1081. if err != nil {
  1082. return nil, err
  1083. }
  1084. endTime, err := time.Parse(dateFormat, end)
  1085. if err != nil {
  1086. return nil, err
  1087. }
  1088. readers, err := csvRetriever.GetCSVReaders(startTime, endTime)
  1089. if err != nil {
  1090. return nil, err
  1091. }
  1092. oocAllocs := make(map[string]*OutOfClusterAllocation)
  1093. for _, reader := range readers {
  1094. err = parseCSV(reader, startTime, endTime, oocAllocs, aggregators, filterType, filterValue, crossCluster)
  1095. if err != nil {
  1096. return nil, err
  1097. }
  1098. }
  1099. var oocAllocsArr []*OutOfClusterAllocation
  1100. for _, alloc := range oocAllocs {
  1101. oocAllocsArr = append(oocAllocsArr, alloc)
  1102. }
  1103. return oocAllocsArr, nil
  1104. }
  1105. func parseCSV(reader *csv.Reader, start, end time.Time, oocAllocs map[string]*OutOfClusterAllocation, aggregators []string, filterType string, filterValue string, crossCluster bool) error {
  1106. headers, _ := reader.Read()
  1107. headerMap := createHeaderMap(headers)
  1108. for {
  1109. var record, err = reader.Read()
  1110. if err == io.EOF {
  1111. break
  1112. }
  1113. if err != nil {
  1114. return err
  1115. }
  1116. meterCategory := record[headerMap["MeterCategory"]]
  1117. category := selectCategory(meterCategory)
  1118. usageDateTime, err := time.Parse(AzureLayout, record[headerMap["UsageDateTime"]])
  1119. if err != nil {
  1120. klog.Errorf("failed to parse usage date: '%s'", record[headerMap["UsageDateTime"]])
  1121. continue
  1122. }
  1123. // Ignore VM's and Storage Items for now
  1124. if category == kubecost.ComputeCategory || category == kubecost.StorageCategory || !isValidUsageDateTime(start, end, usageDateTime) {
  1125. continue
  1126. }
  1127. itemCost, err := strconv.ParseFloat(record[headerMap["PreTaxCost"]], 64)
  1128. if err != nil {
  1129. klog.Infof("failed to parse cost: '%s'", record[headerMap["PreTaxCost"]])
  1130. continue
  1131. }
  1132. itemTags := make(map[string]string)
  1133. itemTagJson := makeValidJSON(record[headerMap["Tags"]])
  1134. if itemTagJson != "" {
  1135. err = json.Unmarshal([]byte(itemTagJson), &itemTags)
  1136. if err != nil {
  1137. klog.Infof("Could not parse item tags %v", err)
  1138. }
  1139. }
  1140. if filterType != "kubernetes_" {
  1141. if value, ok := itemTags[filterType]; !ok || value != filterValue {
  1142. continue
  1143. }
  1144. }
  1145. environment := ""
  1146. for _, agg := range aggregators {
  1147. if tag, ok := itemTags[agg]; ok {
  1148. environment = tag // just set to the first nonempty match
  1149. break
  1150. }
  1151. }
  1152. key := environment + record[headerMap["ConsumedService"]]
  1153. if alloc, ok := oocAllocs[key]; ok {
  1154. alloc.Cost += itemCost
  1155. } else {
  1156. ooc := &OutOfClusterAllocation{
  1157. Aggregator: strings.Join(aggregators, ","),
  1158. Environment: environment,
  1159. Service: record[headerMap["ConsumedService"]],
  1160. Cost: itemCost,
  1161. }
  1162. oocAllocs[key] = ooc
  1163. }
  1164. }
  1165. return nil
  1166. }
  1167. func createHeaderMap(headers []string) map[string]int {
  1168. headerMap := make(map[string]int)
  1169. for i, header := range headers {
  1170. for _, headerString := range HeaderStrings {
  1171. if strings.Contains(header, headerString) {
  1172. headerMap[headerString] = i
  1173. }
  1174. }
  1175. }
  1176. return headerMap
  1177. }
  1178. func makeValidJSON(jsonString string) string {
  1179. if jsonString == "" || (jsonString[0] == '{' && jsonString[len(jsonString)-1] == '}') {
  1180. return jsonString
  1181. }
  1182. return fmt.Sprintf("{%v}", jsonString)
  1183. }
  1184. // UsageDateTime only contains date information and not time because of this filtering usageDate time is inclusive on start and exclusive on end
  1185. func isValidUsageDateTime(start, end, usageDateTime time.Time) bool {
  1186. return (usageDateTime.After(start) || usageDateTime.Equal(start)) && usageDateTime.Before(end)
  1187. }
  1188. func getStartAndEndTimes(usageDateTime time.Time) (time.Time, time.Time) {
  1189. start := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 0, 0, 0, 0, usageDateTime.Location())
  1190. end := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 23, 59, 59, 999999999, usageDateTime.Location())
  1191. return start, end
  1192. }
  1193. func selectCategory(meterCategory string) string {
  1194. if meterCategory == "Virtual Machines" {
  1195. return kubecost.ComputeCategory
  1196. } else if meterCategory == "Storage" {
  1197. return kubecost.StorageCategory
  1198. } else if meterCategory == "Load Balancer" || meterCategory == "Bandwidth" {
  1199. return kubecost.NetworkCategory
  1200. } else {
  1201. return kubecost.OtherCategory
  1202. }
  1203. }
  1204. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1205. }
  1206. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1207. az.DownloadPricingDataLock.RLock()
  1208. defer az.DownloadPricingDataLock.RUnlock()
  1209. pricing, ok := az.Pricing[pvk.Features()]
  1210. if !ok {
  1211. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1212. return &PV{}, nil
  1213. }
  1214. return pricing.PV, nil
  1215. }
  1216. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1217. return ""
  1218. }
  1219. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1220. checks := []*ServiceAccountCheck{}
  1221. for _, v := range az.ServiceAccountChecks {
  1222. checks = append(checks, v)
  1223. }
  1224. return &ServiceAccountStatus{
  1225. Checks: checks,
  1226. }
  1227. }
  1228. const rateCardPricingSource = "Rate Card API"
  1229. // PricingSourceStatus returns the status of the rate card api
  1230. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1231. sources := make(map[string]*PricingSource)
  1232. errMsg := ""
  1233. if az.RateCardPricingError != nil {
  1234. errMsg = az.RateCardPricingError.Error()
  1235. }
  1236. rcps := &PricingSource {
  1237. Name: rateCardPricingSource,
  1238. Error: errMsg,
  1239. }
  1240. if rcps.Error != "" {
  1241. rcps.Available = false
  1242. } else if len(az.Pricing) == 0 {
  1243. rcps.Error = "No Pricing Data Available"
  1244. rcps.Available = false
  1245. }else {
  1246. rcps.Available = true
  1247. }
  1248. sources[rateCardPricingSource] = rcps
  1249. return sources
  1250. }
  1251. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1252. return "", 0.0, nil
  1253. }
  1254. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1255. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1256. }
  1257. func (az *Azure) Regions() []string {
  1258. return azureRegions
  1259. }