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

feat(snmp): group virtual interfaces instead of hiding them (#1142)

Follow-up to #1115, requested in #1125.

Dropping LAG/VLAN/bridge/tunnel interfaces from the ports card hid
information and broke the mental model of the switch: FDB and LLDP entries
referencing their ifIndex resolved to generated names, and an AP-only view
of a switch with LAGs was incomplete. The ifTable walk now keeps every
interface and tags the non-physical ones with their family (lag, vlan,
bridge, tunnel, virtual). The ports card still renders only physical jacks
in the chassis, with a collapsed-by-default "Virtual interfaces (N)"
group below (state persisted), each row labeled by family. FDB/LLDP
resolution now names virtual ports properly instead of falling back to
port-N. The exclusion-based defense for failed walks is preserved: an
unreported ifType stays in the physical group.

Verified against the real Linksys LGS310C: 10 physical jacks plus po1-8
(LAG) and vlan1 (VLAN) listed in the collapsed group. Full suite 48/48.

Closes #1125
Nacho 2 месяцев назад
Родитель
Сommit
b215b2359b

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

@@ -874,7 +874,13 @@
       "detailRouterLinkLldp": "link between routers · LLDP",
       "detailApWifi": "WiFi client behind",
       "detailMac": "MAC {{mac}}",
-      "inferredSwitch": "Switch"
+      "inferredSwitch": "Switch",
+      "virtualGroup": "Virtual interfaces ({{count}})",
+      "fam_lag": "LAG",
+      "fam_vlan": "VLAN",
+      "fam_bridge": "Bridge",
+      "fam_tunnel": "Tunnel",
+      "fam_virtual": "Virtual"
     },
     "radios": {
       "channel": "Channel",

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

@@ -874,7 +874,13 @@
       "detailRouterLinkLldp": "enlace entre routers · LLDP",
       "detailApWifi": "cliente WiFi detrás",
       "detailMac": "MAC {{mac}}",
-      "inferredSwitch": "Switch"
+      "inferredSwitch": "Switch",
+      "virtualGroup": "Interfaces virtuales ({{count}})",
+      "fam_lag": "LAG",
+      "fam_vlan": "VLAN",
+      "fam_bridge": "Bridge",
+      "fam_tunnel": "Túnel",
+      "fam_virtual": "Virtual"
     },
     "radios": {
       "channel": "Canal",

+ 66 - 2
app/src/components/routers/PortPanel.tsx

@@ -1,4 +1,5 @@
 import { motion, useReducedMotion } from 'framer-motion'
+import { useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import type { Router } from '@/data/mock'
@@ -7,7 +8,7 @@ import { SectionHeader } from '@/components/SectionHeader'
 import { getRouterExtras, portPeerDetail, portPeerLabel } from '@/components/routers/routerExtras'
 import type { EthPort, RouterExtras, SfpInfo } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
-import { Activity, Network } from 'lucide-react'
+import { Activity, ChevronDown, ChevronRight, Network } from 'lucide-react'
 import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
@@ -287,6 +288,17 @@ function MiniStat({ label, value }: { label: string; value: string }) {
   )
 }
 
+// FAMILY_LABEL_KEY (#1125): familia ifType (IANA) -> clave i18n de la
+// etiqueta del grupo de interfaces virtuales. Cerrado: el server solo emite
+// estas cinco ("lag"|"vlan"|"bridge"|"tunnel"|"virtual").
+const FAMILY_LABEL_KEY: Record<string, string> = {
+  lag: 'routerDetail.ports.fam_lag',
+  vlan: 'routerDetail.ports.fam_vlan',
+  bridge: 'routerDetail.ports.fam_bridge',
+  tunnel: 'routerDetail.ports.fam_tunnel',
+  virtual: 'routerDetail.ports.fam_virtual',
+}
+
 export function PortPanel({ router, extras, className, snmpStats }: {
   router: Router
   extras?: RouterExtras
@@ -296,7 +308,18 @@ export function PortPanel({ router, extras, className, snmpStats }: {
   const { t } = useTranslation()
   const { isDemo, wan } = useNetPulse()
   const ex = extras ?? (isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS)
-  const ports = ex.ethPorts
+  // #1125: las interfaces no físicas (LAG/VLAN/bridge/túnel/virtual) ya no se
+  // descartan (#1115): se listan en la sección colapsada de abajo. El chasis
+  // y el contador usados/total solo cuentan bocas físicas.
+  const ports = ex.ethPorts.filter((p) => !p.family)
+  const virtualPorts = ex.ethPorts.filter((p) => p.family)
+  const [virtualOpen, setVirtualOpen] = useState(() => localStorage.getItem('np-ports-virtual-open') === '1')
+  const toggleVirtual = () =>
+    setVirtualOpen((v) => {
+      const next = !v
+      localStorage.setItem('np-ports-virtual-open', next ? '1' : '0')
+      return next
+    })
   const used = ports.filter((p) => p.up).length
   const wirelessUplink = ex.backhaul?.kind === 'wireless'
 
@@ -358,6 +381,47 @@ export function PortPanel({ router, extras, className, snmpStats }: {
           </span>
         )}
       </div>
+
+      {/* #1125: las interfaces no físicas (LAG/VLAN/bridge/túnel) se listan
+          aquí, agrupadas y colapsadas por defecto, en vez de desaparecer de
+          la tarjeta (#1115): nada se oculta y el chasis queda limpio. El
+          estado plegado se recuerda. */}
+      {virtualPorts.length > 0 && (
+        <div className="mt-4 rounded-xl border border-border/70 bg-elevated/40">
+          <button
+            type="button"
+            onClick={toggleVirtual}
+            aria-expanded={virtualOpen}
+            className="flex w-full cursor-pointer items-center gap-2 px-4 py-2.5 text-caption font-medium text-text-secondary transition-colors hover:text-text-primary"
+          >
+            {virtualOpen ? (
+              <ChevronDown className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            ) : (
+              <ChevronRight className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            )}
+            {t('routerDetail.ports.virtualGroup', { count: virtualPorts.length })}
+          </button>
+          {virtualOpen && (
+            <ul className="border-t border-border/60 px-4 py-2">
+              {virtualPorts.map((p) => (
+                <li key={p.id} className="flex items-center gap-3 py-1.5 text-caption">
+                  <span className="inline-flex w-16 shrink-0 justify-center rounded border border-border px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wide text-text-muted">
+                    {t(FAMILY_LABEL_KEY[p.family ?? ''] ?? 'routerDetail.ports.fam_virtual', { defaultValue: p.family })}
+                  </span>
+                  <span className="truncate font-mono text-mono-sm text-text-primary">{p.label}</span>
+                  <span className="ml-auto inline-flex shrink-0 items-center gap-2">
+                    {p.speed && <span className="text-text-muted">{p.speed}</span>}
+                    <span
+                      className={p.up ? 'h-1.5 w-1.5 rounded-full bg-ok' : 'h-1.5 w-1.5 rounded-full bg-border-strong/50'}
+                      title={p.up ? t('routerDetail.ports.inUse') : t('routerDetail.ports.free')}
+                    />
+                  </span>
+                </li>
+              ))}
+            </ul>
+          )}
+        </div>
+      )}
     </section>
   )
 }

+ 4 - 0
app/src/components/routers/routerExtras.ts

@@ -70,6 +70,10 @@ export interface EthPort {
   up: boolean
   speed?: string // "2.5 Gbps" | "1 Gbps"
   iface?: string // interfaz física (/proc/net/dev), si difiere del id
+  /** #1125: familia para interfaces NO físicas ("lag"|"vlan"|"bridge"|
+   * "tunnel"|"virtual"); ausente = boca física. La tarjeta las agrupa en
+   * la sección colapsada en vez de ocultarlas (#1115). */
+  family?: string
   rxBytes?: number // contadores acumulados de la boca (#305)
   txBytes?: number
   rxErrors?: number

+ 1 - 0
server-go/internal/adapters/snmp_live.go

@@ -123,6 +123,7 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 			Up:      p.OperUp,
 			Speed:   p.SpeedString(),
 			Iface:   name,
+			Family:  p.Family,
 			RxBytes: p.RxBytes,
 			TxBytes: p.TxBytes,
 			RxErrs:  p.RxErrors,

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

@@ -561,6 +561,10 @@ type EthPort struct {
 	Up          bool     `json:"up"`
 	Speed       string   `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
 	Iface       string   `json:"iface,omitempty"` // iface física (/proc/net/dev)
+	// #1125: familia para interfaces NO físicas ("lag"|"vlan"|"bridge"|
+	// "tunnel"|"virtual"); vacío/ausente = boca física. El frontend las
+	// agrupa en la sección colapsada de la tarjeta de puertos.
+	Family      string   `json:"family,omitempty"`
 	RxBytes     uint64   `json:"rxBytes,omitempty"`
 	TxBytes     uint64   `json:"txBytes,omitempty"`
 	RxErrs      uint64   `json:"rxErrors,omitempty"`

+ 26 - 25
server-go/internal/snmp/ifTable.go

@@ -14,6 +14,12 @@ type PortStats struct {
 	Descr      string
 	Alias      string
 	Type       int
+	// Familia de la interfaz para las NO físicas (#1125): "lag", "vlan",
+	// "bridge", "tunnel" o "virtual". Vacío = boca física (o ifType no
+	// reportado por walk fallido: se conserva en el grupo físico, la misma
+	// defensa de la #1115). El frontend las agrupa colapsadas al pie de la
+	// tarjeta de puertos en vez de ocultarlas.
+	Family     string
 	SpeedBps   uint64
 	HighSpeedMbps uint32
 	OperUp     bool
@@ -88,39 +94,34 @@ func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
 	}
 	out := make([]PortStats, 0, len(byIdx))
 	for _, ps := range byIdx {
+		ps.Family = ifFamily(ps.Type)
 		out = append(out, *ps)
 	}
 	sortByIndex(out)
-	return physicalIfPorts(out), nil
+	return out, nil
 }
 
-// nonPhysicalIfTypes: ifTypes (IANA) que NO son una boca física del switch
-// y no deben aparecer en la tarjeta de puertos (#1115): interfaces LAG,
-// VLANs, loopbacks, bridges y túneles. Verificado en un Linksys LGS310C
+// nonPhysicalIfTypeFamilies: ifTypes (IANA) que NO son una boca física del
+// switch, con su familia para el grupo colapsado de la tarjeta (#1125,
+// alternativa a ocultarlas de la #1115: nada se pierde y las referencias
+// FDB/LLDP por ifIndex siguen resolviendo). Verificado en un Linksys LGS310C
 // real: po1-8 llegan como ieee8023adLag(161) y vlan1 como l3ipvlan(136).
-var nonPhysicalIfTypes = map[int]bool{
-	24:  true, // softwareLoopback
-	53:  true, // propVirtual
-	131: true, // tunnel
-	135: true, // l2vlan
-	136: true, // l3ipvlan
-	161: true, // ieee8023adLag
-	209: true, // bridge
+// Todo ifType que NO esté en el mapa (incluido Type=0 por walk fallido) se
+// trata como físico: la defensa por exclusión de la #1115 se conserva.
+var nonPhysicalIfTypeFamilies = map[int]string{
+	24:  "virtual", // softwareLoopback
+	53:  "virtual", // propVirtual
+	131: "tunnel",  // tunnel
+	135: "vlan",    // l2vlan
+	136: "vlan",    // l3ipvlan
+	161: "lag",     // ieee8023adLag
+	209: "bridge",  // bridge
 }
 
-// physicalIfPorts descarta las interfaces no físicas del ifTable (#1115).
-// Filtra por EXCLUSIÓN y no por "solo ethernetCsmacd": un switch que no
-// reporte ifType (Type=0 por walk fallido) conserva todos sus puertos en
-// lugar de quedarse a cero.
-func physicalIfPorts(ports []PortStats) []PortStats {
-	out := ports[:0]
-	for _, p := range ports {
-		if nonPhysicalIfTypes[p.Type] {
-			continue
-		}
-		out = append(out, p)
-	}
-	return out
+// ifFamily clasifica una interfaz por su ifType: "" = física (o desconocida),
+// en otro caso la familia del grupo virtual (#1125).
+func ifFamily(t int) string {
+	return nonPhysicalIfTypeFamilies[t]
 }
 
 func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {

+ 26 - 24
server-go/internal/snmp/snmp_test.go

@@ -217,30 +217,32 @@ func TestSortByIndex(t *testing.T) {
 	}
 }
 
-// #1115: la tarjeta de puertos solo lista bocas físicas. Verificado en un
-// LGS310C real: po1-8 (ieee8023adLag) y vlan1 (l3ipvlan) fuera; las 10
-// ethernetCsmacd dentro. El filtro es por exclusión: un switch que no
-// reporta ifType (Type=0) conserva sus puertos.
-func TestPhysicalIfPorts(t *testing.T) {
-	in := []PortStats{
-		{Index: 1, Name: "Slot0/1", Type: 6},
-		{Index: 10, Name: "Slot0/10", Type: 6},
-		{Index: 53, Name: "po1", Type: 161},
-		{Index: 61, Name: "vlan1", Type: 136},
-		{Index: 70, Name: "br0", Type: 209},
-		{Index: 71, Name: "lo", Type: 24},
-		{Index: 72, Name: "tun0", Type: 131},
-		{Index: 73, Name: "vlan2", Type: 135},
-		{Index: 74, Name: "mgmt", Type: 53},
-		{Index: 80, Name: "weird0", Type: 0}, // sin ifType reportado: se conserva
-	}
-	got := physicalIfPorts(in)
-	if len(got) != 3 {
-		t.Fatalf("esperaba 3 puertos físicos, obtuve %d: %+v", len(got), got)
-	}
-	for i, want := range []int{1, 10, 80} {
-		if got[i].Index != want {
-			t.Fatalf("puerto %d: Index %d, esperaba %d", i, got[i].Index, want)
+// #1125 (alternativa a la exclusión de la #1115): el ifTable conserva TODAS
+// las interfaces y cada una se clasifica por familia; las no físicas (LAG,
+// VLAN, bridge, túnel, virtual) van al grupo colapsado de la tarjeta en el
+// frontend en vez de desaparecer. Verificado en un LGS310C real: po1-8
+// (ieee8023adLag) y vlan1 (l3ipvlan) clasificados; un ifType no listado o no
+// reportado (Type=0 por walk fallido) sigue siendo físico (defensa #1115).
+func TestIfFamilyClassification(t *testing.T) {
+	cases := []struct {
+		typ    int
+		family string
+	}{
+		{6, ""},          // ethernetCsmacd: física
+		{117, ""},        // gigabitEthernet: física
+		{161, "lag"},     // ieee8023adLag (LGS310C poN)
+		{136, "vlan"},    // l3ipvlan (LGS310C vlan1)
+		{135, "vlan"},    // l2vlan
+		{209, "bridge"},  // bridge
+		{131, "tunnel"},  // tunnel
+		{24, "virtual"},  // softwareLoopback
+		{53, "virtual"},  // propVirtual
+		{0, ""},          // sin ifType: físico (walk fallido conserva todo)
+		{9999, ""},       // desconocido: se trata como físico por exclusión
+	}
+	for _, c := range cases {
+		if got := ifFamily(c.typ); got != c.family {
+			t.Errorf("ifFamily(%d) = %q, esperaba %q", c.typ, got, c.family)
 		}
 	}
 }