runtime_command_queue_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package runtime
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "path/filepath"
  8. "sync"
  9. "testing"
  10. "time"
  11. )
  12. func TestRunSerializesPrivilegedCommands(t *testing.T) {
  13. started := make(chan string, 2)
  14. release := make(chan struct{})
  15. var releaseOnce sync.Once
  16. releaseAll := func() {
  17. releaseOnce.Do(func() { close(release) })
  18. }
  19. defer releaseAll()
  20. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. switch r.URL.Path {
  22. case "/api/ingest/agent":
  23. w.Header().Set("Content-Type", "application/json")
  24. _, _ = w.Write([]byte(`{}`))
  25. case "/api/agents/patio/stream":
  26. w.Header().Set("Content-Type", "text/event-stream")
  27. w.WriteHeader(http.StatusOK)
  28. flusher, ok := w.(http.Flusher)
  29. if !ok {
  30. return
  31. }
  32. _, _ = fmt.Fprint(w, "event: upgrade\ndata: first\n\n")
  33. flusher.Flush()
  34. _, _ = fmt.Fprint(w, "event: upgrade\ndata: second\n\n")
  35. flusher.Flush()
  36. <-r.Context().Done()
  37. default:
  38. w.Header().Set("Content-Type", "application/json")
  39. _, _ = w.Write([]byte(`{}`))
  40. }
  41. }))
  42. defer srv.Close()
  43. ctx, cancel := context.WithCancel(context.Background())
  44. defer cancel()
  45. done := make(chan error, 1)
  46. go func() {
  47. done <- Run(ctx, Options{
  48. Server: srv.URL,
  49. Token: "tok",
  50. Slug: "patio",
  51. AllowInsecureCommands: true,
  52. Interval: 20 * time.Millisecond,
  53. HeartbeatFile: filepath.Join(t.TempDir(), "hb"),
  54. Version: "test",
  55. OnUpgrade: func(data string) {
  56. started <- data
  57. <-release
  58. },
  59. })
  60. }()
  61. waitStarted := func() string {
  62. t.Helper()
  63. select {
  64. case got := <-started:
  65. return got
  66. case <-time.After(5 * time.Second):
  67. t.Fatal("timed out waiting for command to start")
  68. return ""
  69. }
  70. }
  71. if got := waitStarted(); got != "first" {
  72. t.Fatalf("first command = %q, want first", got)
  73. }
  74. select {
  75. case got := <-started:
  76. t.Fatalf("second command started before first finished: %q", got)
  77. case <-time.After(200 * time.Millisecond):
  78. }
  79. releaseAll()
  80. if got := waitStarted(); got != "second" {
  81. t.Fatalf("second command = %q, want second", got)
  82. }
  83. cancel()
  84. select {
  85. case err := <-done:
  86. if err != nil {
  87. t.Fatalf("Run returned error: %v", err)
  88. }
  89. case <-time.After(5 * time.Second):
  90. t.Fatal("Run did not stop after cancellation")
  91. }
  92. }