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

feat(presence): ping stale ARP neighbours before calling them offline (#2108)

A wired host with a static IP that goes idle ages out of the FDB and its ARP entry drops to STALE, so it was reported offline while still up (#2063). Before trusting a STALE entry, the agent pings its IP and re-reads ip neigh: the kernel promotes the entry to REACHABLE when the ARP reply arrives, which confirms the IP-MAC pair rather than just the IP. The SSH client does the same from the unit. Capped per round, throttled, and STALE-only, so it is never a subnet sweep.
Nacho 2 недель назад
Родитель
Сommit
e1e1ccbcb6

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.45
+3.0.46

+ 105 - 0
agent/probe/local.go

@@ -143,6 +143,12 @@ type Prober struct {
 	uciWirelessMu  sync.Mutex
 	uciWirelessRaw string
 	uciWirelessAt  time.Time
+
+	// stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping a
+	// cada IP sale del throttle como mucho cada stalePingInterval; el sondeo
+	// del agente es cada ~30 s y una entrada STALE cambia despacio.
+	stalePingMu sync.Mutex
+	stalePingAt time.Time
 }
 
 // surveyInterval: mínimo entre `iw survey dump` si no hay force (#1214).
@@ -1327,6 +1333,15 @@ func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []s
 	if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" {
 		m, st := ParseIPNeigh(out)
 		if len(m) > 0 {
+			// #2073: un vecino STALE es una direccion que el kernel recuerda
+			// sin confirmar. Antes de darlo por fantasma se comprueba con un
+			// echo corto, que es lo unico que puede resolver el caso de un
+			// host cableado con IP estatica que lleva rato en silencio.
+			var fresh string
+			m, st, fresh = p.confirmStaleNeighbours(ctx, m, st)
+			if fresh != "" {
+				out = fresh
+			}
 			for mac := range st {
 				stale = append(stale, mac)
 			}
@@ -1344,3 +1359,93 @@ func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []s
 	}
 	return m, nil, ParseArpDevs(out)
 }
+
+// Parametros del recheck activo de vecinos (#2073), compartidos por el agente
+// y por el sondeo SSH del servidor. El tope por ronda es deliberado: el caso
+// real son un punado de vecinos idle, no un barrido de subred. Un /24 completo
+// se deja para un arpscan, que necesita raw sockets.
+const (
+	StalePingInterval = 60 * time.Second
+	StalePingMax      = 16
+	StalePingTimeout  = 1500 * time.Millisecond
+)
+
+// StalePingTargets devuelve, en orden determinista y con tope, las IPs de los
+// vecinos STALE que merece la pena sondear. Compartida por el agente (ping
+// local, #2073) y el cliente SSH del servidor (ping desde la unidad), para que
+// los dos caminos sondeen lo mismo.
+func StalePingTargets(arp map[string]string, stale map[string]bool) []string {
+	macs := make([]string, 0, len(stale))
+	for mac := range stale {
+		macs = append(macs, mac)
+	}
+	sort.Strings(macs)
+	ips := make([]string, 0, StalePingMax)
+	for _, mac := range macs {
+		if len(ips) >= StalePingMax {
+			break
+		}
+		if ip := arp[mac]; net.ParseIP(ip) != nil {
+			ips = append(ips, ip)
+		}
+	}
+	return ips
+}
+
+// confirmStaleNeighbours (#2073): manda un echo corto a cada IP de vecino
+// STALE y relee la tabla. El kernel pasa a REACHABLE la entrada cuya respuesta
+// ARP llega, asi que lo que se confirma es la PAREJA IP-MAC: una IP
+// reutilizada por otro equipo no resucita la MAC vieja. Es justo el dato que
+// falta cuando un host cableado con IP estatica lleva rato en silencio, la FDB
+// ha caducado y el ARP solo esta STALE (#2063).
+//
+// Best effort: sin runner, sin vecinos o si la relectura falla, los datos
+// vuelven como estaban. Throttle propio (stalePingInterval) para no lanzar
+// pings en cada sondeo.
+func (p *Prober) confirmStaleNeighbours(ctx context.Context, arp map[string]string, stale map[string]bool) (map[string]string, map[string]bool, string) {
+	if p.run == nil || len(stale) == 0 {
+		return arp, stale, ""
+	}
+	p.stalePingMu.Lock()
+	recent := !p.stalePingAt.IsZero() && time.Since(p.stalePingAt) < StalePingInterval
+	if !recent {
+		p.stalePingAt = time.Now()
+	}
+	p.stalePingMu.Unlock()
+	if recent {
+		return arp, stale, ""
+	}
+
+	ips := StalePingTargets(arp, stale)
+	if len(ips) == 0 {
+		return arp, stale, ""
+	}
+
+	var wg sync.WaitGroup
+	for _, ip := range ips {
+		wg.Add(1)
+		go func(ip string) {
+			defer wg.Done()
+			_, _ = p.run.Run(ctx, "ping -c 1 -W 1 "+ip+" >/dev/null 2>&1", StalePingTimeout)
+		}(ip)
+	}
+	wg.Wait()
+
+	out := p.runBest(ctx, CmdIpNeigh, 3*time.Second)
+	if out == "" {
+		return arp, stale, ""
+	}
+	fresh, stillStale := ParseIPNeigh(out)
+	for mac := range stale {
+		if stillStale[mac] {
+			continue
+		}
+		// Respondio: el kernel ya tiene la entrada confirmada. Se copia la IP
+		// fresca (puede haber cambiado de direccion) y sale del set stale.
+		if ip := fresh[mac]; ip != "" {
+			arp[mac] = ip
+		}
+		delete(stale, mac)
+	}
+	return arp, stale, out
+}

+ 144 - 0
agent/probe/stale_arp_2073_test.go

@@ -0,0 +1,144 @@
+package probe
+
+// stale_arp_2073_test.go - recheck activo de vecinos ARP en STALE.
+//
+// #2063: un host cableado con IP estatica que lleva rato en silencio caduca de
+// la FDB y su entrada ARP queda STALE, asi que NetPulse lo marcaba offline
+// estando arriba. ParseIPNeigh solo acepta estados confirmados (#507), y eso
+// no se toca: lo que se anyade es una comprobacion activa ANTES de dar el
+// vecino por fantasma. El kernel pasa la entrada a REACHABLE cuando llega la
+// respuesta ARP, asi que se confirma la pareja IP-MAC.
+
+import (
+	"context"
+	"fmt"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+)
+
+type staleArpRunner struct {
+	mu    sync.Mutex
+	neigh []string
+	idx   int
+	pings []string
+	fail  string // IP que no responde (el ping devuelve error)
+}
+
+func (r *staleArpRunner) Run(_ context.Context, cmd string, _ time.Duration) (string, error) {
+	if cmd == CmdIpNeigh {
+		r.mu.Lock()
+		defer r.mu.Unlock()
+		if r.idx >= len(r.neigh) {
+			return r.neigh[len(r.neigh)-1], nil
+		}
+		out := r.neigh[r.idx]
+		r.idx++
+		return out, nil
+	}
+	if strings.HasPrefix(cmd, "ping -c 1 -W 1 ") {
+		ip := strings.TrimPrefix(cmd, "ping -c 1 -W 1 ")
+		ip = strings.Fields(ip)[0]
+		r.mu.Lock()
+		r.pings = append(r.pings, ip)
+		fail := r.fail == ip
+		r.mu.Unlock()
+		if fail {
+			return "", &fakeErr{cmd}
+		}
+		return "", nil
+	}
+	return "", &fakeErr{cmd}
+}
+
+func (r *staleArpRunner) pinged() []string {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	out := make([]string, len(r.pings))
+	copy(out, r.pings)
+	return out
+}
+
+const (
+	neighStale = `192.168.1.10 dev br-lan lladdr AA:AA:AA:AA:AA:01 STALE
+192.168.1.11 dev br-lan lladdr AA:AA:AA:AA:AA:02 STALE
+192.168.1.12 dev br-lan lladdr AA:AA:AA:AA:AA:03 REACHABLE
+`
+	neighAfterPing = `192.168.1.10 dev br-lan lladdr AA:AA:AA:AA:AA:01 REACHABLE
+192.168.1.11 dev br-lan lladdr AA:AA:AA:AA:AA:02 STALE
+192.168.1.12 dev br-lan lladdr AA:AA:AA:AA:AA:03 REACHABLE
+`
+)
+
+// El vecino que responde sale del set stale (queda confirmado); el que no
+// responde sigue stale y no se inventa presencia.
+func TestProbeArpConfirmsStaleNeighbourThatAnswers(t *testing.T) {
+	run := &staleArpRunner{neigh: []string{neighStale, neighAfterPing}, fail: "192.168.1.11"}
+	p := NewProber(run, Options{})
+
+	arp, stale, _ := p.probeArp(context.Background())
+
+	got := map[string]bool{}
+	for _, mac := range stale {
+		got[mac] = true
+	}
+	if got["AA:AA:AA:AA:AA:01"] {
+		t.Fatalf("el vecino que respondio sigue stale: %v", stale)
+	}
+	if !got["AA:AA:AA:AA:AA:02"] {
+		t.Fatalf("el vecino que no respondio debe seguir stale: %v", stale)
+	}
+	if arp["AA:AA:AA:AA:AA:01"] != "192.168.1.10" {
+		t.Fatalf("la IP confirmada se conserva: %v", arp)
+	}
+	pings := run.pinged()
+	if len(pings) != 2 {
+		t.Fatalf("solo se sondean los STALE (2), se pingearon %v", pings)
+	}
+}
+
+// El recheck no corre en cada sondeo: el sondeo del agente es cada ~30 s.
+func TestProbeArpStalePingIsThrottled(t *testing.T) {
+	run := &staleArpRunner{neigh: []string{neighStale, neighAfterPing}}
+	p := NewProber(run, Options{})
+
+	_, _, _ = p.probeArp(context.Background())
+	first := len(run.pinged())
+	_, _, _ = p.probeArp(context.Background())
+	if second := len(run.pinged()); second != first {
+		t.Fatalf("la segunda ronda dentro del intervalo no debe pingear: %d -> %d", first, second)
+	}
+}
+
+// Tope por ronda: nunca un barrido, aunque la tabla tenga muchos STALE.
+func TestProbeArpStalePingIsCapped(t *testing.T) {
+	var b strings.Builder
+	for i := 0; i < 40; i++ {
+		fmt.Fprintf(&b, "10.0.0.%d dev br-lan lladdr AA:BB:CC:DD:EE:%02X STALE\n", i+1, i+1)
+	}
+	out := b.String()
+	run := &staleArpRunner{neigh: []string{out, out}}
+	p := NewProber(run, Options{})
+	_, stale, _ := p.probeArp(context.Background())
+	if len(stale) != 40 {
+		t.Fatalf("el fixture debe dar 40 STALE, dio %d", len(stale))
+	}
+	if got := len(run.pinged()); got != StalePingMax {
+		t.Fatalf("se pingearon %d vecinos, se esperaban %d", got, StalePingMax)
+	}
+}
+
+// Sin vecinos STALE no se lanza ni un ping.
+func TestProbeArpNoStaleNoPing(t *testing.T) {
+	out := "192.168.1.12 dev br-lan lladdr AA:AA:AA:AA:AA:03 REACHABLE\n"
+	run := &staleArpRunner{neigh: []string{out, out}}
+	p := NewProber(run, Options{})
+	_, stale, _ := p.probeArp(context.Background())
+	if len(stale) != 0 {
+		t.Fatalf("stale inesperado: %v", stale)
+	}
+	if got := run.pinged(); len(got) != 0 {
+		t.Fatalf("no debe pingear sin STALE: %v", got)
+	}
+}

+ 61 - 0
server-go/internal/adapters/openwrt.go

@@ -70,6 +70,12 @@ type OpenWrtClient struct {
 	radiosMu    sync.Mutex
 	radiosCache []Radio // resumen por banda, refrescado cada radiosTTL
 	radiosAt    time.Time
+
+	// stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping sale
+	// de la propia unidad (esta en la subred), no del servidor, y va con
+	// throttle para no lanzarlo en cada poll.
+	stalePingMu sync.Mutex
+	stalePingAt time.Time
 }
 
 type cpuSample struct{ total, idleAll float64 }
@@ -705,6 +711,13 @@ func radiosToAdapter(in []probe.Radio) []Radio {
 func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool, devs map[string]string) {
 	if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
 		if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
+			// #2073: la misma comprobacion activa que hace el agente, pero
+			// lanzada desde la unidad (esta en la subred; el servidor puede
+			// no estarlo). Un host cableado con IP estatica que lleva rato en
+			// silencio deja el ARP en STALE sin estar apagado.
+			if fresh, ok := c.recheckStaleNeighbours(m, st); ok {
+				return m, st, probe.ParseIPNeighDevs(fresh)
+			}
 			return m, st, probe.ParseIPNeighDevs(out)
 		}
 	}
