Explorar o código

feat(agente): resiliencia — watchdog cron con heartbeat (Plan A) y rearme desde el servidor (Plan B)

Plan A:
- El agente toca /tmp/netpulse-agent.heartbeat en cada push confirmado
  (agent/internal/heartbeat, configurable por NETPULSE_HEARTBEAT_FILE).
- agent/deploy/netpulse-watchdog.sh: cron cada 2 min en el router; relanza
  el servicio si procd se rindió (pgrep) y lo reinicia si el proceso vive
  pero lleva >5 min sin latido.
- install-agent.sh instala/actualiza el watchdog y su entrada de cron de
  forma idempotente; --uninstall también los limpia.

Plan B:
- POST /api/agents/{slug}/rearm: reinicia init.d/netpulse-agent vía el pool
  SSH del sondeo, espera el push de vuelta (30 s) y responde con el
  resultado real (recovered). Cooldown 60 s por slug; 404 sin token, 409
  sin router, 503 sin pool SSH, 502 si falla el SSH.
- Botón «Rearmar» en la cabecera del router (solo agente caído) con estados
  busy/ok/pending/fail; rearmAgent en DataProvider; claves i18n es/en.

Tests: 7 casos del rearme con fake SSH (httpapi/rearm_api_test.go), heartbeat.
Backend completo verde, tsc limpio, PWA build OK.
gnacho hai 4 meses
pai
achega
064cfaa66a

+ 20 - 7
agent/cmd/netpulse-agent/main.go

@@ -28,6 +28,7 @@ import (
 	"syscall"
 	"time"
 
+	"github.com/gnacho/netpulse/agent/internal/heartbeat"
 	"github.com/gnacho/netpulse/agent/internal/push"
 	"github.com/gnacho/netpulse/agent/probe"
 )
@@ -41,6 +42,7 @@ type config struct {
 	interval            time.Duration
 	wanTarget, gwTarget string
 	insecureTLS         bool
+	heartbeatFile       string
 }
 
 // loadEnvFile lee KEY=VALUE de un fichero env (líneas # = comentario).
