fd_leak_linux_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //go:build linux
  2. package tests
  3. import (
  4. "context"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "time"
  9. "hth/internal/app"
  10. "hth/internal/testutil"
  11. )
  12. func countFDs(t *testing.T) int {
  13. t.Helper()
  14. ents, err := os.ReadDir("/proc/self/fd")
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. return len(ents)
  19. }
  20. func TestMockAppStartStopDoesNotLeakFDs(t *testing.T) {
  21. before := countFDs(t)
  22. for i := 0; i < 3; i++ {
  23. dir := t.TempDir()
  24. obs := filepath.Join(dir, "observe.sock")
  25. ctl := filepath.Join(dir, "control.sock")
  26. yaml := `
  27. api_version: hth.api.v1
  28. device_id: prod2u-0
  29. backend: mock
  30. profile: ` + testutil.ProfilePath(t) + `
  31. runtime_root: ` + dir + `
  32. sockets:
  33. observe: ` + obs + `
  34. control: ` + ctl + `
  35. observe_perm: "0660"
  36. control_perm: "0660"
  37. poll:
  38. temperature_ms: 80
  39. motor_status_ms: 80
  40. watchdog:
  41. heartbeat_period_ms: 5000
  42. lease:
  43. min_ttl_ms: 50
  44. max_ttl_ms: 2000
  45. safety:
  46. fan: 10
  47. ptc: 0
  48. door_close_percent: 0
  49. ring_buffer_size: 32
  50. subscriber_buffer_size: 2
  51. grpc:
  52. reflection: false
  53. mock:
  54. seed: 1
  55. startup_complete: true
  56. `
  57. cfgPath := filepath.Join(dir, "hthd.yaml")
  58. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  59. t.Fatal(err)
  60. }
  61. a, err := app.New(cfgPath, "", nil)
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. ctx, cancel := context.WithCancel(context.Background())
  66. errCh := make(chan error, 1)
  67. go func() { errCh <- a.Run(ctx) }()
  68. deadline := time.Now().Add(3 * time.Second)
  69. for time.Now().Before(deadline) {
  70. if _, err := os.Stat(obs); err == nil {
  71. if _, err := os.Stat(ctl); err == nil {
  72. break
  73. }
  74. }
  75. time.Sleep(20 * time.Millisecond)
  76. }
  77. cancel()
  78. a.Stop()
  79. select {
  80. case <-errCh:
  81. case <-time.After(5 * time.Second):
  82. t.Fatal("app.Run did not return after Stop")
  83. }
  84. }
  85. after := countFDs(t)
  86. if after > before+12 {
  87. t.Fatalf("FD leak: before=%d after=%d", before, after)
  88. }
  89. }