Răsfoiți Sursa

feat(integrations): show pushers installed outside NetPulse (#1754)

Closes #1743

A pusher installed by hand before #1674 keeps feeding the fleet, but the Integrations page reads only `router_integrations`, and the app is the only writer of that table. So `/api/agents` shows the unit alive and `/api/integrations` returns an empty list: the page looks broken and there is no way to see the pusher, its version or its last push.

`GET /api/integrations` now also returns `unmanaged`. The agent tokens in kv give the slug set, the registry gives the kind, and the entries are the ones whose kind is `external` and have no row in `router_integrations`. Each item carries slug, kind, version, interval, last push and a fresh flag with the same 3x interval rule as the managed ones.

The page lists them under "Managed outside NetPulse" with the last push and the version, and says that NetPulse cannot start, stop or rotate their token. Nothing is written to `router_integrations` and no action is offered: the process belongs to the host.

The list fills after the first push, because the kind lives in the registry in memory, and an entry disappears as soon as the app owns a row for that slug.

Tests: `TestIntegrationsUnmanagedListsExternalPushers`, `TestIntegrationsUnmanagedSkipsManagedSlug`, `TestIntegrationsUnmanagedIgnoresNativeAgents`.
Nacho 1 lună în urmă
părinte
comite
a0c66df326

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

@@ -713,6 +713,13 @@
     "loading": "Loading integrations...",
     "emptyTitle": "No integrations yet",
     "emptyDesc": "Add an external pusher for a router that NetPulse cannot reach directly.",
+    "unmanagedTitle": "Managed outside NetPulse",
+    "unmanagedDesc": "These pushers feed the fleet but have no integration record, so NetPulse cannot start, stop or rotate their token. They were installed by hand: edit their environment file on the host to change the token or the certificate pin.",
+    "unmanagedPushing": "Pushing",
+    "unmanagedStale": "Stale",
+    "unmanagedVersion": "v{{version}}",
+    "unmanagedLastPush": "Last push {{when}}",
+    "unmanagedInterval": "every {{count}}s",
     "fresh": "Fresh",
     "never": "never",
     "states": {

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

@@ -713,6 +713,13 @@
     "loading": "Cargando integraciones...",
     "emptyTitle": "Aún no hay integraciones",
     "emptyDesc": "Añade un pusher externo para un router al que NetPulse no llega directamente.",
+    "unmanagedTitle": "Gestionadas fuera de NetPulse",
+    "unmanagedDesc": "Estos pushers alimentan la flota pero no tienen registro de integración, así que NetPulse no puede arrancarlos, pararlos ni rotarles el token. Se instalaron a mano: edita su fichero de entorno en el host para cambiar el token o el pin del certificado.",
+    "unmanagedPushing": "Empujando",
+    "unmanagedStale": "Sin datos",
+    "unmanagedVersion": "v{{version}}",
+    "unmanagedLastPush": "Último envío {{when}}",
+    "unmanagedInterval": "cada {{count}}s",
     "fresh": "Reciente",
     "never": "nunca",
     "states": {

+ 18 - 2
app/src/lib/integrationsApi.ts

@@ -22,6 +22,22 @@ export interface Integration {
   fresh: boolean
 }
 
+/** A pusher that feeds the fleet without an integration record (#1743). */
+export interface UnmanagedIntegration {
+  slug: string
+  kind: string
+  version?: string
+  intervalS?: number
+  lastPushMs: number
+  fresh: boolean
+}
+
+export interface IntegrationListResponse {
+  integrations: Integration[]
+  /** Pushers installed by hand: they push, but the app cannot manage them. */
+  unmanaged?: UnmanagedIntegration[]
+}
+
 export interface Vendor {
   id: string
   mode: 'local' | 'ssh'
@@ -99,8 +115,8 @@ export function refreshVendors(): Promise<VendorsResponse> {
   return req<VendorsResponse>('/api/integrations/vendors/refresh', { method: 'POST' })
 }
 
-export function fetchIntegrations(): Promise<{ integrations: Integration[] }> {
-  return req<{ integrations: Integration[] }>('/api/integrations')
+export function fetchIntegrations(): Promise<IntegrationListResponse> {
+  return req<IntegrationListResponse>('/api/integrations')
 }
 
 export function createIntegration(

+ 45 - 1
app/src/pages/Integrations.tsx

@@ -51,7 +51,12 @@ import {
   stopIntegration,
   updateIntegration,
 } from '@/lib/integrationsApi'
-import type { CreateIntegrationInput, Integration, Vendor } from '@/lib/integrationsApi'
+import type {
+  CreateIntegrationInput,
+  Integration,
+  UnmanagedIntegration,
+  Vendor,
+} from '@/lib/integrationsApi'
 
 const POLL_MS = 15_000
 const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/
@@ -91,6 +96,9 @@ export default function Integrations() {
   const [lastRefreshedMs, setLastRefreshedMs] = useState(0)
   const [catalogRefreshing, setCatalogRefreshing] = useState(false)
   const [integrations, setIntegrations] = useState<Integration[]>([])
+  // Pushers instalados a mano: empujan a la flota pero no tienen registro de
+  // integración, así que la app no puede gestionarlos (#1743).
+  const [unmanaged, setUnmanaged] = useState<UnmanagedIntegration[]>([])
   const [loading, setLoading] = useState(true)
   const [refreshing, setRefreshing] = useState(false)
   const [error, setError] = useState('')
@@ -129,6 +137,7 @@ export default function Integrations() {
         setVendors(v.vendors)
         setLastRefreshedMs(v.lastRefreshedAt ?? 0)
         setIntegrations(ints.integrations)
+        setUnmanaged(ints.unmanaged ?? [])
         setError('')
       } catch (err) {
         setError(errMessage(err, t))
@@ -731,6 +740,41 @@ export default function Integrations() {
         </div>
       )}
 
+      {unmanaged.length > 0 && (
+        <>
+          <SectionHeader title={t('integrations.unmanagedTitle')} className="mt-8" />
+          <p className="mt-1 text-caption text-text-muted">{t('integrations.unmanagedDesc')}</p>
+          <div className="mt-3 space-y-3">
+            {unmanaged.map((it) => (
+              <div key={it.slug} className="rounded-2xl border border-border bg-surface p-4">
+                <div className="flex flex-wrap items-center justify-between gap-2">
+                  <div className="flex flex-wrap items-center gap-2">
+                    <span className="font-mono text-sm font-medium text-text-primary">{it.slug}</span>
+                    <StatusPill
+                      tone={it.fresh ? 'ok' : 'warn'}
+                      label={
+                        it.fresh ? t('integrations.unmanagedPushing') : t('integrations.unmanagedStale')
+                      }
+                    />
+                  </div>
+                  {it.version && (
+                    <span className="font-mono text-caption text-text-muted">
+                      {t('integrations.unmanagedVersion', { version: it.version })}
+                    </span>
+                  )}
+                </div>
+                <div className="mt-1 text-caption text-text-muted">
+                  {t('integrations.unmanagedLastPush', { when: agoLabel(it.lastPushMs) })}
+                  {it.intervalS
+                    ? ` · ${t('integrations.unmanagedInterval', { count: it.intervalS })}`
+                    : ''}
+                </div>
+              </div>
+            ))}
+          </div>
+        </>
+      )}
+
       <Dialog open={token !== null} onOpenChange={(open) => !open && setToken(null)}>
         {token !== null && (
           <DialogContent className="max-w-md">

+ 73 - 1
server-go/internal/httpapi/integrations.go

@@ -290,8 +290,80 @@ func (s *server) resumeIntegrations() {
 	s.broadcastIntegrations()
 }
 
+// unmanagedItem es un pusher externo que alimenta la flota sin fila en
+// router_integrations: se instaló a mano, antes de que la app supiera
+// instalarlos (#1743). Solo se describe; la app no puede arrancarlo, pararlo
+// ni rotarle el token.
+type unmanagedItem struct {
+	Slug       string `json:"slug"`
+	Kind       string `json:"kind"`
+	Version    string `json:"version,omitempty"`
+	IntervalS  int    `json:"intervalS,omitempty"`
+	LastPushMs int64  `json:"lastPushMs"`
+	Fresh      bool   `json:"fresh"`
+}
+
+// unmanagedIntegrations lista los pushers externos vivos que la app no
+// gestiona (#1743). Sin esto la página de Integraciones sale vacía mientras
+// /api/agents muestra unidades alimentadas por ellos, y el operador no tiene
+// ni una pista de que el pusher existe.
+//
+// El kind solo vive en memoria (AgentRegistry), así que justo después de un
+// reinicio la lista queda vacía hasta el primer push de cada unidad (~30 s).
+func (s *server) unmanagedIntegrations() []unmanagedItem {
+	out := []unmanagedItem{}
+	if s.db == nil || s.agents == nil {
+		return out
+	}
+	// Los slugs viven en kv como agent.token.<slug>. El cursor se cierra ANTES
+	// de consultar la tienda de integraciones: con SetMaxOpenConns(1), un
+	// QueryRow con las filas abiertas espera la única conexión y bloquea.
+	slugs := []string{}
+	rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
+	if err != nil {
+		return out
+	}
+	for rows.Next() {
+		var key string
+		if rows.Scan(&key) == nil {
+			slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
+		}
+	}
+	rows.Close()
+	if err := rows.Err(); err != nil {
+		return out
+	}
+	store := s.integrationsStore()
+	for _, slug := range slugs {
+		if slug == "" {
+			continue
+		}
+		_, version, kind, interval, ok := s.agents.Info(slug)
+		if !ok || kind != "external" {
+			continue
+		}
+		if _, managed := store.Get(slug); managed {
+			continue
+		}
+		lastPush := s.integrationLastPushMs(slug)
+		fresh := lastPush > 0 && interval > 0 && time.Now().UnixMilli()-lastPush <= int64(interval)*3*1000
+		out = append(out, unmanagedItem{
+			Slug:       slug,
+			Kind:       kind,
+			Version:    version,
+			IntervalS:  interval,
+			LastPushMs: lastPush,
+			Fresh:      fresh,
+		})
+	}
+	return out
+}
+
 func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
-	writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
+	writeJSON(w, http.StatusOK, map[string]any{
+		"integrations": s.integrationList(),
+		"unmanaged":    s.unmanagedIntegrations(),
+	})
 }
 
 type integrationCreateBody struct {

+ 156 - 0
server-go/internal/httpapi/integrations_unmanaged_test.go

@@ -0,0 +1,156 @@
+package httpapi_test
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+// externalPayload es un push de un pusher externo: el kind viaja en el payload
+// y es lo que distingue una integración de un agente nativo.
+func externalPayload(slug, version string, interval int, ts int64) string {
+	return fmt.Sprintf(`{"router":%q,"ts":%d,"version":%q,"kind":"external","interval":%d,"data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, slug, ts, version, interval)
+}
+
+type unmanagedJSON struct {
+	Slug       string `json:"slug"`
+	Kind       string `json:"kind"`
+	Version    string `json:"version"`
+	IntervalS  int    `json:"intervalS"`
+	LastPushMs int64  `json:"lastPushMs"`
+	Fresh      bool   `json:"fresh"`
+}
+
+// getIntegrations devuelve la lista gestionada y la de pushers a mano.
+func getIntegrations(t *testing.T, ts *agentTestServer) ([]string, []unmanagedJSON) {
+	t.Helper()
+	req, _ := http.NewRequest("GET", ts.URL+"/api/integrations", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET /api/integrations: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET /api/integrations: %d", res.StatusCode)
+	}
+	var body struct {
+		Integrations []struct {
+			Slug string `json:"slug"`
+		} `json:"integrations"`
+		Unmanaged []unmanagedJSON `json:"unmanaged"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("decode: %v", err)
+	}
+	managed := make([]string, 0, len(body.Integrations))
+	for _, it := range body.Integrations {
+		managed = append(managed, it.Slug)
+	}
+	return managed, body.Unmanaged
+}
+
+func findUnmanaged(items []unmanagedJSON, slug string) (unmanagedJSON, bool) {
+	for _, it := range items {
+		if it.Slug == slug {
+			return it, true
+		}
+	}
+	return unmanagedJSON{}, false
+}
+
+func hasUnmanaged(items []unmanagedJSON, slug string) bool {
+	_, ok := findUnmanaged(items, slug)
+	return ok
+}
+
+// TestIntegrationsUnmanagedListsExternalPushers: un pusher instalado a mano
+// empuja y no tiene fila en router_integrations. La página de Integraciones
+// debe decirlo en vez de salir vacía (#1743).
+func TestIntegrationsUnmanagedListsExternalPushers(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, _ := createAgentToken(t, ts, "crs305")
+	if status != http.StatusCreated {
+		t.Fatalf("create token: %d", status)
+	}
+	res := ingest(t, ts, token, "203.0.113.9", externalPayload("crs305", "0.1.1+lldp", 30, time.Now().Unix()))
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	managed, unmanaged := getIntegrations(t, ts)
+	if len(managed) != 0 {
+		t.Fatalf("integrations = %v, quería vacío", managed)
+	}
+	item, ok := findUnmanaged(unmanaged, "crs305")
+	if !ok {
+		t.Fatalf("crs305 no aparece en unmanaged: %+v", unmanaged)
+	}
+	if item.Kind != "external" || item.Version != "0.1.1+lldp" || item.IntervalS != 30 {
+		t.Fatalf("item inesperado: %+v", item)
+	}
+	if !item.Fresh {
+		t.Fatalf("un push recién ingerido debe salir fresh: %+v", item)
+	}
+	if item.LastPushMs == 0 {
+		t.Fatalf("lastPushMs vacío: %+v", item)
+	}
+}
+
+// TestIntegrationsUnmanagedSkipsManagedSlug: en cuanto la app posee la fila de
+// integración, el slug sale de la lista de no gestionadas.
+func TestIntegrationsUnmanagedSkipsManagedSlug(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, _ := createAgentToken(t, ts, "fn-switch-8")
+	if status != http.StatusCreated {
+		t.Fatalf("create token: %d", status)
+	}
+	res := ingest(t, ts, token, "203.0.113.10", externalPayload("fn-switch-8", "0.1.0fn3", 30, time.Now().Unix()))
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	if _, unmanaged := getIntegrations(t, ts); !hasUnmanaged(unmanaged, "fn-switch-8") {
+		t.Fatalf("fn-switch-8 debería aparecer sin fila de integración: %+v", unmanaged)
+	}
+
+	err := rintegration.NewStore(ts.db.DB).Upsert(rintegration.Row{
+		Slug: "fn-switch-8", Vendor: "fn", Mode: "local", Host: "127.0.0.1",
+		IntervalS: 30, Enabled: true, State: "running",
+	})
+	if err != nil {
+		t.Fatalf("upsert: %v", err)
+	}
+	managed, unmanaged := getIntegrations(t, ts)
+	if _, ok := findUnmanaged(unmanaged, "fn-switch-8"); ok {
+		t.Fatalf("fn-switch-8 sigue en unmanaged con fila: %+v", unmanaged)
+	}
+	if len(managed) != 1 || managed[0] != "fn-switch-8" {
+		t.Fatalf("integrations = %v", managed)
+	}
+}
+
+// TestIntegrationsUnmanagedIgnoresNativeAgents: un agente nativo (sin kind) no
+// es una integración externa y no debe aparecer.
+func TestIntegrationsUnmanagedIgnoresNativeAgents(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, _ := createAgentToken(t, ts, "patio")
+	if status != http.StatusCreated {
+		t.Fatalf("create token: %d", status)
+	}
+	res := ingest(t, ts, token, "203.0.113.11", validPayload())
+	if res.StatusCode != http.StatusAccepted {
+		t.Fatalf("ingest: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	if _, unmanaged := getIntegrations(t, ts); len(unmanaged) != 0 {
+		t.Fatalf("unmanaged = %+v, quería vacío", unmanaged)
+	}
+}