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

feat(adapters): publish the inventory source and its age (#1917) (#1920)

Nacho 4 недель назад
Родитель
Сommit
8e8cf8c0fc

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+Each unit now reports where its inventory came from and how old it is (#1917). The server already knew the difference internally: a unit without an agent is inventoried over SSH on every tick, and an SNMP switch comes from its own collector, but that detail never left the process, so a client list pushed by an agent a minute ago looked exactly like one read over SSH four hours ago. The router page now shows the source (agent, SSH, SNMP or an integration) next to the age of the last poll. It also matters for units that will never run an agent: a readable inventory is still useful, as long as the operator can see it is not live.
+
 ### Fixed
 
 - A release reuses the agent binaries again when the agent did not change (#1916). The step that downloads the previous release runs inside a temporary directory, and `gh` resolves the repository through git, so every attempt died with "not a git repository", printed a warning and fell back to compiling five architectures that were already built. The download now names the repository explicitly, so the previous assets are really reused and the embedded agent stays bit for bit the published one. Reusing also writes the version stamp of #1914, which the compile path produces but this one did not, otherwise the guard that reads the stamp would disable agent self-upgrade on every release that reused the binaries.

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

@@ -1005,6 +1005,11 @@
     "highTempBanner": "High temperature: {{temp}} (threshold {{threshold}}).",
     "info": {
       "access": "Access",
+      "inventory": "Inventory",
+      "inventoryAgent": "Agent",
+      "inventorySsh": "SSH",
+      "inventorySnmp": "SNMP",
+      "inventoryExternal": "Integration",
       "copied": "Command copied",
       "copySsh": "SSH (copy)",
       "firmwareBase": "(base {{base}})",

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

@@ -1005,6 +1005,11 @@
     "highTempBanner": "Temperatura alta: {{temp}} (umbral {{threshold}}).",
     "info": {
       "access": "Acceso",
+      "inventory": "Inventario",
+      "inventoryAgent": "Agente",
+      "inventorySsh": "SSH",
+      "inventorySnmp": "SNMP",
+      "inventoryExternal": "Integración",
       "copied": "Comando copiado",
       "copySsh": "SSH (copiar)",
       "firmwareBase": "(base {{base}})",

+ 35 - 1
app/src/components/routers/RouterInfo.tsx

@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
 import { Check, ExternalLink, LayoutDashboard, Terminal } from 'lucide-react'
 import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
 import { useTranslation } from 'react-i18next'
-import { fmtUptime } from '@/i18n'
+import { fmtSeenAgo, fmtUptime } from '@/i18n'
 import type { Router } from '@/data/mock'
 import { SectionHeader } from '@/components/SectionHeader'
 import { StatusPill } from '@/components/StatusPill'
@@ -21,6 +21,25 @@ function Row({ label, children }: { label: string; children: React.ReactNode })
   )
 }
 
+/**
+ * #1917: nombre traducido de la vía que produjo el inventario. Las claves van
+ * literales en el switch para que el extractor de i18n las pueda ver.
+ */
+function inventorySourceLabel(source: string, t: (key: string) => string): string {
+  switch (source) {
+    case 'agent':
+      return t('routerDetail.info.inventoryAgent')
+    case 'ssh':
+      return t('routerDetail.info.inventorySsh')
+    case 'snmp':
+      return t('routerDetail.info.inventorySnmp')
+    case 'external':
+      return t('routerDetail.info.inventoryExternal')
+    default:
+      return source
+  }
+}
+
 /** ③ Info + Red (router-detail.md §③) — definition list + acciones ghost. */
 export function RouterInfo({ router, extras }: { router: Router; extras?: RouterExtras }) {
   const { t } = useTranslation()
@@ -79,6 +98,21 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
     { label: 'Uptime', node: fmtUptime(router.uptime) },
     { label: t('routerDetail.info.lastReboot'), node: ex.lastReboot },
     { label: t('routerDetail.info.timezone'), node: ex.timezone ?? '—' },
+    {
+      // #1917: de dónde salió el inventario y cuánto lleva ahí. Una lectura
+      // por SSH de hace cuatro horas sigue siendo válida, pero el operador
+      // tiene que poder verlo en vez de dar el dato por fresco.
+      label: t('routerDetail.info.inventory'),
+      node: router.inventorySource ? (
+        <span className="inline-flex items-center gap-1.5">
+          {inventorySourceLabel(router.inventorySource, t)}
+          <span className="text-text-muted">·</span>
+          <span className="text-text-muted">{fmtSeenAgo(router.inventoryAt)}</span>
+        </span>
+      ) : (
+        '—'
+      ),
+    },
     {
       label: t('routerDetail.info.access'),
       node: router.type === 'managed-switch' || router.type === 'external' ? (

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

@@ -42,6 +42,11 @@ export interface Router {
    *  LuCI). La topología cruza el puerto del cliente con esta lista para
    *  etiquetar su VLAN. Ausente si la unidad no lo reporta. */
   vlans?: VlanPort[]
+  /** #1917: vía que produjo el inventario ("agent"|"external"|"snmp"|"ssh").
+   *  Ausente si la unidad no tiene sondeo del que sacarlo. */
+  inventorySource?: string
+  /** #1917: epoch ms del sondeo que produjo ese inventario. */
+  inventoryAt?: number
   status: Status
   /** Salud 0–100 */
   health: number

+ 54 - 0
server-go/internal/adapters/inventory_source_1917_test.go

@@ -0,0 +1,54 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+)
+
+// #1917: el inventario de una unidad puede venir de cuatro vías distintas y
+// hasta ahora el servidor no lo decía. La tarjeta solo llevaba los datos, así
+// que un operador no podía distinguir un push del agente de hace un minuto de
+// una lectura por SSH de hace horas.
+func TestInventorySourceNamesThePath(t *testing.T) {
+	cases := []struct {
+		name   string
+		kind   string
+		snmp   bool
+		expect string
+	}{
+		{"native agent", "native", false, "agent"},
+		{"netgrip agent", "netgrip", false, "agent"},
+		{"ssh fallback", "", false, "ssh"},
+		{"snmp collector", "", true, "snmp"},
+		{"external pusher", "external", false, "external"},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			p := &routerPolled{agentKind: c.kind, cfg: RouterConfig{SnmpEnabled: c.snmp}}
+			if got := p.inventorySource(); got != c.expect {
+				t.Fatalf("inventorySource() = %q, esperaba %q", got, c.expect)
+			}
+		})
+	}
+}
+
+// La tarjeta tiene que llevar la fuente y la edad juntas: la fuente sola no
+// sirve si el dato es de ayer.
+func TestBuildRouterPublishesInventoryOrigin(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := time.Now().Add(-7 * time.Minute).UnixMilli()
+	p := &routerPolled{
+		cfg:      RouterConfig{ID: "rt2", Name: "rt2", Host: "192.168.1.2"},
+		agentKind: "native",
+		polledAt:  polled,
+	}
+
+	r := l.buildRouter(p, nil)
+
+	if r.InventorySource != "agent" {
+		t.Fatalf("InventorySource = %q, esperaba agent", r.InventorySource)
+	}
+	if r.InventoryAt != polled {
+		t.Fatalf("InventoryAt = %d, esperaba %d", r.InventoryAt, polled)
+	}
+}

+ 21 - 0
server-go/internal/adapters/live.go

@@ -1583,6 +1583,23 @@ func vlanPortsWithNames(ports []VlanPort, luci *probe.LuCILabels) []VlanPort {
 	return out
 }
 
+// inventorySource (#1917) nombra la vía que produjo este sondeo. El sondeo
+// del agente llega con su Kind ya resuelto; el resto sale del cliente SSH o
+// del recolector SNMP, que es lo que distingue "ssh" de "snmp".
+func (p *routerPolled) inventorySource() string {
+	switch p.agentKind {
+	case "native", "netgrip":
+		return "agent"
+	case "":
+		if p.cfg.SnmpEnabled {
+			return "snmp"
+		}
+		return "ssh"
+	default:
+		return p.agentKind
+	}
+}
+
 func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	l.mu.Lock()
 	gw := l.gatewayCfg
@@ -1669,6 +1686,10 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 		r.VitalsAvailable = bptr(v.available)
 	}
 	r.SnmpEnabled = p.cfg.SnmpEnabled
+	// #1917: de dónde salió este inventario y de cuándo es. Se calcula aquí,
+	// donde ya se conoce el agentKind, para no exponer ese detalle interno.
+	r.InventorySource = p.inventorySource()
+	r.InventoryAt = p.polledAt
 	// #1741: la serie de 24 h de una unidad sin throughput nativo (SNMP o
 	// pusher external) sale de sus puertos. Se decide aquí, donde se conoce el
 	// agent kind, porque Router no lo expone y VitalsAvailable ya no sirve de

+ 11 - 2
server-go/internal/adapters/types.go

@@ -184,8 +184,17 @@ type Router struct {
 	// Vlans (#1757): bridge VLAN filtering por puerto (id, tagged, pvid y el
 	// nombre declarado en LuCI). La topología cruza el puerto del cliente con
 	// esta lista para etiquetar su VLAN. Ausente si la unidad no lo reporta.
-	Vlans  []VlanPort `json:"vlans,omitempty"`
-	Status string     `json:"status"` // "online"|"warn"|"offline"|"unreachable"
+	Vlans []VlanPort `json:"vlans,omitempty"`
+	// InventorySource (#1917): vía que produjo el inventario de esta unidad
+	// ("agent", "external", "snmp" o "ssh"). Un inventario leído por SSH es
+	// válido, pero no es lo mismo que un push del agente: la UI necesita
+	// poder decirlo. Ausente cuando no hay sondeo que lo justifique.
+	InventorySource string `json:"inventorySource,omitempty"`
+	// InventoryAt (#1917): epoch ms del sondeo que produjo ese inventario,
+	// para que la UI pueda enseñar su antigüedad en vez de dar por bueno un
+	// dato de hace horas.
+	InventoryAt int64  `json:"inventoryAt,omitempty"`
+	Status      string `json:"status"` // "online"|"warn"|"offline"|"unreachable"
 	Health int        `json:"health"`
 	// LatencyMs (#1384): latencia sondeada de la unidad (ping unidad→gateway
 	// en no-gateway; latencia WAN en el gateway). Null cuando la fuente no la