소스 검색

feat(topology): let a switch override say where it hangs (#2179) (#2280)

Nacho 1 일 전
부모
커밋
da4ebead41

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- A manual topology override of kind `switch` can now say where the switch hangs: pick `switch` and either the unit and port (`routerId:port`) or the device it sits behind. Before, the switch was placed only where its MAC had been learned, so a switch with no FDB entry yet, or one behind another switch, could not be put anywhere. `routerId:port` sets its place and the managed node appears on that port with the rest of the port nested under it; a device or a unit hangs the switch without inventing a node. The parent stays optional and `attach` and `facet` still require it (#2179).
 - The client detail lists every name a source proposes for that client, not only the one in use: DHCP hostname, reservation, known-MAC alias, manual override, GL.iNet, mDNS and reverse DNS, in the precedence order the server follows, without duplicate values. The name in use stays highlighted. This is the evidence a global source preference and a per-client choice will need, and it answers the request to see all candidates now; selection does not change yet (#2163).
 - The client list and the device detail show the VLAN a device sits on when a source resolves it (the bridge FDB for wired and bridged clients, the `tag=` of a Proxmox guest), and the detail keeps the difference between "no VLAN known" and "not in any VLAN". The identity was already MAC-based, so a device that moves between VLANs keeps its row and the badge follows; what was missing was the number on screen. The topology already coloured chips by VLAN, this closes the same gap in the list (#2178).
 - The native agent fills the WAN IPv6 it already had in hand: `ipv6-address` comes in the same ubus dump as the IPv4, and the parser now publishes the first global address (link-local and ULA skipped, a deprecated address only when nothing else is left) in `data.wan.ipv6`. A modem uplink gets it from the child netifd creates for it, and an uplink with no IPv4 still reports its v6. The SSH poller shares the parser, so both paths gain it at once, and a router without v6 keeps the field absent (#2275).

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

@@ -2109,6 +2109,7 @@
       "kindFacet": "Facet",
       "parent": "Attach to",
       "parentPlaceholder": "Select target…",
+      "parentSwitchHint": "Optional: the unit and port, or the device, it hangs from. Without it, the switch goes where its MAC is learned.",
       "parentRouters": "Units",
       "parentPorts": "Ports",
       "parentDevices": "Clients",

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

@@ -2109,6 +2109,7 @@
       "kindFacet": "Faceta",
       "parent": "Dónde cuelga",
       "parentPlaceholder": "Selecciona destino…",
+      "parentSwitchHint": "Opcional: la unidad y el puerto, o el equipo, del que cuelga. Sin esto, el switch va donde se aprende su MAC.",
       "parentRouters": "Unidades",
       "parentPorts": "Puertos",
       "parentDevices": "Clientes",

+ 1 - 0
app/public/locales/ru/translation.json

@@ -2133,6 +2133,7 @@
       "kindFacet": "Грань",
       "parent": "Привязать к",
       "parentPlaceholder": "Выберите цель…",
+      "parentSwitchHint": "Необязательно: устройство и порт, или сам хост, к которому он подключён. Без этого switch встаёт там, где видна его MAC.",
       "parentRouters": "Устройства",
       "parentPorts": "Порты",
       "parentDevices": "Клиенты",

+ 1 - 0
app/public/locales/zh/translation.json

@@ -1765,6 +1765,7 @@
       "kindFacet": "切面",
       "parent": "附加到",
       "parentPlaceholder": "选择目标…",
+      "parentSwitchHint": "可选:所连接的设备与端口,或所连接的设备。留空时,交换机放在学到它 MAC 的位置。",
       "parentRouters": "设备",
       "parentPorts": "端口",
       "parentDevices": "客户端",

+ 30 - 9
app/src/components/topology/TopologyOverridesManager.tsx

@@ -27,6 +27,17 @@ interface OverrideDraft {
   parent: string
 }
 
+/** #2179: el parent lo usan attach y facet (obligatorio) y switch (opcional,
+ * para decir de donde cuelga). hypervisor lo deriva de su propio puerto. */
+function parentApplies(kind: TopologyOverrideKind): boolean {
+  return kind === 'attach' || kind === 'facet' || kind === 'switch'
+}
+
+/** Obligatorio solo donde sin padre no hay nada que hacer. */
+function parentRequired(kind: TopologyOverrideKind): boolean {
+  return kind === 'attach' || kind === 'facet'
+}
+
 const EMPTY: OverrideDraft = { mac: '', kind: 'hypervisor', name: '', parent: '' }
 
 const KIND_STYLE: Record<TopologyOverrideKind, string> = {
@@ -178,7 +189,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
           mac: draft.mac.trim(),
           kind: draft.kind,
           name: draft.name.trim() || undefined,
-          parent: draft.kind === 'attach' || draft.kind === 'facet' ? draft.parent.trim() || undefined : undefined,
+          parent: parentApplies(draft.kind) ? draft.parent.trim() || undefined : undefined,
         }),
       })
       if (!res.ok) throw new Error(`HTTP ${res.status}`)
@@ -212,7 +223,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
         body: JSON.stringify({
           kind: editDraft.kind,
           name: editDraft.name.trim() || undefined,
-          parent: editDraft.kind === 'attach' || editDraft.kind === 'facet' ? editDraft.parent.trim() || undefined : undefined,
+          parent: parentApplies(editDraft.kind) ? editDraft.parent.trim() || undefined : undefined,
         }),
       })
       if (!res.ok) throw new Error(`HTTP ${res.status}`)
