Ver Fonte

feat(probe): accept an optional workloads section for hypervisor-class hosts (#2229)

A host that runs other machines can now report its nested guests in data.workloads, and they land in the unit's detail page as a count plus a list with each workload's state. Census data, never clients or graph nodes, so the fleet canvas is untouched.

The section is additive and optional. nil means the probe failed on this push, so the server keeps the last good one (the same anti-blink rule as multiWan); an empty item list means the host runs nothing. Old agents and old servers ignore the key.
Bob Minowicz há 5 dias atrás
pai
commit
1a8679fa51

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- A host that runs other machines — an RKE2 node, a PVE box, a Docker host — can report the guests nested inside it through an optional `workloads` section in the push: stable id, name, kind and state per guest. The server keeps the census as reported and shows it on the unit's detail page, a count and a list with each workload's state. It is detail data, not graph data: a node with a hundred pods does not draw a hundred clients (#2227).
 - A switch fed only by the Realtek beacon can report the LLDP neighbours it receives, as an optional `lldp` section in the datagram, so the topology gets the chassis name, the local port and the management address from the unit that really sees those frames. The section is bounded (64 neighbours, 128 characters per text field), an old build keeps working unchanged, and an absent section keeps the last known neighbours (#2184).
 - A rejected push says why. The server answered `unauthorized`, `invalid_signature` or `stale_payload` and kept only a timestamp, so the panel showed the same "token rejected" badge for a stale token, an agent older than the server and a unit whose clock is minutes off. The reason is stored next to the timestamp, returned by `/api/agents` as `rejectedReason`, shown in the badge tooltip with what to check, and quoted in the auto-rearm alert, which no longer says "restarted but did not come back" when the pushes never got in (#2211).
 

+ 6 - 0
agent/probe/payload.go

@@ -95,6 +95,12 @@ type PayloadData struct {
 	// Read-only here. nil = this router reports no multi-WAN, which is also
 	// what an older agent sends.
 	MultiWan *MultiWanInfo `json:"multiWan,omitempty"`
+	// Workloads (#2227): the nested guests a hypervisor-class host runs —
+	// pods of an RKE2 node, VMs of a PVE box, containers of a Docker host.
+	// Census data for the unit's detail page, never graph nodes. nil = the
+	// probe failed this push (the server keeps the last good section); an
+	// older pusher sends nothing and changes nothing.
+	Workloads *Workloads `json:"workloads,omitempty"`
 }
 
 // MQTTData: exposición propia del equipo a Home Assistant por MQTT (#832).

+ 27 - 0
agent/probe/workloads.go

@@ -0,0 +1,27 @@
+// workloads.go — la sección neutral `workloads` del payload (#2227): los
+// huéspedes que corre un host clase hipervisor (pods de un nodo RKE2, VMs de
+// un PVE, contenedores de un Docker). Viaja como censo, no como base de
+// datos: el servidor guarda la sección tal cual y la expone en el detalle de
+// la unidad; NO añade clientes al grafo de topología.
+package probe
+
+// WorkloadItem es un huésped anidado. ID es un UID estable del workload —
+// nunca un índice de la lista — para que el servidor pueda seguir a un item
+// entre pushes aunque la fuente reordene. Kind/State crudos de la fuente
+// deben normalizarse a "unknown" por el productor, nunca viajar sin
+// normalizar.
+type WorkloadItem struct {
+	ID    string `json:"id"`
+	Name  string `json:"name"`
+	Kind  string `json:"kind,omitempty"`  // "pod" | "vm" | "container" | ...
+	State string `json:"state,omitempty"` // "running" | "pending" | "stopped" | "unknown"
+}
+
+// Workloads es la sección aditiva: un host clase hipervisor declara aquí sus
+// huéspedes. nil = sonda fallida en este push (el servidor conserva la última
+// buena, la regla anti-parpadeo del contrato); Items vacío = el host no tiene
+// workloads de verdad. Parent es el id estable del host, opcional.
+type Workloads struct {
+	Parent string         `json:"parent,omitempty"`
+	Items  []WorkloadItem `json:"items,omitempty"`
+}

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

@@ -1331,6 +1331,21 @@
       "stickyNote": "Each client stays on one connection at a time, so from a single computer you see one address, not a mix.",
       "source": "Configured in this router's own panel. NetPulse only shows it."
     },
+    "workloads": {
+      "title": "Workloads",
+      "total_one": "{{count}} workload",
+      "total_other": "{{count}} workloads",
+      "empty": "This host reports no workloads.",
+      "showAll": "Show all {{n}}",
+      "collapse": "Collapse",
+      "state": {
+        "running": "Running",
+        "pending": "Pending",
+        "stopped": "Stopped",
+        "unknown": "Unknown"
+      },
+      "source": "Pushed by the host itself. NetPulse only shows it."
+    },
     "wireguard": {
       "lastIp": "Last IP",
       "peersConnected": "Connected peers",

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

@@ -1331,6 +1331,21 @@
       "stickyNote": "Cada cliente se queda en una sola conexión cada vez, así que desde un mismo ordenador verás una dirección, no una mezcla.",
       "source": "Se configura en el panel del propio router. NetPulse solo lo muestra."
     },
+    "workloads": {
+      "title": "Cargas de trabajo",
+      "total_one": "{{count}} carga",
+      "total_other": "{{count}} cargas",
+      "empty": "Este host no reporta cargas de trabajo.",
+      "showAll": "Ver las {{n}}",
+      "collapse": "Cerrar",
+      "state": {
+        "running": "En ejecución",
+        "pending": "Pendiente",
+        "stopped": "Detenida",
+        "unknown": "Desconocido"
+      },
+      "source": "La empuja el propio host. NetPulse solo la muestra."
+    },
     "wireguard": {
       "lastIp": "Última IP",
       "peersConnected": "Peers conectados",

+ 101 - 0
app/src/components/routers/WorkloadsPanel.tsx

@@ -0,0 +1,101 @@
+import { useState } from 'react'
+import { Boxes } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import type { WorkloadItem, WorkloadsInfo } from '@/data/types'
+import { SectionHeader } from '@/components/SectionHeader'
+import { StatusPill } from '@/components/StatusPill'
+import type { PillTone } from '@/components/StatusPill'
+import { cn } from '@/lib/utils'
+
+/** How many guests the collapsed panel lists before "show all". A node's
+ *  real workload list runs into the hundreds; the page stays a dashboard
+ *  first and a manifest on demand. */
+const COLLAPSED_LIMIT = 10
+
+/** One workload's verdict pill. Unknown states stay visible and neutral:
+ *  the producer normalizes, and an unlisted string is a producer bug we
+ *  must not paint over with green. */
+function stateInfo(state: string | undefined): { key: string; tone: PillTone } {
+  switch (state) {
+    case 'running':
+      return { key: 'routerDetail.workloads.state.running', tone: 'ok' }
+    case 'pending':
+      return { key: 'routerDetail.workloads.state.pending', tone: 'info' }
+    case 'stopped':
+      return { key: 'routerDetail.workloads.state.stopped', tone: 'muted' }
+    default:
+      return { key: 'routerDetail.workloads.state.unknown', tone: 'muted' }
+  }
+}
+
+function WorkloadRow({ w }: { w: WorkloadItem }) {
+  const { t } = useTranslation()
+  const s = stateInfo(w.state)
+  return (
+    <li className="flex flex-wrap items-center gap-x-2.5 gap-y-1 py-2">
+      <span
+        className={cn(
+          'h-2 w-2 shrink-0 rounded-full',
+          s.tone === 'ok' ? 'bg-ok' : s.tone === 'info' ? 'bg-info' : 'bg-text-muted',
+        )}
+        aria-hidden="true"
+      />
+      <span className="min-w-0 font-mono text-mono-sm text-text-primary">{w.name}</span>
+      {w.kind && <span className="text-caption text-text-muted">{w.kind}</span>}
+      <span className="flex-1" />
+      <StatusPill tone={s.tone} label={t(s.key)} />
+    </li>
+  )
+}
+
+/**
+ * The nested guests a hypervisor-class host runs (#2227): pods of a node,
+ * VMs of a hypervisor, containers of a Docker box.
+ *
+ * Census, not topology: these live on the host and never join the graph,
+ * which is why they arrive in the detail payload and nowhere else. The
+ * list is read from the host's own pusher, exactly as it reported it.
+ */
+export function WorkloadsPanel({ info }: { info: WorkloadsInfo }) {
+  const { t } = useTranslation()
+  const [showAll, setShowAll] = useState(false)
+  // Defensive: the section comes from a pusher. Items absent means the
+  // unit reported and runs nothing; render the empty verdict, not a hole.
+  const items = [...(info?.items ?? [])].sort((a, b) => a.name.localeCompare(b.name))
+  const shown = showAll ? items : items.slice(0, COLLAPSED_LIMIT)
+
+  return (
+    <section className="rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-12">
+      <div className="flex flex-wrap items-center justify-between gap-2">
+        <div className="flex items-center gap-2">
+          <Boxes className="h-4 w-4 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+          <SectionHeader title={t('routerDetail.workloads.title')} />
+        </div>
+        <StatusPill tone={items.length > 0 ? 'accent' : 'muted'} label={t('routerDetail.workloads.total', { count: items.length })} />
+      </div>
+
+      {items.length === 0 ? (
+        <p className="mt-3 text-caption text-text-muted">{t('routerDetail.workloads.empty')}</p>
+      ) : (
+        <>
+          <ul className="mt-3 divide-y divide-border/60">
+            {shown.map((w) => (
+              <WorkloadRow key={w.id || w.name} w={w} />
+            ))}
+          </ul>
+          {items.length > COLLAPSED_LIMIT && (
+            <button
+              type="button"
+              onClick={() => setShowAll((v) => !v)}
+              className="mt-2 text-caption font-semibold text-accent transition-colors hover:text-accent/80"
+            >
+              {showAll ? t('routerDetail.workloads.collapse') : t('routerDetail.workloads.showAll', { n: items.length })}
+            </button>
+          )}
+        </>
+      )}
+
+      <p className="mt-3 text-caption text-text-muted">{t('routerDetail.workloads.source')}</p>
+    </section>
+  )
+}

+ 6 - 0
app/src/data/DataProvider.tsx

@@ -36,6 +36,7 @@ import type {
   TrafficPoint,
   VlanPort,
   MultiWanInfo,
+  WorkloadsInfo,
   WanInfo,
   WireGuardStats,
 } from '@/data/types'
@@ -107,6 +108,9 @@ export interface RouterDetailData {
   /** Las varias conexiones a internet del router, si reporta más de una.
    *  Solo lectura: las gestiona el panel del propio router. */
   multiWan?: MultiWanInfo
+  /** #2227: las cargas anidadas de un host clase hipervisor (pods de un
+   *  nodo, VMs de un hypervisor). Censo del detalle: nunca nodos del grafo. */
+  workloads?: WorkloadsInfo
   /** Salud del sondeo SNMP (#930): contadores de éxito/fallo por router.
    *  Ausente en routers que no se sondean por SNMP. */
   snmpOk?: number
@@ -1410,6 +1414,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
         vlans?: VlanPort[]
         networks?: NetworkInfo[]
         multiWan?: MultiWanInfo
+        workloads?: WorkloadsInfo
         snmpOk?: number
         snmpFail?: number
         snmpConsecFail?: number
@@ -1432,6 +1437,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
         vlans: json.vlans,
         networks: json.networks,
         multiWan: json.multiWan,
+        workloads: json.workloads,
         snmpOk: json.snmpOk,
         snmpFail: json.snmpFail,
         snmpConsecFail: json.snmpConsecFail,

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

@@ -546,6 +546,29 @@ export interface MultiWanInfo {
   uplinks: MultiWanUplink[]
 }
 
+/** One nested guest of a hypervisor-class host (#2227). id is a stable
+ *  workload UID — never a list index — so the row survives a reordering
+ *  push. kind/state arrive normalized by the producer; unrecognized
+ *  strings must render as unknown, never as running. */
+export interface WorkloadItem {
+  id: string
+  name: string
+  /** pod | vm | container | ... */
+  kind?: string
+  /** running | pending | stopped | unknown */
+  state?: string
+}
+
+/** The host's nested guests, straight from its pusher's `workloads`
+ *  section. Detail-page census data: these are never clients or graph
+ *  nodes (#2227). */
+export interface WorkloadsInfo {
+  /** Stable host/node id, when the pusher declares one. */
+  parent?: string
+  /** Empty = the host reported and runs nothing. */
+  items?: WorkloadItem[]
+}
+
 export interface VlanPort {
   port: string
   vlans: VlanEntry[]

+ 5 - 0
app/src/pages/RouterDetail.tsx

@@ -18,6 +18,7 @@ import { RouterDetailHeader } from '@/components/routers/RouterDetailHeader'
 import { RouterInfo } from '@/components/routers/RouterInfo'
 import { RouterPerformance } from '@/components/routers/RouterPerformance'
 import { MultiWanPanel } from '@/components/routers/MultiWanPanel'
+import { WorkloadsPanel } from '@/components/routers/WorkloadsPanel'
 import { WanLatency } from '@/components/routers/WanLatency'
 import { VlanPanel } from '@/components/routers/VlanPanel'
 import { NetworksPanel } from '@/components/routers/NetworksPanel'
@@ -252,6 +253,10 @@ export default function RouterDetail() {
         <MultiWanPanel info={detail.multiWan} />
       )}
 
+      {/* Las cargas anidadas de un host clase hipervisor (#2227): el censo
+          que su pusher empuja, en el detalle — nunca clientes del grafo. */}
+      {detail?.workloads && <WorkloadsPanel info={detail.workloads} />}
+
       {/* ⑤⑥ Servicios + Puertos (gateway) / Radios + Puertos (APs) */}
       {isGateway ? (
         <>

+ 1 - 0
docs/external-integrations.md

@@ -65,6 +65,7 @@ Start read-only. A useful first slice normally contains only data that already f
 - ARP through `data.arp` and `data.arpDevs`.
 - Interface counters through `data.netIf`.
 - LLDP neighbors through `data.lldp`.
+- The nested guests of a hypervisor-class host (pods, VMs, containers) through `data.workloads` (#2227).
 
 For example, a Bbox, MikroTik or UniFi integration can begin with system, WAN, wireless, DHCP and port data. Optical-line details, instant per-client rates or vendor-specific actions may need a later contract proposal.
 

+ 9 - 1
server-go/internal/adapters/agent.go

@@ -953,6 +953,14 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	if out.multiWan == nil && cached != nil {
 		out.multiWan = cached.multiWan
 	}
+	// Workloads (#2227): the nested guests a hypervisor-class pusher
+	// reports. Structural census data like multiWan, so the same
+	// anti-blink rule: a push without the section recycles the last good
+	// one instead of emptying the panel.
+	out.workloads = p.Data.Workloads
+	if out.workloads == nil && cached != nil {
+		out.workloads = cached.workloads
+	}
 	// Vlans travel in the payload too, and were being dropped here: a
 	// router polled through its agent never reached the SSH path that is
 	// the only other place they are read, so its VLAN panel stayed empty.
@@ -1147,7 +1155,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
 		wireless: out.wireless, fdb: out.fdb, fdbVlans: out.fdbVlans, networks: out.networks, wifiNet: out.wifiNet, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
-		clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
+		clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan, workloads: out.workloads}
 	l.mu.Unlock()
 
 	// Solo con un payload NUEVO alimentamos las series y el monitor de

+ 64 - 0
server-go/internal/adapters/agent_workloads_test.go

@@ -0,0 +1,64 @@
+// agent_workloads_test.go — #2227: la sección neutral `workloads` viaja en
+// el payload del pusher y aterriza en el detalle de la unidad. Un host clase
+// hipervisor (nodo RKE2, caja PVE) declara aquí sus huéspedes anidados; el
+// servidor los guarda tal cual y NO los convierte en clientes del grafo.
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestPolledFromAgentTakesWorkloadsFromPayload(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "rke2-legion", Host: "192.0.2.9", Name: "legion", AgentOnly: true},
+	}, nil)
+	payload := &probe.Payload{
+		Router: "rke2-legion", Ts: 1, Version: "rke2-pusher/0.1",
+		Data: probe.PayloadData{Workloads: &probe.Workloads{
+			Parent: "legion",
+			Items: []probe.WorkloadItem{
+				{ID: "a1b2", Name: "ingress-nginx-controller", Kind: "pod", State: "running"},
+				{ID: "c3d4", Name: "postgres-0", Kind: "pod", State: "pending"},
+			},
+		}},
+	}
+	p := l.polledFromAgent(l.routers[0], payload)
+	if p.workloads == nil || p.workloads.Parent != "legion" || len(p.workloads.Items) != 2 {
+		t.Fatalf("workloads = %+v", p.workloads)
+	}
+	if p.workloads.Items[1].State != "pending" {
+		t.Fatalf("workloads items = %+v", p.workloads.Items)
+	}
+}
+
+// Un push event-driven no trae la sección; descartarla vaciaría el panel del
+// detalle entre pushes completos, mismo contrato anti-parpadeo que multiWan.
+func TestPolledFromAgentKeepsTheLastWorkloadsSection(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "rke2-legion", Host: "192.0.2.9", Name: "legion", AgentOnly: true},
+	}, nil)
+	full := &probe.Payload{Router: "rke2-legion", Ts: 1, Data: probe.PayloadData{
+		Workloads: &probe.Workloads{Items: []probe.WorkloadItem{{ID: "a1b2", Name: "coredns", State: "running"}}},
+	}}
+	l.polledFromAgent(l.routers[0], full)
+
+	eventOnly := &probe.Payload{Router: "rke2-legion", Ts: 2, Data: probe.PayloadData{}}
+	p := l.polledFromAgent(l.routers[0], eventOnly)
+	if p.workloads == nil || len(p.workloads.Items) != 1 || p.workloads.Items[0].Name != "coredns" {
+		t.Fatalf("workloads = %+v, want the last good section", p.workloads)
+	}
+}
+
+// Un pusher viejo (o un router que no es hipervisor) no manda la sección, y
+// el detalle no gana campo: nil = nunca reportó.
+func TestPolledFromAgentWithoutWorkloadsStaysNil(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gw", Host: "192.0.2.1", Name: "gateway", AgentOnly: true},
+	}, nil)
+	p := l.polledFromAgent(l.routers[0], &probe.Payload{Router: "gw", Ts: 1, Version: "2.28.0"})
+	if p.workloads != nil {
+		t.Fatalf("workloads = %+v, want nothing", p.workloads)
+	}
+}

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

