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

fix(wireguard): tolerate per-interface failures in the poll (#714) (#726)

After #713 the WireGuard poll lists the interfaces and dumps each one,
but any single failure aborted the whole aggregation and left the panel
inactive, logging 'WireGuard no disponible' every tick. A dump failure
now skips that interface and the others still report; if wg show
interfaces is not supported it falls back to wg0, and if no interface
responds the result is inactive without an error.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
adbc4b468d
3 измененных файлов с 89 добавлено и 20 удалено
  1. 1 0
      CHANGELOG.md
  2. 23 12
      server-go/internal/adapters/wireguard.go
  3. 65 8
      server-go/internal/adapters/wireguard_test.go

+ 1 - 0
CHANGELOG.md

@@ -23,6 +23,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- **El sondeo de WireGuard ya no se cae entero si falla una interfaz o el listado (#714)**: con el sondeo multi-interfaz (#713) un solo `wg show <iface> dump` que salía con status 1 (interfaz caída o inaccesible) abortaba toda la agregación y dejaba el panel WireGuard en "inactivo" permanente, logueando "no disponible" en cada tick. Ahora el fallo de una interfaz se salta y se agregan los peers de las que responden; si `wg show interfaces` no está soportado (o falla), se cae al default histórico `wg0`; y si ninguna interfaz responde, el panel muestra el túnel inactivo sin loguear error en cada tick.
 - **El feed de alertas ya no muestra español para los tipos que faltaban por migrar (#712)**: los emisores que seguían generando literales sin `type`/`vars` (recuperaciones de agente, router y puerto, acceso SSH perdido/recuperado, handshake de WireGuard, los eventos del beacon del switch, el diagnóstico SFP y el auto-rearme) llevan ahora su slug estable y sus variables, y el frontend traduce el título y la descripción en el idioma del usuario. Los literales se mantienen como respaldo y el dedup/silence (que usan el título) no cambian.
 - **Los clientes cableados y callados de un AP puente ya no vuelven a colgarse del router principal (#694)**: la clasificación de los puertos de subida (uplink) se calculaba cada tick solo con las MACs de bridge presentes en ese sondeo, así que un cliente callado cuya brMac ya no estaba en el FDB del gateway acababa atribuido al principal por dos vías transitorias (el FDB del gateway y el fallback ARP, que gana por orden alfabético). Ahora el servidor recuerda los puertos que alguna vez aprendieron la MAC de bridge de otro router (la clasificación de uplink persiste entre ticks y sobrevive a sondeos fallidos), el gateway no pisa la memoria de boca de un satélite en un puerto de uplink, y la memoria de puerto se refresca mientras el dispositivo siga online por ARP/lease aunque no hable por FDB. Además, `GetBridgeFdb` devuelve `nil` ante un fallo de sonda para no sustituir la caché anti-parpadeo por un FDB vacío.
 - **Las notificaciones push de alertas se traducen al idioma del dispositivo (#689)**: el payload viajaba con los literales en español, así que un usuario con la app en inglés recibía los avisos en español. Ahora el server añade el slug del tipo y sus variables (`type`/`vars`) y el service worker traduce con el catálogo de la app (`alerts.types.*` / `alerts.hints.*`) según el idioma del navegador, manteniendo los literales como fallback.

+ 23 - 12
server-go/internal/adapters/wireguard.go

@@ -20,8 +20,8 @@ const wgUciMarker = "===NETPULSE_UCI==="
 
 // wgStatsCommand devuelve el comando que emite el dump de `wg show <iface>`
 // y, a continuación, la config WireGuard UCI. El exit code es el de `wg show`
-// (si el túnel está caído, la llamada falla y GetWireGuardStats devuelve
-// error, igual que antes).
+// (si el túnel está caído, la llamada falla y GetWireGuardStats salta esa
+// interfaz sin tumbar el resto, issue #714).
 func wgStatsCommand(iface string) string {
 	return fmt.Sprintf("wg show %s dump; rc=$?; echo '%s'; uci show network 2>/dev/null; exit $rc", iface, wgUciMarker)
 }
@@ -39,8 +39,10 @@ func parseWGInterfaces(out string) []string {
 // wgInterfaces resuelve qué interfaces sondear. iface vacío o "auto" →
 // descubre todas con `wg show interfaces`; un valor explícito (una interfaz o
 // una lista separada por comas) actúa como filtro/override sin tocar el
-// router para listarlas (#713).
-func wgInterfaces(pool sshRunner, host, iface string) ([]string, error) {
+// router para listarlas (#713). Si el listado falla en modo auto (p. ej. un
+// `wg` sin el subcomando `interfaces`), cae al default histórico `wg0` para
+// no dejar el panel sin datos (#714).
+func wgInterfaces(pool sshRunner, host, iface string) []string {
 	v := strings.TrimSpace(iface)
 	if v != "" && v != "auto" {
 		out := []string{}
@@ -49,13 +51,13 @@ func wgInterfaces(pool sshRunner, host, iface string) ([]string, error) {
 				out = append(out, s)
 			}
 		}
-		return out, nil
+		return out
 	}
 	raw, err := pool.Run(host, wgListCommand, 0)
 	if err != nil {
-		return nil, err
+		return []string{"wg0"}
 	}
-	return parseWGInterfaces(raw), nil
+	return parseWGInterfaces(raw)
 }
 
 // splitWGUci separa la salida combinada en la parte del dump y la parte UCI.
@@ -237,11 +239,13 @@ func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string
 // device). El nombre de cada peer se resuelve en este orden: nombre de device
 // de NetPulse (peerNames) → description del peer en UCI (OpenWrt) → IP del
 // túnel → "Peer <pubkey8>" (issue #659).
+//
+// Tolerancia a fallos (#714): el fallo del dump de UNA interfaz se salta (se
+// acumulan los peers de las que responden); si TODAS fallan se devuelve
+// Status "inactive" SIN error, para que pollWireGuard no loguee "no
+// disponible" en cada tick.
 func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map[string]WGPeerName) (*WireGuardStats, error) {
-	ifaces, err := wgInterfaces(pool, host, iface)
-	if err != nil {
-		return nil, err
-	}
+	ifaces := wgInterfaces(pool, host, iface)
 	stats := &WireGuardStats{
 		Interface: strings.Join(ifaces, ", "),
 		Subnet:    subnet,
@@ -256,11 +260,14 @@ func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map
 	nowSec := time.Now().Unix()
 	descs := map[string]string{}
 	idx := 1
+	ok := 0
 	for _, ifc := range ifaces {
 		out, err := pool.Run(host, wgStatsCommand(ifc), 0)
 		if err != nil {
-			return nil, err
+			// Una interfaz caída no tumba el resto: se salta (#714).
+			continue
 		}
+		ok++
 		dump, uci := splitWGUci(out)
 		for k, v := range parseWGUciDescs(uci) {
 			descs[k] = v
@@ -270,5 +277,9 @@ func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map
 			idx++
 		}
 	}
+	if ok == 0 {
+		// Ninguna interfaz respondió: túnel inactivo, sin error (#714).
+		stats.Status = "inactive"
+	}
 	return stats, nil
 }

+ 65 - 8
server-go/internal/adapters/wireguard_test.go

@@ -157,10 +157,7 @@ func TestWGInterfacesFilter(t *testing.T) {
 		{"wg0,wg1", []string{"wg0", "wg1"}},
 		{" wg0 , wg1 , ", []string{"wg0", "wg1"}},
 	} {
-		got, err := wgInterfaces(f, "host", tc.iface)
-		if err != nil {
-			t.Fatalf("wgInterfaces(%q): %v", tc.iface, err)
-		}
+		got := wgInterfaces(f, "host", tc.iface)
 		if len(got) != len(tc.want) {
 			t.Errorf("wgInterfaces(%q) = %v, want %v", tc.iface, got, tc.want)
 			continue
@@ -180,10 +177,7 @@ func TestWGInterfacesFilter(t *testing.T) {
 		f := &fakeWGRunner{run: func(cmd string) (string, error) {
 			return "wg0 wg1\n", nil
 		}}
-		got, err := wgInterfaces(f, "host", iface)
-		if err != nil {
-			t.Fatalf("wgInterfaces(%q): %v", iface, err)
-		}
+		got := wgInterfaces(f, "host", iface)
 		if len(got) != 2 || got[0] != "wg0" || got[1] != "wg1" {
 			t.Errorf("wgInterfaces(%q) = %v, want [wg0 wg1]", iface, got)
 		}
@@ -319,3 +313,66 @@ func TestGetWireGuardStatsExplicitFilter(t *testing.T) {
 		t.Errorf("llamada inesperada: %v", f.calls[0])
 	}
 }
+
+func TestWGInterfacesFallsBackOnListError(t *testing.T) {
+	f := &fakeWGRunner{run: func(cmd string) (string, error) {
+		if cmd == wgListCommand {
+			return "", fmt.Errorf("wg show interfaces no soportado")
+		}
+		return "", fmt.Errorf("comando inesperado: %s", cmd)
+	}}
+	got := wgInterfaces(f, "host", "auto")
+	if len(got) != 1 || got[0] != "wg0" {
+		t.Errorf("wgInterfaces(auto) = %v, want [wg0]", got)
+	}
+	if len(f.calls) != 1 || f.calls[0] != wgListCommand {
+		t.Errorf("llamadas = %v, want [%s]", f.calls, wgListCommand)
+	}
+}
+
+func TestGetWireGuardStatsOneInterfaceFails(t *testing.T) {
+	dump0 := wgPeerDump("wg0", wgPeerLine("AAA=", "10.0.0.2/32", "0"))
+	f := &fakeWGRunner{run: func(cmd string) (string, error) {
+		switch {
+		case cmd == wgListCommand:
+			return "wg0 wg1\n", nil
+		case strings.Contains(cmd, "wg show wg0 dump"):
+			return wgStatsOutput(dump0, ""), nil
+		case strings.Contains(cmd, "wg show wg1 dump"):
+			return "", fmt.Errorf("exit status 1")
+		}
+		return "", fmt.Errorf("comando inesperado: %s", cmd)
+	}}
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	if err != nil {
+		t.Fatalf("GetWireGuardStats: %v (no debe abortar por una interfaz caída)", err)
+	}
+	if stats.Status != "active" {
+		t.Errorf("Status = %q, want active", stats.Status)
+	}
+	if len(stats.Peers) != 1 {
+		t.Fatalf("len(Peers) = %d, want 1 (solo wg0)", len(stats.Peers))
+	}
+	if stats.Peers[0].Name != "10.0.0.2" {
+		t.Errorf("Name = %q, want 10.0.0.2", stats.Peers[0].Name)
+	}
+}
+
+func TestGetWireGuardStatsAllFail(t *testing.T) {
+	f := &fakeWGRunner{run: func(cmd string) (string, error) {
+		if cmd == wgListCommand {
+			return "wg0 wg1\n", nil
+		}
+		return "", fmt.Errorf("exit status 1")
+	}}
+	stats, err := GetWireGuardStats(f, "host", "auto", "", nil)
+	if err != nil {
+		t.Fatalf("GetWireGuardStats: %v (todas fallan → inactive sin error)", err)
+	}
+	if stats.Status != "inactive" {
+		t.Errorf("Status = %q, want inactive", stats.Status)
+	}
+	if len(stats.Peers) != 0 {
+		t.Errorf("len(Peers) = %d, want 0", len(stats.Peers))
+	}
+}