@@ -715,6 +728,54 @@ func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool,
 	return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
 }
 
+// recheckStaleNeighbours (#2073): un ping corto por cada vecino STALE, en
+// paralelo y desde la unidad, y una relectura de `ip neigh`. El kernel pasa a
+// REACHABLE la entrada cuya respuesta ARP llega, asi que lo confirmado es la
+// pareja IP-MAC. Devuelve la relectura y si se llego a hacer. Best effort.
+func (c *OpenWrtClient) recheckStaleNeighbours(arp map[string]string, stale map[string]bool) (string, bool) {
+	if c.pool == nil || len(stale) == 0 {
+		return "", false
+	}
+	c.stalePingMu.Lock()
+	recent := !c.stalePingAt.IsZero() && time.Since(c.stalePingAt) < probe.StalePingInterval
+	if !recent {
+		c.stalePingAt = time.Now()
+	}
+	c.stalePingMu.Unlock()
+	if recent {
+		return "", false
+	}
+	ips := probe.StalePingTargets(arp, stale)
+	if len(ips) == 0 {
+		return "", false
+	}
+	var cmd strings.Builder
+	for _, ip := range ips {
+		cmd.WriteString("ping -c 1 -W 1 ")
+		cmd.WriteString(ip)
+		cmd.WriteString(" >/dev/null 2>&1 & ")
+	}
+	cmd.WriteString("wait")
+	if _, err := c.pool.Run(c.Host, cmd.String(), probe.StalePingTimeout+2*time.Second); err != nil {
+		return "", false
+	}
+	out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0)
+	if err != nil || out == "" {
+		return "", false
+	}
+	fresh, stillStale := probe.ParseIPNeigh(out)
+	for mac := range stale {
+		if stillStale[mac] {
+			continue
+		}
+		if ip := fresh[mac]; ip != "" {
+			arp[mac] = ip
+		}
+		delete(stale, mac)
+	}
+	return out, true
+}
+
 // GetNetworks: redes logicas que la unidad declara en UCI (#1889). Es la
 // misma lectura que alimenta las VLANs, asi que una unidad por SSH tambien
 // tiene la vista de redes; lo que no tiene son los contadores por interfaz.

