azureprovider.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. const AzureLayout = "2006-01-02"
  69. var HeaderStrings = []string{"MeterCategory", "UsageDateTime", "InstanceId", "AdditionalInfo", "Tags", "PreTaxCost", "SubscriptionGuid", "ConsumedService", "ResourceGroup", "ResourceType"}
  70. var loadedAzureSecret bool = false
  71. var azureSecret *AzureServiceKey = nil
  72. var loadedAzureStorageConfigSecret bool = false
  73. var azureStorageConfig *AzureStorageConfig = nil
  74. type regionParts []string
  75. func (r regionParts) String() string {
  76. var result string
  77. for _, p := range r {
  78. result += p
  79. }
  80. return result
  81. }
  82. func getRegions(service string, subscriptionsClient subscriptions.Client, providersClient resources.ProvidersClient, subscriptionID string) (map[string]string, error) {
  83. allLocations := make(map[string]string)
  84. supLocations := make(map[string]string)
  85. // retrieve all locations for the subscription id (some of them may not be supported by the required provider)
  86. if locations, err := subscriptionsClient.ListLocations(context.TODO(), subscriptionID); err == nil {
  87. // fill up the map: DisplayName - > Name
  88. for _, loc := range *locations.Value {
  89. allLocations[*loc.DisplayName] = *loc.Name
  90. }
  91. } else {
  92. return nil, err
  93. }
  94. // identify supported locations for the namespace and resource type
  95. const (
  96. providerNamespaceForCompute = "Microsoft.Compute"
  97. resourceTypeForCompute = "locations/vmSizes"
  98. providerNamespaceForAks = "Microsoft.ContainerService"
  99. resourceTypeForAks = "managedClusters"
  100. )
  101. switch service {
  102. case "aks":
  103. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForAks, ""); err == nil {
  104. for _, pr := range *providers.ResourceTypes {
  105. if *pr.ResourceType == resourceTypeForAks {
  106. for _, displName := range *pr.Locations {
  107. if loc, ok := allLocations[displName]; ok {
  108. supLocations[loc] = displName
  109. } else {
  110. klog.V(1).Infof("unsupported cloud region %s", loc)
  111. }
  112. }
  113. break
  114. }
  115. }
  116. } else {
  117. return nil, err
  118. }
  119. return supLocations, nil
  120. default:
  121. if providers, err := providersClient.Get(context.TODO(), providerNamespaceForCompute, ""); err == nil {
  122. for _, pr := range *providers.ResourceTypes {
  123. if *pr.ResourceType == resourceTypeForCompute {
  124. for _, displName := range *pr.Locations {
  125. if loc, ok := allLocations[displName]; ok {
  126. supLocations[loc] = displName
  127. } else {
  128. klog.V(1).Infof("unsupported cloud region %s", loc)
  129. }
  130. }
  131. break
  132. }
  133. }
  134. } else {
  135. return nil, err
  136. }
  137. return supLocations, nil
  138. }
  139. }
  140. func getRetailPrice(region string, skuName string, currencyCode string, spot bool) (string, error) {
  141. pricingURL := "https://prices.azure.com/api/retail/prices?$skip=0"
  142. if currencyCode != "" {
  143. pricingURL += fmt.Sprintf("&currencyCode='%s'", currencyCode)
  144. }
  145. var filterParams []string
  146. if region != "" {
  147. regionParam := fmt.Sprintf("armRegionName eq '%s'", region)
  148. filterParams = append(filterParams, regionParam)
  149. }
  150. if skuName != "" {
  151. skuNameParam := fmt.Sprintf("armSkuName eq '%s'", skuName)
  152. filterParams = append(filterParams, skuNameParam)
  153. }
  154. if len(filterParams) > 0 {
  155. filterParamsEscaped := url.QueryEscape(strings.Join(filterParams[:], " and "))
  156. pricingURL += fmt.Sprintf("&$filter=%s", filterParamsEscaped)
  157. }
  158. log.Infof("starting download retail price payload from \"%s\"", pricingURL)
  159. resp, err := http.Get(pricingURL)
  160. if err != nil {
  161. return "", fmt.Errorf("bogus fetch of \"%s\": %v", pricingURL, err)
  162. }
  163. if resp.StatusCode < 200 && resp.StatusCode > 299 {
  164. return "", fmt.Errorf("retail price responded with error status code %d", resp.StatusCode)
  165. }
  166. pricingPayload := AzureRetailPricing{}
  167. body, err := ioutil.ReadAll(resp.Body)
  168. if err != nil {
  169. return "", fmt.Errorf("Error getting response: %v", err)
  170. }
  171. jsonErr := json.Unmarshal(body, &pricingPayload)
  172. if jsonErr != nil {
  173. return "", fmt.Errorf("Error unmarshalling data: %v", jsonErr)
  174. }
  175. retailPrice := ""
  176. for _, item := range pricingPayload.Items {
  177. if item.Type == "Consumption" && !strings.Contains(item.ProductName, "Windows") {
  178. // if spot is true SkuName should contain "spot, if it is false it should not
  179. if spot == strings.Contains(strings.ToLower(item.SkuName), " spot") {
  180. retailPrice = fmt.Sprintf("%f", item.RetailPrice)
  181. }
  182. }
  183. }
  184. log.DedupedInfof(5, "done parsing retail price payload from \"%s\"\n", pricingURL)
  185. if retailPrice == "" {
  186. return retailPrice, fmt.Errorf("Couldn't find price for product \"%s\" in \"%s\" region", skuName, region)
  187. }
  188. return retailPrice, nil
  189. }
  190. func toRegionID(meterRegion string, regions map[string]string) (string, error) {
  191. var rp regionParts = strings.Split(strings.ToLower(meterRegion), " ")
  192. regionCode := regionCodeMappings[rp[0]]
  193. lastPart := rp[len(rp)-1]
  194. var regionIds []string
  195. if _, err := strconv.Atoi(lastPart); err == nil {
  196. regionIds = []string{
  197. fmt.Sprintf("%s%s%s", regionCode, rp[1:len(rp)-1], lastPart),
  198. fmt.Sprintf("%s%s%s", rp[1:len(rp)-1], regionCode, lastPart),
  199. }
  200. } else {
  201. regionIds = []string{
  202. fmt.Sprintf("%s%s", regionCode, rp[1:]),
  203. fmt.Sprintf("%s%s", rp[1:], regionCode),
  204. }
  205. }
  206. for _, regionID := range regionIds {
  207. if checkRegionID(regionID, regions) {
  208. return regionID, nil
  209. }
  210. }
  211. return "", fmt.Errorf("Couldn't find region")
  212. }
  213. func checkRegionID(regionID string, regions map[string]string) bool {
  214. for region := range regions {
  215. if regionID == region {
  216. return true
  217. }
  218. }
  219. return false
  220. }
  221. // AzureRetailPricing struct for unmarshalling Azure Retail pricing api JSON response
  222. type AzureRetailPricing struct {
  223. BillingCurrency string `json:"BillingCurrency"`
  224. CustomerEntityId string `json:"CustomerEntityId"`
  225. CustomerEntityType string `json:"CustomerEntityType"`
  226. Items []AzureRetailPricingAttributes `json:"Items"`
  227. NextPageLink string `json:"NextPageLink"`
  228. Count int `json:"Count"`
  229. }
  230. //AzureRetailPricingAttributes struct for unmarshalling Azure Retail pricing api JSON response
  231. type AzureRetailPricingAttributes struct {
  232. CurrencyCode string `json:"currencyCode"`
  233. TierMinimumUnits float32 `json:"tierMinimumUnits"`
  234. RetailPrice float32 `json:"retailPrice"`
  235. UnitPrice float32 `json:"unitPrice"`
  236. ArmRegionName string `json:"armRegionName"`
  237. Location string `json:"location"`
  238. EffectiveStartDate *time.Time `json:"effectiveStartDate"`
  239. EffectiveEndDate *time.Time `json:"effectiveEndDate"`
  240. MeterId string `json:"meterId"`
  241. MeterName string `json:"meterName"`
  242. ProductId string `json:"productId"`
  243. SkuId string `json:"skuId"`
  244. ProductName string `json:"productName"`
  245. SkuName string `json:"skuName"`
  246. ServiceName string `json:"serviceName"`
  247. ServiceId string `json:"serviceId"`
  248. ServiceFamily string `json:"serviceFamily"`
  249. UnitOfMeasure string `json:"unitOfMeasure"`
  250. Type string `json:"type"`
  251. IsPrimaryMeterRegion bool `json:"isPrimaryMeterRegion"`
  252. ArmSkuName string `json:"armSkuName"`
  253. }
  254. // AzurePricing either contains a Node or PV
  255. type AzurePricing struct {
  256. Node *Node
  257. PV *PV
  258. }
  259. type Azure struct {
  260. Pricing map[string]*AzurePricing
  261. DownloadPricingDataLock sync.RWMutex
  262. Clientset clustercache.ClusterCache
  263. Config *ProviderConfig
  264. ServiceAccountChecks map[string]*ServiceAccountCheck
  265. }
  266. type azureKey struct {
  267. Labels map[string]string
  268. GPULabel string
  269. GPULabelValue string
  270. }
  271. func (k *azureKey) Features() string {
  272. r, _ := util.GetRegion(k.Labels)
  273. region := strings.ToLower(r)
  274. instance, _ := util.GetInstanceType(k.Labels)
  275. usageType := "ondemand"
  276. return fmt.Sprintf("%s,%s,%s", region, instance, usageType)
  277. }
  278. // GPUType returns value of GPULabel if present
  279. func (k *azureKey) GPUType() string {
  280. if t, ok := k.Labels[k.GPULabel]; ok {
  281. return t
  282. }
  283. return ""
  284. }
  285. func (k *azureKey) isValidGPUNode() bool {
  286. return k.GPUType() == k.GPULabelValue && k.GetGPUCount() != "0"
  287. }
  288. func (k *azureKey) ID() string {
  289. return ""
  290. }
  291. func (k *azureKey) GetGPUCount() string {
  292. instance, _ := util.GetInstanceType(k.Labels)
  293. // Double digits that could get matches lower in logic
  294. if strings.Contains(instance, "NC64") {
  295. return "4"
  296. }
  297. if strings.Contains(instance, "ND96") ||
  298. strings.Contains(instance, "ND40") {
  299. return "8"
  300. }
  301. // Ordered asc because of some series have different gpu counts on different versions
  302. if strings.Contains(instance, "NC6") ||
  303. strings.Contains(instance, "NC4") ||
  304. strings.Contains(instance, "NC8") ||
  305. strings.Contains(instance, "NC16") ||
  306. strings.Contains(instance, "ND6") ||
  307. strings.Contains(instance, "NV12s") ||
  308. strings.Contains(instance, "NV6") {
  309. return "1"
  310. }
  311. if strings.Contains(instance, "NC12") ||
  312. strings.Contains(instance, "ND12") ||
  313. strings.Contains(instance, "NV24s") ||
  314. strings.Contains(instance, "NV12") {
  315. return "2"
  316. }
  317. if strings.Contains(instance, "NC24") ||
  318. strings.Contains(instance, "ND24") ||
  319. strings.Contains(instance, "NV48s") ||
  320. strings.Contains(instance, "NV24") {
  321. return "4"
  322. }
  323. return "0"
  324. }
  325. // Represents an azure storage config
  326. type AzureStorageConfig struct {
  327. SubscriptionId string `json:"azureSubscriptionID"`
  328. AccountName string `json:"azureStorageAccount"`
  329. AccessKey string `json:"azureStorageAccessKey"`
  330. ContainerName string `json:"azureStorageContainer"`
  331. }
  332. // Represents an azure app key
  333. type AzureAppKey struct {
  334. AppID string `json:"appId"`
  335. DisplayName string `json:"displayName"`
  336. Name string `json:"name"`
  337. Password string `json:"password"`
  338. Tenant string `json:"tenant"`
  339. }
  340. // Azure service key for a specific subscription
  341. type AzureServiceKey struct {
  342. SubscriptionID string `json:"subscriptionId"`
  343. ServiceKey *AzureAppKey `json:"serviceKey"`
  344. }
  345. // Validity check on service key
  346. func (ask *AzureServiceKey) IsValid() bool {
  347. return ask.SubscriptionID != "" &&
  348. ask.ServiceKey != nil &&
  349. ask.ServiceKey.AppID != "" &&
  350. ask.ServiceKey.Password != "" &&
  351. ask.ServiceKey.Tenant != ""
  352. }
  353. // Loads the azure authentication via configuration or a secret set at install time.
  354. func (az *Azure) getAzureAuth(forceReload bool, cp *CustomPricing) (subscriptionID, clientID, clientSecret, tenantID string) {
  355. // 1. Check config values first (set from frontend UI)
  356. if cp.AzureSubscriptionID != "" && cp.AzureClientID != "" && cp.AzureClientSecret != "" && cp.AzureTenantID != "" {
  357. subscriptionID = cp.AzureSubscriptionID
  358. clientID = cp.AzureClientID
  359. clientSecret = cp.AzureClientSecret
  360. tenantID = cp.AzureTenantID
  361. return
  362. }
  363. // 2. Check for secret
  364. s, _ := az.loadAzureAuthSecret(forceReload)
  365. if s != nil && s.IsValid() {
  366. subscriptionID = s.SubscriptionID
  367. clientID = s.ServiceKey.AppID
  368. clientSecret = s.ServiceKey.Password
  369. tenantID = s.ServiceKey.Tenant
  370. return
  371. }
  372. // 3. Empty values
  373. return "", "", "", ""
  374. }
  375. func (az *Azure) ConfigureAzureStorage() error {
  376. accessKey, accountName, containerName := az.getAzureStorageConfig(false)
  377. if accessKey != "" && accountName != "" && containerName != "" {
  378. err := env.Set(env.AzureStorageAccessKeyEnvVar, accessKey)
  379. if err != nil {
  380. return err
  381. }
  382. err = env.Set(env.AzureStorageAccountNameEnvVar, accountName)
  383. if err != nil {
  384. return err
  385. }
  386. err = env.Set(env.AzureStorageContainerNameEnvVar, containerName)
  387. if err != nil {
  388. return err
  389. }
  390. }
  391. return nil
  392. }
  393. func (az *Azure) getAzureStorageConfig(forceReload bool) (accessKey, accountName, containerName string) {
  394. if az.ServiceAccountChecks == nil {
  395. az.ServiceAccountChecks = make(map[string]*ServiceAccountCheck)
  396. }
  397. // 1. Check for secret
  398. s, _ := az.loadAzureStorageConfig(forceReload)
  399. if s != nil && s.AccessKey != "" && s.AccountName != "" && s.ContainerName != "" {
  400. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  401. Message: "Azure Storage Config exists",
  402. Status: true,
  403. }
  404. accessKey = s.AccessKey
  405. accountName = s.AccountName
  406. containerName = s.ContainerName
  407. return
  408. }
  409. // 3. Fall back to env vars
  410. accessKey, accountName, containerName = env.GetAzureStorageAccessKey(), env.GetAzureStorageAccountName(), env.GetAzureStorageContainerName()
  411. if accessKey != "" && accountName != "" && containerName != "" {
  412. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  413. Message: "Azure Storage Config exists",
  414. Status: true,
  415. }
  416. } else {
  417. az.ServiceAccountChecks["hasStorage"] = &ServiceAccountCheck{
  418. Message: "Azure Storage Config exists",
  419. Status: false,
  420. }
  421. }
  422. return
  423. }
  424. // Load once and cache the result (even on failure). This is an install time secret, so
  425. // we don't expect the secret to change. If it does, however, we can force reload using
  426. // the input parameter.
  427. func (az *Azure) loadAzureAuthSecret(force bool) (*AzureServiceKey, error) {
  428. if !force && loadedAzureSecret {
  429. return azureSecret, nil
  430. }
  431. loadedAzureSecret = true
  432. exists, err := fileutil.FileExists(authSecretPath)
  433. if !exists || err != nil {
  434. return nil, fmt.Errorf("Failed to locate service account file: %s", authSecretPath)
  435. }
  436. result, err := ioutil.ReadFile(authSecretPath)
  437. if err != nil {
  438. return nil, err
  439. }
  440. var ask AzureServiceKey
  441. err = json.Unmarshal(result, &ask)
  442. if err != nil {
  443. return nil, err
  444. }
  445. azureSecret = &ask
  446. return azureSecret, nil
  447. }
  448. // Load once and cache the result (even on failure). This is an install time secret, so
  449. // we don't expect the secret to change. If it does, however, we can force reload using
  450. // the input parameter.
  451. func (az *Azure) loadAzureStorageConfig(force bool) (*AzureStorageConfig, error) {
  452. if !force && loadedAzureStorageConfigSecret {
  453. return azureStorageConfig, nil
  454. }
  455. loadedAzureStorageConfigSecret = true
  456. exists, err := fileutil.FileExists(storageConfigSecretPath)
  457. if !exists || err != nil {
  458. return nil, fmt.Errorf("Failed to locate azure storage config file: %s", storageConfigSecretPath)
  459. }
  460. result, err := ioutil.ReadFile(storageConfigSecretPath)
  461. if err != nil {
  462. return nil, err
  463. }
  464. var ask AzureStorageConfig
  465. err = json.Unmarshal(result, &ask)
  466. if err != nil {
  467. return nil, err
  468. }
  469. azureStorageConfig = &ask
  470. return azureStorageConfig, nil
  471. }
  472. func (az *Azure) GetKey(labels map[string]string, n *v1.Node) Key {
  473. cfg, err := az.GetConfig()
  474. if err != nil {
  475. klog.Infof("Error loading azure custom pricing information")
  476. }
  477. // azure defaults, see https://docs.microsoft.com/en-us/azure/aks/gpu-cluster
  478. gpuLabel := "accelerator"
  479. gpuLabelValue := "nvidia"
  480. if cfg.GpuLabel != "" {
  481. gpuLabel = cfg.GpuLabel
  482. }
  483. if cfg.GpuLabelValue != "" {
  484. gpuLabelValue = cfg.GpuLabelValue
  485. }
  486. return &azureKey{
  487. Labels: labels,
  488. GPULabel: gpuLabel,
  489. GPULabelValue: gpuLabelValue,
  490. }
  491. }
  492. // CreateString builds strings effectively
  493. func createString(keys ...string) string {
  494. var b strings.Builder
  495. for _, key := range keys {
  496. b.WriteString(key)
  497. }
  498. return b.String()
  499. }
  500. func transformMachineType(subCategory string, mt []string) []string {
  501. switch {
  502. case strings.Contains(subCategory, "Basic"):
  503. return []string{createString("Basic_", mt[0])}
  504. case len(mt) == 2:
  505. return []string{createString("Standard_", mt[0]), createString("Standard_", mt[1])}
  506. default:
  507. return []string{createString("Standard_", mt[0])}
  508. }
  509. }
  510. func addSuffix(mt string, suffixes ...string) []string {
  511. result := make([]string, len(suffixes))
  512. var suffix string
  513. parts := strings.Split(mt, "_")
  514. if len(parts) > 2 {
  515. for _, p := range parts[2:] {
  516. suffix = createString(suffix, "_", p)
  517. }
  518. }
  519. for i, s := range suffixes {
  520. result[i] = createString(parts[0], "_", parts[1], s, suffix)
  521. }
  522. return result
  523. }
  524. func getMachineTypeVariants(mt string) []string {
  525. switch {
  526. case mtStandardB.MatchString(mt):
  527. return []string{createString(mt, "s")}
  528. case mtStandardD.MatchString(mt):
  529. var result []string
  530. result = append(result, addSuffix(mt, "s")[0])
  531. dsType := strings.Replace(mt, "Standard_D", "Standard_DS", -1)
  532. result = append(result, dsType)
  533. result = append(result, addSuffix(dsType, "-1", "-2", "-4", "-8")...)
  534. return result
  535. case mtStandardE.MatchString(mt):
  536. return addSuffix(mt, "s", "-2s", "-4s", "-8s", "-16s", "-32s")
  537. case mtStandardF.MatchString(mt):
  538. return addSuffix(mt, "s")
  539. case mtStandardG.MatchString(mt):
  540. var result []string
  541. gsType := strings.Replace(mt, "Standard_G", "Standard_GS", -1)
  542. result = append(result, gsType)
  543. return append(result, addSuffix(gsType, "-4", "-8", "-16")...)
  544. case mtStandardL.MatchString(mt):
  545. return addSuffix(mt, "s")
  546. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "ms"):
  547. base := strings.TrimSuffix(mt, "ms")
  548. return addSuffix(base, "-2ms", "-4ms", "-8ms", "-16ms", "-32ms", "-64ms")
  549. case mtStandardM.MatchString(mt) && (strings.HasSuffix(mt, "ls") || strings.HasSuffix(mt, "ts")):
  550. return []string{}
  551. case mtStandardM.MatchString(mt) && strings.HasSuffix(mt, "s"):
  552. base := strings.TrimSuffix(mt, "s")
  553. return addSuffix(base, "", "m")
  554. case mtStandardN.MatchString(mt):
  555. return addSuffix(mt, "s")
  556. }
  557. return []string{}
  558. }
  559. func (az *Azure) GetManagementPlatform() (string, error) {
  560. nodes := az.Clientset.GetAllNodes()
  561. if len(nodes) > 0 {
  562. n := nodes[0]
  563. providerID := n.Spec.ProviderID
  564. if strings.Contains(providerID, "aks") {
  565. return "aks", nil
  566. }
  567. }
  568. return "", nil
  569. }
  570. // DownloadPricingData uses provided azure "best guesses" for pricing
  571. func (az *Azure) DownloadPricingData() error {
  572. az.DownloadPricingDataLock.Lock()
  573. defer az.DownloadPricingDataLock.Unlock()
  574. config, err := az.GetConfig()
  575. if err != nil {
  576. return err
  577. }
  578. // Load the service provider keys
  579. subscriptionID, clientID, clientSecret, tenantID := az.getAzureAuth(false, config)
  580. config.AzureSubscriptionID = subscriptionID
  581. config.AzureClientID = clientID
  582. config.AzureClientSecret = clientSecret
  583. config.AzureTenantID = tenantID
  584. var authorizer autorest.Authorizer
  585. if config.AzureClientID != "" && config.AzureClientSecret != "" && config.AzureTenantID != "" {
  586. credentialsConfig := auth.NewClientCredentialsConfig(config.AzureClientID, config.AzureClientSecret, config.AzureTenantID)
  587. a, err := credentialsConfig.Authorizer()
  588. if err != nil {
  589. return err
  590. }
  591. authorizer = a
  592. }
  593. if authorizer == nil {
  594. a, err := auth.NewAuthorizerFromEnvironment()
  595. authorizer = a
  596. if err != nil { // Failed to create authorizer from environment, try from file
  597. a, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
  598. if err != nil {
  599. return err
  600. }
  601. authorizer = a
  602. }
  603. }
  604. sClient := subscriptions.NewClient()
  605. sClient.Authorizer = authorizer
  606. rcClient := commerce.NewRateCardClient(config.AzureSubscriptionID)
  607. rcClient.Authorizer = authorizer
  608. skusClient := skus.NewResourceSkusClient(config.AzureSubscriptionID)
  609. skusClient.Authorizer = authorizer
  610. providersClient := resources.NewProvidersClient(config.AzureSubscriptionID)
  611. providersClient.Authorizer = authorizer
  612. containerServiceClient := containerservice.NewContainerServicesClient(config.AzureSubscriptionID)
  613. containerServiceClient.Authorizer = authorizer
  614. 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)
  615. klog.Infof("Using ratecard query %s", rateCardFilter)
  616. result, err := rcClient.Get(context.TODO(), rateCardFilter)
  617. if err != nil {
  618. return err
  619. }
  620. allPrices := make(map[string]*AzurePricing)
  621. regions, err := getRegions("compute", sClient, providersClient, config.AzureSubscriptionID)
  622. if err != nil {
  623. return err
  624. }
  625. c, err := az.GetConfig()
  626. if err != nil {
  627. return err
  628. }
  629. baseCPUPrice := c.CPU
  630. for _, v := range *result.Meters {
  631. meterName := *v.MeterName
  632. meterRegion := *v.MeterRegion
  633. meterCategory := *v.MeterCategory
  634. meterSubCategory := *v.MeterSubCategory
  635. region, err := toRegionID(meterRegion, regions)
  636. if err != nil {
  637. continue
  638. }
  639. if !strings.Contains(meterSubCategory, "Windows") {
  640. if strings.Contains(meterCategory, "Storage") {
  641. if strings.Contains(meterSubCategory, "HDD") || strings.Contains(meterSubCategory, "SSD") || strings.Contains(meterSubCategory, "Premium Files") {
  642. var storageClass string = ""
  643. if strings.Contains(meterName, "P4 ") {
  644. storageClass = AzureDiskPremiumSSDStorageClass
  645. } else if strings.Contains(meterName, "E4 ") {
  646. storageClass = AzureDiskStandardSSDStorageClass
  647. } else if strings.Contains(meterName, "S4 ") {
  648. storageClass = AzureDiskStandardStorageClass
  649. } else if strings.Contains(meterName, "LRS Provisioned") {
  650. storageClass = AzureFilePremiumStorageClass
  651. }
  652. if storageClass != "" {
  653. var priceInUsd float64
  654. if len(v.MeterRates) < 1 {
  655. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  656. continue
  657. }
  658. for _, rate := range v.MeterRates {
  659. priceInUsd += *rate
  660. }
  661. // rate is in disk per month, resolve price per hour, then GB per hour
  662. pricePerHour := priceInUsd / 730.0 / 32.0
  663. priceStr := fmt.Sprintf("%f", pricePerHour)
  664. key := region + "," + storageClass
  665. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, priceStr)
  666. allPrices[key] = &AzurePricing{
  667. PV: &PV{
  668. Cost: priceStr,
  669. Region: region,
  670. },
  671. }
  672. }
  673. }
  674. }
  675. if strings.Contains(meterCategory, "Virtual Machines") {
  676. usageType := ""
  677. if !strings.Contains(meterName, "Low Priority") {
  678. usageType = "ondemand"
  679. } else {
  680. usageType = "preemptible"
  681. }
  682. var instanceTypes []string
  683. name := strings.TrimSuffix(meterName, " Low Priority")
  684. instanceType := strings.Split(name, "/")
  685. for _, it := range instanceType {
  686. if strings.Contains(meterSubCategory, "Promo") {
  687. it = it + " Promo"
  688. }
  689. instanceTypes = append(instanceTypes, strings.Replace(it, " ", "_", 1))
  690. }
  691. instanceTypes = transformMachineType(meterSubCategory, instanceTypes)
  692. if strings.Contains(name, "Expired") {
  693. instanceTypes = []string{}
  694. }
  695. var priceInUsd float64
  696. if len(v.MeterRates) < 1 {
  697. klog.V(1).Infof("missing rate info %+v", map[string]interface{}{"MeterSubCategory": *v.MeterSubCategory, "region": region})
  698. continue
  699. }
  700. for _, rate := range v.MeterRates {
  701. priceInUsd += *rate
  702. }
  703. priceStr := fmt.Sprintf("%f", priceInUsd)
  704. for _, instanceType := range instanceTypes {
  705. key := fmt.Sprintf("%s,%s,%s", region, instanceType, usageType)
  706. allPrices[key] = &AzurePricing{
  707. Node: &Node{
  708. Cost: priceStr,
  709. BaseCPUPrice: baseCPUPrice,
  710. UsageType: usageType,
  711. },
  712. }
  713. }
  714. }
  715. }
  716. }
  717. // There is no easy way of supporting Standard Azure-File, because it's billed per used GB
  718. // this will set the price to "0" as a workaround to not spam with `Persistent Volume pricing not found for` error
  719. // check https://github.com/kubecost/cost-model/issues/159 for more information (same problem on AWS)
  720. zeroPrice := "0.0"
  721. for region := range regions {
  722. key := region + "," + AzureFileStandardStorageClass
  723. klog.V(4).Infof("Adding PV.Key: %s, Cost: %s", key, zeroPrice)
  724. allPrices[key] = &AzurePricing{
  725. PV: &PV{
  726. Cost: zeroPrice,
  727. Region: region,
  728. },
  729. }
  730. }
  731. az.Pricing = allPrices
  732. return nil
  733. }
  734. func (az *Azure) addPricing(features string, azurePricing *AzurePricing) {
  735. if az.Pricing == nil {
  736. az.Pricing = map[string]*AzurePricing{}
  737. }
  738. az.Pricing[features] = azurePricing
  739. }
  740. // AllNodePricing returns the Azure pricing objects stored
  741. func (az *Azure) AllNodePricing() (interface{}, error) {
  742. az.DownloadPricingDataLock.RLock()
  743. defer az.DownloadPricingDataLock.RUnlock()
  744. return az.Pricing, nil
  745. }
  746. // NodePricing returns Azure pricing data for a single node
  747. func (az *Azure) NodePricing(key Key) (*Node, error) {
  748. az.DownloadPricingDataLock.RLock()
  749. defer az.DownloadPricingDataLock.RUnlock()
  750. azKey, ok := key.(*azureKey)
  751. if !ok {
  752. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  753. }
  754. config, _ := az.GetConfig()
  755. if slv, ok := azKey.Labels[config.SpotLabel]; 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. }