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

feat(orchestr): DDNS module (Phase 17.3) + nav labs badge (#134)

* feat(orchestr): DDNS module (Phase 17.3)

Orchestration module for dynamic DNS on an OpenWrt router.

- Probe (DetectDdns): detects the package manager (apk vs opkg), whether
  ddns-scripts is installed (/etc/init.d/ddns) and whether a ddns service
  section is present/active.
- Enable: apk_install (or opkg install) ddns-scripts if missing, configure the
  ddns service section (enabled, service_name, domain, username, password),
  commit, enable + start the ddns service.
- Disable: enabled=0 + stop + disable (keeps the package, idempotent
  re-enable). Returns no-op if there is nothing configured.
- Gateway-only by default (allowNonGateway pattern from #120); invertDesired
  toggles enabled for manual rollback.

Tests: probe parse (apk active, not installed), enable (installs + configures,
no re-install when present), disable. Suite -race green.

Verified live: dry-run on a 25.12 (apk) router → 10 ops (apk_install +
uci_set_named + 5 uci_set + commit + service enable/start). Apply not run.

Part of #133

* feat(ui): mark orchestration as 'labs' in the nav

Orchestration (plan/apply/rollback on routers) is experimental. The sidebar
item now carries a red Bug icon + 'labs' badge; the collapsed rail shows a
red dot and the tooltip appends '· labs'.

NavItem gains an optional 'badge' field; only orchestration sets it today.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
dcdc71ee23

+ 18 - 1
app/src/components/Layout.tsx

@@ -5,6 +5,7 @@ import { AnimatePresence, motion } from 'framer-motion'
 import {
   BarChart3,
   Bell,
+  Bug,
   ChevronsLeft,
   ChevronsRight,
   Download,
@@ -38,6 +39,8 @@ interface NavItem {
   icon: LucideIcon
   end?: boolean
   adminOnly?: boolean
+  /** Badge de etiqueta junto al ítem (p. ej. "labs" para experimentos). */
+  badge?: string
 }
 
 const NAV_ITEMS: NavItem[] = [
@@ -48,7 +51,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
-  { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true },
+  { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true, badge: 'labs' },
   { to: '/settings', labelKey: 'nav.settings', icon: Settings },
 ]
 
@@ -216,9 +219,13 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
               }
             >
               <item.icon className="h-5 w-5" strokeWidth={1.75} />
+              {item.badge && (
+                <span className="absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-danger" aria-hidden="true" />
+              )}
               <NavItemBadge to={item.to} variant="rail" />
               <span className="pointer-events-none absolute left-full z-50 ml-3 hidden whitespace-nowrap rounded-lg border border-border-strong bg-elevated px-2.5 py-1.5 text-caption font-medium text-text-primary shadow-lg group-hover:block">
                 {t(item.labelKey)}
+                {item.badge && <span className="ml-1.5 text-danger">· {item.badge}</span>}
               </span>
             </NavLink>
           ))}
@@ -266,6 +273,12 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
                 )}
                 <item.icon className="h-[18px] w-[18px] shrink-0" strokeWidth={1.75} />
                 {t(item.labelKey)}
+                {item.badge && (
+                  <span className="ml-auto flex shrink-0 items-center gap-1 rounded-full bg-danger/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-danger">
+                    <Bug className="h-3 w-3" strokeWidth={2.25} aria-hidden="true" />
+                    {item.badge}
+                  </span>
+                )}
                 <NavItemBadge to={item.to} variant="sidebar" />
               </>
             )}
@@ -329,9 +342,13 @@ function Rail() {
             }
           >
             <item.icon className="h-5 w-5" strokeWidth={1.75} />
+            {item.badge && (
+              <span className="absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-danger" aria-hidden="true" />
+            )}
             <NavItemBadge to={item.to} variant="rail" />
             <span className="pointer-events-none absolute left-full ml-3 hidden whitespace-nowrap rounded-lg border border-border-strong bg-elevated px-2.5 py-1.5 text-caption font-medium text-text-primary shadow-lg group-hover:block">
               {t(item.labelKey)}
+              {item.badge && <span className="ml-1.5 text-danger">· {item.badge}</span>}
             </span>
           </NavLink>
         ))}

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

