costmodel_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. package costmodel
  2. import (
  3. "math"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "github.com/google/go-cmp/cmp"
  8. "github.com/opencost/opencost/core/pkg/clustercache"
  9. "github.com/opencost/opencost/core/pkg/storage"
  10. "github.com/opencost/opencost/core/pkg/util"
  11. "github.com/opencost/opencost/pkg/cloud/models"
  12. "github.com/opencost/opencost/pkg/cloud/provider"
  13. "github.com/opencost/opencost/pkg/config"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. v1 "k8s.io/api/core/v1"
  17. "k8s.io/apimachinery/pkg/api/resource"
  18. )
  19. func TestIsValidNodeName(t *testing.T) {
  20. tests := []string{
  21. "ip-10-1-2-3.ec2.internal",
  22. "node-1",
  23. "another.test.node",
  24. "10-55.23-10",
  25. "s21",
  26. "s1",
  27. "s",
  28. }
  29. for _, test := range tests {
  30. if !isValidNodeName(test) {
  31. t.Errorf("Expected %s to be a valid node name", test)
  32. }
  33. }
  34. chars := "abcdefghijklmnopqrstuvwxyz"
  35. longName := ""
  36. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  37. for i := 0; i < 255; i++ {
  38. longName += string(chars[r.Intn(len(chars))])
  39. }
  40. fails := []string{
  41. longName,
  42. "192.168.1.1:80",
  43. "10.0.0.1:443",
  44. "127.0.0.1:8080",
  45. "172.16.254.1:22",
  46. "0.0.0.0:5000",
  47. "::1:80",
  48. "2001:db8::1:443",
  49. "2001:0db8:85a3:0000:0000:8a2e:0370:7334:8080",
  50. "fe80::1:22",
  51. "10.1.2.3:10240",
  52. ":::80",
  53. "node$-15",
  54. "not:valid",
  55. ".hello-world",
  56. "hello-world.",
  57. "i--",
  58. }
  59. for _, fail := range fails {
  60. if isValidNodeName(fail) {
  61. t.Errorf("Expected %s to be an invalid node name", fail)
  62. }
  63. }
  64. }
  65. func TestGetGPUCount(t *testing.T) {
  66. tests := []struct {
  67. name string
  68. node *clustercache.Node
  69. expectedGPU float64
  70. expectedVGPU float64
  71. expectedError bool
  72. }{
  73. {
  74. name: "Standard NVIDIA GPU",
  75. node: &clustercache.Node{
  76. Status: v1.NodeStatus{
  77. Capacity: v1.ResourceList{
  78. "nvidia.com/gpu": resource.MustParse("2"),
  79. },
  80. },
  81. },
  82. expectedGPU: 2.0,
  83. expectedVGPU: 2.0,
  84. },
  85. {
  86. name: "NVIDIA GPU with GFD - renameByDefault=true",
  87. node: &clustercache.Node{
  88. Labels: map[string]string{
  89. "nvidia.com/gpu.replicas": "4",
  90. "nvidia.com/gpu.count": "1",
  91. },
  92. Status: v1.NodeStatus{
  93. Capacity: v1.ResourceList{
  94. "nvidia.com/gpu.shared": resource.MustParse("4"),
  95. },
  96. },
  97. },
  98. expectedGPU: 1.0,
  99. expectedVGPU: 4.0,
  100. },
  101. {
  102. name: "NVIDIA GPU with GFD - renameByDefault=false",
  103. node: &clustercache.Node{
  104. Labels: map[string]string{
  105. "nvidia.com/gpu.replicas": "4",
  106. "nvidia.com/gpu.count": "1",
  107. },
  108. Status: v1.NodeStatus{
  109. Capacity: v1.ResourceList{
  110. "nvidia.com/gpu": resource.MustParse("4"),
  111. },
  112. },
  113. },
  114. expectedGPU: 1.0,
  115. expectedVGPU: 4.0,
  116. },
  117. {
  118. name: "No GPU",
  119. node: &clustercache.Node{
  120. Status: v1.NodeStatus{
  121. Capacity: v1.ResourceList{},
  122. },
  123. },
  124. expectedGPU: -1.0,
  125. expectedVGPU: -1.0,
  126. },
  127. }
  128. for _, tt := range tests {
  129. t.Run(tt.name, func(t *testing.T) {
  130. gpu, vgpu, err := getGPUCount(nil, tt.node)
  131. if tt.expectedError {
  132. assert.Error(t, err)
  133. } else {
  134. assert.NoError(t, err)
  135. assert.Equal(t, tt.expectedGPU, gpu)
  136. assert.Equal(t, tt.expectedVGPU, vgpu)
  137. }
  138. })
  139. }
  140. }
  141. func Test_CostData_GetController_CronJob(t *testing.T) {
  142. cases := []struct {
  143. name string
  144. cd CostData
  145. expectedName string
  146. expectedKind string
  147. expectedHasController bool
  148. }{
  149. {
  150. name: "batch/v1beta1 CronJob Job name",
  151. cd: CostData{
  152. // batch/v1beta1 CronJobs create Jobs with a 10 character
  153. // timestamp appended to the end of the name.
  154. //
  155. // It looks like this:
  156. // CronJob: cronjob-1
  157. // Job: cronjob-1-1651057200
  158. // Pod: cronjob-1-1651057200-mf5c9
  159. Jobs: []string{"cronjob-1-1651057200"},
  160. },
  161. expectedName: "cronjob-1",
  162. expectedKind: "job",
  163. expectedHasController: true,
  164. },
  165. {
  166. name: "batch/v1 CronJob Job name",
  167. cd: CostData{
  168. // batch/v1CronJobs create Jobs with an 8 character timestamp
  169. // appended to the end of the name.
  170. //
  171. // It looks like this:
  172. // CronJob: cj-v1
  173. // Job: cj-v1-27517770
  174. // Pod: cj-v1-27517770-xkrgn
  175. Jobs: []string{"cj-v1-27517770"},
  176. },
  177. expectedName: "cj-v1",
  178. expectedKind: "job",
  179. expectedHasController: true,
  180. },
  181. }
  182. for _, c := range cases {
  183. t.Run(c.name, func(t *testing.T) {
  184. name, kind, hasController := c.cd.GetController()
  185. if name != c.expectedName {
  186. t.Errorf("Name mismatch. Expected: %s. Got: %s", c.expectedName, name)
  187. }
  188. if kind != c.expectedKind {
  189. t.Errorf("Kind mismatch. Expected: %s. Got: %s", c.expectedKind, kind)
  190. }
  191. if hasController != c.expectedHasController {
  192. t.Errorf("HasController mismatch. Expected: %t. Got: %t", c.expectedHasController, hasController)
  193. }
  194. })
  195. }
  196. }
  197. func TestGetContainerAllocation(t *testing.T) {
  198. cases := []struct {
  199. name string
  200. req *util.Vector
  201. used *util.Vector
  202. allocationType string
  203. expected []*util.Vector
  204. }{
  205. {
  206. name: "request > usage",
  207. req: &util.Vector{
  208. Value: 100,
  209. Timestamp: 1672531200,
  210. },
  211. used: &util.Vector{
  212. Value: 50,
  213. Timestamp: 1672531200,
  214. },
  215. allocationType: "RAM",
  216. expected: []*util.Vector{
  217. {
  218. Value: 100,
  219. Timestamp: 1672531200,
  220. },
  221. },
  222. },
  223. {
  224. name: "usage > request",
  225. req: &util.Vector{
  226. Value: 50,
  227. Timestamp: 1672531200,
  228. },
  229. used: &util.Vector{
  230. Value: 100,
  231. Timestamp: 1672531200,
  232. },
  233. allocationType: "RAM",
  234. expected: []*util.Vector{
  235. {
  236. Value: 100,
  237. Timestamp: 1672531200,
  238. },
  239. },
  240. },
  241. {
  242. name: "only request is non-nil",
  243. req: &util.Vector{
  244. Value: 100,
  245. Timestamp: 1672531200,
  246. },
  247. used: nil,
  248. allocationType: "CPU",
  249. expected: []*util.Vector{
  250. {
  251. Value: 100,
  252. Timestamp: 1672531200,
  253. },
  254. },
  255. },
  256. {
  257. name: "only used is non-nil",
  258. req: nil,
  259. used: &util.Vector{
  260. Value: 100,
  261. Timestamp: 1672531200,
  262. },
  263. allocationType: "CPU",
  264. expected: []*util.Vector{
  265. {
  266. Value: 100,
  267. Timestamp: 1672531200,
  268. },
  269. },
  270. },
  271. {
  272. name: "both req and used are nil",
  273. req: nil,
  274. used: nil,
  275. allocationType: "GPU",
  276. expected: []*util.Vector{
  277. {
  278. Value: 0,
  279. Timestamp: float64(time.Now().UTC().Unix()),
  280. },
  281. },
  282. },
  283. {
  284. name: "NaN in request value",
  285. req: &util.Vector{
  286. Value: math.NaN(),
  287. Timestamp: 1672531200,
  288. },
  289. used: &util.Vector{
  290. Value: 50,
  291. Timestamp: 1672531200,
  292. },
  293. allocationType: "RAM",
  294. expected: []*util.Vector{
  295. {
  296. Value: 50,
  297. Timestamp: 1672531200,
  298. },
  299. },
  300. },
  301. {
  302. name: "NaN in used value",
  303. req: &util.Vector{
  304. Value: 100,
  305. Timestamp: 1672531200,
  306. },
  307. used: &util.Vector{
  308. Value: math.NaN(),
  309. Timestamp: 1672531200,
  310. },
  311. allocationType: "CPU",
  312. expected: []*util.Vector{
  313. {
  314. Value: 100,
  315. Timestamp: 1672531200,
  316. },
  317. },
  318. },
  319. }
  320. for _, tc := range cases {
  321. t.Run(tc.name, func(t *testing.T) {
  322. // For the nil case, the timestamp is dynamic, so we need to handle it separately
  323. if tc.name == "both req and used are nil" {
  324. result := getContainerAllocation(tc.req, tc.used, tc.allocationType)
  325. if result[0].Value != 0 {
  326. t.Errorf("Expected value to be 0, but got %f", result[0].Value)
  327. }
  328. if time.Now().UTC().Unix()-int64(result[0].Timestamp) > 5 {
  329. t.Errorf("Expected timestamp to be recent, but it was not")
  330. }
  331. return
  332. }
  333. result := getContainerAllocation(tc.req, tc.used, tc.allocationType)
  334. if diff := cmp.Diff(tc.expected, result); diff != "" {
  335. t.Errorf("getContainerAllocation() mismatch (-want +got):\n%s", diff)
  336. }
  337. })
  338. }
  339. }
  340. func TestStorageCostAnnotations(t *testing.T) {
  341. t.Parallel()
  342. confMan := config.NewConfigFileManager(storage.NewFileStorage("../../"))
  343. customProvider := &provider.CSVProvider{
  344. CSVLocation: "../../configs/pricing_schema_pv.csv",
  345. CustomProvider: &provider.CustomProvider{
  346. Config: provider.NewProviderConfig(confMan, "../../configs/default.json"),
  347. },
  348. }
  349. err := customProvider.DownloadPricingData()
  350. assert.NoError(t, err)
  351. costModel := &CostModel{
  352. Provider: customProvider,
  353. }
  354. providerConfig, err := customProvider.GetConfig()
  355. assert.NoError(t, err)
  356. assert.NotNil(t, providerConfig)
  357. type testCase struct {
  358. name string
  359. pv *models.PV
  360. pvc *clustercache.PersistentVolume
  361. expectedCost string
  362. }
  363. testCases := []testCase{
  364. {
  365. name: "Cost from provider",
  366. pv: &models.PV{},
  367. pvc: &clustercache.PersistentVolume{
  368. Name: "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d",
  369. },
  370. expectedCost: "0.1337",
  371. },
  372. {
  373. name: "Cost from custom provider config",
  374. pv: &models.PV{},
  375. pvc: &clustercache.PersistentVolume{
  376. Name: "fake-name",
  377. },
  378. expectedCost: providerConfig.Storage,
  379. },
  380. {
  381. name: "Cost from annotations",
  382. pv: &models.PV{},
  383. pvc: &clustercache.PersistentVolume{
  384. Name: "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d",
  385. Annotations: map[string]string{
  386. annotationStorageCost: "123.123",
  387. },
  388. },
  389. expectedCost: "123.123",
  390. },
  391. {
  392. name: "Cost from storage class and with no annotations",
  393. pv: &models.PV{
  394. Parameters: map[string]string{
  395. annotationStorageCost: "123.124",
  396. },
  397. },
  398. pvc: &clustercache.PersistentVolume{
  399. Name: "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d",
  400. },
  401. expectedCost: "123.124",
  402. },
  403. {
  404. name: "Cost from storage class and with annotations",
  405. pv: &models.PV{
  406. Parameters: map[string]string{
  407. annotationStorageCost: "123.124",
  408. },
  409. },
  410. pvc: &clustercache.PersistentVolume{
  411. Name: "pvc-08e1f205-d7a9-4430-90fc-7b3965a18c4d",
  412. Annotations: map[string]string{
  413. annotationStorageCost: "123.125",
  414. },
  415. },
  416. expectedCost: "123.125",
  417. },
  418. }
  419. for _, testCase := range testCases {
  420. t.Run(testCase.name, func(t *testing.T) {
  421. t.Parallel()
  422. err := costModel.GetPVCost(testCase.pv, testCase.pvc, "default-region")
  423. assert.NoError(t, err)
  424. assert.Equal(t, testCase.expectedCost, testCase.pv.Cost)
  425. })
  426. }
  427. }
  428. func TestNodeCostAnnotations(t *testing.T) {
  429. t.Parallel()
  430. confMan := config.NewConfigFileManager(storage.NewFileStorage("../../"))
  431. customProvider := &provider.CSVProvider{
  432. CSVLocation: "../../configs/pricing_schema_region.csv",
  433. CustomProvider: &provider.CustomProvider{
  434. Config: provider.NewProviderConfig(confMan, "../../configs/default.json"),
  435. },
  436. }
  437. err := customProvider.DownloadPricingData()
  438. assert.NoError(t, err)
  439. costModel := &CostModel{
  440. Provider: customProvider,
  441. Cache: NewFakeNodeCache([]*clustercache.Node{
  442. {
  443. Name: "test-node-001",
  444. Labels: map[string]string{
  445. "topology.kubernetes.io/region": "regionone",
  446. },
  447. },
  448. {
  449. Name: "test-node-002",
  450. Labels: map[string]string{
  451. "topology.kubernetes.io/region": "regionone",
  452. },
  453. Annotations: map[string]string{
  454. "opencost.io/node-cpu-hourly-cost": "111",
  455. "opencost.io/node-ram-hourly-cost": "222",
  456. },
  457. },
  458. }),
  459. }
  460. assert.NotNil(t, costModel)
  461. providerConfig, err := customProvider.GetConfig()
  462. assert.NoError(t, err)
  463. assert.NotNil(t, providerConfig)
  464. nodeCost, err := costModel.GetNodeCost()
  465. assert.NoError(t, err)
  466. assert.NotNil(t, nodeCost)
  467. assert.NotEmpty(t, nodeCost)
  468. type testCase struct {
  469. node string
  470. VCPUCost string
  471. RAMCost string
  472. }
  473. testCases := []testCase{
  474. {
  475. node: "test-node-001",
  476. VCPUCost: "+Inf",
  477. RAMCost: "+Inf",
  478. },
  479. {
  480. node: "test-node-002",
  481. VCPUCost: "111",
  482. RAMCost: "222",
  483. },
  484. }
  485. for _, tc := range testCases {
  486. t.Run(tc.node, func(t *testing.T) {
  487. t.Parallel()
  488. nodeCost, ok := nodeCost[tc.node]
  489. require.True(t, ok)
  490. assert.Equal(t, tc.VCPUCost, nodeCost.VCPUCost)
  491. assert.Equal(t, tc.RAMCost, nodeCost.RAMCost)
  492. })
  493. }
  494. }
  495. // FakeNodeCache implements ClusterCache interface for testing
  496. type FakeNodeCache struct {
  497. clustercache.ClusterCache
  498. nodes []*clustercache.Node
  499. }
  500. func (f FakeNodeCache) GetAllNodes() []*clustercache.Node {
  501. return f.nodes
  502. }
  503. func NewFakeNodeCache(nodes []*clustercache.Node) FakeNodeCache {
  504. return FakeNodeCache{
  505. nodes: nodes,
  506. }
  507. }