Sfoglia il codice sorgente

feat(orchestr): tcp_check healthcheck + manual rollback endpoint (Fase 17 prereqs) (#128)

* feat(executor): add tcp_check Kind with retry budget

New Kind that opens a TCP connection to host:port. Success (exit 0) if the
port accepts connections within a 10s budget (500ms retries); failure (exit
1) otherwise. Unlike the ping-based healthcheck, this verifies an actual
service is listening (AdGuard :3000, Tailscale, OpenVPN...).

Implemented in Go (net.DialTimeout), not shell, so it does not depend on nc
being present on OpenWrt stock. Host/port validated by strict regex
(1-65535, no leading zeros).

* feat(orchestr): AdGuard tcp_check after start + manual rollback endpoint

AdGuard plans (none/apk/opkg/binary) now include a tcp_check to the UI port
after 'service start', so the executor rolls back if AdGuard does not come up
instead of silently applying DNS changes to a dead service.

POST /api/plans/{id}/rollback lets an admin revert an applied plan:
- Verifies the plan is in status 'applied' (409 otherwise).
- Computes the inverse desired state (AdGuard: toggle enabled) and re-runs
  the SSH probe to build the rollback Ops.
- Dispatches them to the agent over SSE ('rollback' event) with the same
  snapshot+healthcheck+auto-rollback the agent already does.

Manager: SetRollingBack (status 'rolling_back' + audit) and SetResult now
translates the agent result when the plan was rolling back (applied ->
rolled_back, failed stays failed). invertDesired is per-module; unsupported
modules return 400 rollback_unsupported.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 mesi fa
parent
commit
cb4f1ab936

+ 39 - 0
agent/executor/executor.go

@@ -11,6 +11,7 @@ import (
 	"encoding/base64"
 	"encoding/json"
 	"fmt"
+	"net"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -80,6 +81,11 @@ var (
 	reMode        = regexp.MustCompile(`^[0-7]{3,4}$`)
 	// base64 estándar (sin newlines). La validación final la hace base64.Decode.
 	reBase64 = regexp.MustCompile(`^[A-Za-z0-9+/]+={0,2}$`)
+
+	// tcp_check: host (IPv4 o hostname simple) + puerto (1-65535).
+	reHost = regexp.MustCompile(`^([0-9]{1,3}[.]){3}[0-9]{1,3}$|^[a-zA-Z0-9.-]{1,253}$`)
+	// rePort valida 1-65535 sin ceros a la izquierda.
+	rePort = regexp.MustCompile(`^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$`)
 )
 
 // opSpec define los args requeridos y su validación para cada Kind.
@@ -215,8 +221,41 @@ var allowlist = map[string]opSpec{
 		},
 		configs: func(a map[string]string) []string { return nil },
 	},
+	// tcp_check: abre una conexión TCP al host:port. Éxito (exit 0) si conecta
+	// dentro del budget; fallo (exit 1) si no. Es un healthcheck real de
+	// servicio (el ping del executor solo confirma red). Usado por módulos que
+	// abren puerto (AdGuard :3000, Tailscale, OpenVPN...): si el servicio no
+	// levanta, esta op falla → el executor revierte staged.
+	// Se hace en Go (no shell) para no depender de nc, que no siempre está en
+	// OpenWrt stock. Reintenta durante tcpCheckBudget (10 s por defecto) cada
+	// tcpCheckRetry: un servicio puede tardar unos segundos en abrir puerto
+	// tras `service start` (AdGuard, Tailscale...).
+	"tcp_check": {
+		required: map[string]*regexp.Regexp{"host": reHost, "port": rePort},
+		exec: func(_ Runner, a map[string]string) int {
+			addr := net.JoinHostPort(a["host"], a["port"])
+			start := time.Now()
+			for time.Since(start) < tcpCheckBudget {
+				conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
+				if err == nil {
+					_ = conn.Close()
+					return 0
+				}
+				time.Sleep(tcpCheckRetry)
+			}
+			return 1
+		},
+		configs: func(a map[string]string) []string { return nil },
+	},
 }
 
+// tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
+// Son vars de paquete (no const) para poder acortarlos en tests.
+var (
+	tcpCheckBudget = 10 * time.Second
+	tcpCheckRetry  = 500 * time.Millisecond
+)
+
 // Executor aplica Ops allowlistedas con snapshot + healthcheck + rollback.
 type Executor struct {
 	run        Runner

+ 58 - 0
agent/executor/executor_test.go

@@ -1,7 +1,9 @@
 package executor
 
 import (
+	"net"
 	"os"
+	"strconv"
 	"strings"
 	"testing"
 	"time"
@@ -415,3 +417,59 @@ func TestMarshalUnmarshalOps(t *testing.T) {
 		t.Fatalf("roundtrip failed: %+v", got)
 	}
 }
+
+// TestValidateTcpCheck: args host/port validados por regex.
+func TestValidateTcpCheck(t *testing.T) {
+	cases := []struct {
+		name, host, port string
+		ok               bool
+	}{
+		{"ipv4", "127.0.0.1", "3000", true},
+		{"localhost", "localhost", "53", true},
+		{"lan-ip", "192.168.1.1", "80", true},
+		{"port-zero", "127.0.0.1", "0", false},
+		{"port-too-high", "127.0.0.1", "65536", false},
+		{"port-leading-zero", "127.0.0.1", "03000", false},
+		{"host-space", "127.0.0.1 ", "3000", false},
+		{"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
+		{"missing-port", "127.0.0.1", "", false},
+	}
+	for _, c := range cases {
+		op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
+		err := Validate(op)
+		if (err == nil) != c.ok {
+			t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
+		}
+	}
+}
+
+// TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
+// puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
+func TestTcpCheckExecOpenThenClosed(t *testing.T) {
+	// Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
+	prev := tcpCheckBudget
+	tcpCheckBudget = 300 * time.Millisecond
+	defer func() { tcpCheckBudget = prev }()
+
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("no pude abrir listener: %v", err)
+	}
+	port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
+
+	spec, ok := allowlist["tcp_check"]
+	if !ok {
+		t.Fatal("tcp_check no está en allowlist")
+	}
+
+	// Puerto abierto → 0
+	if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
+		t.Errorf("puerto abierto: esperaba 0, got %d", rc)
+	}
+
+	// Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
+	ln.Close()
+	if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
+		t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
+	}
+}

+ 68 - 0
server-go/internal/httpapi/orchestr.go

@@ -101,6 +101,56 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 		writeJSON(w, http.StatusAccepted, map[string]string{"status": "applying", "planId": id})
 	})))
 
+	// POST /api/plans/{id}/rollback — revertir un plan ya aplicado.
+	//
+	// Calcula el "desired inverso" del módulo (p. ej. AdGuard: si el plan era
+	// enabled=true, el inverso es enabled=false), vuelve a sondear el router
+	// (para detectar el escenario actual) y envía las Ops inversas al agente
+	// vía SSE. El agente las ejecuta con su snapshot+healthcheck+rollback
+	// automático. El resultado llega por POST /api/agents/{slug}/apply-result.
+	mux.Handle("POST /api/plans/{id}/rollback", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("id")
+		plan, err := mgr.GetPlan(id)
+		if err != nil {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if plan.Status != "applied" {
+			writeError(w, http.StatusConflict, "plan_not_applied",
+				"Solo se puede revertir un plan aplicado (estado actual: "+plan.Status+")")
+			return
+		}
+		inverseDesired, err := invertDesired(plan.Resource, plan.Desired)
+		if err != nil {
+			writeError(w, http.StatusBadRequest, "rollback_unsupported", err.Error())
+			return
+		}
+		// Recalcular ops inversas (vuelve a sondear el escenario del router).
+		diff, _, err := s.computeModuleDiff(plan.Resource, plan.RouterID, inverseDesired)
+		if err != nil {
+			s.writeModuleErr(w, err)
+			return
+		}
+		if s.agentHub == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_agent_hub")
+			return
+		}
+		applyData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": diff})
+		sent := s.agentHub.Send(plan.RouterID, "rollback", json.RawMessage(applyData))
+		if !sent {
+			writeError(w, http.StatusServiceUnavailable, "agent_not_connected",
+				"El agente no está conectado vía SSE")
+			return
+		}
+		user := auth.UserFromContext(r.Context())
+		actor := ""
+		if user != nil {
+			actor = user.Username
+		}
+		mgr.SetRollingBack(id, actor)
+		writeJSON(w, http.StatusAccepted, map[string]string{"status": "rolling_back", "planId": id})
+	})))
+
 	// El agente reporta el resultado del apply. Auth por token de agente
 	// (Bearer, mismo que ingesta — ya validado por RequireAuth bypass).
 	mux.HandleFunc("POST /api/agents/{slug}/apply-result", func(w http.ResponseWriter, r *http.Request) {
@@ -225,3 +275,21 @@ func (s *server) writeModuleErr(w http.ResponseWriter, err error) {
 		writeError(w, http.StatusInternalServerError, "module_error", err.Error())
 	}
 }
+
+// invertDesired devuelve el estado deseado opuesto para un módulo, de forma
+// que computeModuleDiff(inverseDesired) genere las Ops que deshacen el plan
+// original. Solo los módulos que saben invertirse lo soportan (hoy AdGuard:
+// toggle Enabled; el rollback de enabled=true es disable).
+func invertDesired(resource string, desired json.RawMessage) (json.RawMessage, error) {
+	switch resource {
+	case "adguard":
+		var d orchestr.AdGuardDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, fmt.Errorf("desired inválido: %w", err)
+		}
+		d.Enabled = !d.Enabled
+		return json.Marshal(d)
+	default:
+		return nil, fmt.Errorf("rollback no soportado para el módulo %q", resource)
+	}
+}