@@ -282,6 +282,26 @@ func (s *server) computeModuleDiff(resource, routerID string, desired json.RawMe
 		}
 		ops := orchestr.GuestWiFiOps(d, sc)
 		return ops, guestWiFiMethod(d.Enabled), nil
+	case "ddns":
+		var d orchestr.DdnsDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errInvalidDesired, err)
+		}
+		host := s.hostOfRouter(routerID)
+		if host == "" {
+			return nil, "", errRouterNotFound
+		}
+		// Gateway-only por defecto (patrón #120/#17.2).
+		isGateway, _ := s.gatewayInfo(routerID)
+		if !isGateway && !d.AllowNonGateway {
+			return nil, "", errGatewayOnly
+		}
+		sc, err := orchestr.DetectDdns(s.pool, host)
+		if err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errProbeFailed, err)
+		}
+		ops := orchestr.DdnsOps(d, sc)
+		return ops, guestWiFiMethod(d.Enabled), nil
 	default:
 		return nil, "", fmt.Errorf("%w: %s", errUnknownModule, resource)
 	}
@@ -374,6 +394,13 @@ func invertDesired(resource string, desired json.RawMessage) (json.RawMessage, e
 		}
 		d.Enabled = !d.Enabled
 		return json.Marshal(d)
+	case "ddns":
+		var d orchestr.DdnsDesired
+		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)
 	}

+ 133 - 0
server-go/internal/orchestr/ddns.go

@@ -0,0 +1,133 @@
+// ddns.go — módulo de orquestación "DDNS" (Fase 17.3).
+//
+// Instala ddns-scripts (apk/opkg según el router) y configura el servicio de
+// DNS dinámico (service_name, dominio, usuario/contraseña) en /etc/config/ddns,
+// luego arranca el servicio ddns. Reutiliza los Kinds de 17.1 (apk_install /
+// install para opkg) y el patrón de secciones del 17.2.
+package orchestr
+
+import (
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// ddnsSection es la sección UCI del servicio DDNS que gestiona este módulo.
+// El probe detecta si ya existe una sección activa; si no, se usa esta.
+const ddnsSection = "myddns"
+
+// DdnsDesired es el estado deseado del módulo DDNS.
+type DdnsDesired struct {
+	Enabled     bool   `json:"enabled"`
+	ServiceName string `json:"serviceName"` // proveedor (duckdns.org, dyndns.org...)
+	Domain      string `json:"domain"`
+	Username    string `json:"username"`
+	Password    string `json:"password"`
+	// AllowNonGateway: gateway-only por defecto (patrón #120).
+	AllowNonGateway bool `json:"allowNonGateway,omitempty"`
+}
+
+// DdnsScenario describe el estado del DDNS en el router.
+type DdnsScenario struct {
+	// Manager: "apk" | "opkg" (gestor de paquetes del router).
+	Manager string
+	// Installed: /etc/init.d/ddns existe (ddns-scripts instalado).
+	Installed bool
+	// ActiveSection: hay una sección ddns con enabled='1'.
+	ActiveSection bool
+	// SectionExists: existe la sección ddnsSection en uci.
+	SectionExists bool
+}
+
+// probeDdnsCmd detecta gestor, instalación y sección activa.
+const probeDdnsCmd = `echo '===PKG_MGR==='
+[ -x /usr/bin/apk ] && echo apk || echo opkg
+echo '===INSTALLED==='
+[ -x /etc/init.d/ddns ] && echo yes || echo no
+echo '===DDNS_UCI==='
+uci show ddns 2>/dev/null
+echo '===END==='`
+
+// DetectDdns ejecuta el probe y devuelve el escenario.
+func DetectDdns(run CommandRunner, host string) (DdnsScenario, error) {
+	out, err := run.Run(host, probeDdnsCmd, 8*time.Second)
+	if err != nil {
+		return DdnsScenario{}, err
+	}
+	return parseDdns(out), nil
+}
+
+// parseDdns extrae el escenario del output del probe. Función pura.
+func parseDdns(out string) DdnsScenario {
+	sc := DdnsScenario{}
+	sections := splitSections(out)
+	sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
+	sc.Installed = strings.TrimSpace(firstNonEmpty(sections["INSTALLED"])) == "yes"
+	uci := strings.Join(sections["DDNS_UCI"], "\n")
+	sc.SectionExists = strings.Contains(uci, "ddns."+ddnsSection+"=service")
+	if strings.Contains(uci, "ddns."+ddnsSection+".enabled='1'") {
+		sc.ActiveSection = true
+	}
+	return sc
+}
+
+// DdnsOps genera las Ops para activar/desactivar DDNS.
+func DdnsOps(desired DdnsDesired, sc DdnsScenario) []executor.Op {
+	if !desired.Enabled {
+		return ddnsDisableOps(sc)
+	}
+	// Si no hay sección, crearla (uci_set_named → sección nombrada).
+	var ops []executor.Op
+	if !sc.Installed {
+		if sc.Manager == "apk" {
+			ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "ddns-scripts"}, Desc: "Install ddns-scripts (apk)"})
+		} else {
+			ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "ddns-scripts"}, Desc: "Install ddns-scripts (opkg)"})
+		}
+	}
+	// Configurar la sección service.
+	if !sc.SectionExists {
+		ops = append(ops, executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "ddns", "section": ddnsSection, "type": "service"}, Desc: "Create ddns service section"})
+	}
+	svcName := desired.ServiceName
+	if svcName == "" {
+		svcName = "duckdns.org"
+	}
+	ops = append(ops,
+		executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "enabled", "value": "1"}, Desc: "Enable ddns service"},
+		executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "service_name", "value": svcName}, Desc: "Set ddns provider"},
+		executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "domain", "value": desired.Domain}, Desc: "Set ddns domain"},
+		executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "username", "value": desired.Username}, Desc: "Set ddns username"},
+		executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "password", "value": desired.Password}, Desc: "Set ddns password"},
+		executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "ddns"}, Desc: "Commit ddns config"},
+		executor.Op{Kind: "service", Args: map[string]string{"name": "ddns", "action": "enable"}, Desc: "Enable ddns on boot"},
+		executor.Op{Kind: "service", Args: map[string]string{"name": "ddns", "action": "start"}, Desc: "Start ddns service"},
+	)
+	return ops
+}
+
+// ddnsDisableOps desactiva el servicio sin desinstalar el paquete.
+func ddnsDisableOps(sc DdnsScenario) []executor.Op {
+	if !sc.SectionExists && !sc.Installed {
+		// No hay nada que desactivar.
+		return []executor.Op{}
+	}
+	return []executor.Op{
+		{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "enabled", "value": "0"}, Desc: "Disable ddns service"},
+		{Kind: "uci_commit", Args: map[string]string{"config": "ddns"}, Desc: "Commit ddns config"},
+		{Kind: "service", Args: map[string]string{"name": "ddns", "action": "stop"}, Desc: "Stop ddns service"},
+		{Kind: "service", Args: map[string]string{"name": "ddns", "action": "disable"}, Desc: "Disable ddns on boot"},
+	}
+}
+
+// validateDdnsOps valida cada op contra el executor (usado en tests).
+func validateDdnsOps(ops []executor.Op) error {
+	for _, op := range ops {
+		if err := executor.Validate(op); err != nil {
+			return fmt.Errorf("%s: %w", op.Desc, err)
+		}
+	}
+	return nil
+}

