cloud_test.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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","azureSubscriptionID":"","azureClientID":"","azureClientSecret":"","azureTenantID":"","azureBillingRegion":"","azureBillingAccount":"","azureOfferDurableID":"","azureStorageSubscriptionID":"","azureStorageAccount":"","azureStorageAccessKey":"","azureStorageContainer":"","azureContainerPath":"","azureCloud":"","currencyCode":"","discount":"","negotiatedDiscount":"","clusterName":"","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 := &clustercache.MockClusterCache{Nodes: []*clustercache.Node{n}}
  238. fm := FakeClusterMap{}
  239. d, _ := time.ParseDuration("1m")
  240. model := costmodel.NewCostModel("cluster-uid", 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","azureSubscriptionID":"","azureClientID":"","azureClientSecret":"","azureTenantID":"","azureBillingRegion":"","azureBillingAccount":"","azureOfferDurableID":"","azureStorageSubscriptionID":"","azureStorageAccount":"","azureStorageAccessKey":"","azureStorageContainer":"","azureContainerPath":"","azureCloud":"","currencyCode":"","discount":"","negotiatedDiscount":"","clusterName":"","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 := &clustercache.MockClusterCache{Nodes: []*clustercache.Node{n}}
  293. fm := FakeClusterMap{}
  294. d, _ := time.ParseDuration("1m")
  295. model := costmodel.NewCostModel("cluster-uid", 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 FakeClusterMap struct {
  483. clusters.ClusterMap
  484. }
  485. func TestNodePriceFromCSVWithBadConfig(t *testing.T) {
  486. const invalidConfigJson = `{
  487. "provider":"base",
  488. "description":"Default prices based on GCP us-central1",
  489. "CPU":"0.031611",
  490. "spotCPU":"0.006655",
  491. "RAM":"0.004237",
  492. "spotRAM":"0.000892",
  493. "GPU":"0.95",
  494. "spotGPU":"0.308",
  495. "storage":"0.00005479452",
  496. "zoneNetworkEgress":"0.01",
  497. "regionNetworkEgress":"0.01",
  498. "internetNetworkEgress":"0.12",
  499. "firstFiveForwardingRulesCost":"",
  500. "additionalForwardingRuleCost":"",
  501. "LBIngressDataCost":"",
  502. "athenaBucketName":"",
  503. "athenaRegion":"",
  504. "athenaDatabase":"",
  505. "athenaTable":"",
  506. "athenaWorkgroup":"",
  507. "masterPayerARN":"",
  508. "customPricesEnabled":"false",
  509. "azureSubscriptionID":"",
  510. "azureClientID":"",
  511. "azureClientSecret":"",
  512. "azureTenantID":"",
  513. "azureBillingRegion":"",
  514. "azureOfferDurableID":"",
  515. "azureStorageSubscriptionID":"",
  516. "azureStorageAccount":"",
  517. "azureStorageAccessKey":"",
  518. "azureStorageContainer":"",
  519. "azureContainerPath":"",
  520. "azureCloud":"",
  521. "currencyCode":"",
  522. "discount":"",
  523. "negotiatedDiscount":"",
  524. "clusterName":""
  525. }`
  526. tempPath := t.TempDir()
  527. currentPath, err := filepath.Abs(".")
  528. if err != nil {
  529. t.Skip(fmt.Sprintf("Unable to get absolute path for current dir: '%s' - Error: %s - Skipping test.", currentPath, err))
  530. return
  531. }
  532. configPath, err := filepath.Rel(currentPath, tempPath)
  533. if err != nil {
  534. t.Skip(fmt.Sprintf("Unable to get relative path for temp dir: '%s' - Error: %s - Skipping test.", tempPath, err))
  535. return
  536. }
  537. err = os.WriteFile(filepath.Join(configPath, "invalid.json"), []byte(invalidConfigJson), 0644)
  538. if err != nil {
  539. t.Skip(fmt.Sprintf("Unable to write temporary json config file: '%s' - Error: %s - Skipping test.", filepath.Join(configPath, "invalid.json"), err))
  540. return
  541. }
  542. t.Logf("Setting Config Path to: %s", configPath)
  543. t.Setenv(env.ConfigPathEnvVar, configPath)
  544. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  545. c := &provider.CSVProvider{
  546. CSVLocation: "../../../configs/pricing_schema_case.csv",
  547. CustomProvider: &provider.CustomProvider{
  548. Config: provider.NewProviderConfig(confMan, "invalid.json"),
  549. },
  550. }
  551. c.DownloadPricingData()
  552. n := &clustercache.Node{}
  553. n.SpecProviderID = "fake"
  554. n.Name = "nameWant"
  555. n.Labels = make(map[string]string)
  556. n.Labels["foo"] = "labelFooWant"
  557. n.Labels[v1.LabelTopologyRegion] = "regionone"
  558. fc := &clustercache.MockClusterCache{Nodes: []*clustercache.Node{n}}
  559. fm := FakeClusterMap{}
  560. d, _ := time.ParseDuration("1m")
  561. model := costmodel.NewCostModel("cluster-uid", nil, c, fc, fm, d)
  562. _, err = model.GetNodeCost()
  563. if err != nil {
  564. t.Errorf("Error in node pricing: %s", err)
  565. }
  566. }
  567. func TestSourceMatchesFromCSV(t *testing.T) {
  568. os.Setenv(env.ConfigPathEnvVar, "../../../configs")
  569. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  570. c := &provider.CSVProvider{
  571. CSVLocation: "../../../configs/pricing_schema_case.csv",
  572. CustomProvider: &provider.CustomProvider{
  573. Config: provider.NewProviderConfig(confMan, "default.json"),
  574. },
  575. }
  576. c.DownloadPricingData()
  577. n := &clustercache.Node{}
  578. n.SpecProviderID = "fake"
  579. n.Name = "nameWant"
  580. n.Labels = make(map[string]string)
  581. n.Labels["foo"] = "labelFooWant"
  582. n.Labels[v1.LabelTopologyRegion] = "regionone"
  583. n2 := &clustercache.Node{}
  584. 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"
  585. n2.Labels = make(map[string]string)
  586. n2.Labels[v1.LabelTopologyRegion] = "eastus2"
  587. n2.Labels["foo"] = "labelFooWant"
  588. k := c.GetKey(n2.Labels, n2)
  589. resN, _, err := c.NodePricing(k)
  590. if err != nil {
  591. t.Errorf("Error in NodePricing: %s", err.Error())
  592. } else {
  593. wantPrice := "0.13370357"
  594. gotPrice := resN.Cost
  595. if gotPrice != wantPrice {
  596. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  597. }
  598. }
  599. n3 := &clustercache.Node{}
  600. n3.SpecProviderID = "fake"
  601. n3.Name = "nameWant"
  602. n3.Labels = make(map[string]string)
  603. n3.Labels[v1.LabelTopologyRegion] = "eastus2"
  604. n3.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  605. fc := &clustercache.MockClusterCache{Nodes: []*clustercache.Node{n, n2, n3}}
  606. fm := FakeClusterMap{}
  607. d, _ := time.ParseDuration("1m")
  608. model := costmodel.NewCostModel("cluster-uid", nil, c, fc, fm, d)
  609. _, err = model.GetNodeCost()
  610. if err != nil {
  611. t.Errorf("Error in node pricing: %s", err)
  612. }
  613. p, err := model.GetPricingSourceCounts()
  614. if err != nil {
  615. t.Errorf("Error in pricing source counts: %s", err)
  616. } else if p.TotalNodes != 3 {
  617. t.Errorf("Wanted 3 nodes got %d", p.TotalNodes)
  618. }
  619. if p.PricingTypeCounts[""] != 1 {
  620. t.Errorf("Wanted 1 default match got %d: %+v", p.PricingTypeCounts[""], p.PricingTypeCounts)
  621. }
  622. if p.PricingTypeCounts["csvExact"] != 1 {
  623. t.Errorf("Wanted 1 exact match got %d: %+v", p.PricingTypeCounts["csvExact"], p.PricingTypeCounts)
  624. }
  625. if p.PricingTypeCounts["csvClass"] != 1 {
  626. t.Errorf("Wanted 1 class match got %d: %+v", p.PricingTypeCounts["csvClass"], p.PricingTypeCounts)
  627. }
  628. }
  629. func TestNodePriceFromCSVWithCase(t *testing.T) {
  630. n := &clustercache.Node{}
  631. 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"
  632. n.Labels = make(map[string]string)
  633. n.Labels[v1.LabelTopologyRegion] = "eastus2"
  634. wantPrice := "0.13370357"
  635. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  636. c := &provider.CSVProvider{
  637. CSVLocation: "../../../configs/pricing_schema_case.csv",
  638. CustomProvider: &provider.CustomProvider{
  639. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  640. },
  641. }
  642. c.DownloadPricingData()
  643. k := c.GetKey(n.Labels, n)
  644. resN, _, err := c.NodePricing(k)
  645. if err != nil {
  646. t.Errorf("Error in NodePricing: %s", err.Error())
  647. } else {
  648. gotPrice := resN.Cost
  649. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  650. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  651. if gotPriceFloat != wantPriceFloat {
  652. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  653. }
  654. }
  655. }
  656. func TestNodePriceFromCSVMixed(t *testing.T) {
  657. labelFooWant := "OnDemand"
  658. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  659. n := &clustercache.Node{}
  660. n.Labels = make(map[string]string)
  661. n.Labels["TestClusterUsage"] = labelFooWant
  662. n.Labels["nvidia.com/gpu_type"] = "a100-ondemand"
  663. n.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(2, 0)}
  664. wantPrice := "1.904110"
  665. labelFooWant2 := "Reserved"
  666. n2 := &clustercache.Node{}
  667. n2.Labels = make(map[string]string)
  668. n2.Labels["TestClusterUsage"] = labelFooWant2
  669. n2.Labels["nvidia.com/gpu_type"] = "a100-reserved"
  670. n2.Status.Capacity = v1.ResourceList{"nvidia.com/gpu": *resource.NewScaledQuantity(1, 0)}
  671. wantPrice2 := "1.654795"
  672. c := &provider.CSVProvider{
  673. CSVLocation: "../../../configs/pricing_schema_mixed_gpu_ondemand.csv",
  674. CustomProvider: &provider.CustomProvider{
  675. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  676. },
  677. }
  678. c.DownloadPricingData()
  679. k := c.GetKey(n.Labels, n)
  680. resN, _, err := c.NodePricing(k)
  681. if err != nil {
  682. t.Errorf("Error in NodePricing: %s", err.Error())
  683. } else {
  684. gotPrice := resN.Cost
  685. wantPriceFloat, _ := strconv.ParseFloat(wantPrice, 64)
  686. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  687. if gotPriceFloat != wantPriceFloat {
  688. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  689. }
  690. }
  691. k2 := c.GetKey(n2.Labels, n2)
  692. resN2, _, err2 := c.NodePricing(k2)
  693. if err2 != nil {
  694. t.Errorf("Error in NodePricing: %s", err.Error())
  695. } else {
  696. gotPrice := resN2.Cost
  697. wantPriceFloat, _ := strconv.ParseFloat(wantPrice2, 64)
  698. gotPriceFloat, _ := strconv.ParseFloat(gotPrice, 64)
  699. if gotPriceFloat != wantPriceFloat {
  700. t.Errorf("Wanted price '%f' got price '%f'", wantPriceFloat, gotPriceFloat)
  701. }
  702. }
  703. }
  704. func TestNodePriceFromCSVByClass(t *testing.T) {
  705. n := &clustercache.Node{}
  706. n.SpecProviderID = "fakeproviderid"
  707. n.Labels = make(map[string]string)
  708. n.Labels[v1.LabelTopologyRegion] = "eastus2"
  709. n.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  710. wantpricefloat := 0.13370357
  711. wantPrice := fmt.Sprintf("%f", (math.Round(wantpricefloat*1000000) / 1000000))
  712. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  713. c := &provider.CSVProvider{
  714. CSVLocation: "../../../configs/pricing_schema_case.csv",
  715. CustomProvider: &provider.CustomProvider{
  716. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  717. },
  718. }
  719. c.DownloadPricingData()
  720. k := c.GetKey(n.Labels, n)
  721. resN, _, err := c.NodePricing(k)
  722. if err != nil {
  723. t.Errorf("Error in NodePricing: %s", err.Error())
  724. } else {
  725. gotPrice := resN.Cost
  726. if gotPrice != wantPrice {
  727. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  728. }
  729. }
  730. n2 := &clustercache.Node{}
  731. n2.SpecProviderID = "fakeproviderid"
  732. n2.Labels = make(map[string]string)
  733. n2.Labels[v1.LabelTopologyRegion] = "fakeregion"
  734. n2.Labels[v1.LabelInstanceTypeStable] = "Standard_F32s_v2"
  735. k2 := c.GetKey(n2.Labels, n)
  736. c.DownloadPricingData()
  737. resN2, _, err := c.NodePricing(k2)
  738. if resN2 != nil {
  739. t.Errorf("CSV provider should return nil on missing node, instead returned %+v", resN2)
  740. }
  741. }
  742. func TestPVPricing_CaseInsensitive(t *testing.T) {
  743. confMan := config.NewConfigFileManager(storage.NewFileStorage("./"))
  744. wantPrice := "0.1337"
  745. c := &provider.CSVProvider{
  746. CSVLocation: "../../../configs/pricing_schema_pv.csv",
  747. PVMapField: "metadata.name",
  748. CustomProvider: &provider.CustomProvider{
  749. Config: provider.NewProviderConfig(confMan, "../../../configs/default.json"),
  750. },
  751. }
  752. c.DownloadPricingData()
  753. t.Run("UppercaseInput", func(t *testing.T) {
  754. pv := &clustercache.PersistentVolume{}
  755. pv.Name = "PVC-08e1f205-d7a9-4430-90fc-7b3965a18c4D"
  756. key := c.GetPVKey(pv, make(map[string]string), "")
  757. resPV, err := c.PVPricing(key)
  758. if err != nil {
  759. t.Errorf("Error in PVPricing: %s", err.Error())
  760. } else {
  761. gotPrice := resPV.Cost
  762. if gotPrice != wantPrice {
  763. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  764. }
  765. }
  766. })
  767. t.Run("LowercaseInput", func(t *testing.T) {
  768. pv := &clustercache.PersistentVolume{}
  769. pv.Name = "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d"
  770. key := c.GetPVKey(pv, make(map[string]string), "")
  771. resPV, err := c.PVPricing(key)
  772. if err != nil {
  773. t.Errorf("Error in PVPricing: %s", err.Error())
  774. } else {
  775. gotPrice := resPV.Cost
  776. if gotPrice != wantPrice {
  777. t.Errorf("Wanted price '%s' got price '%s'", wantPrice, gotPrice)
  778. }
  779. }
  780. })
  781. }