+ 59 - 0
server-go/internal/httpapi/orchestr_internal_test.go

@@ -0,0 +1,59 @@
+package httpapi
+
+import (
+	"encoding/json"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+)
+
+// TestInvertDesiredAdGuard: el inverso de enabled=true es enabled=false (y
+// viceversa); el resto de campos se conservan.
+func TestInvertDesiredAdGuard(t *testing.T) {
+	cases := []struct {
+		name string
+		in   bool
+		want bool
+	}{
+		{"enabled_to_disabled", true, false},
+		{"disabled_to_enabled", false, true},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			in, _ := json.Marshal(orchestr.AdGuardDesired{
+				Enabled: c.in, Port: "3000", UpstreamDNS: "1.1.1.1",
+			})
+			out, err := invertDesired("adguard", in)
+			if err != nil {
+				t.Fatalf("invertDesired err: %v", err)
+			}
+			var got orchestr.AdGuardDesired
+			if err := json.Unmarshal(out, &got); err != nil {
+				t.Fatalf("unmarshal err: %v", err)
+			}
+			if got.Enabled != c.want {
+				t.Errorf("Enabled: in=%v want=%v got=%v", c.in, c.want, got.Enabled)
+			}
+			// El resto de campos se conservan (no se pierden al invertir).
+			if got.Port != "3000" || got.UpstreamDNS != "1.1.1.1" {
+				t.Errorf("campos no conservados: port=%q dns=%q", got.Port, got.UpstreamDNS)
+			}
+		})
+	}
+}
+
+// TestInvertDesiredUnsupported: un módulo que no sabe invertirse devuelve error.
+func TestInvertDesiredUnsupported(t *testing.T) {
+	_, err := invertDesired("wireguard", json.RawMessage(`{}`))
+	if err == nil {
+		t.Error("esperaba error para módulo no soportado")
+	}
+}
+
+// TestInvertDesiredInvalidJSON: JSON malformado devuelve error (no panic).
+func TestInvertDesiredInvalidJSON(t *testing.T) {
+	_, err := invertDesired("adguard", json.RawMessage(`{bad json`))
+	if err == nil {
+		t.Error("esperaba error para JSON inválido")
+	}
+}

+ 7 - 3
server-go/internal/orchestr/modules.go