@@ -218,6 +218,11 @@ type routerPolled struct {
 	// reported (no such panel, or an older agent); an empty uplink list =
 	// reported, and there is nothing to show.
 	multiWan *MultiWanInfo
+	// workloads (#2227): the nested guests a hypervisor-class host runs, as
+	// its pusher's `workloads` section reports them. Detail-page census
+	// data only: these never become clients or graph nodes. nil = never
+	// reported.
+	workloads *WorkloadsInfo
 	// discovery: mDNS services + randomized MACs (#338). nil = sin datos
 	// (umdns no instalado o sonda fallida).
 	discovery *probe.DiscoveryData
@@ -264,6 +269,10 @@ type extrasSnapshot struct {
 	// the page every time a device associates. Unlike wanInfo, which is a
 	// live address and must never be recycled, this is structural.
 	multiWan *MultiWanInfo
+	// workloads: last good `workloads` section (#2227). Same anti-blink
+	// rule as multiWan: it only ever arrives in a full push, and an
+	// event-driven push without it must not empty the panel.
+	workloads *WorkloadsInfo
 	// system (#441): última sección system BUENA del payload del agente.
 	// Los pushes event-driven (wireless-only) van sin ella; sin este cache
 	// las vitales del router parpadeaban a 0 entre pushes completos.
@@ -5317,10 +5326,15 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	if p != nil {
 		multiWan = p.multiWan
 	}
+	var workloads *WorkloadsInfo
+	if p != nil {
+		workloads = p.workloads
+	}
 	detail := &RouterDetail{
 		Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
 		Series:  PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
 		Clients: clients, Extras: extras, Vlans: vlans, Networks: networks, MultiWan: multiWan,
+		Workloads: workloads,
 	}
 	// #930: contadores de salud SNMP del router (solo si se sondea por SNMP).
 	if cfg.SnmpEnabled {

+ 2 - 0
server-go/internal/adapters/openwrt.go

@@ -124,6 +124,8 @@ type (
 	WanUplink       = probe.WanUplink
 	VlanEntry       = probe.VlanEntry
 	DhcpReservation = probe.DhcpReservation
+	WorkloadsInfo   = probe.Workloads
+	WorkloadItem    = probe.WorkloadItem
 )
 
 // NewOpenWrtClient crea el cliente de un router.

+ 6 - 0
server-go/internal/adapters/types.go

@@ -813,6 +813,12 @@ type RouterDetail struct {
 	// the router never reported any; an empty uplink list = it reported
 	// and there is nothing to show, which is what removes the panel.
 	MultiWan *MultiWanInfo `json:"multiWan,omitempty"`
+	// Workloads (#2227): the nested guests a hypervisor-class host runs,
+	// straight from its pusher's `workloads` section — census for the
+	// detail page, never clients or graph nodes. nil = the unit never
+	// reported the section; an empty item list = it reported, and runs
+	// nothing.
+	Workloads *WorkloadsInfo `json:"workloads,omitempty"`
 	// --- salud del sondeo SNMP (#930): solo routers sondeados por SNMP ---
 	// Contadores de éxito/fallo del poll SNMP por router (omitempty: ausente
 	// en routers que no se sondean por SNMP).