azureprovider.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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. sci := v.(map[string]interface{})
  946. sc := make(map[string]string)
  947. for k, val := range sci {
  948. sc[k] = val.(string)
  949. }
  950. c.SharedCosts = sc //todo: support reflection/multiple map fields
  951. }
  952. }
  953. if env.IsRemoteEnabled() {
  954. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  955. if err != nil {
  956. return err
  957. }
  958. }
  959. return nil
  960. })
  961. }
  962. func (az *Azure) GetConfig() (*CustomPricing, error) {
  963. c, err := az.Config.GetCustomPricingData()
  964. if err != nil {
  965. return nil, err
  966. }
  967. if c.Discount == "" {
  968. c.Discount = "0%"
  969. }
  970. if c.NegotiatedDiscount == "" {
  971. c.NegotiatedDiscount = "0%"
  972. }
  973. if c.CurrencyCode == "" {
  974. c.CurrencyCode = "USD"
  975. }
  976. if c.AzureBillingRegion == "" {
  977. c.AzureBillingRegion = "US"
  978. }
  979. if c.ShareTenancyCosts == "" {
  980. c.ShareTenancyCosts = defaultShareTenancyCost
  981. }
  982. if c.SpotLabel == "" {
  983. c.SpotLabel = defaultSpotLabel
  984. }
  985. if c.SpotLabelValue == "" {
  986. c.SpotLabelValue = defaultSpotLabelValue
  987. }
  988. return c, nil
  989. }
  990. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  991. // "start" and "end" are dates of the format YYYY-MM-DD
  992. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  993. func (az *Azure) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  994. var csvRetriever CSVRetriever = AzureCSVRetriever{}
  995. err := az.ConfigureAzureStorage() // load Azure Storage config
  996. if err != nil {
  997. return nil, err
  998. }
  999. return getExternalAllocations(start, end, aggregators, filterType, filterValue, crossCluster, csvRetriever)
  1000. }
  1001. func getExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool, csvRetriever CSVRetriever) ([]*OutOfClusterAllocation, error) {
  1002. dateFormat := "2006-1-2"
  1003. startTime, err := time.Parse(dateFormat, start)
  1004. if err != nil {
  1005. return nil, err
  1006. }
  1007. endTime, err := time.Parse(dateFormat, end)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. readers, err := csvRetriever.GetCSVReaders(startTime, endTime)
  1012. if err != nil {
  1013. return nil, err
  1014. }
  1015. oocAllocs := make(map[string]*OutOfClusterAllocation)
  1016. for _, reader := range readers {
  1017. err = parseCSV(reader, startTime, endTime, oocAllocs, aggregators, filterType, filterValue, crossCluster)
  1018. if err != nil {
  1019. return nil, err
  1020. }
  1021. }
  1022. var oocAllocsArr []*OutOfClusterAllocation
  1023. for _, alloc := range oocAllocs {
  1024. oocAllocsArr = append(oocAllocsArr, alloc)
  1025. }
  1026. return oocAllocsArr, nil
  1027. }
  1028. func parseCSV(reader *csv.Reader, start, end time.Time, oocAllocs map[string]*OutOfClusterAllocation, aggregators []string, filterType string, filterValue string, crossCluster bool) error {
  1029. headers, _ := reader.Read()
  1030. headerMap := createHeaderMap(headers)
  1031. for {
  1032. var record, err = reader.Read()
  1033. if err == io.EOF {
  1034. break
  1035. }
  1036. if err != nil {
  1037. return err
  1038. }
  1039. meterCategory := record[headerMap["MeterCategory"]]
  1040. category := selectCategory(meterCategory)
  1041. usageDateTime, err := time.Parse(AzureLayout, record[headerMap["UsageDateTime"]])
  1042. if err != nil {
  1043. klog.Errorf("failed to parse usage date: '%s'", record[headerMap["UsageDateTime"]])
  1044. continue
  1045. }
  1046. // Ignore VM's and Storage Items for now
  1047. if category == kubecost.ComputeCategory || category == kubecost.StorageCategory || !isValidUsageDateTime(start, end, usageDateTime) {
  1048. continue
  1049. }
  1050. itemCost, err := strconv.ParseFloat(record[headerMap["PreTaxCost"]], 64)
  1051. if err != nil {
  1052. klog.Infof("failed to parse cost: '%s'", record[headerMap["PreTaxCost"]])
  1053. continue
  1054. }
  1055. itemTags := make(map[string]string)
  1056. itemTagJson := makeValidJSON(record[headerMap["Tags"]])
  1057. if itemTagJson != "" {
  1058. err = json.Unmarshal([]byte(itemTagJson), &itemTags)
  1059. if err != nil {
  1060. klog.Infof("Could not parse item tags %v", err)
  1061. }
  1062. }
  1063. if filterType != "kubernetes_" {
  1064. if value, ok := itemTags[filterType]; !ok || value != filterValue {
  1065. continue
  1066. }
  1067. }
  1068. environment := ""
  1069. for _, agg := range aggregators {
  1070. if tag, ok := itemTags[agg]; ok {
  1071. environment = tag // just set to the first nonempty match
  1072. break
  1073. }
  1074. }
  1075. key := environment + record[headerMap["ConsumedService"]]
  1076. if alloc, ok := oocAllocs[key]; ok {
  1077. alloc.Cost += itemCost
  1078. } else {
  1079. ooc := &OutOfClusterAllocation{
  1080. Aggregator: strings.Join(aggregators, ","),
  1081. Environment: environment,
  1082. Service: record[headerMap["ConsumedService"]],
  1083. Cost: itemCost,
  1084. }
  1085. oocAllocs[key] = ooc
  1086. }
  1087. }
  1088. return nil
  1089. }
  1090. func createHeaderMap(headers []string) map[string]int {
  1091. headerMap := make(map[string]int)
  1092. for i, header := range headers {
  1093. for _, headerString := range HeaderStrings {
  1094. if strings.Contains(header, headerString) {
  1095. headerMap[headerString] = i
  1096. }
  1097. }
  1098. }
  1099. return headerMap
  1100. }
  1101. func makeValidJSON(jsonString string) string {
  1102. if jsonString == "" || (jsonString[0] == '{' && jsonString[len(jsonString)-1] == '}') {
  1103. return jsonString
  1104. }
  1105. return fmt.Sprintf("{%v}", jsonString)
  1106. }
  1107. // UsageDateTime only contains date information and not time because of this filtering usageDate time is inclusive on start and exclusive on end
  1108. func isValidUsageDateTime(start, end, usageDateTime time.Time) bool {
  1109. return (usageDateTime.After(start) || usageDateTime.Equal(start)) && usageDateTime.Before(end)
  1110. }
  1111. func getStartAndEndTimes(usageDateTime time.Time) (time.Time, time.Time) {
  1112. start := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 0, 0, 0, 0, usageDateTime.Location())
  1113. end := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 23, 59, 59, 999999999, usageDateTime.Location())
  1114. return start, end
  1115. }
  1116. func selectCategory(meterCategory string) string {
  1117. if meterCategory == "Virtual Machines" {
  1118. return kubecost.ComputeCategory
  1119. } else if meterCategory == "Storage" {
  1120. return kubecost.StorageCategory
  1121. } else if meterCategory == "Load Balancer" || meterCategory == "Bandwidth" {
  1122. return kubecost.NetworkCategory
  1123. } else {
  1124. return kubecost.OtherCategory
  1125. }
  1126. }
  1127. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1128. }
  1129. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1130. az.DownloadPricingDataLock.RLock()
  1131. defer az.DownloadPricingDataLock.RUnlock()
  1132. pricing, ok := az.Pricing[pvk.Features()]
  1133. if !ok {
  1134. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1135. return &PV{}, nil
  1136. }
  1137. return pricing.PV, nil
  1138. }
  1139. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1140. return ""
  1141. }
  1142. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1143. checks := []*ServiceAccountCheck{}
  1144. for _, v := range az.ServiceAccountChecks {
  1145. checks = append(checks, v)
  1146. }
  1147. return &ServiceAccountStatus{
  1148. Checks: checks,
  1149. }
  1150. }
  1151. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1152. return make(map[string]*PricingSource)
  1153. }
  1154. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1155. return "", 0.0, nil
  1156. }
  1157. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1158. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1159. }