@@ -67,6 +67,8 @@ func AdGuardOps(desired AdGuardDesired, sc AdGuardScenario) ([]executor.Op, erro
 
 // adGuardConfigOps: asume AdGuard ya instalado (opkg/apk/binario presente).
 // Solo configura el DNS forwarding de dnsmasq y arranca el servicio procd.
+// tcp_check al puerto de la UI verifica que el servicio levantó de verdad
+// (si no, el executor revierte staged).
 func adGuardConfigOps(port, dns string) []executor.Op {
 	return []executor.Op{
 		{Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "no_resolv", "value": "1"}, Desc: "Don't use /etc/resolv.conf"},
@@ -74,6 +76,7 @@ func adGuardConfigOps(port, dns string) []executor.Op {
 		{Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit DHCP changes"},
 		{Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "enable"}, Desc: "Enable AdGuard Home on boot"},
 		{Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard Home"},
+		{Kind: "tcp_check", Args: map[string]string{"host": "127.0.0.1", "port": port}, Desc: "Check AdGuard Home UI is listening"},
 		{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}, Desc: "Restart dnsmasq to apply DNS forwarding"},
 	}
 }
@@ -92,9 +95,9 @@ func adGuardDisableOps() []executor.Op {
 }
 
 // adGuardBinaryOps: escenario "binary" (download oficial de GitHub + init procd).
-// Plan (13 ops): download → extract → mv binario → chmod → write config →
-// write init.d → chmod init.d → enable + start service → DNS forward + commit
-// + dnsmasq restart.
+// Plan (14 ops): download → extract → mv binario → chmod → write config →
+// write init.d → chmod init.d → enable + start service → tcp_check UI →
+// DNS forward + commit + dnsmasq restart.
 //
 // La estructura del tarball oficial es `AdGuardHome/AdGuardHome` (binario) +
 // README/LICENSE/homepage; por eso se extrae a /tmp y se mueve solo el binario.
@@ -115,6 +118,7 @@ func adGuardBinaryOps(sc AdGuardScenario, port, dns string) []executor.Op {
 		{Kind: "chmod", Args: map[string]string{"mode": "0755", "path": "/etc/init.d/adguardhome"}, Desc: "Make init script executable"},
 		{Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "enable"}, Desc: "Enable AdGuard Home on boot"},
 		{Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard Home"},
+		{Kind: "tcp_check", Args: map[string]string{"host": "127.0.0.1", "port": port}, Desc: "Check AdGuard Home UI is listening"},
 		{Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "no_resolv", "value": "1"}, Desc: "Don't use /etc/resolv.conf"},
 		{Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "127.0.0.1#" + port}, Desc: "Forward DNS to AdGuard on port " + port},
 		{Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit DHCP changes"},

+ 3 - 2
server-go/internal/orchestr/modules_test.go

@@ -117,12 +117,13 @@ func TestAdGuardOpsEscenarioBinary(t *testing.T) {
 		t.Fatalf("binary inesperado error: %v", err)
 	}
 	// Secuencia esperada: download → extract → mv → chmod → write_file config
-	// → write_file init.d → chmod init.d → enable → start → uci_set ×2 → commit → dnsmasq restart.
+	// → write_file init.d → chmod init.d → enable → start → tcp_check UI →
+	// uci_set ×2 → commit → dnsmasq restart.
 	kinds := make([]string, len(ops))
 	for i, op := range ops {
 		kinds[i] = op.Kind
 	}
-	wantSeq := []string{"download", "extract_tarball", "mv", "chmod", "write_file", "write_file", "chmod", "service", "service", "uci_set", "uci_set", "uci_commit", "service"}
+	wantSeq := []string{"download", "extract_tarball", "mv", "chmod", "write_file", "write_file", "chmod", "service", "service", "tcp_check", "uci_set", "uci_set", "uci_commit", "service"}
 	if len(kinds) != len(wantSeq) {
 		t.Fatalf("binary plan length: got %d want %d\nkinds: %v", len(kinds), len(wantSeq), kinds)
 	}

+ 28 - 2
server-go/internal/orchestr/orchestr.go

@@ -99,17 +99,43 @@ func (m *Manager) SetApplying(id string) error {
 	return err
 }
 
+// SetRollingBack marca el plan como en revertido en curso (un admin disparó
+// POST /api/plans/{id}/rollback). Registra auditoría.
+func (m *Manager) SetRollingBack(id, actor string) error {
+	_, err := m.db.Exec(`UPDATE orchestr_plans SET status = 'rolling_back' WHERE id = ?`, id)
+	if err != nil {
+		return err
+	}
+	m.audit(id, "rollback", actor, "manual rollback triggered")
+	return nil
+}
+
 // SetResult actualiza el plan con el resultado del agente y registra auditoría.
+// Si el plan estaba en 'rolling_back', traduce el resultado del agente al
+// estado semántico del plan (applied → rolled_back, fallido → failed).
 func (m *Manager) SetResult(id string, res ApplyResult) error {
+	var prev string
+	if err := m.db.QueryRow(`SELECT status FROM orchestr_plans WHERE id = ?`, id).Scan(&prev); err != nil {
+		return err
+	}
+	final := res.Status
+	if prev == "rolling_back" {
+		switch res.Status {
+		case "applied":
+			final = "rolled_back"
+		case "rolled_back":
+			final = "failed" // el propio rollback no pudo revertir
+		}
+	}
 	resJSON, _ := json.Marshal(res)
 	now := time.Now().Unix()
 	_, err := m.db.Exec(
 		`UPDATE orchestr_plans SET status = ?, applied_at = ?, result = ? WHERE id = ?`,
-		res.Status, now, string(resJSON), id)
+		final, now, string(resJSON), id)
 	if err != nil {
 		return err
 	}
-	m.audit(id, res.Status, "agent", res.Error)
+	m.audit(id, final, "agent", res.Error)
 	return nil
 }