+ 152 - 0
server-go/internal/orchestr/ddns_test.go

@@ -0,0 +1,152 @@
+package orchestr
+
+import (
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// Fixture: router apk con ddns-scripts instalado y sección activa.
+// Formato de `uci show ddns` (no de fichero config).
+const ddnsOutApkActivo = `===PKG_MGR===
+apk
+===INSTALLED===
+yes
+===DDNS_UCI===
+ddns.global=ddns
+ddns.global.ddns_dateformat='%F %R'
+ddns.global.ddns_loglines='250'
+ddns.global.upd_privateip='0'
+ddns.myddns=service
+ddns.myddns.enabled='1'
+ddns.myddns.service_name='duckdns.org'
+ddns.myddns.lookup_host='mi.duckdns.org'
+ddns.myddns.domain='mi.duckdns.org'
+ddns.myddns.username='token'
+ddns.myddns.password='token123'
+ddns.myddns.ip_source='network'
+ddns.myddns.ip_network='wan'
+===END===`
+
+// TestParseDdnsApkActivo: detecta apk, instalado y sección activa.
+func TestParseDdnsApkActivo(t *testing.T) {
+	sc := parseDdns(ddnsOutApkActivo)
+	if sc.Manager != "apk" {
+		t.Errorf("Manager: got %q want apk", sc.Manager)
+	}
+	if !sc.Installed {
+		t.Error("Installed: esperaba true")
+	}
+	if !sc.SectionExists {
+		t.Error("SectionExists: esperaba true")
+	}
+	if !sc.ActiveSection {
+		t.Error("ActiveSection: esperaba true (enabled='1')")
+	}
+}
+
+// TestParseDdnsNoInstalado: sin ddns-scripts ni sección.
+func TestParseDdnsNoInstalado(t *testing.T) {
+	out := `===PKG_MGR===
+opkg
+===INSTALLED===
+no
+===DDNS_UCI===
+===END===`
+	sc := parseDdns(out)
+	if sc.Manager != "opkg" {
+		t.Errorf("Manager: got %q want opkg", sc.Manager)
+	}
+	if sc.Installed {
+		t.Error("Installed: esperaba false")
+	}
+	if sc.SectionExists || sc.ActiveSection {
+		t.Error("no debería haber sección activa sin ddns-scripts")
+	}
+}
+
+// TestDdnsOpsEnableInstalaYConfigura: enable instala + configura + arranca.
+func TestDdnsOpsEnableInstalaYConfigura(t *testing.T) {
+	sc := parseDdns(`===PKG_MGR===
+apk
+===INSTALLED===
+no
+===DDNS_UCI===
+===END===`)
+	ops := DdnsOps(DdnsDesired{
+		Enabled: true, ServiceName: "duckdns.org",
+		Domain: "mi.duckdns.org", Username: "token", Password: "token123",
+	}, sc)
+	if err := validateDdnsOps(ops); err != nil {
+		t.Fatalf("ops enable no validan en executor: %v", err)
+	}
+	// Debe instalar con apk_install y crear la sección con uci_set_named.
+	kinds := map[string]bool{}
+	for _, o := range ops {
+		kinds[o.Kind] = true
+	}
+	if !kinds["apk_install"] {
+		t.Error("enable sin apk_install (ddns-scripts no instalado)")
+	}
+	if !kinds["uci_set_named"] {
+		t.Error("enable sin uci_set_named (sección ddns a crear)")
+	}
+	if !kinds["service"] {
+		t.Error("enable sin service (start/enable ddns)")
+	}
+	// Verificar que configura los campos clave.
+	found := false
+	for _, o := range ops {
+		if o.Kind == "uci_set" && o.Args["option"] == "domain" && o.Args["value"] == "mi.duckdns.org" {
+			found = true
+		}
+	}
+	if !found {
+		t.Error("enable sin uci_set del dominio")
+	}
+}
+
+// TestDdnsOpsEnableYaInstalado: no re-instala si ya está.
+func TestDdnsOpsEnableYaInstalado(t *testing.T) {
+	sc := parseDdns(ddnsOutApkActivo)
+	ops := DdnsOps(DdnsDesired{
+		Enabled: true, ServiceName: "duckdns.org",
+		Domain: "mi.duckdns.org", Username: "token", Password: "token123",
+	}, sc)
+	if err := validateDdnsOps(ops); err != nil {
+		t.Fatalf("ops no validan: %v", err)
+	}
+	for _, o := range ops {
+		if o.Kind == "apk_install" || o.Kind == "install" {
+			t.Error("no debería re-instalar ddns-scripts si ya está")
+		}
+		if o.Kind == "uci_set_named" {
+			t.Error("no debería recrear la sección si ya existe")
+		}
+	}
+}
+
+// TestDdnsOpsDisable: desactiva (enabled=0 + stop + disable) sin desinstalar.
+func TestDdnsOpsDisable(t *testing.T) {
+	sc := parseDdns(ddnsOutApkActivo)
+	ops := DdnsOps(DdnsDesired{Enabled: false}, sc)
+	if err := validateDdnsOps(ops); err != nil {
+		t.Fatalf("ops disable no validan: %v", err)
+	}
+	joined := strings.Join(kindsOf(ops), ",")
+	if !strings.Contains(joined, "uci_set") {
+		t.Error("disable sin uci_set enabled=0")
+	}
+	if !strings.Contains(joined, "service") {
+		t.Error("disable sin service stop/disable")
+	}
+}
+
+func kindsOf(ops []executor.Op) []string {
+	out := make([]string, len(ops))
+	for i, o := range ops {
+		out[i] = o.Kind
+	}
+	return out
+}