cloud_test.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. package provider_test
  2. import (
  3. "fmt"
  4. "math"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/opencost/opencost/core/pkg/clusters"
  12. "github.com/opencost/opencost/core/pkg/env"
  13. "github.com/opencost/opencost/core/pkg/storage"
  14. "github.com/opencost/opencost/core/pkg/clustercache"
  15. "github.com/opencost/opencost/pkg/cloud/provider"
  16. "github.com/opencost/opencost/pkg/config"
  17. "github.com/opencost/opencost/pkg/costmodel"
  18. v1 "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/api/resource"
  20. )
  21. const (
  22. providerIDMap = "spec.providerID"
  23. nameMap = "metadata.name"
  24. labelMapFoo = "metadata.labels.foo"
  25. )
  26. func TestRegionValueFromMapField(t *testing.T) {
  27. wantRegion := "useast"
  28. wantpid := strings.ToLower("/subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/MC_test_test_eastus/providers/Microsoft.Compute/virtualMachines/aks-agentpool-20139558-0")
  29. providerIDWant := wantRegion + "," + wantpid
  30. n := &clustercache.Node{}
  31. n.SpecProviderID = "azure:///subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/MC_test_test_eastus/providers/Microsoft.Compute/virtualMachines/aks-agentpool-20139558-0"
  32. n.Labels = make(map[string]string)
  33. n.Labels[v1.LabelTopologyRegion] = wantRegion
  34. got := provider.NodeValueFromMapField(providerIDMap, n, true)
  35. if got != providerIDWant {
  36. t.Errorf("Assert on '%s' want '%s' got '%s'", providerIDMap, providerIDWant, got)
  37. }
  38. }
  39. func TestTransformedValueFromMapField(t *testing.T) {
  40. providerIDWant := "i-05445591e0d182d42"
  41. n := &clustercache.Node{}
  42. n.SpecProviderID = "aws:///us-east-1a/i-05445591e0d182d42"
  43. got := provider.NodeValueFromMapField(providerIDMap, n, false)
  44. if got != providerIDWant {
  45. t.Errorf("Assert on '%s' want '%s' got '%s'", providerIDMap, providerIDWant, got)
  46. }
  47. providerIDWant2 := strings.ToLower("/subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/MC_test_test_eastus/providers/Microsoft.Compute/virtualMachines/aks-agentpool-20139558-0")
  48. n2 := &clustercache.Node{}
  49. n2.SpecProviderID = "azure:///subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/MC_test_test_eastus/providers/Microsoft.Compute/virtualMachines/aks-agentpool-20139558-0"
  50. got2 := provider.NodeValueFromMapField(providerIDMap, n2, false)
  51. if got2 != providerIDWant2 {
  52. t.Errorf("Assert on '%s' want '%s' got '%s'", providerIDMap, providerIDWant2, got2)
  53. }
  54. providerIDWant3 := strings.ToLower("/subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/mc_testspot_testspot_eastus/providers/Microsoft.Compute/virtualMachineScaleSets/aks-nodepool1-19213364-vmss/virtualMachines/0")
  55. n3 := &clustercache.Node{}
  56. n3.SpecProviderID = "azure:///subscriptions/0bd50fdf-c923-4e1e-850c-196dd3dcc5d3/resourceGroups/mc_testspot_testspot_eastus/providers/Microsoft.Compute/virtualMachineScaleSets/aks-nodepool1-19213364-vmss/virtualMachines/0"
  57. got3 := provider.NodeValueFromMapField(providerIDMap, n3, false)
  58. if got3 != providerIDWant3 {
  59. t.Errorf("Assert on '%s' want '%s' got '%s'", providerIDMap, providerIDWant3, got3)
  60. }
  61. }
  62. func TestNodeValueFromMapField(t *testing.T) {
  63. providerIDWant := "providerid"
  64. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  65. labelFooWant := "labelfoo"
  66. n := &clustercache.Node{}
  67. n.SpecProviderID = providerIDWant
  68. n.Name = nameWant
  69. n.Labels = make(map[string]string)
  70. n.Labels["foo"] = labelFooWant
  71. got := provider.NodeValueFromMapField(providerIDMap, n, false)
  72. if got != providerIDWant {
  73. t.Errorf("Assert on '%s' want '%s' got '%s'", providerIDMap, providerIDWant, got)
  74. }
  75. got = provider.NodeValueFromMapField(nameMap, n, false)
  76. if got != nameWant {
  77. t.Errorf("Assert on '%s' want '%s' got '%s'", nameMap, nameWant, got)
  78. }
  79. got = provider.NodeValueFromMapField(labelMapFoo, n, false)
  80. if got != labelFooWant {
  81. t.Errorf("Assert on '%s' want '%s' got '%s'", labelMapFoo, labelFooWant, got)
  82. }
  83. }
  84. func TestPVPriceFromCSV(t *testing.T) {
  85. nameWant := "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d"
  86. pv := &clustercache.PersistentVolume{}
  87. pv.Name = nameWant
  88. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  89. wantPrice := "0.1337"
  90. c := &provider.CSVProvider{
  91. CSVLocation: "../../../configs/pricing_schema_pv.csv",
  92. CustomProvider: &provider.CustomProvider{
  93. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  94. },
  95. }
  96. c.DownloadPricingData()
  97. k := c.GetPVKey(pv, make(map[string]string), "")
  98. resPV, err := c.PVPricing(k)
  99. if err != nil {
  100. t.Errorf("Error in NodePricing: %s", err.Error())
  101. } else {
  102. gotPrice := resPV.Cost
  103. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  104. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  105. if gotPriceFloat != wantPriceFloat {
  106. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  107. }
  108. }
  109. }
  110. func TestPVPriceFromCSVStorageClass(t *testing.T) {
  111. nameWant := "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d"
  112. storageClassWant := "storageclass0"
  113. pv := &clustercache.PersistentVolume{}
  114. pv.Name = nameWant
  115. pv.Spec.StorageClassName = storageClassWant
  116. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  117. wantPrice := "0.1338"
  118. c := &provider.CSVProvider{
  119. CSVLocation: "../../../configs/pricing_schema_pv_storageclass.csv",
  120. CustomProvider: &provider.CustomProvider{
  121. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  122. },
  123. }
  124. c.DownloadPricingData()
  125. k := c.GetPVKey(pv, make(map[string]string), "")
  126. resPV, err := c.PVPricing(k)
  127. if err != nil {
  128. t.Errorf("Error in NodePricing: %s", err.Error())
  129. } else {
  130. gotPrice := resPV.Cost
  131. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  132. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  133. if gotPriceFloat != wantPriceFloat {
  134. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  135. }
  136. }
  137. }
  138. func TestNodePriceFromCSVWithGPU(t *testing.T) {
  139. providerIDWant := "providerid"
  140. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  141. labelFooWant := "labelfoo"
  142. wantGPU := "2"
  143. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  144. n := &clustercache.Node{}
  145. n.SpecProviderID = providerIDWant
  146. n.Name = nameWant
  147. n.Labels = make(map[string]string)
  148. n.Labels["foo"] = labelFooWant
  149. n.Labels["nvidia.com/gpu_type"] = "Quadro_RTX_4000"
  150. n.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  151. wantPrice := "1.633700"
  152. n2 := &clustercache.Node{}
  153. n2.SpecProviderID = providerIDWant
  154. n2.Name = nameWant
  155. n2.Labels = make(map[string]string)
  156. n2.Labels["foo"] = labelFooWant
  157. n2.Labels["gpu.nvidia.com/class"] = "Quadro_RTX_4001"
  158. n2.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  159. wantPrice2 := "1.733700"
  160. c := &provider.CSVProvider{
  161. CSVLocation: "../../../configs/pricing_schema.csv",
  162. CustomProvider: &provider.CustomProvider{
  163. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  164. },
  165. }
  166. c.DownloadPricingData()
  167. k := c.GetKey(n.Labels, n)
  168. resN, _, err := c.NodePricing(k)
  169. if err != nil {
  170. t.Errorf("Error in NodePricing: %s", err.Error())
  171. } else {
  172. gotGPU := resN.GPU
  173. gotPrice := resN.Cost
  174. if gotGPU != wantGPU {
  175. t.Errorf("Wanted gpu count '%s' got gpu count '%s'", wantGPU, gotGPU)
  176. }
  177. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  178. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  179. if gotPriceFloat != wantPriceFloat {
  180. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  181. }
  182. }
  183. k2 := c.GetKey(n2.Labels, n2)
  184. resN2, _, err := c.NodePricing(k2)
  185. if err != nil {
  186. t.Errorf("Error in NodePricing: %s", err.Error())
  187. } else {
  188. gotGPU := resN2.GPU
  189. gotPrice := resN2.Cost
  190. if gotGPU != wantGPU {
  191. t.Errorf("Wanted gpu count '%s' got gpu count '%s'", wantGPU, gotGPU)
  192. }
  193. wantPriceFloat, _ := strconv.ParseFloat(wantPrice2, 64)
  194. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  195. if gotPriceFloat != wantPriceFloat {
  196. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  197. }
  198. }
  199. }
  200. func TestNodePriceFromCSVWithGPULabels(t *testing.T) {
  201. const defaultConfigJson = `{"provider":"base","description":"Default prices based on GCP us-central1","CPU":"0.021811","spotCPU":"0.006543","RAM":"0.002923","spotRAM":"0.000877","GPU":"0.95","spotGPU":"0.308","storage":"0.00005479452","zoneNetworkEgress":"0.01","regionNetworkEgress":"0.01","internetNetworkEgress":"0.12","firstFiveForwardingRulesCost":"","additionalForwardingRuleCost":"","LBIngressDataCost":"","athenaBucketName":"","athenaRegion":"","athenaDatabase":"","athenaCatalog":"","athenaTable":"","athenaWorkgroup":"","masterPayerARN":"","customPricesEnabled":"false","defaultIdle":"","azureSubscriptionID":"","azureClientID":"","azureClientSecret":"","azureTenantID":"","azureBillingRegion":"","azureBillingAccount":"","azureOfferDurableID":"","azureStorageSubscriptionID":"","azureStorageAccount":"","azureStorageAccessKey":"","azureStorageContainer":"","azureContainerPath":"","azureCloud":"","currencyCode":"","discount":"","negotiatedDiscount":"","sharedOverhead":"","clusterName":"","sharedNamespaces":"","sharedLabelNames":"","sharedLabelValues":"","shareTenancyCosts":"true","readOnly":"","editorAccess":"","kubecostToken":"","googleAnalyticsTag":"","excludeProviderID":"","defaultLBPrice":""}`
  202. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  203. wantGPUCost := "0.75"
  204. tempPath := t.TempDir()
  205. currentPath, err := filepath.Abs(".")
  206. if err != nil {
  207. t.Skip(fmt.Sprintf("Unable to get absolute path for current dir: '%s' - Error: %s - Skipping test.", currentPath, err))
  208. return
  209. }
  210. configPath, err := filepath.Rel(currentPath, tempPath)
  211. if err != nil {
  212. t.Skip(fmt.Sprintf("Unable to get relative path for temp dir: '%s' - Error: %s - Skipping test.", tempPath, err))
  213. return
  214. }
  215. err = os.WriteFile(filepath.Join(configPath, "default.json"), []byte(defaultConfigJson), 0644)
  216. if err != nil {
  217. t.Skip(fmt.Sprintf("Unable to write temporary json config file: '%s' - Error: %s - Skipping test.", filepath.Join(configPath, "default.json"), err))
  218. return
  219. }
  220. t.Logf("Setting Config Path to: %s", configPath)
  221. t.Setenv(env.ConfigPathEnvVar, configPath)
  222. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  223. n := &clustercache.Node{}
  224. n.SpecProviderID = "providerid"
  225. n.Name = nameWant
  226. n.Labels = make(map[string]string)
  227. n.Labels["foo"] = "labelfoo"
  228. n.Labels["nvidia.com/gpu_type"] = "Quadro_RTX_4000"
  229. n.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  230. c := &provider.CSVProvider{
  231. CSVLocation: "../../../configs/pricing_schema_gpu_labels.csv",
  232. CustomProvider: &provider.CustomProvider{
  233. Config: provider.NewProviderConfig(confMan, "default.json"),
  234. },
  235. }
  236. c.DownloadPricingData()
  237. fc := NewFakeNodeCache([]*clustercache.Node{n})
  238. fm := FakeClusterMap{}
  239. d, _ := time.ParseDuration("1m")
  240. model := costmodel.NewCostModel(nil, c, fc, fm, d)
  241. nodeMap, err := model.GetNodeCost()
  242. if err != nil {
  243. t.Errorf("Error in NodePricing: %s", err.Error())
  244. } else {
  245. if node, ok := nodeMap[nameWant]; ok {
  246. if node.GPUCost != wantGPUCost {
  247. t.Errorf("Wanted gpu cost '%v' got gpu cost '%v'", wantGPUCost, node.GPUCost)
  248. }
  249. } else {
  250. t.Errorf("Node %s not found in node map", nameWant)
  251. }
  252. }
  253. }
  254. func TestRKE2NodePriceFromCSVWithGPULabels(t *testing.T) {
  255. const defaultConfigJson = `{"provider":"base","description":"Default prices based on GCP us-central1","CPU":"0.021811","spotCPU":"0.006543","RAM":"0.002923","spotRAM":"0.000877","GPU":"0.95","spotGPU":"0.308","storage":"0.00005479452","zoneNetworkEgress":"0.01","regionNetworkEgress":"0.01","internetNetworkEgress":"0.12","firstFiveForwardingRulesCost":"","additionalForwardingRuleCost":"","LBIngressDataCost":"","athenaBucketName":"","athenaRegion":"","athenaDatabase":"","athenaCatalog":"","athenaTable":"","athenaWorkgroup":"","masterPayerARN":"","customPricesEnabled":"false","defaultIdle":"","azureSubscriptionID":"","azureClientID":"","azureClientSecret":"","azureTenantID":"","azureBillingRegion":"","azureBillingAccount":"","azureOfferDurableID":"","azureStorageSubscriptionID":"","azureStorageAccount":"","azureStorageAccessKey":"","azureStorageContainer":"","azureContainerPath":"","azureCloud":"","currencyCode":"","discount":"","negotiatedDiscount":"","sharedOverhead":"","clusterName":"","sharedNamespaces":"","sharedLabelNames":"","sharedLabelValues":"","shareTenancyCosts":"true","readOnly":"","editorAccess":"","kubecostToken":"","googleAnalyticsTag":"","excludeProviderID":"","defaultLBPrice":""}`
  256. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  257. wantGPUCost := "0.750000"
  258. tempPath := t.TempDir()
  259. currentPath, err := filepath.Abs(".")
  260. if err != nil {
  261. t.Skip(fmt.Sprintf("Unable to get absolute path for current dir: '%s' - Error: %s - Skipping test.", currentPath, err))
  262. return
  263. }
  264. configPath, err := filepath.Rel(currentPath, tempPath)
  265. if err != nil {
  266. t.Skip(fmt.Sprintf("Unable to get relative path for temp dir: '%s' - Error: %s - Skipping test.", tempPath, err))
  267. return
  268. }
  269. err = os.WriteFile(filepath.Join(configPath, "default.json"), []byte(defaultConfigJson), 0644)
  270. if err != nil {
  271. t.Skip(fmt.Sprintf("Unable to write temporary json config file: '%s' - Error: %s - Skipping test.", filepath.Join(configPath, "default.json"), err))
  272. return
  273. }
  274. t.Logf("Setting Config Path to: %s", configPath)
  275. t.Setenv(env.ConfigPathEnvVar, configPath)
  276. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  277. n := &clustercache.Node{}
  278. n.SpecProviderID = "providerid"
  279. n.Name = nameWant
  280. n.Labels = make(map[string]string)
  281. n.Labels["foo"] = "labelfoo"
  282. n.Labels["nvidia.com/gpu_type"] = "Quadro_RTX_4000"
  283. n.Labels[v1.LabelInstanceTypeStable] = "rke2"
  284. n.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  285. c := &provider.CSVProvider{
  286. CSVLocation: "../../../configs/pricing_schema_gpu_labels.csv",
  287. CustomProvider: &provider.CustomProvider{
  288. Config: provider.NewProviderConfig(confMan, "default.json"),
  289. },
  290. }
  291. c.DownloadPricingData()
  292. fc := NewFakeNodeCache([]*clustercache.Node{n})
  293. fm := FakeClusterMap{}
  294. d, _ := time.ParseDuration("1m")
  295. model := costmodel.NewCostModel(nil, c, fc, fm, d)
  296. nodeMap, err := model.GetNodeCost()
  297. if err != nil {
  298. t.Errorf("Error in NodePricing: %s", err.Error())
  299. } else {
  300. if node, ok := nodeMap[nameWant]; ok {
  301. if node.GPUCost != wantGPUCost {
  302. t.Errorf("Wanted gpu cost '%v' got gpu cost '%v'", wantGPUCost, node.GPUCost)
  303. }
  304. } else {
  305. t.Errorf("Node %s not found in node map", nameWant)
  306. }
  307. }
  308. }
  309. func TestNodePriceFromCSVSpecialChar(t *testing.T) {
  310. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  311. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  312. n := &clustercache.Node{}
  313. n.Name = nameWant
  314. n.Labels = make(map[string]string)
  315. n.Labels["<http://metadata.label.servers.com/label|metadata.label.servers.com/label>"] = nameWant
  316. wantPrice := "0.133700"
  317. c := &provider.CSVProvider{
  318. CSVLocation: "../../../configs/pricing_schema_special_char.csv",
  319. CustomProvider: &provider.CustomProvider{
  320. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  321. },
  322. }
  323. c.DownloadPricingData()
  324. k := c.GetKey(n.Labels, n)
  325. resN, _, err := c.NodePricing(k)
  326. if err != nil {
  327. t.Errorf("Error in NodePricing: %s", err.Error())
  328. } else {
  329. gotPrice := resN.Cost
  330. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  331. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  332. if gotPriceFloat != wantPriceFloat {
  333. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  334. }
  335. }
  336. }
  337. func TestNodePriceFromCSV(t *testing.T) {
  338. providerIDWant := "providerid"
  339. nameWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  340. labelFooWant := "labelfoo"
  341. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  342. n := &clustercache.Node{}
  343. n.SpecProviderID = providerIDWant
  344. n.Name = nameWant
  345. n.Labels = make(map[string]string)
  346. n.Labels["foo"] = labelFooWant
  347. wantPrice := "0.133700"
  348. c := &provider.CSVProvider{
  349. CSVLocation: "../../../configs/pricing_schema.csv",
  350. CustomProvider: &provider.CustomProvider{
  351. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  352. },
  353. }
  354. c.DownloadPricingData()
  355. k := c.GetKey(n.Labels, n)
  356. resN, _, err := c.NodePricing(k)
  357. if err != nil {
  358. t.Errorf("Error in NodePricing: %s", err.Error())
  359. } else {
  360. gotPrice := resN.Cost
  361. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  362. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  363. if gotPriceFloat != wantPriceFloat {
  364. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  365. }
  366. }
  367. unknownN := &clustercache.Node{}
  368. unknownN.SpecProviderID = providerIDWant
  369. unknownN.Name = "unknownname"
  370. unknownN.Labels = make(map[string]string)
  371. unknownN.Labels["foo"] = labelFooWant
  372. unknownN.Labels[v1.LabelTopologyRegion] = "fakeregion"
  373. k2 := c.GetKey(unknownN.Labels, unknownN)
  374. resN2, _, _ := c.NodePricing(k2)
  375. if resN2 != nil {
  376. t.Errorf("CSV provider should return nil on missing node")
  377. }
  378. c2 := &provider.CSVProvider{
  379. CSVLocation: "../../../configs/fake.csv",
  380. CustomProvider: &provider.CustomProvider{
  381. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  382. },
  383. }
  384. k3 := c.GetKey(n.Labels, n)
  385. resN3, _, _ := c2.NodePricing(k3)
  386. if resN3 != nil {
  387. t.Errorf("CSV provider should return nil on missing csv")
  388. }
  389. }
  390. func TestNodePriceFromCSVWithRegion(t *testing.T) {
  391. providerIDWant := "gke-standard-cluster-1-pool-1-91dc432d-cg69"
  392. nameWant := "foo"
  393. labelFooWant := "labelfoo"
  394. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  395. n := &clustercache.Node{}
  396. n.SpecProviderID = providerIDWant
  397. n.Name = nameWant
  398. n.Labels = make(map[string]string)
  399. n.Labels["foo"] = labelFooWant
  400. n.Labels[v1.LabelTopologyRegion] = "regionone"
  401. wantPrice := "0.133700"
  402. n2 := &clustercache.Node{}
  403. n2.SpecProviderID = providerIDWant
  404. n2.Name = nameWant
  405. n2.Labels = make(map[string]string)
  406. n2.Labels["foo"] = labelFooWant
  407. n2.Labels[v1.LabelTopologyRegion] = "regiontwo"
  408. wantPrice2 := "0.133800"
  409. n3 := &clustercache.Node{}
  410. n3.SpecProviderID = providerIDWant
  411. n3.Name = nameWant
  412. n3.Labels = make(map[string]string)
  413. n3.Labels["foo"] = labelFooWant
  414. n3.Labels[v1.LabelTopologyRegion] = "fakeregion"
  415. wantPrice3 := "0.1339"
  416. c := &provider.CSVProvider{
  417. CSVLocation: "../../../configs/pricing_schema_region.csv",
  418. CustomProvider: &provider.CustomProvider{
  419. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  420. },
  421. }
  422. c.DownloadPricingData()
  423. k := c.GetKey(n.Labels, n)
  424. resN, _, err := c.NodePricing(k)
  425. if err != nil {
  426. t.Errorf("Error in NodePricing: %s", err.Error())
  427. } else {
  428. gotPrice := resN.Cost
  429. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  430. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  431. if gotPriceFloat != wantPriceFloat {
  432. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  433. }
  434. }
  435. k2 := c.GetKey(n2.Labels, n2)
  436. resN2, _, err := c.NodePricing(k2)
  437. if err != nil {
  438. t.Errorf("Error in NodePricing: %s", err.Error())
  439. } else {
  440. gotPrice := resN2.Cost
  441. wantPriceFloat, _ := strconv.ParseFloat(wantPrice2, 64)
  442. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  443. if gotPriceFloat != wantPriceFloat {
  444. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  445. }
  446. }
  447. k3 := c.GetKey(n3.Labels, n3)
  448. resN3, _, err := c.NodePricing(k3)
  449. if err != nil {
  450. t.Errorf("Error in NodePricing: %s", err.Error())
  451. } else {
  452. gotPrice := resN3.Cost
  453. wantPriceFloat, _ := strconv.ParseFloat(wantPrice3, 64)
  454. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  455. if gotPriceFloat != wantPriceFloat {
  456. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  457. }
  458. }
  459. unknownN := &clustercache.Node{}
  460. unknownN.SpecProviderID = "fake providerID"
  461. unknownN.Name = "unknownname"
  462. unknownN.Labels = make(map[string]string)
  463. unknownN.Labels[v1.LabelTopologyRegion] = "fakeregion"
  464. unknownN.Labels["foo"] = labelFooWant
  465. k4 := c.GetKey(unknownN.Labels, unknownN)
  466. resN4, _, _ := c.NodePricing(k4)
  467. if resN4 != nil {
  468. t.Errorf("CSV provider should return nil on missing node, instead returned %+v", resN4)
  469. }
  470. c2 := &provider.CSVProvider{
  471. CSVLocation: "../../../configs/fake.csv",
  472. CustomProvider: &provider.CustomProvider{
  473. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  474. },
  475. }
  476. k5 := c.GetKey(n.Labels, n)
  477. resN5, _, _ := c2.NodePricing(k5)
  478. if resN5 != nil {
  479. t.Errorf("CSV provider should return nil on missing csv")
  480. }
  481. }
  482. type FakeCache struct {
  483. nodes []*clustercache.Node
  484. clustercache.ClusterCache
  485. }
  486. func (f FakeCache) GetAllNodes() []*clustercache.Node {
  487. return f.nodes
  488. }
  489. func (f FakeCache) GetAllDaemonSets() []*clustercache.DaemonSet {
  490. return nil
  491. }
  492. func NewFakeNodeCache(nodes []*clustercache.Node) FakeCache {
  493. return FakeCache{
  494. nodes: nodes,
  495. }
  496. }
  497. type FakeClusterMap struct {
  498. clusters.ClusterMap
  499. }
  500. func TestNodePriceFromCSVWithBadConfig(t *testing.T) {
  501. const invalidConfigJson = `{
  502. "provider":"base",
  503. "description":"Default prices based on GCP us-central1",
  504. "CPU":"0.031611",
  505. "spotCPU":"0.006655",
  506. "RAM":"0.004237",
  507. "spotRAM":"0.000892",
  508. "GPU":"0.95",
  509. "spotGPU":"0.308",
  510. "storage":"0.00005479452",
  511. "zoneNetworkEgress":"0.01",
  512. "regionNetworkEgress":"0.01",
  513. "internetNetworkEgress":"0.12",
  514. "firstFiveForwardingRulesCost":"",
  515. "additionalForwardingRuleCost":"",
  516. "LBIngressDataCost":"",
  517. "athenaBucketName":"",
  518. "athenaRegion":"",
  519. "athenaDatabase":"",
  520. "athenaTable":"",
  521. "athenaWorkgroup":"",
  522. "masterPayerARN":"",
  523. "customPricesEnabled":"false",
  524. "defaultIdle":"",
  525. "azureSubscriptionID":"",
  526. "azureClientID":"",
  527. "azureClientSecret":"",
  528. "azureTenantID":"",
  529. "azureBillingRegion":"",
  530. "azureOfferDurableID":"",
  531. "azureStorageSubscriptionID":"",
  532. "azureStorageAccount":"",
  533. "azureStorageAccessKey":"",
  534. "azureStorageContainer":"",
  535. "azureContainerPath":"",
  536. "azureCloud":"",
  537. "currencyCode":"",
  538. "discount":"",
  539. "negotiatedDiscount":"",
  540. "sharedOverhead":"",
  541. "clusterName":"",
  542. "sharedNamespaces":"",
  543. "sharedLabelNames":"",
  544. "sharedLabelValues":"",
  545. "shareTenancyCosts":"true",
  546. "readOnly":"",
  547. "editorAccess":"",
  548. "kubecostToken":"",
  549. "googleAnalyticsTag":"",
  550. "excludeProviderID":""
  551. }`
  552. tempPath := t.TempDir()
  553. currentPath, err := filepath.Abs(".")
  554. if err != nil {
  555. t.Skip(fmt.Sprintf("Unable to get absolute path for current dir: '%s' - Error: %s - Skipping test.", currentPath, err))
  556. return
  557. }
  558. configPath, err := filepath.Rel(currentPath, tempPath)
  559. if err != nil {
  560. t.Skip(fmt.Sprintf("Unable to get relative path for temp dir: '%s' - Error: %s - Skipping test.", tempPath, err))
  561. return
  562. }
  563. err = os.WriteFile(filepath.Join(configPath, "invalid.json"), []byte(invalidConfigJson), 0644)
  564. if err != nil {
  565. t.Skip(fmt.Sprintf("Unable to write temporary json config file: '%s' - Error: %s - Skipping test.", filepath.Join(configPath, "invalid.json"), err))
  566. return
  567. }
  568. t.Logf("Setting Config Path to: %s", configPath)
  569. t.Setenv(env.ConfigPathEnvVar, configPath)
  570. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  571. c := &provider.CSVProvider{
  572. CSVLocation: "../../../configs/pricing_schema_case.csv",
  573. CustomProvider: &provider.CustomProvider{
  574. Config: provider.NewProviderConfig(confMan, "invalid.json"),
  575. },
  576. }
  577. c.DownloadPricingData()
  578. n := &clustercache.Node{}
  579. n.SpecProviderID = "fake"
  580. n.Name = "nameWant"
  581. n.Labels = make(map[string]string)
  582. n.Labels["foo"] = "labelFooWant"
  583. n.Labels[v1.LabelTopologyRegion] = "regionone"
  584. fc := NewFakeNodeCache([]*clustercache.Node{n})
  585. fm := FakeClusterMap{}
  586. d, _ := time.ParseDuration("1m")
  587. model := costmodel.NewCostModel(nil, c, fc, fm, d)
  588. _, err = model.GetNodeCost()
  589. if err != nil {
  590. t.Errorf("Error in node pricing: %s", err)
  591. }
  592. }
  593. func TestSourceMatchesFromCSV(t *testing.T) {
  594. os.Setenv(env.ConfigPathEnvVar, "../../../configs")
  595. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  596. c := &provider.CSVProvider{
  597. CSVLocation: "../../../configs/pricing_schema_case.csv",
  598. CustomProvider: &provider.CustomProvider{
  599. Config: provider.NewProviderConfig(confMan, "default.json"),
  600. },
  601. }
  602. c.DownloadPricingData()
  603. n := &clustercache.Node{}
  604. n.SpecProviderID = "fake"
  605. n.Name = "nameWant"
  606. n.Labels = make(map[string]string)
  607. n.Labels["foo"] = "labelFooWant"
  608. n.Labels[v1.LabelTopologyRegion] = "regionone"
  609. n2 := &clustercache.Node{}
  610. n2.SpecProviderID = "azure:///subscriptions/123a7sd-asd-1234-578a9-123abcdef/resourceGroups/case_12_STaGe_TeSt7/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-agent-worker0-12stagetest7-ezggnore/virtualMachines/7"
  611. n2.Labels = make(map[string]string)
  612. n2.Labels[v1.LabelTopologyRegion] = "eastus2"
  613. n2.Labels["foo"] = "labelFooWant"
  614. k := c.GetKey(n2.Labels, n2)
  615. resN, _, err := c.NodePricing(k)
  616. if err != nil {
  617. t.Errorf("Error in NodePricing: %s", err.Error())
  618. } else {
  619. wantPrice := "0.13370357"
  620. gotPrice := resN.Cost
  621. if gotPrice != wantPrice {
  622. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  623. }
  624. }
  625. n3 := &clustercache.Node{}
  626. n3.SpecProviderID = "fake"
  627. n3.Name = "nameWant"
  628. n3.Labels = make(map[string]string)
  629. n3.Labels[v1.LabelTopologyRegion] = "eastus2"
  630. n3.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  631. fc := NewFakeNodeCache([]*clustercache.Node{n, n2, n3})
  632. fm := FakeClusterMap{}
  633. d, _ := time.ParseDuration("1m")
  634. model := costmodel.NewCostModel(nil, c, fc, fm, d)
  635. _, err = model.GetNodeCost()
  636. if err != nil {
  637. t.Errorf("Error in node pricing: %s", err)
  638. }
  639. p, err := model.GetPricingSourceCounts()
  640. if err != nil {
  641. t.Errorf("Error in pricing source counts: %s", err)
  642. } else if p.TotalNodes != 3 {
  643. t.Errorf("Wanted 3 nodes got %d", p.TotalNodes)
  644. }
  645. if p.PricingTypeCounts[""] != 1 {
  646. t.Errorf("Wanted 1 default match got %d: %+v", p.PricingTypeCounts[""], p.PricingTypeCounts)
  647. }
  648. if p.PricingTypeCounts["csvExact"] != 1 {
  649. t.Errorf("Wanted 1 exact match got %d: %+v", p.PricingTypeCounts["csvExact"], p.PricingTypeCounts)
  650. }
  651. if p.PricingTypeCounts["csvClass"] != 1 {
  652. t.Errorf("Wanted 1 class match got %d: %+v", p.PricingTypeCounts["csvClass"], p.PricingTypeCounts)
  653. }
  654. }
  655. func TestNodePriceFromCSVWithCase(t *testing.T) {
  656. n := &clustercache.Node{}
  657. n.SpecProviderID = "azure:///subscriptions/123a7sd-asd-1234-578a9-123abcdef/resourceGroups/case_12_STaGe_TeSt7/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-agent-worker0-12stagetest7-ezggnore/virtualMachines/7"
  658. n.Labels = make(map[string]string)
  659. n.Labels[v1.LabelTopologyRegion] = "eastus2"
  660. wantPrice := "0.13370357"
  661. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  662. c := &provider.CSVProvider{
  663. CSVLocation: "../../../configs/pricing_schema_case.csv",
  664. CustomProvider: &provider.CustomProvider{
  665. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  666. },
  667. }
  668. c.DownloadPricingData()
  669. k := c.GetKey(n.Labels, n)
  670. resN, _, err := c.NodePricing(k)
  671. if err != nil {
  672. t.Errorf("Error in NodePricing: %s", err.Error())
  673. } else {
  674. gotPrice := resN.Cost
  675. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  676. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  677. if gotPriceFloat != wantPriceFloat {
  678. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  679. }
  680. }
  681. }
  682. func TestNodePriceFromCSVMixed(t *testing.T) {
  683. labelFooWant := "OnDemand"
  684. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  685. n := &clustercache.Node{}
  686. n.Labels = make(map[string]string)
  687. n.Labels["TestClusterUsage"] = labelFooWant
  688. n.Labels["nvidia.com/gpu_type"] = "a100-ondemand"
  689. n.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  690. wantPrice := "1.904110"
  691. labelFooWant2 := "Reserved"
  692. n2 := &clustercache.Node{}
  693. n2.Labels = make(map[string]string)
  694. n2.Labels["TestClusterUsage"] = labelFooWant2
  695. n2.Labels["nvidia.com/gpu_type"] = "a100-reserved"
  696. n2.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(1, 0)}
  697. wantPrice2 := "1.654795"
  698. c := &provider.CSVProvider{
  699. CSVLocation: "../../../configs/pricing_schema_mixed_gpu_ondemand.csv",
  700. CustomProvider: &provider.CustomProvider{
  701. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  702. },
  703. }
  704. c.DownloadPricingData()
  705. k := c.GetKey(n.Labels, n)
  706. resN, _, err := c.NodePricing(k)
  707. if err != nil {
  708. t.Errorf("Error in NodePricing: %s", err.Error())
  709. } else {
  710. gotPrice := resN.Cost
  711. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  712. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  713. if gotPriceFloat != wantPriceFloat {
  714. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  715. }
  716. }
  717. k2 := c.GetKey(n2.Labels, n2)
  718. resN2, _, err2 := c.NodePricing(k2)
  719. if err2 != nil {
  720. t.Errorf("Error in NodePricing: %s", err.Error())
  721. } else {
  722. gotPrice := resN2.Cost
  723. wantPriceFloat, _ := strconv.ParseFloat(wantPrice2, 64)
  724. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  725. if gotPriceFloat != wantPriceFloat {
  726. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  727. }
  728. }
  729. }
  730. func TestNodePriceFromCSVByClass(t *testing.T) {
  731. n := &clustercache.Node{}
  732. n.SpecProviderID = "fakeproviderid"
  733. n.Labels = make(map[string]string)
  734. n.Labels[v1.LabelTopologyRegion] = "eastus2"
  735. n.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  736. wantpricefloat := 0.13370357
  737. wantPrice := fmt.Sprintf("%f", (math.Round(wantpricefloat*1000000) / 1000000))
  738. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  739. c := &provider.CSVProvider{
  740. CSVLocation: "../../../configs/pricing_schema_case.csv",
  741. CustomProvider: &provider.CustomProvider{
  742. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  743. },
  744. }
  745. c.DownloadPricingData()
  746. k := c.GetKey(n.Labels, n)
  747. resN, _, err := c.NodePricing(k)
  748. if err != nil {
  749. t.Errorf("Error in NodePricing: %s", err.Error())
  750. } else {
  751. gotPrice := resN.Cost
  752. if gotPrice != wantPrice {
  753. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  754. }
  755. }
  756. n2 := &clustercache.Node{}
  757. n2.SpecProviderID = "fakeproviderid"
  758. n2.Labels = make(map[string]string)
  759. n2.Labels[v1.LabelTopologyRegion] = "fakeregion"
  760. n2.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  761. k2 := c.GetKey(n2.Labels, n)
  762. c.DownloadPricingData()
  763. resN2, _, err := c.NodePricing(k2)
  764. if resN2 != nil {
  765. t.Errorf("CSV provider should return nil on missing node, instead returned %+v", resN2)
  766. }
  767. }