azureprovider.go 39 KB

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