@@ -301,7 +312,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
                   >
                     {t(`settings.overrides.kind.${o.kind}`)}
                   </span>
-                  {(o.kind === 'attach' || o.kind === 'facet') && o.parent && (
+                  {parentApplies(o.kind) && o.parent && (
                     <span className="truncate font-mono text-caption text-text-muted">→ {o.parent}</span>
                   )}
                 </div>
@@ -393,8 +404,13 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               onChange={(v) => setDraft((d) => ({ ...d, kind: v }))}
               ariaLabel={t('settings.overrides.kind')}
             />
-            {(draft.kind === 'attach' || draft.kind === 'facet') && (
-              <ParentPicker value={draft.parent} onChange={(v) => setDraft((d) => ({ ...d, parent: v }))} />
+            {parentApplies(draft.kind) && (
+              <div>
+                <ParentPicker value={draft.parent} onChange={(v) => setDraft((d) => ({ ...d, parent: v }))} />
+                {draft.kind === 'switch' && (
+                  <span className="mt-1 block text-caption text-text-muted">{t('settings.overrides.parentSwitchHint')}</span>
+                )}
+              </div>
             )}
             {/* #1982: dos botones "+Add" (el de abrir y el de guardar)
                 dejaban la duda de cual aplicaba y no habia salida explicita.
@@ -413,7 +429,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               </button>
               <button
                 type="submit"
-                disabled={submitting || !draft.mac.trim() || ((draft.kind === 'attach' || draft.kind === 'facet') && !draft.parent.trim())}
+                disabled={submitting || !draft.mac.trim() || (parentRequired(draft.kind) && !draft.parent.trim())}
                 className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-medium text-canvas transition-opacity duration-150 hover:opacity-90 disabled:opacity-40"
               >
                 <Check className="h-4 w-4" strokeWidth={2} />
@@ -448,8 +464,13 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               onChange={(v) => setEditDraft((d) => ({ ...d, kind: v }))}
               ariaLabel={t('settings.overrides.kind')}
             />
-            {(editDraft.kind === 'attach' || editDraft.kind === 'facet') && (
-              <ParentPicker value={editDraft.parent} onChange={(v) => setEditDraft((d) => ({ ...d, parent: v }))} />
+            {parentApplies(editDraft.kind) && (
+              <div>
+                <ParentPicker value={editDraft.parent} onChange={(v) => setEditDraft((d) => ({ ...d, parent: v }))} />
+                {editDraft.kind === 'switch' && (
+                  <span className="mt-1 block text-caption text-text-muted">{t('settings.overrides.parentSwitchHint')}</span>
+                )}
+              </div>
             )}
             <div className="flex items-center justify-end gap-2">
               <button
@@ -461,7 +482,7 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
               </button>
               <button
                 type="submit"
-                disabled={editSubmitting || ((editDraft.kind === 'attach' || editDraft.kind === 'facet') && !editDraft.parent.trim())}
+                disabled={editSubmitting || (parentRequired(editDraft.kind) && !editDraft.parent.trim())}
                 className="flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-medium text-canvas transition-opacity duration-150 hover:opacity-90 disabled:opacity-40"
               >
                 <Pencil className="h-4 w-4" strokeWidth={2} />

+ 33 - 1
server-go/internal/adapters/topology_override.go

@@ -195,7 +195,9 @@ func applyTopologyOverrides(routers []Router, devices []Device, dists []Distribu
 	}
 
 	// 2) switch: el puerto del target → distnode managed; el resto del puerto
-	//    se anida bajo él.
+	//    se anida bajo él. #2179: si el override trae parent, manda sobre la
+	//    evidencia: "router:puerto" fija el sitio (y por tanto el distnode),
+	//    una MAC o un id de router lo cuelgan cuando no hay puerto aprendido.
 	for _, ov := range overrides {
 		if !ov.Enabled || ov.Kind != "switch" {
 			continue
@@ -206,7 +208,37 @@ func applyTopologyOverrides(routers []Router, devices []Device, dists []Distribu
 		}
 		sw := &devices[idx]
 		sw.Infra = "managed-switch"
+		attached := ""
+		if p := strings.TrimSpace(ov.Parent); p != "" {
+			pkind, pRouter, pPort, pMAC := parseParentRef(p)
+			switch pkind {
+			case parentRefPort:
+				if routerByID[pRouter] {
+					// Intención explícita del admin: el switch se dibuja en
+					// ese puerto de esa unidad aunque el FDB aún no lo haya
+					// aprendido ahí.
+					sw.RouterID = pRouter
+					sw.Port = pPort
+				}
+			case parentRefRouter:
+				if routerByID[pRouter] {
+					attached = pRouter
+					if sw.RouterID == "" {
+						sw.RouterID = pRouter
+					}
+				}
+			case parentRefMAC:
+				if pIdx, ok := byMAC[pMAC]; ok {
+					attached = devices[pIdx].ID
+				}
+			}
+		}
 		if sw.Port == "" {
+			// Sin puerto no hay distnode que dibujar; el parent, si lo hay, al
+			// menos deja el switch colgando de donde el admin dijo.
+			if attached != "" {
+				sw.AttachTo = attached
+			}
 			continue
 		}
 		id := fmt.Sprintf("dist-%s-%s", sw.RouterID, sw.Port)

+ 66 - 0
server-go/internal/adapters/topology_override_test.go

@@ -416,3 +416,69 @@ func TestParseParentRefMACOnlyWithColons(t *testing.T) {
 		t.Fatalf("esperaba VM anidada bajo host con parent en minúsculas, got %+v", out[1])
 	}
 }
+
+// #2179: un switch manual sin puerto aprendido se coloca diciendo de dónde
+// cuelga. "router:puerto" fija el sitio y el distnode managed sale en ese
+// puerto, con el resto de la boca anidada debajo.
+func TestApplySwitchOverrideConParentPuerto(t *testing.T) {
+	devices := []Device{
+		devOverride("switch-manual", "aa:bb:cc:00:00:01", "rtr1", ""),
+		devOverride("d1", "00:00:00:00:00:01", "rtr1", "lan4"),
+		devOverride("d2", "00:00:00:00:00:02", "rtr1", "lan4"),
+	}
+	routers := []Router{{ID: "rtr1"}}
+	overrides := []TopologyOverride{
+		{Kind: "switch", MAC: "aa:bb:cc:00:00:01", Name: "switch-garaje", Parent: "rtr1:lan4", Enabled: true},
+	}
+	out, dists := applyTopologyOverrides(routers, devices, nil, overrides)
+	byID := map[string]Device{}
+	for _, d := range out {
+		byID[d.ID] = d
+	}
+	if byID["switch-manual"].Infra != "managed-switch" || byID["switch-manual"].Port != "lan4" {
+		t.Fatalf("el parent no colocó el switch: %+v", byID["switch-manual"])
+	}
+	if len(dists) != 1 || dists[0].Kind != "managed" || dists[0].Port != "lan4" || dists[0].RouterID != "rtr1" {
+		t.Fatalf("distnode managed inesperado: %+v", dists)
+	}
+	if byID["d1"].AttachTo != dists[0].ID || byID["d2"].AttachTo != dists[0].ID {
+		t.Fatalf("los vecinos del puerto no cuelgan del switch: %+v %+v", byID["d1"], byID["d2"])
+	}
+}
+
+// #2179: sin puerto que aprender, una MAC padre deja el switch colgando de ese
+// equipo (nada de distnode inventado).
+func TestApplySwitchOverrideConParentMAC(t *testing.T) {
+	devices := []Device{
+		devOverride("host", "c8:ff:bf:08:6f:ba", "rtr1", "lan4"),
+		devOverride("switch-manual", "aa:bb:cc:00:00:01", "rtr1", ""),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "switch", MAC: "aa:bb:cc:00:00:01", Parent: "C8:FF:BF:08:6F:BA", Enabled: true},
+	}
+	out, dists := applyTopologyOverrides(nil, devices, nil, overrides)
+	byID := map[string]Device{}
+	for _, d := range out {
+		byID[d.ID] = d
+	}
+	if byID["switch-manual"].AttachTo != "host" || byID["switch-manual"].Infra != "managed-switch" {
+		t.Fatalf("el switch no quedó colgado del host: %+v", byID["switch-manual"])
+	}
+	if len(dists) != 0 {
+		t.Fatalf("no debía inventarse distnode sin puerto: %+v", dists)
+	}
+}
+
+// #2179: el parent de un switch es opcional; sin él se comporta como antes.
+func TestApplySwitchOverrideSinParentNoCambia(t *testing.T) {
+	devices := []Device{
+		devOverride("switch-manual", "aa:bb:cc:00:00:01", "rtr1", "lan2"),
+	}
+	overrides := []TopologyOverride{
+		{Kind: "switch", MAC: "aa:bb:cc:00:00:01", Enabled: true},
+	}
+	out, dists := applyTopologyOverrides(nil, devices, nil, overrides)
+	if out[0].Port != "lan2" || len(dists) != 1 || dists[0].Port != "lan2" {
+		t.Fatalf("sin parent debe seguir el puerto del FDB: %+v %+v", out[0], dists)
+	}
+}

+ 9 - 7
server-go/internal/httpapi/topology_override.go

@@ -48,17 +48,19 @@ func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Req
 		writeError(w, http.StatusBadRequest, "invalid_kind")
 		return
 	}
-	// parent (solo kind=attach) acepta: MAC de device (formato original),
-	// id de router, o "routerId:puerto" (issue #690). La store lo normaliza
-	// (adapters.NormalizeParentRef) al guardarlo.
-	// kind=facet (NETPULSE-ONE-LEGION): parent es SIEMPRE la MAC del device
-	// anfitrión; el target (mac) es el id del agente (slug, ruta #1485).
-	if body.Kind == "attach" || body.Kind == "facet" {
+	// parent: obligatorio en attach y facet. En switch es opcional y dice de
+	// dónde cuelga el switch (#2179): "routerId:puerto" fija el puerto donde
+	// se aprende, y una MAC o un id de router lo cuelgan sin depender de la
+	// evidencia del FDB. En hypervisor se ignora: su sitio sale de su puerto.
+	switch body.Kind {
+	case "attach", "facet":
 		if strings.TrimSpace(body.Parent) == "" {
 			writeError(w, http.StatusBadRequest, "attach_requires_parent")
 			return
 		}
-	} else {
+	case "switch":
+		// parent opcional, tal cual venga
+	default:
 		body.Parent = ""
 	}
 	o, err := topooverride.Add(s.db.DB, topooverride.AddInput{

+ 38 - 0
server-go/internal/httpapi/topology_override_test.go

@@ -87,3 +87,41 @@ func TestTopologyOverrideCreateNormalizesAndValidatesMAC(t *testing.T) {
 		t.Errorf("MAC vacía: esperaba 400, got %d", rec.Code)
 	}
 }
+
+// #2179: un switch puede decir de dónde cuelga. El parent es opcional ahí
+// (antes se descartaba) y sigue siendo obligatorio en attach y facet.
+func TestTopologyOverrideSwitchKeepsParent(t *testing.T) {
+	s := newOverrideTestServer(t)
+
+	post := func(body string) *httptest.ResponseRecorder {
+		t.Helper()
+		req := httptest.NewRequest(http.MethodPost, "/api/topology/overrides", strings.NewReader(body))
+		req.Header.Set("Content-Type", "application/json")
+		rec := httptest.NewRecorder()
+		s.handleTopologyOverrideCreate(rec, req)
+		return rec
+	}
+
+	rec := post(`{"mac":"aa:bb:cc:dd:ee:10","kind":"switch","parent":"rtr1:lan4"}`)
+	if rec.Code != http.StatusCreated {
+		t.Fatalf("switch con parent: esperaba 201, got %d: %s", rec.Code, rec.Body.String())
+	}
+	var resp struct {
+		Override adapters.TopologyOverride `json:"override"`
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+		t.Fatalf("decodificar: %v", err)
+	}
+	if resp.Override.Parent != "rtr1:lan4" {
+		t.Fatalf("el parent del switch se perdió: %q", resp.Override.Parent)
+	}
+
+	// Opcional: un switch sin parent se acepta.
+	if rec := post(`{"mac":"aa:bb:cc:dd:ee:11","kind":"switch"}`); rec.Code != http.StatusCreated {
+		t.Fatalf("switch sin parent: esperaba 201, got %d", rec.Code)
+	}
+	// En attach el parent sigue siendo obligatorio.
+	if rec := post(`{"mac":"aa:bb:cc:dd:ee:12","kind":"attach"}`); rec.Code != http.StatusBadRequest {
+		t.Fatalf("attach sin parent: esperaba 400, got %d", rec.Code)
+	}
+}