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

feat(agents): one-click first install from the agents table (#486)

The reinstall endpoint already creates the agent token when missing, but
the UI never offered it for routers that had no agent yet, so a new
router could only be onboarded through the pairing token or the API.
Every OpenWrt router now gets a row in the agents table; routers without
an agent show Install agent (register, deploy over SSH) next to the
copy-command fallback, with proper first-install confirm and status
texts. To keep legacy routers from doubling up, the agents list also
returns the board hostname and rows match on routerId, slug or hostname.
README no longer points to the Settings > Agents submenu that never
existed.

Closes #483

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

+ 23 - 12
README.md

@@ -190,15 +190,23 @@ are added from Settings. Polling is strictly read-only.
 
 ### Installing the agents (recommended: let the app do it)
 
-Once the router is in the table and its SSH key is authorized, the app can
-install and start the agent by itself: Settings → Agents → **Reinstall**.
-Over one SSH session the server detects the architecture, downloads the
-embedded agent binary from itself (token-authenticated), verifies its
-SHA256, writes the config, installs the procd init (with a self-heal step
-that re-downloads the binary after a `sysupgrade`, which only preserves
-`/etc`), sets up the watchdog cron and restarts the service. The agent
-shows up as connected within seconds. Re-running it is safe: it rotates
-the token and reinstalls.
+Once the router is in the table and the server's SSH key is authorized on
+it, the app can install and start the agent by itself: open the **Routers**
+page and scroll to the agents table at the bottom. Every OpenWrt router
+shows a row there; routers without an agent offer an **Install agent**
+button, and existing agents offer **Reinstall**. Over one SSH session the
+server registers the agent if needed (its token is created on the fly),
+detects the architecture, downloads the embedded agent binary from itself
+(token-authenticated), verifies its SHA256, writes the config, installs
+the procd init (with a self-heal step that re-downloads the binary after a
+`sysupgrade`, which only preserves `/etc`), sets up the watchdog cron and
+restarts the service. The agent shows up as connected within seconds.
+Re-running it is safe: it rotates the token and reinstalls.
+
+For routers the server cannot SSH into, use the pairing token instead:
+Settings → Agent adoption shows a reusable pairing token, and
+`install-agent.sh --pairing-token` (run from any machine that can reach
+both the router and the server) registers the agent on first contact.
 
 ## OpenWrt packages
 
@@ -229,9 +237,12 @@ install, LuCI picks up the new pages automatically (the package restarts
 `rpcd` and clears the index cache).
 
 The package ships an empty config, so the service stays inactive until you
-point it at your server (the app cannot know these values). Create the
-agent in the web UI (Settings → Agents) to get its one-time token, then on
-the router:
+point it at your server (the app cannot know these values). If the server
+can already SSH into the router, skip all of this and press **Install
+agent** in the Routers page agents table: it registers the agent, writes
+the config and starts the service for you. Otherwise, create the agent
+via the pairing token (Settings → Agent adoption plus `install-agent.sh
+--pairing-token`) or `POST /api/agents`, and on the router:
 
 ```sh
 uci set netpulse-agent.main.server='http://<netpulse-server-ip>:3000'

+ 8 - 0
app/public/locales/en/translation.json

@@ -748,6 +748,14 @@
       "reinstallDone": "Agent reinstalled and reporting again.",
       "reinstallPending": "Agent installed; waiting for it to report (up to 40s).",
       "reinstallFail": "Reinstall failed",
+      "install": "Install agent",
+      "installing": "Installing…",
+      "installed": "Installed",
+      "installTip": "Registers the agent and deploys it to this router over SSH (binary, config, service and watchdog). Requires the server's public key authorized on the router.",
+      "installConfirm": "Install the agent on {{router}}? Its token will be created and deployed over SSH.",
+      "installDone": "Agent installed and reporting.",
+      "installPending": "Agent installed; waiting for it to report (up to 40s).",
+      "installFail": "Install failed",
       "copyCmd": "Copy command",
       "copyCmdTip": "Generates the manual install one-liner (fallback for routers without SSH). The token rotates on every generation.",
       "copied": "Command copied",

+ 8 - 0
app/public/locales/es/translation.json

@@ -748,6 +748,14 @@
       "reinstallDone": "Agente reinstalado y empujando de nuevo.",
       "reinstallPending": "Agente instalado; esperando a que empuje (hasta 40 s).",
       "reinstallFail": "Fallo al reinstalar",
+      "install": "Instalar agente",
+      "installing": "Instalando…",
+      "installed": "Instalado",
+      "installTip": "Registra el agente y lo despliega en este router por SSH (binario, config, servicio y watchdog). Requiere la clave pública del servidor autorizada en el router.",
+      "installConfirm": "¿Instalar el agente en {{router}}? Se creará su token y se desplegará por SSH.",
+      "installDone": "Agente instalado y empujando.",
+      "installPending": "Agente instalado; esperando a que empuje (hasta 40 s).",
+      "installFail": "Fallo al instalar",
       "copyCmd": "Copiar comando",
       "copyCmdTip": "Genera el one-liner de instalación manual (fallback para routers sin SSH). El token se rota en cada generación.",
       "copied": "Comando copiado",

+ 29 - 12
app/src/components/routers/AgentsSection.tsx

@@ -66,7 +66,9 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
   const isNetgrip = agent?.kind === 'netgrip'
   const isOpenWrt = isOpenWrtType(router?.type)
   const isStale = agent !== undefined && !agent.fresh
-  const isMissing = agent === undefined && router?.agentOnly === true
+  // #483: sin agente = TOD router nativo OpenWrt sin agente (antes solo los
+  // agent-only): la fila ofrece Instalar, que registra y despliega.
+  const isMissing = agent === undefined
   const canRecover = isOpenWrt && (isStale || isMissing) && auth?.role === 'admin'
   // #443: reinstall disponible SIEMPRE para admins en agentes nativos OpenWrt
   // (sanos o caídos): antes solo aparecía cuando estaba stale o faltaba, y el
@@ -101,16 +103,22 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
 
   const reinstall = async () => {
     if (reinstallState === 'busy') return
-    if (!window.confirm(t('routers.agents.reinstallConfirm', { router: router?.name ?? slug }))) return
+    // #483: primera instalación vs reinstalación: mismo endpoint (reinstall
+    // crea el token si el agente no existía), textos distintos.
+    const confirmKey = isMissing ? 'routers.agents.installConfirm' : 'routers.agents.reinstallConfirm'
+    const doneKey = isMissing ? 'routers.agents.installDone' : 'routers.agents.reinstallDone'
+    const pendingKey = isMissing ? 'routers.agents.installPending' : 'routers.agents.reinstallPending'
+    const failKey = isMissing ? 'routers.agents.installFail' : 'routers.agents.reinstallFail'
+    if (!window.confirm(t(confirmKey, { router: router?.name ?? slug }))) return
     setReinstallState('busy')
     setReinstallMsg('')
     const res = await reinstallAgent(slug)
     if (res && !res.error) {
       setReinstallState('done')
-      setReinstallMsg(res.recovered ? t('routers.agents.reinstallDone') : t('routers.agents.reinstallPending'))
+      setReinstallMsg(res.recovered ? t(doneKey) : t(pendingKey))
     } else {
       setReinstallState('fail')
-      setReinstallMsg(res?.error ?? t('routers.agents.reinstallFail'))
+      setReinstallMsg(res?.error ?? t(failKey))
     }
     window.setTimeout(() => setReinstallState('idle'), 8000)
   }
@@ -222,7 +230,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
               type="button"
               onClick={() => void reinstall()}
               disabled={reinstallState === 'busy'}
-              title={t('routers.agents.reinstallTip')}
+              title={t(isMissing ? 'routers.agents.installTip' : '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'
@@ -234,12 +242,12 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
             >
               <RotateCcw className={cn('h-3.5 w-3.5', reinstallState === 'busy' && 'animate-spin')} strokeWidth={1.75} />
               {reinstallState === 'busy'
-                ? t('routers.agents.reinstalling')
+                ? t(isMissing ? 'routers.agents.installing' : 'routers.agents.reinstalling')
                 : reinstallState === 'done'
-                  ? t('routers.agents.reinstalled')
+                  ? t(isMissing ? 'routers.agents.installed' : 'routers.agents.reinstalled')
                   : reinstallState === 'fail'
                     ? t('routers.agents.reinstallRetry')
-                    : t('routers.agents.reinstall')}
+                    : t(isMissing ? 'routers.agents.install' : 'routers.agents.reinstall')}
             </button>
           )}
           {canRecover && !isNetgrip && (
@@ -445,16 +453,25 @@ export function AgentsSection() {
 
   // Filas: agentes registrados (por slug) + routers agent-only sin agente.
   const rows = useMemo(() => {
-    const agentBySlug = new Map(agents.map((a) => [a.slug, a]))
     const routerBySlug = new Map(routers.map((r) => [r.id, r]))
     const out: { agent?: AgentInfo; router?: Router }[] = agents.map((a) => ({
       agent: a,
       router: routerBySlug.get(a.slug),
     }))
+    // #483: también fila para TODO router nativo OpenWrt sin agente (no solo
+    // agent-only): el botón Instalar registra el agente y lo despliega por
+    // SSH. El emparejamiento usa las tres claves (routerId de tabla, slug y
+    // hostname del board) para no duplicar filas en routers legacy cuyo id
+    // de overview difiere del id de tabla.
     for (const r of routers) {
-      if (r.agentOnly && !agentBySlug.has(r.id) && isOpenWrtType(r.type)) {
-        out.push({ router: r })
-      }
+      if (!isOpenWrtType(r.type)) continue
+      const covered = agents.some(
+        (a) =>
+          a.routerId === r.id ||
+          a.slug === r.id ||
+          (a.hostname !== undefined && a.hostname.toLowerCase() === r.id.toLowerCase()),
+      )
+      if (!covered) out.push({ router: r })
     }
     return out
   }, [agents, routers])

+ 3 - 0
app/src/data/types.ts

@@ -409,6 +409,9 @@ export interface AgentInfo {
   slug: string
   /** id del router asociado. Puede no coincidir con `slug` (#282). */
   routerId?: string
+  /** Hostname del board del último payload: tercera clave de emparejamiento
+   *  para routers legacy cuyo id de overview difiere del id de tabla (#483). */
+  hostname?: string
   /** Unix SEGUNDOS del último push; null si nunca empujó */
   lastSeen: number | null
   /** Versión del binario netpulse-agent ("" si aún no se conoce) */

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

@@ -364,6 +364,11 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 type agentListItem struct {
 	Slug     string `json:"slug"`
 	RouterID string `json:"routerId,omitempty"` // id del router asociado (#282)
+	// Hostname del board del último payload: los routers legacy del overview
+	// se llaman por hostname (flint2) y su id de tabla es otro (gateway);
+	// con esta tercera clave la UI puede emparejar fila↔router sin duplicar
+	// (#483).
+	Hostname string `json:"hostname,omitempty"`
 	LastSeen *int64 `json:"lastSeen"`           // unix SEGUNDOS; null si nunca empujó
 	Version  string `json:"version,omitempty"`
 	Fresh    bool   `json:"fresh"`
@@ -474,6 +479,9 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 					_, item.Fresh = s.agents.Fresh(slug)
 				}
 				item.RouterID = resolveAgentRouter(slug, payload, routerByID)
+				if payload != nil && payload.Data.System != nil && payload.Data.System.Board != nil {
+					item.Hostname = strings.ToLower(strings.TrimSpace(payload.Data.System.Board.Hostname))
+				}
 				// Fase 6.3 (issue #243): upgrade disponible si el agente
 				// reporta una versión distinta del binario embebido y el router
 				// asociado es actualizable (nativo OpenWrt/GL.iNet).