+ 112 - 0
server-go/internal/adapters/stale_arp_2073_test.go

@@ -0,0 +1,112 @@
+package adapters
+
+// stale_arp_2073_test.go - recheck activo de vecinos ARP en STALE por SSH.
+//
+// El mismo caso que cubre el agente (#2063) pero en una unidad sondeada por
+// SSH: el ping sale de la propia unidad, que es quien esta en la subred, y la
+// confirmacion se lee de la relectura de `ip neigh` (la entrada pasa a
+// REACHABLE cuando llega la respuesta ARP).
+
+import (
+	"context"
+	"errors"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+type staleArpPool struct {
+	mu    sync.Mutex
+	neigh []string
+	idx   int
+	calls []string
+}
+
+func (p *staleArpPool) Run(_, cmd string, _ time.Duration) (string, error) {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	p.calls = append(p.calls, cmd)
+	if cmd == probe.CmdIpNeigh {
+		if p.idx >= len(p.neigh) {
+			return p.neigh[len(p.neigh)-1], nil
+		}
+		out := p.neigh[p.idx]
+		p.idx++
+		return out, nil
+	}
+	if strings.Contains(cmd, "ping -c 1 -W 1") {
+		return "", nil
+	}
+	return "", errors.New("unexpected command")
+}
+
+func (p *staleArpPool) RunCtx(_ context.Context, host, cmd string, timeout time.Duration) (string, error) {
+	return p.Run(host, cmd, timeout)
+}
+
+func (p *staleArpPool) pingCalls() []string {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	var out []string
+	for _, c := range p.calls {
+		if strings.Contains(c, "ping -c 1 -W 1") {
+			out = append(out, c)
+		}
+	}
+	return out
+}
+
+const (
+	sshNeighStale = `192.168.2.10 dev br-lan lladdr AA:AA:AA:AA:AA:01 STALE
+192.168.2.11 dev br-lan lladdr AA:AA:AA:AA:AA:02 STALE
+192.168.2.12 dev br-lan lladdr AA:AA:AA:AA:AA:03 REACHABLE
+`
+	sshNeighAfterPing = `192.168.2.10 dev br-lan lladdr AA:AA:AA:AA:AA:01 REACHABLE
+192.168.2.11 dev br-lan lladdr AA:AA:AA:AA:AA:02 STALE
+192.168.2.12 dev br-lan lladdr AA:AA:AA:AA:AA:03 REACHABLE
+`
+)
+
+func TestGetArpRechecksStaleFromTheUnit(t *testing.T) {
+	pool := &staleArpPool{neigh: []string{sshNeighStale, sshNeighAfterPing}}
+	c := &OpenWrtClient{Host: "192.168.2.11", pool: pool}
+
+	arp, stale, _ := c.GetArp()
+
+	if stale["AA:AA:AA:AA:AA:01"] {
+		t.Fatalf("el vecino que respondio sigue stale: %v", stale)
+	}
+	if !stale["AA:AA:AA:AA:AA:02"] {
+		t.Fatalf("el vecino que no respondio debe seguir stale: %v", stale)
+	}
+	if arp["AA:AA:AA:AA:AA:01"] != "192.168.2.10" {
+		t.Fatalf("la IP confirmada se conserva: %v", arp)
+	}
+	pings := pool.pingCalls()
+	if len(pings) != 1 {
+		t.Fatalf("se esperaba un unico comando de ping, hubo %d: %v", len(pings), pings)
+	}
+	for _, want := range []string{"192.168.2.10", "192.168.2.11", "wait"} {
+		if !strings.Contains(pings[0], want) {
+			t.Fatalf("el comando de ping no lleva %q: %q", want, pings[0])
+		}
+	}
+	if strings.Contains(pings[0], "192.168.2.12") {
+		t.Fatalf("no se sondea un vecino ya confirmado: %q", pings[0])
+	}
+}
+
+func TestGetArpStaleRecheckIsThrottled(t *testing.T) {
+	pool := &staleArpPool{neigh: []string{sshNeighStale, sshNeighAfterPing}}
+	c := &OpenWrtClient{Host: "192.168.2.11", pool: pool}
+
+	_, _, _ = c.GetArp()
+	first := len(pool.pingCalls())
+	_, _, _ = c.GetArp()
+	if second := len(pool.pingCalls()); second != first {
+		t.Fatalf("la segunda lectura dentro del intervalo no debe pingear: %d -> %d", first, second)
+	}
+}