azureprovider.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. klog.V(4).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 {
  163. log.DedupedInfof(5, "retail price responded with 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. az.DownloadPricingDataLock.Lock()
  735. defer az.DownloadPricingDataLock.Unlock()
  736. if az.Pricing == nil {
  737. az.Pricing = map[string]*AzurePricing{}
  738. }
  739. az.Pricing[features] = azurePricing
  740. }
  741. // AllNodePricing returns the Azure pricing objects stored
  742. func (az *Azure) AllNodePricing() (interface{}, error) {
  743. az.DownloadPricingDataLock.RLock()
  744. defer az.DownloadPricingDataLock.RUnlock()
  745. return az.Pricing, nil
  746. }
  747. // NodePricing returns Azure pricing data for a single node
  748. func (az *Azure) NodePricing(key Key) (*Node, error) {
  749. az.DownloadPricingDataLock.RLock()
  750. defer az.DownloadPricingDataLock.RUnlock()
  751. azKey, ok := key.(*azureKey)
  752. if !ok {
  753. return nil, fmt.Errorf("azure: NodePricing: key is of type %T", key)
  754. }
  755. config, _ := az.GetConfig()
  756. if slv, ok := azKey.Labels[config.SpotLabel];
  757. ok && slv == config.SpotLabelValue && config.SpotLabel != "" && config.SpotLabelValue != "" {
  758. features := strings.Split(azKey.Features(), ",")
  759. region := features[0]
  760. instance := features[1]
  761. spotFeatures := fmt.Sprintf("%s,%s,%s", region, instance, "spot")
  762. if n, ok := az.Pricing[spotFeatures]; ok {
  763. log.DedupedInfof(5, "Returning pricing for node %s: %+v from key %s", azKey, n, spotFeatures)
  764. if azKey.isValidGPUNode() {
  765. n.Node.GPU = "1" // TODO: support multiple GPUs
  766. }
  767. return n.Node, nil
  768. }
  769. log.Infof("[Info] found spot instance, trying to get retail price for %s: %s, ", spotFeatures, azKey)
  770. spotCost, err := getRetailPrice(region, instance, config.CurrencyCode, true)
  771. if err != nil {
  772. log.DedupedWarningf(5, "failed to retrieve spot retail pricing")
  773. } else {
  774. gpu := ""
  775. if azKey.isValidGPUNode() {
  776. gpu = "1"
  777. }
  778. spotNode := &Node{
  779. Cost: spotCost,
  780. UsageType: "spot",
  781. GPU: gpu,
  782. }
  783. az.addPricing(spotFeatures, &AzurePricing{
  784. Node: spotNode,
  785. })
  786. return spotNode, nil
  787. }
  788. }
  789. if n, ok := az.Pricing[azKey.Features()]; ok {
  790. klog.V(4).Infof("Returning pricing for node %s: %+v from key %s", azKey, n, azKey.Features())
  791. if azKey.isValidGPUNode() {
  792. n.Node.GPU = azKey.GetGPUCount()
  793. }
  794. return n.Node, nil
  795. }
  796. klog.V(1).Infof("[Warning] no pricing data found for %s: %s", azKey.Features(), azKey)
  797. c, err := az.GetConfig()
  798. if err != nil {
  799. return nil, fmt.Errorf("No default pricing data available")
  800. }
  801. if azKey.isValidGPUNode() {
  802. return &Node{
  803. VCPUCost: c.CPU,
  804. RAMCost: c.RAM,
  805. UsesBaseCPUPrice: true,
  806. GPUCost: c.GPU,
  807. GPU: azKey.GetGPUCount(),
  808. }, nil
  809. }
  810. return &Node{
  811. VCPUCost: c.CPU,
  812. RAMCost: c.RAM,
  813. UsesBaseCPUPrice: true,
  814. }, nil
  815. }
  816. // Stubbed NetworkPricing for Azure. Pull directly from azure.json for now
  817. func (az *Azure) NetworkPricing() (*Network, error) {
  818. cpricing, err := az.Config.GetCustomPricingData()
  819. if err != nil {
  820. return nil, err
  821. }
  822. znec, err := strconv.ParseFloat(cpricing.ZoneNetworkEgress, 64)
  823. if err != nil {
  824. return nil, err
  825. }
  826. rnec, err := strconv.ParseFloat(cpricing.RegionNetworkEgress, 64)
  827. if err != nil {
  828. return nil, err
  829. }
  830. inec, err := strconv.ParseFloat(cpricing.InternetNetworkEgress, 64)
  831. if err != nil {
  832. return nil, err
  833. }
  834. return &Network{
  835. ZoneNetworkEgressCost: znec,
  836. RegionNetworkEgressCost: rnec,
  837. InternetNetworkEgressCost: inec,
  838. }, nil
  839. }
  840. func (azr *Azure) LoadBalancerPricing() (*LoadBalancer, error) {
  841. fffrc := 0.025
  842. afrc := 0.010
  843. lbidc := 0.008
  844. numForwardingRules := 1.0
  845. dataIngressGB := 0.0
  846. var totalCost float64
  847. if numForwardingRules < 5 {
  848. totalCost = fffrc*numForwardingRules + lbidc*dataIngressGB
  849. } else {
  850. totalCost = fffrc*5 + afrc*(numForwardingRules-5) + lbidc*dataIngressGB
  851. }
  852. return &LoadBalancer{
  853. Cost: totalCost,
  854. }, nil
  855. }
  856. type azurePvKey struct {
  857. Labels map[string]string
  858. StorageClass string
  859. StorageClassParameters map[string]string
  860. DefaultRegion string
  861. ProviderId string
  862. }
  863. func (az *Azure) GetPVKey(pv *v1.PersistentVolume, parameters map[string]string, defaultRegion string) PVKey {
  864. providerID := ""
  865. if pv.Spec.AzureDisk != nil {
  866. providerID = pv.Spec.AzureDisk.DiskName
  867. }
  868. return &azurePvKey{
  869. Labels: pv.Labels,
  870. StorageClass: pv.Spec.StorageClassName,
  871. StorageClassParameters: parameters,
  872. DefaultRegion: defaultRegion,
  873. ProviderId: providerID,
  874. }
  875. }
  876. func (key *azurePvKey) ID() string {
  877. return key.ProviderId
  878. }
  879. func (key *azurePvKey) GetStorageClass() string {
  880. return key.StorageClass
  881. }
  882. func (key *azurePvKey) Features() string {
  883. storageClass := key.StorageClassParameters["storageaccounttype"]
  884. storageSKU := key.StorageClassParameters["skuName"]
  885. if storageClass != "" {
  886. if strings.EqualFold(storageClass, "Premium_LRS") {
  887. storageClass = AzureDiskPremiumSSDStorageClass
  888. } else if strings.EqualFold(storageClass, "StandardSSD_LRS") {
  889. storageClass = AzureDiskStandardSSDStorageClass
  890. } else if strings.EqualFold(storageClass, "Standard_LRS") {
  891. storageClass = AzureDiskStandardStorageClass
  892. }
  893. } else {
  894. if strings.EqualFold(storageSKU, "Premium_LRS") {
  895. storageClass = AzureFilePremiumStorageClass
  896. } else if strings.EqualFold(storageSKU, "Standard_LRS") {
  897. storageClass = AzureFileStandardStorageClass
  898. }
  899. }
  900. if region, ok := util.GetRegion(key.Labels); ok {
  901. return region + "," + storageClass
  902. }
  903. return key.DefaultRegion + "," + storageClass
  904. }
  905. func (*Azure) GetAddresses() ([]byte, error) {
  906. return nil, nil
  907. }
  908. func (*Azure) GetDisks() ([]byte, error) {
  909. return nil, nil
  910. }
  911. func (az *Azure) ClusterInfo() (map[string]string, error) {
  912. remoteEnabled := env.IsRemoteEnabled()
  913. m := make(map[string]string)
  914. m["name"] = "Azure Cluster #1"
  915. c, err := az.GetConfig()
  916. if err != nil {
  917. return nil, err
  918. }
  919. if c.ClusterName != "" {
  920. m["name"] = c.ClusterName
  921. }
  922. m["provider"] = "azure"
  923. m["remoteReadEnabled"] = strconv.FormatBool(remoteEnabled)
  924. m["id"] = env.GetClusterID()
  925. return m, nil
  926. }
  927. func (az *Azure) UpdateConfigFromConfigMap(a map[string]string) (*CustomPricing, error) {
  928. return az.Config.UpdateFromMap(a)
  929. }
  930. func (az *Azure) UpdateConfig(r io.Reader, updateType string) (*CustomPricing, error) {
  931. defer az.DownloadPricingData()
  932. return az.Config.Update(func(c *CustomPricing) error {
  933. a := make(map[string]interface{})
  934. err := json.NewDecoder(r).Decode(&a)
  935. if err != nil {
  936. return err
  937. }
  938. for k, v := range a {
  939. kUpper := strings.Title(k) // Just so we consistently supply / receive the same values, uppercase the first letter.
  940. vstr, ok := v.(string)
  941. if ok {
  942. err := SetCustomPricingField(c, kUpper, vstr)
  943. if err != nil {
  944. return err
  945. }
  946. } else {
  947. sci := v.(map[string]interface{})
  948. sc := make(map[string]string)
  949. for k, val := range sci {
  950. sc[k] = val.(string)
  951. }
  952. c.SharedCosts = sc //todo: support reflection/multiple map fields
  953. }
  954. }
  955. if env.IsRemoteEnabled() {
  956. err := UpdateClusterMeta(env.GetClusterID(), c.ClusterName)
  957. if err != nil {
  958. return err
  959. }
  960. }
  961. return nil
  962. })
  963. }
  964. func (az *Azure) GetConfig() (*CustomPricing, error) {
  965. c, err := az.Config.GetCustomPricingData()
  966. if err != nil {
  967. return nil, err
  968. }
  969. if c.Discount == "" {
  970. c.Discount = "0%"
  971. }
  972. if c.NegotiatedDiscount == "" {
  973. c.NegotiatedDiscount = "0%"
  974. }
  975. if c.CurrencyCode == "" {
  976. c.CurrencyCode = "USD"
  977. }
  978. if c.AzureBillingRegion == "" {
  979. c.AzureBillingRegion = "US"
  980. }
  981. if c.ShareTenancyCosts == "" {
  982. c.ShareTenancyCosts = defaultShareTenancyCost
  983. }
  984. if c.SpotLabel == "" {
  985. c.SpotLabel = defaultSpotLabel
  986. }
  987. if c.SpotLabelValue == "" {
  988. c.SpotLabelValue = defaultSpotLabelValue
  989. }
  990. return c, nil
  991. }
  992. // ExternalAllocations represents tagged assets outside the scope of kubernetes.
  993. // "start" and "end" are dates of the format YYYY-MM-DD
  994. // "aggregator" is the tag used to determine how to allocate those assets, ie namespace, pod, etc.
  995. func (az *Azure) ExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool) ([]*OutOfClusterAllocation, error) {
  996. var csvRetriever CSVRetriever = AzureCSVRetriever{}
  997. err := az.ConfigureAzureStorage() // load Azure Storage config
  998. if err != nil {
  999. return nil, err
  1000. }
  1001. return getExternalAllocations(start, end, aggregators, filterType, filterValue, crossCluster, csvRetriever)
  1002. }
  1003. func getExternalAllocations(start string, end string, aggregators []string, filterType string, filterValue string, crossCluster bool, csvRetriever CSVRetriever) ([]*OutOfClusterAllocation, error) {
  1004. dateFormat := "2006-1-2"
  1005. startTime, err := time.Parse(dateFormat, start)
  1006. if err != nil {
  1007. return nil, err
  1008. }
  1009. endTime, err := time.Parse(dateFormat, end)
  1010. if err != nil {
  1011. return nil, err
  1012. }
  1013. readers, err := csvRetriever.GetCSVReaders(startTime, endTime)
  1014. if err != nil {
  1015. return nil, err
  1016. }
  1017. oocAllocs := make(map[string]*OutOfClusterAllocation)
  1018. for _, reader := range readers {
  1019. err = parseCSV(reader, startTime, endTime, oocAllocs, aggregators, filterType, filterValue, crossCluster)
  1020. if err != nil {
  1021. return nil, err
  1022. }
  1023. }
  1024. var oocAllocsArr []*OutOfClusterAllocation
  1025. for _, alloc := range oocAllocs {
  1026. oocAllocsArr = append(oocAllocsArr, alloc)
  1027. }
  1028. return oocAllocsArr, nil
  1029. }
  1030. func parseCSV(reader *csv.Reader, start, end time.Time, oocAllocs map[string]*OutOfClusterAllocation, aggregators []string, filterType string, filterValue string, crossCluster bool) error {
  1031. headers, _ := reader.Read()
  1032. headerMap := createHeaderMap(headers)
  1033. for {
  1034. var record, err = reader.Read()
  1035. if err == io.EOF {
  1036. break
  1037. }
  1038. if err != nil {
  1039. return err
  1040. }
  1041. meterCategory := record[headerMap["MeterCategory"]]
  1042. category := selectCategory(meterCategory)
  1043. usageDateTime, err := time.Parse(AzureLayout, record[headerMap["UsageDateTime"]])
  1044. if err != nil {
  1045. klog.Errorf("failed to parse usage date: '%s'", record[headerMap["UsageDateTime"]])
  1046. continue
  1047. }
  1048. // Ignore VM's and Storage Items for now
  1049. if category == kubecost.ComputeCategory || category == kubecost.StorageCategory || !isValidUsageDateTime(start, end, usageDateTime) {
  1050. continue
  1051. }
  1052. itemCost, err := strconv.ParseFloat(record[headerMap["PreTaxCost"]], 64)
  1053. if err != nil {
  1054. klog.Infof("failed to parse cost: '%s'", record[headerMap["PreTaxCost"]])
  1055. continue
  1056. }
  1057. itemTags := make(map[string]string)
  1058. itemTagJson := makeValidJSON(record[headerMap["Tags"]])
  1059. if itemTagJson != "" {
  1060. err = json.Unmarshal([]byte(itemTagJson), &itemTags)
  1061. if err != nil {
  1062. klog.Infof("Could not parse item tags %v", err)
  1063. }
  1064. }
  1065. if filterType != "kubernetes_" {
  1066. if value, ok := itemTags[filterType]; !ok || value != filterValue {
  1067. continue
  1068. }
  1069. }
  1070. environment := ""
  1071. for _, agg := range aggregators {
  1072. if tag, ok := itemTags[agg]; ok {
  1073. environment = tag // just set to the first nonempty match
  1074. break
  1075. }
  1076. }
  1077. key := environment + record[headerMap["ConsumedService"]]
  1078. if alloc, ok := oocAllocs[key]; ok {
  1079. alloc.Cost += itemCost
  1080. } else {
  1081. ooc := &OutOfClusterAllocation{
  1082. Aggregator: strings.Join(aggregators, ","),
  1083. Environment: environment,
  1084. Service: record[headerMap["ConsumedService"]],
  1085. Cost: itemCost,
  1086. }
  1087. oocAllocs[key] = ooc
  1088. }
  1089. }
  1090. return nil
  1091. }
  1092. func createHeaderMap(headers []string) map[string]int {
  1093. headerMap := make(map[string]int)
  1094. for i, header := range headers {
  1095. for _, headerString := range HeaderStrings {
  1096. if strings.Contains(header, headerString) {
  1097. headerMap[headerString] = i
  1098. }
  1099. }
  1100. }
  1101. return headerMap
  1102. }
  1103. func makeValidJSON(jsonString string) string {
  1104. if jsonString == "" || (jsonString[0] == '{' && jsonString[len(jsonString)-1] == '}') {
  1105. return jsonString
  1106. }
  1107. return fmt.Sprintf("{%v}", jsonString)
  1108. }
  1109. // UsageDateTime only contains date information and not time because of this filtering usageDate time is inclusive on start and exclusive on end
  1110. func isValidUsageDateTime(start, end, usageDateTime time.Time) bool {
  1111. return (usageDateTime.After(start) || usageDateTime.Equal(start)) && usageDateTime.Before(end)
  1112. }
  1113. func getStartAndEndTimes(usageDateTime time.Time) (time.Time, time.Time) {
  1114. start := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 0, 0, 0, 0, usageDateTime.Location())
  1115. end := time.Date(usageDateTime.Year(), usageDateTime.Month(), usageDateTime.Day(), 23, 59, 59, 999999999, usageDateTime.Location())
  1116. return start, end
  1117. }
  1118. func selectCategory(meterCategory string) string {
  1119. if meterCategory == "Virtual Machines" {
  1120. return kubecost.ComputeCategory
  1121. } else if meterCategory == "Storage" {
  1122. return kubecost.StorageCategory
  1123. } else if meterCategory == "Load Balancer" || meterCategory == "Bandwidth" {
  1124. return kubecost.NetworkCategory
  1125. } else {
  1126. return kubecost.OtherCategory
  1127. }
  1128. }
  1129. func (az *Azure) ApplyReservedInstancePricing(nodes map[string]*Node) {
  1130. }
  1131. func (az *Azure) PVPricing(pvk PVKey) (*PV, error) {
  1132. az.DownloadPricingDataLock.RLock()
  1133. defer az.DownloadPricingDataLock.RUnlock()
  1134. pricing, ok := az.Pricing[pvk.Features()]
  1135. if !ok {
  1136. klog.V(4).Infof("Persistent Volume pricing not found for %s: %s", pvk.GetStorageClass(), pvk.Features())
  1137. return &PV{}, nil
  1138. }
  1139. return pricing.PV, nil
  1140. }
  1141. func (az *Azure) GetLocalStorageQuery(window, offset time.Duration, rate bool, used bool) string {
  1142. return ""
  1143. }
  1144. func (az *Azure) ServiceAccountStatus() *ServiceAccountStatus {
  1145. checks := []*ServiceAccountCheck{}
  1146. for _, v := range az.ServiceAccountChecks {
  1147. checks = append(checks, v)
  1148. }
  1149. return &ServiceAccountStatus{
  1150. Checks: checks,
  1151. }
  1152. }
  1153. func (az *Azure) PricingSourceStatus() map[string]*PricingSource {
  1154. return make(map[string]*PricingSource)
  1155. }
  1156. func (*Azure) ClusterManagementPricing() (string, float64, error) {
  1157. return "", 0.0, nil
  1158. }
  1159. func (az *Azure) CombinedDiscountForNode(instanceType string, isPreemptible bool, defaultDiscount, negotiatedDiscount float64) float64 {
  1160. return 1.0 - ((1.0 - defaultDiscount) * (1.0 - negotiatedDiscount))
  1161. }