@@ -78,13 +80,14 @@ func loadConfig() (config, error) {
 		return fromFile[key]
 	}
 	cfg := config{
-		server:      strings.TrimRight(get("NETPULSE_SERVER"), "/"),
-		token:       get("NETPULSE_TOKEN"),
-		slug:        get("NETPULSE_SLUG"),
-		interval:    15 * time.Second,
-		wanTarget:   get("NETPULSE_WAN_TARGET"),
-		gwTarget:    get("NETPULSE_GW_TARGET"),
-		insecureTLS: get("NETPULSE_INSECURE_TLS") == "1",
+		server:        strings.TrimRight(get("NETPULSE_SERVER"), "/"),
+		token:         get("NETPULSE_TOKEN"),
+		slug:          get("NETPULSE_SLUG"),
+		interval:      15 * time.Second,
+		wanTarget:     get("NETPULSE_WAN_TARGET"),
+		gwTarget:      get("NETPULSE_GW_TARGET"),
+		insecureTLS:   get("NETPULSE_INSECURE_TLS") == "1",
+		heartbeatFile: get("NETPULSE_HEARTBEAT_FILE"),
 	}
 	if v := get("NETPULSE_INTERVAL"); v != "" {
 		if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
@@ -144,11 +147,21 @@ func run() error {
 	defer stop()
 
 	log.Printf("[netpulse-agent] v%s · %s → %s cada %s", Version, cfg.slug, cfg.server, cfg.interval)
+	hbFile := cfg.heartbeatFile
+	if hbFile == "" {
+		hbFile = heartbeat.DefaultFile
+	}
 	for {
 		payload := prober.Build(ctx, cfg.slug, Version)
 		if err := client.Push(ctx, payload); err != nil {
 			log.Printf("[netpulse-agent] push falló (%v); buffered=%d descartados=%d",
 				err, client.Buffered(), client.Dropped())
+		} else {
+			// Push confirmado por el servidor → latido para el watchdog cron.
+			// Tolerante: un fallo de heartbeat nunca afecta al ciclo de push.
+			if err := heartbeat.Touch(hbFile, time.Now()); err != nil {
+				log.Printf("[netpulse-agent] heartbeat: %v", err)
+			}
 		}
 		select {
 		case <-ctx.Done():

+ 56 - 0
agent/deploy/netpulse-watchdog.sh

@@ -0,0 +1,56 @@
+#!/bin/sh
+# =============================================================================
+# netpulse-watchdog — Fase 6.1 (Plan A): auto-supervisión del agente desde el
+# propio router. Se ejecuta desde cron cada 2 minutos:
+#
+#   1. Proceso muerto → /etc/init.d/netpulse-agent restart
+#      (reinicia la instancia procd y RESETA su contador de reintentos, que
+#      es el hueco que deja al agente caído para siempre tras 5 crashes).
+#   2. Proceso vivo PERO heartbeat viejo (> MAX_AGE s) → restart
+#      ("vivo pero roto": el proceso anda pero no consigue empujar datos
+#      confirmados por el servidor).
+#   3. Proceso vivo sin fichero de heartbeat → NO hacer nada (arranque
+#      reciente o backoff inicial con el servidor caído; reiniciar solo
+#      resetearía el backoff sin aportar nada).
+#
+# El heartbeat lo escribe el agente (agent/internal/heartbeat) tras cada push
+# CONFIRMADO: /tmp/netpulse-agent.heartbeat (tmpfs, nada en NAND).
+#
+# Si el binario no existe (variante /tmp tras un reboot) no hace nada: la
+# reinstalación es cosa del servidor (POST /api/agents/{slug}/rearm en el
+# futuro, hoy install-agent.sh).
+# =============================================================================
+INIT=/etc/init.d/netpulse-agent
+HB=/tmp/netpulse-agent.heartbeat
+MAX_AGE=300 # 5 min sin latido = "vivo pero roto"
+
+# El env puede mover el heartbeat (NETPULSE_HEARTBEAT_FILE)
+[ -f /etc/netpulse-agent.env ] && . /etc/netpulse-agent.env 2>/dev/null
+[ -n "${NETPULSE_HEARTBEAT_FILE:-}" ] && HB="$NETPULSE_HEARTBEAT_FILE"
+
+log() { logger -t netpulse-watchdog "$*"; }
+
+# ¿Hay binario? Sin él no hay nada que vigilar.
+if [ ! -x /usr/sbin/netpulse-agent ] && [ ! -x /tmp/netpulse-agent ]; then
+    exit 0
+fi
+
+if ! pgrep -x netpulse-agent >/dev/null 2>&1; then
+    log "agente no está en marcha — reiniciando servicio"
+    $INIT restart >/dev/null 2>&1
+    exit 0
+fi
+
+if [ -f "$HB" ]; then
+    now=$(date +%s)
+    hb=$(cat "$HB" 2>/dev/null)
+    case "$hb" in
+        '' | *[!0-9]*) exit 0 ;; # fichero corrupto: no actuar a ciegas
+    esac
+    age=$((now - hb))
+    if [ "$age" -gt "$MAX_AGE" ]; then
+        log "proceso vivo pero sin latido en ${age}s — reiniciando servicio"
+        $INIT restart >/dev/null 2>&1
+    fi
+fi
+exit 0

+ 51 - 0
agent/internal/heartbeat/heartbeat.go

@@ -0,0 +1,51 @@
+// Package heartbeat — Fase 6.1 (resiliencia del agente): el agente toca un
+// fichero en /tmp (RAM, nada en NAND) tras cada push CONFIRMADO por el
+// servidor. El watchdog cron del router (agent/deploy/watchdog.sh) usa la
+// edad de ese fichero para distinguir "proceso vivo y empujando" de
+// "proceso vivo pero roto" (vivo sin latido → reinicio del servicio).
+//
+// Diseño: stateless, sin dependencias, tolerante a cualquier fallo — un
+// error de heartbeat NUNCA puede afectar al ciclo de push.
+package heartbeat
+
+import (
+	"bytes"
+	"os"
+	"path/filepath"
+	"strconv"
+	"time"
+)
+
+// DefaultFile: latido por defecto en tmpfs (se pierde al reiniciar el
+// router, que es lo correcto: tras un reboot el watchdog ve "sin fichero" y
+// no hace nada porque el agente aún no ha tenido tiempo de empujar).
+const DefaultFile = "/tmp/netpulse-agent.heartbeat"
+
+// Touch escribe el unix actual en el fichero de heartbeat. Nunca devuelve
+// error: el caller (main del agente) lo ignora deliberadamente.
+func Touch(path string, now time.Time) error {
+	if path == "" {
+		path = DefaultFile
+	}
+	_ = os.MkdirAll(filepath.Dir(path), 0o755)
+	return os.WriteFile(path, []byte(strconv.FormatInt(now.Unix(), 10)+"\n"), 0o644)
+}
+
+// Age: segundos desde el último latido; (0, false) si el fichero no existe
+// o es ilegible (agente recién instalado / reboot reciente → el watchdog no
+// debe actuar por ausencia de fichero, solo por latido viejo CON fichero).
+func Age(path string, now time.Time) (time.Duration, bool) {
+	data, err := os.ReadFile(path)
+	if err != nil {
+		return 0, false
+	}
+	ts, err := strconv.ParseInt(string(bytes.TrimSpace(data)), 10, 64)
+	if err != nil || ts <= 0 {
+		return 0, false
+	}
+	age := now.Sub(time.Unix(ts, 0))
+	if age < 0 {
+		age = 0
+	}
+	return age, true
+}

+ 46 - 0
agent/internal/heartbeat/heartbeat_test.go

@@ -0,0 +1,46 @@
+package heartbeat
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+)
+
+func TestTouchAndAge(t *testing.T) {
+	dir := t.TempDir()
+	path := filepath.Join(dir, "hb")
+	now := time.Unix(1_000_000, 0)
+
+	if err := Touch(path, now); err != nil {
+		t.Fatalf("Touch: %v", err)
+	}
+	age, ok := Age(path, now.Add(17*time.Second))
+	if !ok || age != 17*time.Second {
+		t.Fatalf("Age = %v, %v; quiero 17s, true", age, ok)
+	}
+}
+
+func TestAgeSinFichero(t *testing.T) {
+	age, ok := Age(filepath.Join(t.TempDir(), "noexiste"), time.Now())
+	if ok || age != 0 {
+		t.Fatalf("Age(sin fichero) = %v, %v; quiero 0, false", age, ok)
+	}
+}
+
+func TestAgeFicheroCorrupto(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "hb")
+	if err := os.WriteFile(path, []byte("no-es-un-ts\n"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	if _, ok := Age(path, time.Now()); ok {
+		t.Fatal("Age con contenido no numérico debe devolver ok=false")
+	}
+}
+
+func TestTouchCreaDirectorio(t *testing.T) {
+	path := filepath.Join(t.TempDir(), "sub", "dir", "hb")
+	if err := Touch(path, time.Unix(42, 0)); err != nil {
+		t.Fatalf("Touch con dirs inexistentes: %v", err)
+	}
+}

+ 6 - 1
app/public/locales/en/translation.json

@@ -410,7 +410,12 @@
       "freshTip": "netpulse-agent v{{version}} · pushes every 15 s",
       "freshTipUnknown": "netpulse-agent · pushes every 15 s",
       "stale": "Agent down",
-      "staleTip": "No data from agent — polling via SSH"
+      "staleTip": "No data from agent — polling via SSH",
+      "rearm": "Rearm",
+      "rearming": "Restarting…",
+      "rearmOk": "Agent rearmed",
+      "rearmPending": "Restarted; waiting for the first push",
+      "rearmFail": "Could not rearm"
     },
     "colClients": "Clients",
     "colCpu": "CPU",

+ 6 - 1
app/public/locales/es/translation.json

@@ -410,7 +410,12 @@
       "freshTip": "netpulse-agent v{{version}} · empuja cada 15 s",
       "freshTipUnknown": "netpulse-agent · empuja cada 15 s",
       "stale": "Agente caído",
-      "staleTip": "Sin datos del agente — sondeando por SSH"
+      "staleTip": "Sin datos del agente — sondeando por SSH",
+      "rearm": "Rearmar",
+      "rearming": "Reiniciando…",
+      "rearmOk": "Agente rearmado",
+      "rearmPending": "Reiniciado; esperando el primer push",
+      "rearmFail": "No se pudo rearmar"
     },
     "colClients": "Clientes",
     "colCpu": "CPU",

+ 65 - 0
app/src/components/routers/AgentRearmButton.tsx

@@ -0,0 +1,65 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Loader2 } from 'lucide-react'
+import { useNetPulse } from '@/data/DataProvider'
+import type { AgentInfo } from '@/data/types'
+import { cn } from '@/lib/utils'
+
+interface AgentRearmButtonProps {
+  agent: AgentInfo | undefined
+  className?: string
+}
+
+type RearmState = 'idle' | 'busy' | 'ok' | 'pending' | 'fail'
+
+/**
+ * Botón «Rearmar» (Fase 6.1, Plan B): solo aparece con un agente registrado
+ * y NO fresh (caído). Reinicia el servicio procd en el router vía
+ * POST /api/agents/{slug}/rearm y refleja el resultado real:
+ *   ok      → el agente volvió a empujar (recuperado)
+ *   pending → reiniciado pero sin push en 30 s
+ *   fail    → petición fallida (SSH, cooldown, sin servidor…)
+ * El estado ok/pending/fail dura 6 s y vuelve a idle.
+ */
+export function AgentRearmButton({ agent, className }: AgentRearmButtonProps) {
+  const { t } = useTranslation()
+  const { rearmAgent } = useNetPulse()
+  const [state, setState] = useState<RearmState>('idle')
+
+  if (!agent || agent.fresh) return null
+
+  const label =
+    state === 'busy' ? t('routers.agent.rearming')
+    : state === 'ok' ? t('routers.agent.rearmOk')
+    : state === 'pending' ? t('routers.agent.rearmPending')
+    : state === 'fail' ? t('routers.agent.rearmFail')
+    : t('routers.agent.rearm')
+
+  const onClick = async () => {
+    if (state === 'busy') return
+    setState('busy')
+    const res = await rearmAgent(agent.slug)
+    const next: RearmState = res === null ? 'fail' : res.recovered ? 'ok' : 'pending'
+    setState(next)
+    window.setTimeout(() => setState('idle'), 6000)
+  }
+
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      disabled={state === 'busy'}
+      title={t('routers.agent.staleTip')}
+      className={cn(
+        'inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-semibold transition-opacity hover:opacity-90 disabled:opacity-50',
+        state === 'ok' ? 'bg-ok text-canvas'
+        : state === 'fail' ? 'bg-danger text-canvas'
+        : 'bg-warn text-canvas',
+        className,
+      )}
+    >
+      {state === 'busy' && <Loader2 className="h-3 w-3 animate-spin" />}
+      {label}
+    </button>
+  )
+}

