Просмотр исходного кода

fix(agent): serialize privileged commands (#1593)

Route apply, upgrade, firmware upgrade and config backup through one worker queue so they cannot overlap on the router. The queue keeps arrival order and stops with the agent context.

Closes #1589
Nacho 1 месяц назад
Родитель
Сommit
d6501960dd
2 измененных файлов с 137 добавлено и 12 удалено
  1. 37 12
      agent/runtime/runtime.go
  2. 100 0
      agent/runtime/runtime_command_queue_test.go

+ 37 - 12
agent/runtime/runtime.go

@@ -209,6 +209,23 @@ func Run(ctx context.Context, opts Options) error {
 	// SSE bidireccional: el servidor envía comandos al agente. Reutiliza el
 	// SSE bidireccional: el servidor envía comandos al agente. Reutiliza el
 	// mismo transporte (mismo pinning SPKI que el push).
 	// mismo transporte (mismo pinning SPKI que el push).
 	refreshCh := make(chan struct{}, 1)
 	refreshCh := make(chan struct{}, 1)
+	commandCh := make(chan func(), 16)
+	go func() {
+		for {
+			select {
+			case <-ctx.Done():
+				return
+			case fn := <-commandCh:
+				fn()
+			}
+		}
+	}()
+	enqueue := func(fn func()) {
+		select {
+		case commandCh <- fn:
+		case <-ctx.Done():
+		}
+	}
 	go func() {
 	go func() {
 		sse := sseclient.New(opts.Server, opts.Slug, opts.Token,
 		sse := sseclient.New(opts.Server, opts.Slug, opts.Token,
 			&http.Client{Timeout: 0, Transport: transport},
 			&http.Client{Timeout: 0, Transport: transport},
@@ -220,24 +237,32 @@ func Run(ctx context.Context, opts Options) error {
 					}
 					}
 				}
 				}
 				if ev.Name == "apply" && ev.Data != "" {
 				if ev.Name == "apply" && ev.Data != "" {
-					go a.handleApply(ex, transport, ev.Data)
+					data := ev.Data
+					enqueue(func() { a.handleApply(ex, transport, data) })
 				}
 				}
 				if ev.Name == "upgrade" {
 				if ev.Name == "upgrade" {
-					if opts.OnUpgrade != nil {
-						go opts.OnUpgrade(ev.Data)
-					} else {
-						go handleUpgrade(opts, transport, ev.Data)
-					}
+					data := ev.Data
+					enqueue(func() {
+						if opts.OnUpgrade != nil {
+							opts.OnUpgrade(data)
+						} else {
+							handleUpgrade(opts, transport, data)
+						}
+					})
 				}
 				}
 				if ev.Name == "firmware_upgrade" && ev.Data != "" {
 				if ev.Name == "firmware_upgrade" && ev.Data != "" {
-					go handleFirmwareUpgrade(opts, transport, ev.Data)
+					data := ev.Data
+					enqueue(func() { handleFirmwareUpgrade(opts, transport, data) })
 				}
 				}
 				if ev.Name == "config_backup" {
 				if ev.Name == "config_backup" {
-					if opts.OnConfigBackup != nil {
-						go opts.OnConfigBackup(ev.Data)
-					} else {
-						go handleConfigBackup(opts, transport)
-					}
+					data := ev.Data
+					enqueue(func() {
+						if opts.OnConfigBackup != nil {
+							opts.OnConfigBackup(data)
+						} else {
+							handleConfigBackup(opts, transport)
+						}
+					})
 				}
 				}
 				log.Debug("[netpulse-agent] SSE evento", "event", ev.Name)
 				log.Debug("[netpulse-agent] SSE evento", "event", ev.Name)
 			})
 			})

+ 100 - 0
agent/runtime/runtime_command_queue_test.go

@@ -0,0 +1,100 @@
+package runtime
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"path/filepath"
+	"sync"
+	"testing"
+	"time"
+)
+
+func TestRunSerializesPrivilegedCommands(t *testing.T) {
+	started := make(chan string, 2)
+	release := make(chan struct{})
+	var releaseOnce sync.Once
+	releaseAll := func() {
+		releaseOnce.Do(func() { close(release) })
+	}
+	defer releaseAll()
+
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/api/ingest/agent":
+			w.Header().Set("Content-Type", "application/json")
+			_, _ = w.Write([]byte(`{}`))
+		case "/api/agents/patio/stream":
+			w.Header().Set("Content-Type", "text/event-stream")
+			w.WriteHeader(http.StatusOK)
+			flusher, ok := w.(http.Flusher)
+			if !ok {
+				return
+			}
+			_, _ = fmt.Fprint(w, "event: upgrade\ndata: first\n\n")
+			flusher.Flush()
+			_, _ = fmt.Fprint(w, "event: upgrade\ndata: second\n\n")
+			flusher.Flush()
+			<-r.Context().Done()
+		default:
+			w.Header().Set("Content-Type", "application/json")
+			_, _ = w.Write([]byte(`{}`))
+		}
+	}))
+	defer srv.Close()
+
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
+	done := make(chan error, 1)
+	go func() {
+		done <- Run(ctx, Options{
+			Server:        srv.URL,
+			Token:         "tok",
+			Slug:          "patio",
+			Interval:      20 * time.Millisecond,
+			HeartbeatFile: filepath.Join(t.TempDir(), "hb"),
+			Version:       "test",
+			OnUpgrade: func(data string) {
+				started <- data
+				<-release
+			},
+		})
+	}()
+
+	waitStarted := func() string {
+		t.Helper()
+		select {
+		case got := <-started:
+			return got
+		case <-time.After(5 * time.Second):
+			t.Fatal("timed out waiting for command to start")
+			return ""
+		}
+	}
+
+	if got := waitStarted(); got != "first" {
+		t.Fatalf("first command = %q, want first", got)
+	}
+	select {
+	case got := <-started:
+		t.Fatalf("second command started before first finished: %q", got)
+	case <-time.After(200 * time.Millisecond):
+	}
+
+	releaseAll()
+	if got := waitStarted(); got != "second" {
+		t.Fatalf("second command = %q, want second", got)
+	}
+
+	cancel()
+	select {
+	case err := <-done:
+		if err != nil {
+			t.Fatalf("Run returned error: %v", err)
+		}
+	case <-time.After(5 * time.Second):
+		t.Fatal("Run did not stop after cancellation")
+	}
+}