Quellcode durchsuchen

feat(fase10): AdGuard module + Orchestration UI (10.2) (#95)

First end-to-end module for Phase 10. AdGuard Home can be enabled/disabled
declaratively from the web app, with plan review and apply confirmation.

Server (orchestr/modules.go):
- AdGuardOps: desired state → Ops (install + DNS forwarding + service
  restart on enable; revert on disable).
- ModuleDiff: dispatches to the right module by resource name. POST
  /api/plans now auto-computes Ops from desired state if no explicit diff.

Frontend (pages/Orchestration.tsx):
- New /orchestration route (admin only). Router selector, AdGuard
  enable/disable toggle + port/upstream inputs, Generate Plan button,
  Ops review list with kind+desc, Apply button, live polling for result.
- Status badges: pending → applying → applied/failed/rolled_back.
- Nav item (Wrench icon) + i18n keys (es+en).

Agent v2.8.0 deployed to 4 routers (executor + apply SSE handler active).

Co-authored-by: gnacho <hnacho@proton.me>
Nacho vor 3 Monaten
Ursprung
Commit
9b1b3f21de

+ 20 - 2
app/public/locales/en/translation.json

@@ -137,7 +137,8 @@
     "uptime_other": "{{d}} days, {{h}}h",
     "viewAll": "View all",
     "viewDetail": "View {{name}} detail",
-    "viewDetailShort": "View detail"
+    "viewDetailShort": "View detail",
+    "adminOnly": "Admin only"
   },
   "devices": {
     "badges": {
@@ -305,7 +306,8 @@
     "topology": "Topology",
     "topologyDesc": "Visual network map",
     "collapse": "Collapse menu",
-    "expand": "Expand menu"
+    "expand": "Expand menu",
+    "orchestration": "Orchestration"
   },
   "notFound": {
     "construction": "This page is under construction. The mockup will complete it in the next iteration."
@@ -810,5 +812,21 @@
   "demo": {
     "banner": "Demo mode — changes are not applied to the system",
     "exit": "Exit demo"
+  },
+  "orchestration": {
+    "title": "Orchestration",
+    "subtitle": "Configure network services declaratively. Every change goes through a reviewable plan before applying.",
+    "router": "Router",
+    "generatePlan": "Generate plan",
+    "plan": "Plan",
+    "apply": "Apply",
+    "applying": "Applying…",
+    "applied": "Applied successfully",
+    "failed": "Failed",
+    "adguard": {
+      "enable": "Enable AdGuard Home",
+      "port": "Port",
+      "upstream": "Upstream DNS"
+    }
   }
 }

+ 20 - 2
app/public/locales/es/translation.json

@@ -137,7 +137,8 @@
     "uptime_other": "{{d}} días, {{h}} h",
     "viewAll": "Ver todos",
     "viewDetail": "Ver detalle de {{name}}",
-    "viewDetailShort": "Ver detalle"
+    "viewDetailShort": "Ver detalle",
+    "adminOnly": "Solo administrador"
   },
   "devices": {
     "badges": {
@@ -306,7 +307,8 @@
     "topology": "Topología",
     "topologyDesc": "Mapa visual de la red",
     "collapse": "Plegar menú",
-    "expand": "Desplegar menú"
+    "expand": "Desplegar menú",
+    "orchestration": "Orquestación"
   },
   "notFound": {
     "construction": "Esta página está en construcción. El mockup la completará en la siguiente iteración."
@@ -811,5 +813,21 @@
   "demo": {
     "banner": "Modo demo — los cambios no se aplican al sistema",
     "exit": "Salir del demo"
+  },
+  "orchestration": {
+    "title": "Orquestación",
+    "subtitle": "Configura servicios de red de forma declarativa. Cada cambio pasa por un plan revisable antes de aplicarse.",
+    "router": "Router",
+    "generatePlan": "Generar plan",
+    "plan": "Plan",
+    "apply": "Aplicar",
+    "applying": "Aplicando…",
+    "applied": "Aplicado correctamente",
+    "failed": "Falló",
+    "adguard": {
+      "enable": "Activar AdGuard Home",
+      "port": "Puerto",
+      "upstream": "DNS upstream"
+    }
   }
 }

+ 2 - 0
app/src/App.tsx

@@ -10,6 +10,7 @@ import Devices from '@/pages/Devices'
 import Topology from '@/pages/Topology'
 import Alerts from '@/pages/Alerts'
 import Reports from '@/pages/Reports'
+import Orchestration from '@/pages/Orchestration'
 import Settings from '@/pages/Settings'
 import Placeholder from '@/pages/Placeholder'
 
@@ -38,6 +39,7 @@ export default function App() {
         <Route path="topology" element={<Topology />} />
         <Route path="alerts" element={<Alerts />} />
         <Route path="reports" element={<Reports />} />
+        <Route path="orchestration" element={<Orchestration />} />
         <Route path="settings" element={<Settings />} />
         <Route path="*" element={<Placeholder title="Página no encontrada" />} />
       </Route>

+ 3 - 0
app/src/components/Layout.tsx

@@ -15,6 +15,7 @@ import {
   Router as RouterIcon,
   Settings,
   Waypoints,
+  Wrench,
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
@@ -35,6 +36,7 @@ interface NavItem {
   labelKey: string
   icon: LucideIcon
   end?: boolean
+  adminOnly?: boolean
 }
 
 const NAV_ITEMS: NavItem[] = [
@@ -44,6 +46,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
+  { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true },
   { to: '/settings', labelKey: 'nav.settings', icon: Settings },
 ]
 

+ 256 - 0
app/src/pages/Orchestration.tsx

@@ -0,0 +1,256 @@
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+import { motion } from 'framer-motion'
+import { ChevronRight, CheckCircle2, AlertCircle, Loader2, Wand2 } from 'lucide-react'
+import { useNetPulse } from '@/data/DataProvider'
+import { useAuth } from '@/data/AuthContext'
+
+interface Op {
+  kind: string
+  desc: string
+  args: Record<string, string>
+}
+
+interface Plan {
+  id: string
+  routerId: string
+  resource: string
+  diff: Op[]
+  status: string
+  result?: { status: string; error?: string; duration_ms?: number }
+}
+
+export default function Orchestration() {
+  const { t } = useTranslation()
+  const { agents } = useNetPulse()
+  const auth = useAuth()
+  const [routerId, setRouterId] = useState('')
+  const [agEnabled, setAgEnabled] = useState(true)
+  const [agPort, setAgPort] = useState('3000')
+  const [agDns, setAgDns] = useState('1.1.1.1')
+  const [plan, setPlan] = useState<Plan | null>(null)
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState('')
+
+  // Auto-seleccionar el primer router
+  useEffect(() => {
+    if (!routerId && agents.length > 0) setRouterId(agents[0].slug)
+  }, [agents, routerId])
+
+  const createPlan = async () => {
+    setBusy(true)
+    setError('')
+    setPlan(null)
+    try {
+      const res = await fetch('/api/plans', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          routerId,
+          resource: 'adguard',
+          desired: { enabled: agEnabled, port: agPort, upstreamDns: agDns },
+        }),
+      })
+      if (!res.ok) throw new Error(await res.text())
+      setPlan(await res.json())
+    } catch (e) {
+      setError(String(e))
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  const applyPlan = async () => {
+    if (!plan) return
+    setBusy(true)
+    setError('')
+    try {
+      const res = await fetch(`/api/plans/${plan.id}/apply`, { method: 'POST' })
+      if (!res.ok) throw new Error(await res.text())
+      setPlan({ ...plan, status: 'applying' })
+      // Poll hasta que termine
+      const poll = setInterval(async () => {
+        const r = await fetch(`/api/plans/${plan.id}`)
+        if (!r.ok) return
+        const p: Plan = await r.json()
+        setPlan(p)
+        if (p.status !== 'applying') {
+          clearInterval(poll)
+          setBusy(false)
+        }
+      }, 2000)
+    } catch (e) {
+      setError(String(e))
+      setBusy(false)
+    }
+  }
+
+  if (auth?.role !== 'admin') {
+    return (
+      <div className="flex min-h-[50vh] items-center justify-center text-text-secondary">
+        {t('common.adminOnly')}
+      </div>
+    )
+  }
+
+  return (
+    <div className="space-y-4 md:space-y-5">
+      <header>
+        <nav className="mb-1 flex items-center gap-1 text-caption text-text-muted">
+          <Link to="/" className="transition-colors hover:text-accent">{t('common.home')}</Link>
+          <ChevronRight className="h-3 w-3" strokeWidth={1.75} aria-hidden />
+          <span className="text-text-secondary">{t('nav.orchestration')}</span>
+        </nav>
+        <h1 className="font-display text-h1 text-text-primary">{t('orchestration.title')}</h1>
+        <p className="mt-0.5 text-sm text-text-secondary">{t('orchestration.subtitle')}</p>
+      </header>
+
+      <div className="rounded-2xl border border-border bg-surface p-5">
+        <div className="mb-4 flex items-center gap-2">
+          <Wand2 className="h-4 w-4 text-accent" strokeWidth={1.75} />
+          <h2 className="text-sm font-semibold text-text-primary">AdGuard Home</h2>
+        </div>
+
+        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
+          <label className="flex flex-col gap-1">
+            <span className="text-caption font-medium text-text-secondary">{t('orchestration.router')}</span>
+            <select
+              value={routerId}
+              onChange={(e) => setRouterId(e.target.value)}
+              className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+            >
+              {agents.map((a) => (
+                <option key={a.slug} value={a.slug}>{a.slug}</option>
+              ))}
+            </select>
+          </label>
+
+          <label className="flex items-center gap-2 pt-6">
+            <input
+              type="checkbox"
+              checked={agEnabled}
+              onChange={(e) => setAgEnabled(e.target.checked)}
+              className="h-4 w-4 rounded border-border"
+            />
+            <span className="text-sm text-text-primary">{t('orchestration.adguard.enable')}</span>
+          </label>
+
+          {agEnabled && (
+            <>
+              <label className="flex flex-col gap-1">
+                <span className="text-caption font-medium text-text-secondary">{t('orchestration.adguard.port')}</span>
+                <input
+                  type="text"
+                  value={agPort}
+                  onChange={(e) => setAgPort(e.target.value)}
+                  className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                />
+              </label>
+              <label className="flex flex-col gap-1">
+                <span className="text-caption font-medium text-text-secondary">{t('orchestration.adguard.upstream')}</span>
+                <input
+                  type="text"
+                  value={agDns}
+                  onChange={(e) => setAgDns(e.target.value)}
+                  className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                />
+              </label>
+            </>
+          )}
+        </div>
+
+        <div className="mt-4 flex gap-2">
+          <button
+            type="button"
+            onClick={() => void createPlan()}
+            disabled={busy || !routerId}
+            className="inline-flex items-center gap-1.5 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-60"
+          >
+            <Wand2 className="h-4 w-4" strokeWidth={1.75} />
+            {t('orchestration.generatePlan')}
+          </button>
+        </div>
+      </div>
+
+      {error && (
+        <div className="rounded-xl border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-600 dark:text-rose-400">
+          {error}
+        </div>
+      )}
+
+      {plan && (
+        <motion.div
+          initial={{ opacity: 0, y: 8 }}
+          animate={{ opacity: 1, y: 0 }}
+          className="rounded-2xl border border-border bg-surface p-5"
+        >
+          <div className="mb-3 flex items-center justify-between">
+            <h3 className="text-sm font-semibold text-text-primary">
+              {t('orchestration.plan')} · {plan.id.slice(0, 8)}
+            </h3>
+            <PlanStatusBadge status={plan.status} />
+          </div>
+
+          <div className="space-y-1">
+            {plan.diff.map((op, i) => (
+              <div key={i} className="flex items-center gap-2 rounded-lg bg-canvas/60 px-3 py-2">
+                <span className="font-mono text-xs text-text-muted">{op.kind}</span>
+                <span className="text-sm text-text-primary">{op.desc}</span>
+              </div>
+            ))}
+          </div>
+
+          {plan.status === 'pending' && (
+            <button
+              type="button"
+              onClick={() => void applyPlan()}
+              disabled={busy}
+              className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-60"
+            >
+              {t('orchestration.apply')}
+            </button>
+          )}
+
+          {plan.status === 'applying' && (
+            <div className="mt-4 flex items-center gap-2 text-sm text-text-secondary">
+              <Loader2 className="h-4 w-4 animate-spin" strokeWidth={1.75} />
+              {t('orchestration.applying')}
+            </div>
+          )}
+
+          {plan.result && plan.status !== 'applying' && plan.status !== 'pending' && (
+            <div className={`mt-4 flex items-center gap-2 rounded-lg px-3 py-2 text-sm ${
+              plan.status === 'applied'
+                ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
+                : 'bg-rose-500/10 text-rose-600 dark:text-rose-400'
+            }`}>
+              {plan.status === 'applied'
+                ? <CheckCircle2 className="h-4 w-4" strokeWidth={1.75} />
+                : <AlertCircle className="h-4 w-4" strokeWidth={1.75} />}
+              {plan.status === 'applied'
+                ? t('orchestration.applied')
+                : `${t('orchestration.failed')}: ${plan.result.error || plan.status}`}
+              {plan.result.duration_ms ? ` (${plan.result.duration_ms}ms)` : ''}
+            </div>
+          )}
+        </motion.div>
+      )}
+    </div>
+  )
+}
+
+function PlanStatusBadge({ status }: { status: string }) {
+  const colors: Record<string, string> = {
+    pending: 'bg-surface-2 text-text-secondary',
+    applying: 'bg-accent-soft text-accent',
+    applied: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
+    failed: 'bg-rose-500/10 text-rose-600 dark:text-rose-400',
+    rolled_back: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
+  }
+  return (
+    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${colors[status] || colors.pending}`}>
+      {status}
+    </span>
+  )
+}

+ 12 - 2
server-go/internal/httpapi/orchestr.go

@@ -31,15 +31,25 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 		}
 		if !readJSONBody(r, &body) || body.RouterID == "" || body.Resource == "" {
 			writeError(w, http.StatusBadRequest, "invalid_body",
-				`Se esperaba { "routerId": "...", "resource": "...", "diff": [...] }`)
+				`Se esperaba { "routerId": "...", "resource": "adguard", "desired": {...} }`)
 			return
 		}
+		// Si no hay diff explícito, calcularlo desde desired vía el módulo.
+		diff := body.Diff
+		if len(diff) == 0 && len(body.Desired) > 0 {
+			computed, _, err := orchestr.ModuleDiff(body.Resource, body.Desired)
+			if err != nil {
+				writeError(w, http.StatusBadRequest, "unknown_module", err.Error())
+				return
+			}
+			diff = computed
+		}
 		user := auth.UserFromContext(r.Context())
 		username := ""
 		if user != nil {
 			username = user.Username
 		}
-		plan, err := mgr.CreatePlan(body.RouterID, body.Resource, body.Desired, body.Diff, username)
+		plan, err := mgr.CreatePlan(body.RouterID, body.Resource, body.Desired, diff, username)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "plan_error")
 			return

+ 74 - 0
server-go/internal/orchestr/modules.go

@@ -0,0 +1,74 @@
+// modules.go — módulos de orquestación (Fase 10). Cada módulo convierte un
+// estado deseado en una lista de Ops allowlistedas.
+//
+// Por ahora los módulos generan Ops estáticamente (declarar lo que se quiere).
+// En el futuro, el diff será dinámico: leer el estado actual del router vía
+// SSH y generar solo las Ops necesarias para llegar al estado deseado.
+package orchestr
+
+import (
+	"encoding/json"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// AdGuardDesired es el estado deseado para el módulo AdGuard Home.
+type AdGuardDesired struct {
+	Enabled     bool   `json:"enabled"`
+	Port        string `json:"port"`         // puerto de escucha de AdGuard (default "3000")
+	UpstreamDNS string `json:"upstreamDns"`  // DNS upstream (default "1.1.1.1")
+}
+
+// AdGuardOps genera las Ops para activar/desactivar AdGuard Home en un router.
+// Activar: instala el paquete, reenvía DNS de dnsmasq hacia AdGuard y reinicia.
+// Desactivar: restaura el DNS upstream de dnsmasq y para AdGuard.
+func AdGuardOps(desired AdGuardDesired) []executor.Op {
+	if !desired.Enabled {
+		return []executor.Op{
+			{Kind: "uci_delete", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server"}, Desc: "Remove AdGuard DNS forwarding"},
+			{Kind: "uci_delete", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "no_resolv"}, Desc: "Restore /etc/resolv.conf usage"},
+			{Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit DHCP changes"},
+			{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}, Desc: "Restart dnsmasq"},
+			{Kind: "service", Args: map[string]string{"name": "adguard-home", "action": "disable"}, Desc: "Disable AdGuard Home"},
+			{Kind: "service", Args: map[string]string{"name": "adguard-home", "action": "stop"}, Desc: "Stop AdGuard Home"},
+		}
+	}
+
+	port := desired.Port
+	if port == "" {
+		port = "3000"
+	}
+	dns := desired.UpstreamDNS
+	if dns == "" {
+		dns = "1.1.1.1"
+	}
+
+	return []executor.Op{
+		{Kind: "install", Args: map[string]string{"package": "adguard-home"}, Desc: "Install AdGuard Home"},
+		{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"},
+		{Kind: "service", Args: map[string]string{"name": "adguard-home", "action": "enable"}, Desc: "Enable AdGuard Home on boot"},
+		{Kind: "service", Args: map[string]string{"name": "adguard-home", "action": "restart"}, Desc: "Start AdGuard Home"},
+		{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}, Desc: "Restart dnsmasq to apply DNS forwarding"},
+	}
+}
+
+// ModuleDiff despacha al módulo correcto según el tipo de recurso.
+// Devuelve la lista de Ops y el desired serializado.
+func ModuleDiff(resource string, desired json.RawMessage) ([]executor.Op, json.RawMessage, error) {
+	switch resource {
+	case "adguard":
+		var d AdGuardDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, desired, err
+		}
+		return AdGuardOps(d), desired, nil
+	default:
+		return nil, desired, &unknownModuleError{resource}
+	}
+}
+
+type unknownModuleError struct{ resource string }
+
+func (e *unknownModuleError) Error() string { return "módulo desconocido: " + e.resource }