+ 10 - 0
app/src/components/routers/RouterDetailHeader.tsx

@@ -7,6 +7,7 @@ import type { Router } from '@/data/mock'
 import { HealthRing } from '@/components/HealthRing'
 import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
+import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 
@@ -85,6 +86,15 @@ export function RouterDetailHeader({ router }: { router: Router }) {
                   <AgentBadge agent={agent} />
                 </motion.span>
               )}
+              {agent && !agent.fresh && (
+                <motion.span
+                  initial={reduce ? false : { opacity: 0, scale: 0.9 }}
+                  animate={{ opacity: 1, scale: 1 }}
+                  transition={{ duration: 0.2, delay: 0.15 + (pills.length + 1) * 0.06 }}
+                >
+                  <AgentRearmButton agent={agent} />
+                </motion.span>
+              )}
             </div>
           </div>
         </div>

+ 34 - 1
app/src/data/DataProvider.tsx

@@ -133,6 +133,13 @@ export interface NetPulseApi extends NetPulseData {
   markAlertsRead: (ids: string[]) => void
   /** POST /api/alerts/read-all (live). Demo: estado local. Optimista. */
   markAllAlertsRead: () => void
+  /**
+   * Fase 6.1 (Plan B): POST /api/agents/{slug}/rearm — reinicia el servicio
+   * procd del agente en el router (vía SSH del servidor) y espera a que
+   * vuelva a empujar. Devuelve `{ recovered }` o null si la petición falló
+   * (demo siempre null: no hay agentes que rearmar).
+   */
+  rearmAgent: (slug: string) => Promise<{ recovered: boolean; message?: string } | null>
 }
 
 // ---------------------------------------------------------------------------
