azureprovider.go 42 KB

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