cloud_test.go 26 KB

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