@@ -660,6 +667,31 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
+  /**
+   * Fase 6.1 (Plan B): rearme del servicio del agente en el router. El
+   * backend ejecuta `init.d restart` por SSH y espera hasta 30 s el push de
+   * vuelta → por eso aquí NO hay timeout corto: se deja respirar. null =
+   * petición fallida (red, 4xx/5xx, demo).
+   */
+  const rearmAgent = useCallback(
+    async (slug: string): Promise<{ recovered: boolean; message?: string } | null> => {
+      if (modeRef.current !== 'live') return null
+      try {
+        const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/rearm`, {
+          method: 'POST',
+          signal: AbortSignal.timeout(60_000),
+        })
+        if (res.status === 401) redirectLogin()
+        if (!res.ok) return null
+        const json = (await res.json()) as { recovered?: boolean; message?: string }
+        return { recovered: json.recovered ?? false, message: json.message }
+      } catch {
+        return null
+      }
+    },
+    [],
+  )
+
   const getRouterDetail = useCallback(async (id: string): Promise<RouterDetailData | null> => {
     if (modeRef.current === 'live') {
       const res = await fetch(`/api/routers/${encodeURIComponent(id)}`)
@@ -761,8 +793,9 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       setAlertConfig,
       markAlertsRead,
       markAllAlertsRead,
+      rearmAgent,
     }),
-    [bundle, connectionStatus, agents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead],
+    [bundle, connectionStatus, agents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, rearmAgent],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 55 - 0
install-agent.sh

@@ -77,6 +77,11 @@ if [ "$UNINSTALL" -eq 1 ]; then
         $INIT_DST stop 2>/dev/null || true
         $INIT_DST disable 2>/dev/null || true
         rm -f $INIT_DST $ENV_FILE /usr/sbin/$BIN_NAME /tmp/$BIN_NAME
+        rm -f /usr/sbin/netpulse-watchdog /tmp/netpulse-agent.heartbeat
+        # quitar la línea del watchdog del crontab (si existe)
+        if [ -f /etc/crontabs/root ]; then
+            sed -i '/netpulse-watchdog/d' /etc/crontabs/root
+        fi
     "
     ok "$BIN_NAME desinstalado de $HOST"
     exit 0
@@ -189,6 +194,56 @@ fi
 ssh "$SSH" "chmod 0755 $INIT_DST && $INIT_DST enable && $INIT_DST restart"
 ok "servicio $INIT_NAME habilitado y arrancado"
 
+# ------------------------------------------------------------ watchdog cron --
+# Fase 6.1 (Plan A): cron cada 2 min relanza el agente si procd se rindió o
+# si está "vivo pero roto" (heartbeat viejo). Idempotente: reemplaza la
+# línea previa del crontab.
+info "instalando watchdog (cron, cada 2 min)"
+WATCHDOG_DST="/usr/sbin/netpulse-watchdog"
+if [ -f "$SCRIPT_DIR/agent/deploy/netpulse-watchdog.sh" ]; then
+    scp -Oq "$SCRIPT_DIR/agent/deploy/netpulse-watchdog.sh" "$SSH:$WATCHDOG_DST"
+else
+    ssh "$SSH" "cat > $WATCHDOG_DST" <<'WATCHDOGEOF'
+#!/bin/sh
+INIT=/etc/init.d/netpulse-agent
+HB=/tmp/netpulse-agent.heartbeat
+MAX_AGE=300
+[ -f /etc/netpulse-agent.env ] && . /etc/netpulse-agent.env 2>/dev/null
+[ -n "${NETPULSE_HEARTBEAT_FILE:-}" ] && HB="$NETPULSE_HEARTBEAT_FILE"
+log() { logger -t netpulse-watchdog "$*"; }
+if [ ! -x /usr/sbin/netpulse-agent ] && [ ! -x /tmp/netpulse-agent ]; then
+    exit 0
+fi
+if ! pgrep -x netpulse-agent >/dev/null 2>&1; then
+    log "agente no está en marcha — reiniciando servicio"
+    $INIT restart >/dev/null 2>&1
+    exit 0
+fi
+if [ -f "$HB" ]; then
+    now=$(date +%s)
+    hb=$(cat "$HB" 2>/dev/null)
+    case "$hb" in
+        '' | *[!0-9]*) exit 0 ;;
+    esac
+    age=$((now - hb))
+    if [ "$age" -gt "$MAX_AGE" ]; then
+        log "proceso vivo pero sin latido en ${age}s — reiniciando servicio"
+        $INIT restart >/dev/null 2>&1
+    fi
+fi
+exit 0
+WATCHDOGEOF
+fi
+ssh "$SSH" "
+    chmod 0755 $WATCHDOG_DST
+    mkdir -p /etc/crontabs
+    sed -i '/netpulse-watchdog/d' /etc/crontabs/root 2>/dev/null
+    echo '*/2 * * * * $WATCHDOG_DST' >> /etc/crontabs/root
+    /etc/init.d/cron enable
+    /etc/init.d/cron restart
+"
+ok "watchdog en cron (*/2 * * * *)"
+
 sleep 2
 if ssh "$SSH" "logread -e $INIT_NAME" 2>/dev/null | tail -2 | grep -q .; then
     info "últimas líneas de syslog:"

+ 3 - 0
server-go/cmd/netpulse/main.go

@@ -91,6 +91,7 @@ func run() error {
 	}
 	agentReg := adapters.NewAgentRegistry(agentTTL)
 	var adapter adapters.Snapshotter
+	var sshPool *adapters.SSHPool
 	if cfg.DemoMode {
 		adapter = adapters.NewDemo(alerts.New(dbHandle, nil))
 	} else {
@@ -99,6 +100,7 @@ func run() error {
 			log.Printf("[netpulse] aviso: pool SSH no disponible (%v); sirviendo dataset demo", err)
 			adapter = adapters.NewDemo(alerts.New(dbHandle, nil))
 		} else {
+			sshPool = pool
 			live := adapters.NewLive(cfg, dbHandle, routers, pool)
 			live.SetAgents(agentReg)
 			adapter = live
@@ -145,6 +147,7 @@ func run() error {
 		Static:  static,
 		Updater: upd,
 		Agents:  agentReg,
+		Pool:    sshPool,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},

+ 125 - 0
server-go/internal/httpapi/agent.go

@@ -27,6 +27,7 @@ import (
 	"time"
 
 	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 )
@@ -44,6 +45,12 @@ const (
 // agentSlugRe: slugs de equipo válidos (mismo alfabeto que routerstore).
 var agentSlugRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
 
+// SSHRunner ejecuta comandos en los routers (adapters.SSHPool en
+// producción; fake en tests). Fase 6.1: rearme de agentes.
+type SSHRunner interface {
+	Run(host, cmd string, timeout time.Duration) (string, error)
+}
+
 // ---------------------------------------------------------------------------
 // Rate limit por IP (ventana fija de 1 min; purga oportunista)
 // ---------------------------------------------------------------------------
@@ -298,3 +305,121 @@ func (s *server) handleAgentsDelete(w http.ResponseWriter, r *http.Request) {
 	}
 	w.WriteHeader(http.StatusNoContent)
 }
+
+// ---------------------------------------------------------------------------
+// POST /api/agents/{slug}/rearm — Fase 6.1 (Plan B): reiniciar el servicio
+// procd del agente en el router vía SSH (el mismo canal del sondeo). El
+// servidor espera hasta ~30 s a que llegue un push nuevo y responde con el
+// resultado real, no con suposiciones.
+// ---------------------------------------------------------------------------
+
+const (
+	rearmCmd      = "/etc/init.d/netpulse-agent restart"
+	rearmSSHWait  = 10 * time.Second // timeout del comando SSH
+	rearmPollWait = 30 * time.Second // cuánto esperar el push de vuelta
+	rearmCooldown = 60 * time.Second // anti-martilleo por slug
+)
+
+type rearmResponse struct {
+	Slug      string `json:"slug"`
+	Restarted bool   `json:"restarted"` // el comando SSH se ejecutó
+	Recovered bool   `json:"recovered"` // llegó un push nuevo tras el reinicio
+	Message   string `json:"message,omitempty"`
+}
+
+func (s *server) handleAgentRearm(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if !agentSlugRe.MatchString(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if s.db == nil {
+		writeError(w, http.StatusInternalServerError, "db_error")
+		return
+	}
+	// El slug debe tener token registrado (si no, 404 como DELETE)
+	var exists int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&exists); err != nil || exists == 0 {
+		writeError(w, http.StatusNotFound, "not_found", "ese slug no tiene agente registrado")
+		return
+	}
+	// Resolver host del router (tabla routers)
+	host := ""
+	for _, rc := range routerstore.ListRouters(s.db.DB) {
+		if rc.ID == slug {
+			host = rc.Host
+			break
+		}
+	}
+	if host == "" {
+		writeError(w, http.StatusConflict, "router_unknown", "no hay router con ese slug en la tabla routers")
+		return
+	}
+	if s.pool == nil {
+		writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH (modo demo o clave ausente)")
+		return
+	}
+
+	// Anti-martilleo por slug (60 s)
+	s.rearmMu.Lock()
+	if last, ok := s.lastRearm[slug]; ok && time.Since(last) < rearmCooldown {
+		s.rearmMu.Unlock()
+		writeError(w, http.StatusTooManyRequests, "cooldown",
+			fmt.Sprintf("rearme reciente; espera %d s", int(rearmCooldown.Seconds())))
+		return
+	}
+	if s.lastRearm == nil {
+		s.lastRearm = map[string]time.Time{}
+	}
+	s.lastRearm[slug] = time.Now()
+	s.rearmMu.Unlock()
+
+	before := time.Now()
+	// Marcar el lastSeen previo para saber si el push que llega es NUEVO
+	var prevSeen time.Time
+	if s.agents != nil {
+		if seen, _, ok := s.agents.Info(slug); ok {
+			prevSeen = seen
+		}
+	}
+
+	if _, err := s.pool.Run(host, rearmCmd, rearmSSHWait); err != nil {
+		writeError(w, http.StatusBadGateway, "ssh_failed", fmt.Sprintf("no pude reiniciar el servicio en %s: %v", host, err))
+		return
+	}
+
+	// Esperar a que el agente vuelva a empujar (poll cada 2 s hasta rearmPollWait)
+	recovered := false
+	deadline := time.Now().Add(s.rearmPollWait)
+	pollInterval := 2 * time.Second
+	if s.rearmPollWait < pollInterval {
+		pollInterval = 50 * time.Millisecond
+	}
+	for time.Now().Before(deadline) {
+		time.Sleep(pollInterval)
+		if s.agents == nil {
+			break
+		}
+		if seen, _, ok := s.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
+			recovered = true
+			break
+		}
+	}
+
+	resp := rearmResponse{Slug: slug, Restarted: true, Recovered: recovered}
+	if recovered {
+		resp.Message = "servicio reiniciado y el agente volvió a empujar"
+		if s.adapter != nil {
+			s.adapter.AlertsEngine().Emit(alerts.AlertEvent{
+				ID:       fmt.Sprintf("alert-agent-rearm-%s-%d", slug, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false, Severity: "info",
+				Title:       fmt.Sprintf("Agente rearmado en %s", slug),
+				Description: "Reinicio del servicio netpulse-agent desde el servidor — el agente vuelve a empujar",
+				Time:        "ahora mismo", RouterID: slug,
+			})
+		}
+	} else {
+		resp.Message = "servicio reiniciado, pero el agente aún no ha empujado en 30 s"
+	}
+	writeJSON(w, http.StatusOK, resp)
+}

+ 292 - 0
server-go/internal/httpapi/rearm_api_test.go

@@ -0,0 +1,292 @@
+// rearm_api_test.go — Fase 6.1 (Plan B): POST /api/agents/{slug}/rearm.
+// Casos: 404 sin slug registrado, 409 slug sin router en la tabla routers,
+// 503 sin pool SSH (modo demo), 502 si el SSH falla, 200 recuperado (un push
+// de vuelta llega tras el reinicio), 200 sin push de vuelta y 429 por cooldown.
+package httpapi_test
+
+import (
+	"encoding/json"
+	"errors"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// rearmBody refleja la respuesta JSON de POST /api/agents/{slug}/rearm.
+type rearmBody struct {
+	Slug      string `json:"slug"`
+	Restarted bool   `json:"restarted"`
+	Recovered bool   `json:"recovered"`
+	Message   string `json:"message"`
+}
+
+// fakeSSH registra los comandos ejecutados y falla si fail=true.
+type fakeSSH struct {
+	mu   sync.Mutex
+	cmds []string
+	fail bool
+}
+
+func (f *fakeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	if f.fail {
+		return "", errors.New("ssh down")
+	}
+	f.cmds = append(f.cmds, host+":"+cmd)
+	return "", nil
+}
+
+func (f *fakeSSH) count() int {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	return len(f.cmds)
+}
+
+type rearmTestServer struct {
+	*httptest.Server
+	db     *db.DB
+	agents *adapters.AgentRegistry
+	ssh    *fakeSSH
+	cookie string
+}
+
+// makeRearmTestServer: app real con registry + router "patio" en la tabla
+// routers. pool=nil simula demo sin SSH; pollWait corto para no dormir tests.
+func makeRearmTestServer(t *testing.T, pool *fakeSSH, pollWait time.Duration) *rearmTestServer {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	// Router "patio" en la tabla routers (slug = name slugificado)
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
+		Name: "patio", Host: "192.168.1.4", Type: "openwrt",
+	}); err != nil {
+		t.Fatalf("AddRouter: %v", err)
+	}
+	reg := adapters.NewAgentRegistry(90 * time.Second)
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	var runner httpapi.SSHRunner
+	if pool != nil {
+		runner = pool
+	}
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
+		Agents: reg, Pool: runner, RearmPollWait: pollWait, Started: time.Now(),
+	})
+	srv := httptest.NewServer(handler)
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	if status != 204 {
+		t.Fatalf("login: %d", status)
+	}
+	ts := &rearmTestServer{Server: srv, db: d, agents: reg, ssh: pool, cookie: cookie}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+// rearm dispara el POST y devuelve status + body.
+func rearm(t *testing.T, ts *rearmTestServer, slug string) (int, rearmBody) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents/"+slug+"/rearm", strings.NewReader(""))
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("rearm: %v", err)
+	}
+	defer res.Body.Close()
+	var body rearmBody
+	data, _ := io.ReadAll(res.Body)
+	_ = json.Unmarshal(data, &body)
+	return res.StatusCode, body
+}
+
+// rearmRaw devuelve status + body crudo (mensajes de error).
+func rearmRaw(t *testing.T, ts *rearmTestServer, slug string) (int, string) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents/"+slug+"/rearm", strings.NewReader(""))
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("rearm: %v", err)
+	}
+	defer res.Body.Close()
+	data, _ := io.ReadAll(res.Body)
+	return res.StatusCode, string(data)
+}
+
+// createRearmToken crea el token de un slug vía API (con sesión).
+func createRearmToken(t *testing.T, ts *rearmTestServer, slug string) (int, string) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents", strings.NewReader(`{"slug":"`+slug+`"}`))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST /api/agents: %v", err)
+	}
+	defer res.Body.Close()
+	var body struct {
+		Token string `json:"token"`
+	}
+	data, _ := io.ReadAll(res.Body)
+	_ = json.Unmarshal(data, &body)
+	return res.StatusCode, body.Token
+}
+
+// rearmIngest hace un push de agente contra ts (mismo contrato que ingest de
+// agent_api_test.go, pero con URL directa).
+func rearmIngest(t *testing.T, ts *rearmTestServer, token, payload string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("X-Forwarded-For", "10.9.9.1")
+	if token != "" {
+		req.Header.Set("Authorization", "Bearer "+token)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("ingest: %v", err)
+	}
+	return res
+}
+
+func TestRearmSinSlugRegistrado404(t *testing.T) {
+	ts := makeRearmTestServer(t, &fakeSSH{}, time.Second)
+	status, _ := rearm(t, ts, "noexiste")
+	if status != 404 {
+		t.Fatalf("slug sin token: quiero 404, tuve %d", status)
+	}
+}
+
+func TestRearmSinRouter409(t *testing.T) {
+	ts := makeRearmTestServer(t, &fakeSSH{}, time.Second)
+	// Token sin router asociado en la tabla routers
+	if st, tok := createRearmToken(t, ts, "solitario"); st != 201 || tok == "" {
+		t.Fatalf("create: %d", st)
+	}
+	status, body := rearmRaw(t, ts, "solitario")
+	if status != 409 {
+		t.Fatalf("quiero 409 router_unknown, tuve %d (%s)", status, body)
+	}
+	if ts.ssh.count() != 0 {
+		t.Fatalf("no debe ejecutarse SSH con router desconocido")
+	}
+}
+
+func TestRearmRecuperado200(t *testing.T) {
+	ssh := &fakeSSH{}
+	ts := makeRearmTestServer(t, ssh, 1500*time.Millisecond)
+	st, tok := createRearmToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	// Estado previo (prevSeen): un push anterior para que el rearme espere
+	// uno NUEVO.
+	ts.agents.Ingest(&probe.Payload{Router: "patio", Ts: time.Now().Unix(), Version: "0.1.0"})
+
+	// En paralelo: 200 ms después el agente "vuelve a empujar"
+	go func() {
+		time.Sleep(200 * time.Millisecond)
+		res := rearmIngest(t, ts, tok, validPayload)
+		res.Body.Close()
+	}()
+
+	status, body := rearm(t, ts, "patio")
+	if status != 200 {
+		t.Fatalf("quiero 200, tuve %d", status)
+	}
+	if !body.Restarted || !body.Recovered {
+		t.Fatalf("quiero restarted+recovered, tuve %+v", body)
+	}
+	if ssh.count() != 1 {
+		t.Fatalf("quiero 1 comando SSH, tuve %d", ssh.count())
+	}
+}
+
+func TestRearmSinPushVuelta(t *testing.T) {
+	ts := makeRearmTestServer(t, &fakeSSH{}, 300*time.Millisecond)
+	st, _ := createRearmToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	status, body := rearm(t, ts, "patio")
+	if status != 200 {
+		t.Fatalf("quiero 200, tuve %d", status)
+	}
+	if !body.Restarted || body.Recovered {
+		t.Fatalf("quiero restarted sin recovered, tuve %+v", body)
+	}
+}
+
+func TestRearmSSHCae502(t *testing.T) {
+	ssh := &fakeSSH{fail: true}
+	ts := makeRearmTestServer(t, ssh, time.Second)
+	st, _ := createRearmToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	status, body := rearmRaw(t, ts, "patio")
+	if status != 502 {
+		t.Fatalf("quiero 502 ssh_failed, tuve %d (%s)", status, body)
+	}
+}
+
+func TestRearmCooldown429(t *testing.T) {
+	ts := makeRearmTestServer(t, &fakeSSH{}, 100*time.Millisecond)
+	st, _ := createRearmToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	if status, _ := rearm(t, ts, "patio"); status != 200 {
+		t.Fatalf("primer rearme: quiero 200, tuve %d", status)
+	}
+	status, body := rearmRaw(t, ts, "patio")
+	if status != 429 {
+		t.Fatalf("segundo rearme inmediato: quiero 429, tuve %d (%s)", status, body)
+	}
+}
+
+func TestRearmSinPool503(t *testing.T) {
+	// pool nil → demo sin SSH: el endpoint debe decirlo claramente.
+	ts := makeRearmTestServer(t, nil, time.Second)
+	st, _ := createRearmToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	status, body := rearmRaw(t, ts, "patio")
+	if status != 503 {
+		t.Fatalf("quiero 503 ssh_unavailable, tuve %d (%s)", status, body)
+	}
+}

+ 21 - 1
server-go/internal/httpapi/server.go

@@ -42,6 +42,13 @@ type Deps struct {
 	// Agents: registry de agentes nativos (ingesta POST /api/ingest/agent y
 	// last_seen/versión de GET /api/agents). nil → ingesta 503.
 	Agents *adapters.AgentRegistry
+	// Pool: ejecutor de comandos SSH del sondeo. nil (demo / sin clave) → el
+	// rearme de agentes responde 503 (POST /api/agents/{slug}/rearm, Fase 6.1).
+	// Es una interfaz para poder inyectar un fake en los tests.
+	Pool SSHRunner
+	// RearmPollWait: cuánto esperar el push de vuelta tras rearmar (default
+	// 30 s; los tests lo bajan). <= 0 → rearmPollWait.
+	RearmPollWait time.Duration
 	// LastOverview devuelve el último overview del poller (nil si aún no hay).
 	LastOverview func() *adapters.Overview
 	// PollNow dispara un ciclo de sondeo inmediato (POST /api/refresh);
@@ -57,6 +64,8 @@ type server struct {
 	hub     *sse.Hub
 	secret  string
 	agents  *adapters.AgentRegistry
+	pool    SSHRunner
+	rearmPollWait time.Duration
 	lastOv  func() *adapters.Overview
 	pollNow func()
 	started time.Time
@@ -67,15 +76,24 @@ type server struct {
 
 	// Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
 	ingestLimit *ipRateLimit
+
+	// Anti-martilleo del rearme de agentes (60 s por slug, Fase 6.1).
+	rearmMu   sync.Mutex
+	lastRearm map[string]time.Time
 }
 
 // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
 func NewHandler(d Deps) http.Handler {
 	s := &server{
 		cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
-		secret: d.Secret, agents: d.Agents, lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
+		secret: d.Secret, agents: d.Agents, pool: d.Pool,
+		rearmPollWait: d.RearmPollWait,
+		lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
 		ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
 	}
+	if s.rearmPollWait <= 0 {
+		s.rearmPollWait = rearmPollWait
+	}
 	mode := d.Adapter.Mode()
 
 	mux := http.NewServeMux()
@@ -114,6 +132,8 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("POST /api/agents", s.handleAgentsCreate)
 	mux.HandleFunc("GET /api/agents", s.handleAgentsList)
 	mux.HandleFunc("DELETE /api/agents/{slug}", s.handleAgentsDelete)
+	// Fase 6.1 (Plan B): rearme del servicio procd del agente vía SSH.
+	mux.HandleFunc("POST /api/agents/{slug}/rearm", s.handleAgentRearm)
 
 	// --- Web Push (Fase 6 Bloque C; tras sesión como el resto del API) ---
 	mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)