mem_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "runtime"
  8. "testing"
  9. "time"
  10. "github.com/opencost/opencost/pkg/cmd"
  11. "github.com/stretchr/testify/require"
  12. )
  13. func TestMemory(t *testing.T) {
  14. //os.Setenv("KUBECONFIG", "/Users/r2k1/p/playground/costanalysis.yaml") // CHANGEME
  15. os.Setenv("PROMETHEUS_SERVER_ENDPOINT", "http://localhost:9092")
  16. os.Setenv("KUBERNETES_PORT", "443")
  17. os.Setenv("PPROF_ENABLED", "true")
  18. os.Setenv("CACHE_WARMING_ENABLED", "false")
  19. os.Setenv("DISABLE_AGGREGATE_COST_MODEL_CACHE", "true")
  20. os.Setenv("MAX_QUERY_CONCURRENCY", "5")
  21. go func() {
  22. err := cmd.Execute(nil)
  23. require.NoError(t, err)
  24. }()
  25. maxUsage := uint64(0)
  26. go trackMaxMemoryUsage(100*time.Microsecond, &maxUsage)
  27. time.Sleep(60 * time.Second) // wait for opencost to start
  28. generateLoad(t)
  29. t.Log("Max memory usage, KiB:", maxUsage/1024)
  30. }
  31. func generateLoad(t *testing.T) {
  32. end := time.Now()
  33. start := end.Add(-time.Hour * 24)
  34. testFetch(t, fmt.Sprintf("http://localhost:9003/metrics"))
  35. testFetch(t, fmt.Sprintf("http://localhost:9003/allocation/compute?aggregate=namespace,controllerKind,controller,label:app,label:team,label:pod_template_hash&idleByNode=true&includeIdle=true&includeProportionalAssetResourceCosts=true&step=window&window=%s,%s", start.Format("2006-01-02T15:04:05Z"), end.Format("2006-01-02T15:04:05Z")))
  36. testFetch(t, fmt.Sprintf("http://localhost:9003/assets?window=%s,%s", start.Format("2006-01-02T15:04:05Z"), end.Format("2006-01-02T15:04:05Z")))
  37. }
  38. func testFetch(t *testing.T, url string) {
  39. startTime := time.Now()
  40. resp, err := http.Get(url)
  41. require.NoError(t, err)
  42. require.Less(t, resp.StatusCode, 300)
  43. require.GreaterOrEqual(t, resp.StatusCode, 200)
  44. data, err := io.ReadAll(resp.Body)
  45. require.NoError(t, err)
  46. t.Logf("%s, %v MiB, %s", time.Since(startTime), len(data)/1024/1024, url)
  47. }
  48. func trackMaxMemoryUsage(interval time.Duration, maxUsage *uint64) {
  49. var memStats runtime.MemStats
  50. for {
  51. runtime.ReadMemStats(&memStats)
  52. // Update maxUsage if the current HeapAlloc is greater
  53. if memStats.HeapAlloc > *maxUsage {
  54. *maxUsage = memStats.HeapAlloc
  55. }
  56. time.Sleep(interval)
  57. }
  58. }