Переглянути джерело

feat(agents): offer rearm and reinstall for inactive agents (#1711)

Nacho 1 місяць тому
батько
коміт
b9a429423e

+ 8 - 0
CHANGELOG.md

@@ -7,6 +7,14 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- Inactive agents in the fleet table now offer Rearm, Reinstall and the copyable install command next to Remove, so a rejected token (HTTP 401 after a reboot or a server move) can be fixed without removing the agent or losing its history. NetGrip rows offer Rearm only and external pushers keep Remove only.
+
+### Changed
+
+- The manual documents the agent recovery flow (Rearm restarts the agent service, Reinstall rotates a rejected token) and the agent tooltips and banners point to the agents section on Devices, which hosts the reinstall action, instead of the router detail page.
+
 ### Fixed
 
 - The greeting line on the Overview ("N important alerts") now counts the same alerts as the bell and the Alerts page (unread, level-filtered), instead of the health score breakdown. A health penalty without a visible alert, such as a down VPN peer with the vpn category set to "Nada", used to leave a phantom counter that could not be cleared from anywhere (#1707).

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

@@ -1150,8 +1150,9 @@
       "freshTip": "netpulse-agent v{{version}} · pushes every 15 s",
       "freshTipUnknown": "netpulse-agent · pushes every 15 s",
       "stale": "Agent down",
-      "staleTip": "Agent registered but not responding — reinstall it from the router detail",
+      "staleTip": "Agent registered but not responding. Rearm restarts its service over SSH and, if the server rejects its pushes (401, invalidated token), Reinstall rotates the token without deleting history.",
       "rearm": "Rearm",
+      "rearmTip": "Restarts the agent service on the router over SSH and waits for its first push (up to 30s). Use it when the process stopped reporting. It does not fix a rejected token: Reinstall, which issues a new one, is the action for that.",
       "rearming": "Restarting…",
       "netgripRestart": "Restart NetGrip",
       "netgripRestarting": "Restarting NetGrip…",
@@ -1174,10 +1175,10 @@
       "upgradeNotConnected": "Agent not connected",
       "upgradeFail": "Could not update",
       "upgradeTip": "Update from v{{version}} to the server version",
-      "downBanner": "Agent is down — reinstall it from the router detail",
+      "downBanner": "Agent is down - rearm or reinstall it from the agents section on Devices",
       "notInstalled": "Agent not installed",
-      "notInstalledTip": "This router is configured to run agent-only, but the agent is not installed. Reinstall it from the router detail.",
-      "notInstalledBanner": "Agent not installed — reinstall it from the router detail",
+      "notInstalledTip": "This router is configured to run agent-only, but the agent is not installed. Install it from the agents section on Devices.",
+      "notInstalledBanner": "Agent not installed - install it from the agents section on Devices",
       "stepRequested": "Command sent",
       "stepDownloading": "Downloading {{pct}}%",
       "stepSwapping": "Installing binary",
@@ -1252,7 +1253,7 @@
       "reinstalling": "Reinstalling…",
       "reinstalled": "Reinstalled",
       "reinstallRetry": "Retry",
-      "reinstallTip": "Reinstall the agent on this router (binary, config and service) via SSH. Use this if the agent was removed by a firmware update or manual uninstall.",
+      "reinstallTip": "Reinstalls the agent on this router (binary, config and service) over SSH and rotates its token. Use it if the agent was removed by a firmware update or a manual uninstall, or if the server rejects its pushes with 401 (token invalidated by a reboot or a server move). The router's history is preserved.",
       "reinstallConfirm": "Reinstall the agent on {{router}}? The current agent (if any) will be replaced and its token rotated.",
       "reinstallDone": "Agent reinstalled and reporting again.",
       "reinstallPending": "Agent installed; waiting for it to report (up to 40s).",

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

@@ -1150,8 +1150,9 @@
       "freshTip": "netpulse-agent v{{version}} · empuja cada 15 s",
       "freshTipUnknown": "netpulse-agent · empuja cada 15 s",
       "stale": "Agente caído",
-      "staleTip": "Agente registrado pero sin respuesta — reinstálalo desde el detalle",
+      "staleTip": "Agente registrado pero sin respuesta. Rearmar reinicia su servicio por SSH y, si el servidor le rechaza los pushes (401, token invalidado), Reinstalar rota el token sin borrar el historial.",
       "rearm": "Rearmar",
+      "rearmTip": "Reinicia el servicio del agente en el router vía SSH y espera su primer push (hasta 30 s). Útil si el proceso dejó de reportar. No arregla un token rechazado: para eso está Reinstalar, que genera uno nuevo.",
       "rearming": "Reiniciando…",
       "netgripRestart": "Reiniciar NetGrip",
       "netgripRestarting": "Reiniciando NetGrip…",
@@ -1174,10 +1175,10 @@
       "upgradeNotConnected": "Agente no conectado",
       "upgradeFail": "No se pudo actualizar",
       "upgradeTip": "Actualizar de v{{version}} a la versión del servidor",
-      "downBanner": "Agente caído — reinstálalo desde el detalle",
+      "downBanner": "Agente caído - rearmarlo o reinstalarlo desde la sección de agentes de Dispositivos",
       "notInstalled": "Agente no instalado",
-      "notInstalledTip": "El router está configurado para funcionar solo con agente, pero el agente no está instalado. Reinstálalo desde el detalle.",
-      "notInstalledBanner": "Agente no instalado — reinstálalo desde el detalle",
+      "notInstalledTip": "El router está configurado para funcionar solo con agente, pero el agente no está instalado. Instálalo desde la sección de agentes de Dispositivos.",
+      "notInstalledBanner": "Agente no instalado - instálalo desde la sección de agentes de Dispositivos",
       "stepRequested": "Comando enviado",
       "stepDownloading": "Descargando {{pct}} %",
       "stepSwapping": "Instalando binario",
@@ -1252,7 +1253,7 @@
       "reinstalling": "Reinstalando…",
       "reinstalled": "Reinstalado",
       "reinstallRetry": "Reintentar",
-      "reinstallTip": "Reinstala el agente en este router (binario, config y servicio) vía SSH. Úsalo si el agente fue borrado por una actualización de firmware o una desinstalación manual.",
+      "reinstallTip": "Reinstala el agente en este router (binario, config y servicio) vía SSH y rota su token. Úsalo si el agente fue borrado por una actualización de firmware o una desinstalación manual, o si el servidor rechaza sus pushes con 401 (token invalidado por un reinicio o una mudanza del servidor). El historial del router se conserva.",
       "reinstallConfirm": "¿Reinstalar el agente en {{router}}? El agente actual (si lo hay) será sustituido y su token rotado.",
       "reinstallDone": "Agente reinstalado y empujando de nuevo.",
       "reinstallPending": "Agente instalado; esperando a que empuje (hasta 40 s).",

+ 3 - 1
app/src/components/routers/AgentRearmButton.tsx

@@ -92,7 +92,9 @@ export function AgentRearmButton({ agent, className }: AgentRearmButtonProps) {
       type="button"
       onClick={onClick}
       disabled={state === 'busy'}
-      title={netgrip ? t('routers.agent.netgripRestartTip') : t('routers.agent.staleTip')}
+      // #1702: tooltip propio de la acción (qué reinicia y cuándo no basta):
+      // antes reutilizaba el del estado caído, que no explica el botón.
+      title={netgrip ? t('routers.agent.netgripRestartTip') : t('routers.agent.rearmTip')}
       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'

+ 83 - 13
app/src/components/routers/AgentsSection.tsx

@@ -32,9 +32,15 @@ import { cn, copyToClipboard } from '@/lib/utils'
  *   - Rearmar (canal rearm existente): preferente cuando el proceso vive pero
  *     no reporta (heartbeat stale) - NO reinstala en seco.
  *   - Reinstalar (POST /api/agents/{slug}/reinstall, #246): despliega el
- *     agente vía SSH desde el server, con estados de progreso.
+ *     agente vía SSH desde el server y ROTA el token, con estados de progreso.
  *   - Copiar comando de instalación: one-liner manual como fallback para
- *     routers sin SSH.
+ *     routers sin SSH (también rota el token).
+ * #1702: las acciones de recuperación (rearmar/reinstalar/copiar comando)
+ * se ofrecen TAMBIÉN con el agente inactivo (sin pulso): un 401 eterno tras
+ * un reinicio o una mudanza del servidor se arregla rotando el token sin
+ * retirar el agente ni borrar su historial. Solo Retirar sigue siendo
+ * exclusivo del estado sin pulso (y Actualizar/Desinstalar, que necesitan
+ * el agente vivo para tener sentido).
  */
 
 function isOpenWrtType(t: string | undefined): boolean {
@@ -204,7 +210,9 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
       className={cn(
         'border-b border-border/60 last:border-0',
         // #1382: agente sin pulso (equipo apagado o quitado de la red):
-        // toda la fila en acento rojo; la única acción ofrecida es Retirar.
+        // toda la fila en acento rojo. Desde #1702 la fila también ofrece
+        // las acciones de recuperación (rearmar/reinstalar/copiar comando)
+        // para arreglar un token rechazado sin borrar el historial.
         isStale && 'bg-danger/5',
       )}
     >
@@ -278,9 +286,11 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
       </td>
       <td className="py-3">
         <div className="flex flex-wrap items-center gap-2">
-          {/* #1382: con el agente SIN pulso la única acción operable es
-              Retirar (abajo): actualizar/rearmar/reinstalar/desinstalar
-              necesitan un equipo vivo en la red. */}
+          {/* Agente con pulso: acciones completas. Con el agente SIN pulso
+              (#1702) las acciones de recuperación siguen disponibles abajo
+              (rearmar/reinstalar/copiar comando arreglan un token rechazado
+              sin borrar el historial); solo se ocultan Actualizar y
+              Desinstalar, que necesitan el agente vivo para tener sentido. */}
           {!isStale && (
           <>
           {/* Actualizar: self-update del agente con progreso en vivo (#243).
@@ -293,17 +303,12 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
           <AgentBackupButton agent={agent} routerId={agent?.routerId} className="h-8" />
           {isNetgrip ? (
             // #363: NetGrip fresco se auto-actualiza desde su panel; el hint
-            // lo explica. (El rearm por SSH de un NetGrip caído de #569 quedó
-            // absorbido por la regla #1382: sin pulso -> solo Retirar.)
+            // lo explica.
             <span className="text-caption text-text-muted">
               {t('routers.agents.netgripHint')}
             </span>
           ) : (
             <>
-          {/* Rearm: canal preferente para heartbeat stale (proceso vivo).
-              Solo agentes NATIVOS OpenWrt: los externos (switch por beacon)
-              no tienen SSH - solo alertan (#291). */}
-          {agent && agent.kind !== 'external' && agent.kind !== 'netgrip' && <AgentRearmButton agent={agent} />}
           {/* #443: Reinstalar vía SSH desde el server; siempre visible para
               admins en agentes nativos OpenWrt (la acción se mudó aquí desde
               la tarjeta Info del detalle). */}
@@ -332,7 +337,7 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
                     : t(isMissing ? 'routers.agents.install' : 'routers.agents.reinstall')}
             </button>
           )}
-          {/* #624: Desinstalar vía SSH desde el server — libera espacio en
+          {/* #624: Desinstalar vía SSH desde el server - libera espacio en
               routers con poco room (p. ej. UniFi 6 Lite) donde el reinstall
               no cabe; hay que quitarlo antes de reinstalar. */}
           {canUninstall && (
@@ -390,6 +395,71 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
           )}
           </>
           )}
+          {/* #1702: agente inactivo (sin pulso): las acciones de recuperación
+              junto a Retirar. Rearmar reinicia el servicio por SSH (primer
+              intento, heartbeat stale); Reinstalar rota el token y redespliega
+              (arregla el 401 de un token invalidado por un reinicio o una
+              mudanza del servidor); Copiar comando es el fallback manual
+              cuando el server no llega por SSH. NetGrip: solo Rearmar (el
+              backend reinicia su servicio y rechaza reinstall/manual con
+              netgrip_managed, y rotar el token sin aplicarlo lo dejaría en
+              401 eterno). Externos: nada (sin SSH, solo Retirar). */}
+          {isStale && agent && agent.kind !== 'external' && (
+          <>
+          <AgentRearmButton agent={agent} />
+          {!isNetgrip && canReinstall && (
+            <button
+              type="button"
+              onClick={() => void reinstall()}
+              disabled={reinstallState === 'busy'}
+              title={t('routers.agents.reinstallTip')}
+              className={cn(
+                'inline-flex h-8 items-center gap-1.5 rounded-lg border px-2.5 text-caption font-semibold transition-colors disabled:opacity-50',
+                reinstallState === 'done'
+                  ? 'border-ok/40 bg-ok/10 text-ok'
+                  : reinstallState === 'fail'
+                    ? 'border-danger/40 bg-danger/10 text-danger'
+                    : 'border-border text-text-secondary hover:border-accent/40 hover:text-accent',
+              )}
+            >
+              <RotateCcw className={cn('h-3.5 w-3.5', reinstallState === 'busy' && 'animate-spin')} strokeWidth={1.75} />
+              {reinstallState === 'busy'
+                ? t('routers.agents.reinstalling')
+                : reinstallState === 'done'
+                  ? t('routers.agents.reinstalled')
+                  : reinstallState === 'fail'
+                    ? t('routers.agents.reinstallRetry')
+                    : t('routers.agents.reinstall')}
+            </button>
+          )}
+          {!isNetgrip && canRecover && (
+            <button
+              type="button"
+              onClick={() => void copyCmd()}
+              disabled={copyState === 'busy'}
+              title={t('routers.agents.copyCmdTip')}
+              className={cn(
+                'inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-2.5 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent disabled:opacity-50',
+                copyState === 'done' && 'border-ok/40 bg-ok/10 text-ok',
+                copyState === 'fail' && 'border-danger/40 bg-danger/10 text-danger',
+              )}
+            >
+              {copyState === 'busy' ? (
+                <Clipboard className="h-3.5 w-3.5 animate-pulse" strokeWidth={1.75} />
+              ) : copyState === 'done' ? (
+                <Check className="h-3.5 w-3.5" strokeWidth={1.75} />
+              ) : (
+                <Clipboard className="h-3.5 w-3.5" strokeWidth={1.75} />
+              )}
+              {copyState === 'done'
+                ? t('routers.agents.copied')
+                : copyState === 'fail'
+                  ? t('routers.agents.cmdFail')
+                  : t('routers.agents.copyCmd')}
+            </button>
+          )}
+          </>
+          )}
           {/* #1382: Retirar de la flota (server-side, cualquier kind): revoca
               el token y olvida el estado. Solo con el agente sin pulso
               (equipo apagado o quitado de la red); si vuelve hay que

+ 12 - 1
docs/manual.en.md

@@ -106,7 +106,7 @@ Routers are onboarded under **Settings > Devices** (see the onboarding procedure
 
 - The **colored dot** per router: green = online, amber = warned (for example high temperature), red = down.
 - The **card** summarizes the key metrics; the warning icon appears when temperature exceeds the threshold.
-- In the **agents section**, "Agent down" means the agent was registered but stopped reporting (usually fixed by reinstalling from the router detail).
+- In the **agents section**, "Agent down" means the agent was registered but stopped reporting. It may be a stopped process or a rejected token (for example after moving the server): rearm first and, if it still does not push, reinstall (see the recovery procedure below).
 - "No system metrics" means that device is monitored by SNMP or beacon and does not report CPU/RAM/temperature.
 
 ### Design decisions
@@ -134,6 +134,17 @@ Routers are onboarded under **Settings > Devices** (see the onboarding procedure
 
 For routers the server cannot reach over SSH, use the **pairing token** (Settings > Agent adoption) with `install-agent.sh --pairing-token`.
 
+### Procedure: recover a down agent (rearm or reinstall)
+
+An agent in the "Agent down" state stopped pushing. The agents section on **Devices** (the red row) offers the recovery actions to admins, in this order:
+
+1. **Rearm**: restarts the agent service on the router over SSH and waits for its first push (up to 30s). It is the quick path when the process hung or stopped, and it touches neither the config nor the token. If it cannot restart it, the row itself shows the reason (no SSH, cooldown, unknown router).
+2. **Reinstall**: redeploys the agent (binary, config and service) over SSH and **rotates its token**. It is the right action when the server rejects pushes with HTTP 401, which typically happens after a router reboot or when moving or restoring the server's database: the token stored on the agent no longer exists on the server. The agent's identity and its history are preserved.
+3. **Copy command**: generates a manual install one-liner with a fresh token for routers the server cannot reach over SSH. Paste it on the router itself.
+4. **Remove**: only when retiring the device. Revokes the token and forgets the agent state.
+
+The **Rearm** button also appears next to the "Agent down" badge in the router detail header. Both actions require the admin role and rearming has a 60 second cooldown per agent. If pushes still return 401 after rearming and reinstalling, check that `NETPULSE_SERVER` and the token in the router's `/etc/netpulse-agent.env` point to the current server.
+
 ### Procedure: upgrade all agents
 
 1. In **Devices**, if there are outdated agents you will see a notice with the count.

+ 12 - 1
docs/manual.es.md

@@ -106,7 +106,7 @@ Los routers se dan de alta en **Ajustes > Dispositivos** (ver el procedimiento d
 
 - El **punto de color** de cada router: verde = online, ámbar = con aviso (por ejemplo temperatura alta), rojo = caído.
 - La **tarjeta** resume las métricas clave; el icono de aviso aparece cuando la temperatura supera el umbral.
-- En la **sección de agentes**, "Agente caído" significa que el agente estaba registrado pero dejó de reportar (suele resolverse reinstalando desde el detalle del router).
+- En la **sección de agentes**, "Agente caído" significa que el agente estaba registrado pero dejó de reportar. Puede ser un proceso parado o un token rechazado (por ejemplo tras mover el servidor): rearma primero y, si sigue sin empujar, reinstala (ver el procedimiento de recuperación más abajo).
 - "Sin métricas de sistema" indica que ese dispositivo se monitoriza por SNMP o por beacon y no reporta CPU/RAM/temperatura.
 
 ### Decisiones de diseño
@@ -134,6 +134,17 @@ Los routers se dan de alta en **Ajustes > Dispositivos** (ver el procedimiento d
 
 Para routers a los que el servidor no puede acceder por SSH, usa el **token de emparejamiento** (Ajustes > Adopción de agentes) con `install-agent.sh --pairing-token`.
 
+### Procedimiento: recuperar un agente caído (rearmar o reinstalar)
+
+Un agente en estado "Agente caído" dejó de empujar. La sección de agentes de **Dispositivos** (la fila en rojo) ofrece las acciones de recuperación a los administradores, en este orden:
+
+1. **Rearmar**: reinicia el servicio del agente en el router vía SSH y espera su primer push (hasta 30 s). Es la vía rápida cuando el proceso se quedó colgado o parado, y no toca la configuración ni el token. Si no puede reiniciarlo, la propia fila muestra el motivo (sin SSH, enfriamiento, router desconocido).
+2. **Reinstalar**: redespliega el agente (binario, config y servicio) vía SSH y **rota su token**. Es la acción correcta cuando el servidor rechaza los pushes con HTTP 401, algo típico tras un reinicio del router o al mover o restaurar la base del servidor: el token que guarda el agente dejó de existir en el servidor. La identidad del agente y su historial se conservan.
+3. **Copiar comando**: genera un one-liner de instalación manual con un token nuevo para routers a los que el servidor no llega por SSH. Pégalo en el propio router.
+4. **Retirar**: solo al dar de baja el equipo. Revoca el token y olvida el estado del agente.
+
+El botón **Rearmar** aparece también junto a la insignia "Agente caído" en la cabecera del detalle del router. Ambas acciones exigen rol de administrador y el rearme tiene un enfriamiento de 60 segundos por agente. Si tras rearmar y reinstalar los pushes siguen en 401, revisa que `NETPULSE_SERVER` y el token del `/etc/netpulse-agent.env` del router apunten al servidor actual.
+
 ### Procedimiento: actualizar todos los agentes
 
 1. En **Dispositivos**, si hay agentes desactualizados verás un aviso con el número.