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

fix(agent): retry the neighbour scan on another interface of the radio (#1839) (#1846)

Nacho 1 месяц назад
Родитель
Сommit
4c9c033c28

+ 1 - 0
CHANGELOG.md

@@ -41,6 +41,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- The neighbour scan survives a radio whose AP interface refuses to scan (#1839). On Asuswrt and other Broadcom firmwares every radio exposes an AP interface and a managed one, the AP one answers `Operation not supported (-95)` to a scan, and the picker preferred AP, so those units reported no neighbours at all while the managed interface on the same radio would have answered. The agent keeps the AP first and, when the scan fails, retries on another interface of the same radio within the same cycle, at most twice, which leaves the uplink alone on units where AP works and fixes the ones where it does not. Each radio also reports the outcome of its scan, the interface that answered and the reason when none did, so a refusal and an empty band no longer look the same on the server.
 - The channel plan stops moving a wide radio to the other half of the channel it already uses (#1844). The current block was matched by equality, so a 40 or 80 MHz radio on a channel that is not the block primary matched no block, kept the "this channel cannot be recommended" flag and fell into the DFS path, which suggests a channel without looking at the neighbour count. A radio on 48 at 80 MHz got 36 with every score at zero, and 36 to 48 is the same block, so the advice was not even a different channel. The block is now found by coverage and the plan will not suggest the primary of the block the radio is already on. The 2.4 GHz overlap rule and the DFS rule keep moving a radio without measurements, because there the move is the point.
 - A reinstall no longer downgrades an agent that is ahead of the server (#1840). The binary and the package endpoints compare the version the router last reported with the one embedded in the server and answer with a conflict when the router is newer, because serving an older build would revert fixes without a word. A unit that is down or has never reported is not blocked, so self-heal keeps working, and `?force=1` is the explicit way to reinstall anyway. The release workflow also fails when `agent/VERSION` goes backwards, which is how a server ended up embedding an agent older than the fleet.
 - A gateway without AdGuard no longer leaves half a row empty (#1834). The row width was decided by the two visibility checkboxes while the AdGuard card decided on its own whether to render, so on a unit without AdGuard the WireGuard card kept half the row and the other half stayed blank. The span now follows the cards that actually render: one card takes the full row, two split it. WireGuard is held to the same rule as AdGuard and only appears when the unit has a tunnel, which leaves a configured but idle tunnel visible because the interface is still there.

+ 36 - 0
agent/probe/iwdev.go

@@ -6,6 +6,7 @@
 package probe
 
 import (
+	"sort"
 	"strconv"
 	"strings"
 )
@@ -102,3 +103,38 @@ func pickScanIface(group []IwDevIface) IwDevIface {
 	}
 	return group[0]
 }
+
+// IwDevScanAlternates returns the other interfaces of the same radio, in the
+// order worth trying when the chosen one refuses the scan (#1839). On
+// Asuswrt/dhd every phy exposes an AP VAP that answers
+// NL80211_CMD_TRIGGER_SCAN with "Operation not supported" while the managed
+// VAP of the same phy accepts it and returns BSSes.
+func IwDevScanAlternates(ifaces []IwDevIface, chosen IwDevIface) []IwDevIface {
+	if chosen.Phy < 0 {
+		return nil
+	}
+	var out []IwDevIface
+	for _, i := range ifaces {
+		if i.Phy != chosen.Phy || i.Iface == chosen.Iface {
+			continue
+		}
+		out = append(out, i)
+	}
+	sort.SliceStable(out, func(a, b int) bool { return altRank(out[a]) < altRank(out[b]) })
+	return out
+}
+
+// altRank orders scan fallbacks: a managed VAP first, then anything else, and
+// monitor and P2P-device last because they are not expected to answer either.
+func altRank(i IwDevIface) int {
+	switch {
+	case strings.EqualFold(i.Type, "managed"):
+		return 0
+	case strings.EqualFold(i.Type, "monitor"):
+		return 3
+	case strings.EqualFold(i.Type, "P2P-device"):
+		return 4
+	default:
+		return 1
+	}
+}

+ 67 - 9
agent/probe/local.go

@@ -8,6 +8,7 @@ package probe
 import (
 	"context"
 	"encoding/json"
+	"errors"
 	"fmt"
 	"log/slog"
 	"net"
@@ -42,11 +43,31 @@ func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration)
 	defer cancel()
 	out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output()
 	if err != nil {
+		// #1839: iw escribe el motivo en stderr ("command failed: Operation
+		// not supported (-95)") y Output() lo tira. Sin el, un scan rechazado
+		// y un scan vacio llegan al servidor exactamente igual.
+		var ee *exec.ExitError
+		if errors.As(err, &ee) {
+			if msg := lastLine(ee.Stderr); msg != "" {
+				return "", fmt.Errorf("%w: %s", err, msg)
+			}
+		}
 		return "", err
 	}
 	return string(out), nil
 }
 
+// lastLine devuelve la ultima linea no vacia de b.
+func lastLine(b []byte) string {
+	lines := strings.Split(strings.TrimSpace(string(b)), "\n")
+	for i := len(lines) - 1; i >= 0; i-- {
+		if line := strings.TrimSpace(lines[i]); line != "" {
+			return line
+		}
+	}
+	return ""
+}
+
 // Options configura las sondas opcionales del prober.
 type Options struct {
 	// WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway.
@@ -254,10 +275,11 @@ func (p *Prober) scanDue() bool {
 // the log, which made that correlation impossible from a router: the log line
 // carries the interfaces, per-radio duration and BSS count to line a drop up
 // against the scan that caused it.
-func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) []ScanResult {
-	targets := IwDevScanTargets(ParseIwDevDetailed(iwDev))
+func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) ([]ScanResult, []ScanOutcome) {
+	ifaces := ParseIwDevDetailed(iwDev)
+	targets := IwDevScanTargets(ifaces)
 	if len(targets) == 0 {
-		return nil
+		return nil, nil
 	}
 	names := make([]string, len(targets))
 	for i, t := range targets {
@@ -266,17 +288,49 @@ func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) []ScanResult
 	start := time.Now()
 	slog.Info("neighbor scan start", "radios", len(targets), "ifaces", strings.Join(names, ","))
 	var scans []ScanResult
+	outcomes := make([]ScanOutcome, 0, len(targets))
 	for _, t := range targets {
 		at := time.Now()
-		out := p.runBest(ctx, CmdScanIface(t.Iface), scanIfaceTimeout)
-		got := ParseScan("==IFACE==" + t.Iface + "\n" + out)
+		used, out, err := p.scanWithFallback(ctx, ifaces, t)
+		got := ParseScan("==IFACE==" + used.Iface + "\n" + out)
 		scans = append(scans, got...)
-		slog.Info("neighbor scan radio", "iface", t.Iface, "phy", t.Phy,
-			"bss", len(got), "duration_ms", time.Since(at).Milliseconds())
+		oc := ScanOutcome{Iface: used.Iface, Phy: used.Phy, BSS: len(got)}
+		if err != nil {
+			oc.Error = err.Error()
+		}
+		outcomes = append(outcomes, oc)
+		slog.Info("neighbor scan radio", "iface", used.Iface, "phy", used.Phy,
+			"bss", len(got), "duration_ms", time.Since(at).Milliseconds(), "error", oc.Error)
 	}
 	slog.Info("neighbor scan done", "bss", len(scans),
 		"duration_ms", time.Since(start).Milliseconds(), "empty", len(scans) == 0)
-	return scans
+	return scans, outcomes
+}
+
+// scanWithFallback scans the interface chosen for the radio and, when it
+// refuses (#1839: on Asuswrt/dhd the AP VAP answers NL80211_CMD_TRIGGER_SCAN
+// with "Operation not supported"), tries the other interfaces of the same phy
+// in the same cycle. Nothing is remembered between cycles: caching a failure
+// would turn one bad scan into a permanent choice.
+func (p *Prober) scanWithFallback(ctx context.Context, ifaces []IwDevIface, chosen IwDevIface) (IwDevIface, string, error) {
+	out, err := p.run.Run(ctx, CmdScanIface(chosen.Iface), scanIfaceTimeout)
+	if err == nil {
+		return chosen, out, nil
+	}
+	used, lastErr := chosen, err
+	for i, alt := range IwDevScanAlternates(ifaces, chosen) {
+		if i >= maxScanFallbacks {
+			break
+		}
+		out, err = p.run.Run(ctx, CmdScanIface(alt.Iface), scanIfaceTimeout)
+		if err == nil {
+			slog.Info("neighbor scan fallback", "from", chosen.Iface, "to", alt.Iface,
+				"phy", alt.Phy, "reason", lastErr.Error())
+			return alt, out, nil
+		}
+		used, lastErr = alt, err
+	}
+	return used, "", lastErr
 }
 
 // probeVlans reports the bridge VLANs, preferring what the kernel says over
@@ -644,9 +698,13 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 		// sin NINGÚN vecino aunque las demás interfaces sí hubieran
 		// escaneado con éxito.
 		if p.scanDue() && iwDev != "" {
-			if scans := p.scanNeighbours(ctx, iwDev); len(scans) > 0 {
+			scans, outcomes := p.scanNeighbours(ctx, iwDev)
+			if len(scans) > 0 {
 				wd.Scans = scans
 			}
+			if len(outcomes) > 0 {
+				wd.ScanOutcomes = outcomes
+			}
 		}
 		// BSSIDs propios (#1087), del mismo `iw dev` de arriba.
 		if iwDev != "" {

+ 13 - 0
agent/probe/payload.go

@@ -122,6 +122,15 @@ type SystemData struct {
 	FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
 }
 
+// ScanOutcome (#1839) is the result of the neighbour scan on one radio: the
+// interface that answered (or was tried last) and the reason when none did.
+type ScanOutcome struct {
+	Iface string `json:"iface"`
+	Phy   int    `json:"phy"`
+	BSS   int    `json:"bss"`
+	Error string `json:"error,omitempty"`
+}
+
 // WirelessData: clientes asociados + radios agregadas por banda.
 type WirelessData struct {
 	Clients map[string]WirelessClient `json:"clients"` // {} = sin clientes; sección ausente = sonda fallida
@@ -129,6 +138,10 @@ type WirelessData struct {
 	// Scans: redes vecinas vistas por cada interfaz WiFi (Fase 18/#452).
 	// nil/ausente = el scan no se pudo realizar en este push.
 	Scans []ScanResult `json:"scans,omitempty"`
+	// ScanOutcomes (#1839): que paso en el scan de cada radio. "Se nego" y
+	// "acepto sin ver nada" llegan igual en Scans (vacio), y el motivo solo
+	// lo ve el agente, asi que viaja aqui. nil con agentes antiguos.
+	ScanOutcomes []ScanOutcome `json:"scanOutcomes,omitempty"`
 	// OwnBssids: BSSIDs de las interfaces AP de ESTE equipo (#1087), de
 	// `iw dev`. El server los usa de semilla exacta para no contar las
 	// propias redes como vecinas (casos con MAC aleatorizada o guest cuya

+ 4 - 0
agent/probe/probe.go

@@ -130,6 +130,10 @@ const (
 	// hechos. Cada interfaz tiene ahora su propio tiempo y un fallo o un
 	// cuelgue solo vacía su propia sección.
 	scanIfaceTimeout = 8 * time.Second
+	// maxScanFallbacks (#1839): reintentos por radio cuando la interfaz
+	// elegida rechaza el scan. Dos basta para cubrir AP + managed + una
+	// tercera, y acota el peor caso (3 x 8 s por radio).
+	maxScanFallbacks = 2
 	// CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
 	// resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
 	CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`

+ 149 - 0
agent/probe/scan_fallback_1839_test.go

@@ -0,0 +1,149 @@
+package probe
+
+// scan_fallback_1839_test.go — #1839: en Asuswrt (dhd/Broadcom) cada radio
+// expone una VAP AP y una managed. La AP contesta al scan con "Operation not
+// supported (-95)" y la managed si devuelve BSSes. El agente elegia la AP
+// (para que el nombre de interfaz en wifi_scans fuera el de siempre) y se
+// quedaba sin vecinos sin dejar rastro. Ahora, si la elegida falla, se
+// reintenta en el mismo ciclo con otra interfaz del mismo phy, y el resultado
+// por radio viaja en scanOutcomes.
+
+import (
+	"context"
+	"strings"
+	"testing"
+	"time"
+)
+
+// iwDevAsuswrt reproduce una radio con VAP AP y managed en el mismo phy, más
+// una segunda radio distinta que no debe entrar en los reintentos.
+const iwDevAsuswrt = "phy#1\n" +
+	"\tInterface wl1.1\n" +
+	"\t\taddr 62:22:32:5b:5c:99\n" +
+	"\t\tssid I1_LAN\n" +
+	"\t\ttype AP\n" +
+	"\t\tchannel 48 (5240 MHz), width: 80 MHz, center1: 5210 MHz\n" +
+	"\tInterface eth6\n" +
+	"\t\taddr 62:22:32:5b:5c:9a\n" +
+	"\t\ttype managed\n" +
+	"\t\tchannel 48 (5240 MHz), width: 80 MHz, center1: 5210 MHz\n" +
+	"phy#0\n" +
+	"\tInterface wl0.1\n" +
+	"\t\taddr 62:22:32:5b:5c:98\n" +
+	"\t\tssid I1_LAN\n" +
+	"\t\ttype AP\n" +
+	"\t\tchannel 11 (2462 MHz), width: 20 MHz, center1: 2462 MHz\n"
+
+// scan5g es la salida real que devuelve la VAP managed en el equipo del
+// reportero: freqs 5200/5240, o sea el mismo bloque de 80 MHz.
+const scan5g = "BSS a4:2b:b0:11:22:33(on eth6)\n" +
+	"\tlast seen: 275247.799s [boottime]\n" +
+	"\tfreq: 5240.0\n" +
+	"\tcapability: ESS (0x1011)\n" +
+	"\tsignal: -58.00 dBm\n" +
+	"\tlast seen: 120 ms ago\n" +
+	"\tSSID: Vecino_5G\n"
+
+// runnerVapApRechaza simula la AP que rechaza el scan y la managed que
+// responde.
+type runnerVapApRechaza struct {
+	fakeRunner
+	fail map[string]bool
+}
+
+func (r runnerVapApRechaza) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) {
+	if r.fail[cmd] {
+		return "", &fakeErr{cmd}
+	}
+	return r.fakeRunner.Run(ctx, cmd, timeout)
+}
+
+func TestIwDevScanAlternates(t *testing.T) {
+	ifaces := ParseIwDevDetailed(iwDevAsuswrt)
+	chosen := IwDevScanTargets(ifaces)[0]
+	if chosen.Iface != "wl1.1" {
+		t.Fatalf("se esperaba la AP como objetivo: %+v", chosen)
+	}
+	alts := IwDevScanAlternates(ifaces, chosen)
+	if len(alts) != 1 || alts[0].Iface != "eth6" {
+		t.Fatalf("solo la managed del mismo phy vale como reintento: %+v", alts)
+	}
+	// Monitor va despues de managed.
+	withMonitor := append(append([]IwDevIface{}, ifaces...), IwDevIface{Iface: "mon0", Phy: 1, Type: "monitor"})
+	alts = IwDevScanAlternates(withMonitor, chosen)
+	if len(alts) != 2 || alts[0].Iface != "eth6" || alts[1].Iface != "mon0" {
+		t.Fatalf("orden de reintentos: %+v", alts)
+	}
+	if got := IwDevScanAlternates(ifaces, IwDevIface{Iface: "wlan0", Phy: -1}); got != nil {
+		t.Fatalf("sin phy no hay reintento posible: %+v", got)
+	}
+}
+
+func TestScanRechazadoReintentaEnLaManaged(t *testing.T) {
+	run := runnerVapApRechaza{
+		fakeRunner: fakeRunner{outs: map[string]string{
+			CmdIwDev:                 iwDevAsuswrt,
+			CmdScanIface("eth6"):     scan5g,
+			CmdScanIface("wl0.1"):    "",
+			CmdScanIface("wl1.1"):    "",
+			CmdScanIface("phy1-ap0"): "",
+		}},
+		fail: map[string]bool{CmdScanIface("wl1.1"): true},
+	}
+	p := NewProber(run, Options{})
+	pl := p.Build(context.Background(), "rt-ax92u", "test")
+	if pl.Data.Wireless == nil {
+		t.Fatal("sección wireless ausente")
+	}
+	w := pl.Data.Wireless
+	if len(w.Scans) != 1 || w.Scans[0].Iface != "eth6" || w.Scans[0].SSID != "Vecino_5G" {
+		t.Fatalf("el vecino debe venir de la managed: %+v", w.Scans)
+	}
+	if len(w.ScanOutcomes) != 2 {
+		t.Fatalf("un outcome por radio: %+v", w.ScanOutcomes)
+	}
+	if o := w.ScanOutcomes[0]; o.Iface != "eth6" || o.Phy != 1 || o.BSS != 1 || o.Error != "" {
+		t.Fatalf("outcome de la radio 5 GHz: %+v", o)
+	}
+}
+
+func TestScanRechazadoRegistraElMotivo(t *testing.T) {
+	run := runnerVapApRechaza{
+		fakeRunner: fakeRunner{outs: map[string]string{CmdIwDev: iwDevAsuswrt}},
+		fail: map[string]bool{
+			CmdScanIface("wl1.1"): true,
+			CmdScanIface("eth6"):  true,
+			CmdScanIface("wl0.1"): true,
+		},
+	}
+	p := NewProber(run, Options{})
+	pl := p.Build(context.Background(), "rt-ax92u", "test")
+	if pl.Data.Wireless == nil {
+		t.Fatal("sección wireless ausente")
+	}
+	w := pl.Data.Wireless
+	if len(w.Scans) != 0 {
+		t.Fatalf("sin respuesta no hay vecinos: %+v", w.Scans)
+	}
+	if len(w.ScanOutcomes) != 2 {
+		t.Fatalf("un outcome por radio: %+v", w.ScanOutcomes)
+	}
+	for _, o := range w.ScanOutcomes {
+		if o.Error == "" {
+			t.Fatalf("el motivo debe quedar registrado: %+v", o)
+		}
+	}
+}
+
+// TestShellRunnerExponeElStderr cubre la otra mitad del issue: el motivo lo
+// escribe iw en stderr y Output() lo descartaba.
+func TestShellRunnerExponeElStderr(t *testing.T) {
+	_, err := ShellRunner{}.Run(context.Background(),
+		"printf 'command failed: Operation not supported (-95)\\n' >&2; exit 1", 5*time.Second)
+	if err == nil {
+		t.Fatal("se esperaba error")
+	}
+	if !strings.Contains(err.Error(), "Operation not supported (-95)") {
+		t.Fatalf("el error debe llevar el motivo del stderr: %v", err)
+	}
+}

+ 3 - 0
agent/probe/scan_periface_test.go

@@ -109,6 +109,9 @@ func TestScanPorInterfazThrottle(t *testing.T) {
 		"\tInterface phy0-ap1\n\t\taddr 62:22:32:5b:5c:98\n\t\ttype AP\n"
 	run := &countingRunner{fakeRunner: fakeRunner{outs: map[string]string{
 		CmdIwDev: iwDev,
+		// La AP responde (aqui, sin BSS): el test mide la agrupacion por
+		// radio, no el reintento de #1839.
+		CmdScanIface("phy0-ap0"): "",
 	}}}
 	p := NewProber(run, Options{})
 	ctx := context.Background()