Pārlūkot izejas kodu

fix(clients): hold a new MAC for a minute before calling it a client (#1818) (#1850)

Nacho 1 mēnesi atpakaļ
vecāks
revīzija
d45ac18a70

+ 1 - 0
CHANGELOG.md

@@ -42,6 +42,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- Addresses that come and go within a minute are no longer clients (#1818). Randomised MACs, phones that probe once and mesh units that bounce an association all reached the device table, the counters and the new-client alert within a single poll. A MAC the database has never seen now has to stay online for a minute before it is stored, counted or alerted, and when it finally lands the row keeps the moment it was first seen instead of the moment it was promoted. The wait is kept in memory on purpose: it is a judgement about the current poll cycle, so a restart costs one extra minute at most, and a device that already exists in the table is never held back. Without a database the check steps aside and the old behaviour returns.
 - 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.

+ 7 - 0
server-go/internal/adapters/arp_test.go

@@ -255,6 +255,13 @@ func TestGetRoutersCountsClientsNotLeases(t *testing.T) {
 	cfg := RouterConfig{ID: "gateway", Name: "Gateway", Host: "192.0.2.1", IsGateway: true, AgentOnly: true}
 	l.SetRouters([]RouterConfig{cfg})
 
+	// #1818: un cliente nuevo se retiene un minuto antes de listarse. Estos dos
+	// ya estaban vistos, que es lo que este test mide (leases vs asociados).
+	l.noteDevicesSeen([]Device{
+		{MAC: "02:00:00:00:00:01", Online: true, Hostname: "one"},
+		{MAC: "02:00:00:00:00:02", Online: true, Hostname: "two"},
+	}, 1000)
+
 	// Three leases, but only two of those hosts are associated right now.
 	l.mu.Lock()
 	l.lastPolled = map[string]*routerPolled{"gateway": {

+ 7 - 1
server-go/internal/adapters/device_seen.go

@@ -225,7 +225,13 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) []Device {
 		if name == "" && d.Name != "" && !isMACLike(d.Name) {
 			name = d.Name
 		}
-		if _, err := stmt.Exec(mac, nowMs, nowMs, name, saneIP(d.IP), inferredDeviceType(d)); err != nil {
+		// #1818: el alta guarda el primer avistamiento real, no el del ciclo en
+		// que el cliente supero el minuto de permanencia.
+		first := nowMs
+		if d.FirstSeenMs > 0 && d.FirstSeenMs < nowMs {
+			first = d.FirstSeenMs
+		}
+		if _, err := stmt.Exec(mac, first, nowMs, name, saneIP(d.IP), inferredDeviceType(d)); err != nil {
 			return nil
 		}
 		// #1323: primera vez CON nombre (los sin nombre los cubre

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

@@ -289,6 +289,9 @@ type Live struct {
 	routers    []RouterConfig
 	gatewayCfg *RouterConfig
 	clients    map[string]*OpenWrtClient
+	// #1818: MAC nuevas que aun no han demostrado permanencia (60 s).
+	transientMu sync.Mutex
+	transient   map[string]transientSeen
 
 	lastGood    map[string]*Router
 	lastStatus  map[string]string
@@ -4052,6 +4055,9 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	// #1292: lápidas filtradas de la lista final (una estación stale del AP
 	// re-emite la MAC en cada ciclo sin pasar por device_seen).
 	devices = l.filterTombstoned(devices)
+	// #1818: fuera los MAC que duran menos de un minuto, ANTES de alertar de
+	// desconocidos y de escribir en device_seen.
+	devices = l.settleTransient(devices, time.Now().UnixMilli())
 	l.trackUnknownDevices(devices, distNodes)
 	l.trackOfflineDevices(devices)
 	l.trackDevicePresence(devices, time.Now().UnixMilli())
@@ -4518,6 +4524,8 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	clients := []Device{}
 	detDevices, _ := inferTopology(polledAll, l.buildDevices(polledAll, ""))
 	// #954: first/last seen también en los clientes del detalle del router.
+	// #1818: mismo gate de permanencia que el overview.
+	detDevices = l.settleTransient(detDevices, time.Now().UnixMilli())
 	l.applyDeviceSeen(detDevices)
 	for _, d := range detDevices {
 		if d.RouterID == id {
@@ -4708,6 +4716,8 @@ func (l *Live) attributedDevices() []Device {
 	// nunca se persistía y aquí se mostraba "—" para siempre. Escribir también
 	// desde la lista que la UI realmente consume hace el write-through
 	// inevitable; el upsert es idempotente y barato.
+	// #1818: mismo gate de permanencia antes de persistir.
+	devices = l.settleTransient(devices, time.Now().UnixMilli())
 	l.noteDevicesSeen(devices, time.Now().UnixMilli())
 	l.applyDeviceSeen(devices)
 	// #1145: retención indefinida - clientes del registro que ya no se ven

+ 78 - 0
server-go/internal/adapters/transient.go

@@ -0,0 +1,78 @@
+package adapters
+
+// #1818: una MAC que aparece y desaparece en segundos no es un cliente, es
+// ruido de asociacion (moviles que rotan direccion, sondas, reasociaciones del
+// mismo equipo). El reportero pedia justo esto: ignorar la direccion si se va
+// dentro de los primeros 60 s y avisar solo de lo que persiste.
+const (
+	// transientDwellMs es el tiempo minimo que una MAC nueva tiene que seguir
+	// viendose para considerarse un cliente.
+	transientDwellMs = 60_000
+	// transientExpiryMs olvida las MAC que llevan este tiempo sin aparecer, para
+	// que el mapa no crezca sin limite con equipos de paso.
+	transientExpiryMs = 600_000
+)
+
+// transientSeen guarda cuando se vio por primera vez y por ultima una MAC
+// todavia provisional.
+type transientSeen struct {
+	first int64
+	last  int64
+}
+
+// settleTransient filtra los dispositivos que aun no han demostrado que se
+// quedan. Un MAC que no esta en device_seen ni en el mapa provisional entra en
+// el mapa y desaparece de la lista; en cuanto sigue viendose pasados 60 s desde
+// la primera vez, se deja pasar con su first_seen real. Los que ya estan en el
+// registro pasan siempre.
+//
+// El estado vive en memoria a proposito: si el proceso reinicia, los
+// provisionales vuelven a empezar la cuenta, que es lo correcto (no se pierde
+// ningun cliente real, solo se retrasa un minuto su primera aparicion). Con la
+// BD no disponible se devuelve la lista intacta: mejor mostrar un cliente
+// efimero que ocultar la red entera.
+func (l *Live) settleTransient(devices []Device, nowMs int64) []Device {
+	if l.db == nil {
+		return devices
+	}
+	known, err := l.seenByMac()
+	if err != nil {
+		return devices
+	}
+	l.transientMu.Lock()
+	defer l.transientMu.Unlock()
+	if l.transient == nil {
+		l.transient = map[string]transientSeen{}
+	}
+	for mac, t := range l.transient {
+		if nowMs-t.last > transientExpiryMs {
+			delete(l.transient, mac)
+		}
+	}
+	out := make([]Device, 0, len(devices))
+	for _, d := range devices {
+		mac := normSeenMAC(d.MAC)
+		if mac == "" || !d.Online {
+			out = append(out, d)
+			continue
+		}
+		if _, ok := known[mac]; ok {
+			out = append(out, d)
+			continue
+		}
+		t, seen := l.transient[mac]
+		if !seen {
+			l.transient[mac] = transientSeen{first: nowMs, last: nowMs}
+			continue
+		}
+		t.last = nowMs
+		if nowMs-t.first < transientDwellMs {
+			l.transient[mac] = t
+			continue
+		}
+		delete(l.transient, mac)
+		d.FirstSeenMs = t.first
+		out = append(out, d)
+	}
+	return out
+}

+ 98 - 0
server-go/internal/adapters/transient_1818_test.go

@@ -0,0 +1,98 @@
+package adapters
+
+// transient_1818_test.go — #1818: una MAC que aparece y desaparece en menos de
+// un minuto no debe listarse, ni alertar, ni entrar en device_seen.
+
+import "testing"
+
+func transientLive(t *testing.T) *Live {
+	t.Helper()
+	d := openLiveTestDB(t)
+	return NewLive(nil, d, []RouterConfig{{ID: "gw", Name: "Gateway"}}, nil)
+}
+
+// El caso del issue: la MAC se ve, aguanta menos de un minuto y se va.
+func TestTransientMACIgnoradaAntesDelMinuto(t *testing.T) {
+	l := transientLive(t)
+	// Registro pre-poblado: el primer arranque siembra en silencio.
+	l.noteDevicesSeen([]Device{{MAC: "aa:aa:aa:00:00:01", Online: true, Hostname: "viejo"}}, 1000)
+
+	mac := "5A:3B:41:63:08:FE"
+	devs := []Device{{MAC: mac, Online: true, Hostname: "efimero", RouterID: "gw"}}
+
+	if got := l.settleTransient(devs, 10_000); len(got) != 0 {
+		t.Fatalf("el primer avistamiento no debe pasar: %+v", got)
+	}
+	if got := l.settleTransient(devs, 40_000); len(got) != 0 {
+		t.Fatalf("a los 30 s sigue siendo provisional: %+v", got)
+	}
+	got := l.settleTransient(devs, 71_000)
+	if len(got) != 1 {
+		t.Fatalf("a los 61 s debe pasar: %+v", got)
+	}
+	if got[0].FirstSeenMs != 10_000 {
+		t.Fatalf("first seen debe ser el primer avistamiento, got %d", got[0].FirstSeenMs)
+	}
+	// Ya promocionado, no vuelve a retenerse. En produccion el mismo ciclo que
+	// lo deja pasar lo persiste, y a partir de ahi el registro es la fuente.
+	l.noteDevicesSeen(got, 71_000)
+	if got := l.settleTransient(devs, 72_000); len(got) != 1 {
+		t.Fatalf("un cliente ya visto debe pasar siempre: %+v", got)
+	}
+}
+
+// Una MAC de paso no debe quedar ni en el mapa ni en el registro.
+func TestTransientMACQueNoPersisteNoSeGuarda(t *testing.T) {
+	l := transientLive(t)
+	l.noteDevicesSeen([]Device{{MAC: "aa:aa:aa:00:00:01", Online: true, Hostname: "viejo"}}, 1000)
+
+	mac := "5A:3B:41:63:08:FE"
+	l.settleTransient([]Device{{MAC: mac, Online: true, Hostname: "efimero", RouterID: "gw"}}, 10_000)
+
+	// Pasada la ventana de expiracion, el mapa se olvida de ella.
+	l.settleTransient(nil, 10_000+transientExpiryMs+1)
+	if len(l.transient) != 0 {
+		t.Fatalf("la MAC provisional debe purgarse: %+v", l.transient)
+	}
+	seen, err := l.seenByMac()
+	if err != nil {
+		t.Fatalf("seenByMac: %v", err)
+	}
+	if _, ok := seen[normSeenMAC(mac)]; ok {
+		t.Fatal("una MAC de paso no debe entrar en device_seen")
+	}
+}
+
+// Un cliente que ya esta en el registro no se retiene aunque el proceso acabe
+// de arrancar (el mapa provisional esta vacio).
+func TestTransientClienteConocidoPasaSiempre(t *testing.T) {
+	l := transientLive(t)
+	l.noteDevicesSeen([]Device{{MAC: "aa:aa:aa:00:00:01", Online: true, Hostname: "viejo"}}, 1000)
+
+	devs := []Device{{MAC: "AA:AA:AA:00:00:01", Online: true, Hostname: "viejo", RouterID: "gw"}}
+	if got := l.settleTransient(devs, 2000); len(got) != 1 {
+		t.Fatalf("un cliente ya registrado pasa siempre: %+v", got)
+	}
+}
+
+// El alta guarda el primer avistamiento real, no el ciclo en que se promociono.
+func TestNoteDevicesSeenGuardaElPrimerAvistamiento(t *testing.T) {
+	l := transientLive(t)
+	l.noteDevicesSeen([]Device{{MAC: "aa:aa:aa:00:00:01", Online: true, Hostname: "viejo"}}, 1000)
+	l.noteDevicesSeen([]Device{{MAC: "5A:3B:41:63:08:FE", Online: true, Hostname: "nuevo", FirstSeenMs: 10_000}}, 71_000)
+
+	seen, err := l.seenByMac()
+	if err != nil {
+		t.Fatalf("seenByMac: %v", err)
+	}
+	row, ok := seen["5A:3B:41:63:08:FE"]
+	if !ok {
+		t.Fatal("el cliente promocionado debe estar en device_seen")
+	}
+	if row.first != 10_000 {
+		t.Fatalf("first_seen debe ser el primer avistamiento, got %d", row.first)
+	}
+	if row.last != 71_000 {
+		t.Fatalf("last_seen debe ser el ciclo actual, got %d", row.last)
+	}
+}