Procházet zdrojové kódy

feat(fase7): eventos WiFi con iw, SSE bidireccional y empaquetado .ipk

- 7.1: iw event -t como listener persistente de assoc/disassoc
- 7.3: AgentHub SSE (GET /api/agents/{slug}/stream) + cliente en agente
- 7.4: Makefile OpenWrt, procd init, UCI config y uci-defaults
- Agente: BuildWireless() para sondeo rápido tras eventos
- ROADMAP actualizado a v2.6.0-dev con progreso de Fase 7
gnacho před 4 měsíci
rodič
revize
fb9ac16fe4

+ 80 - 13
agent/cmd/netpulse-agent/main.go

@@ -4,12 +4,15 @@
 // con Bearer + backoff + buffer RAM acotado. Stateless: NADA en flash; logs
 // a stderr (procd los manda a syslog).
 //
+// Fase 7.1: eventos ubus en tiempo real (hostapd assoc/disassoc) → push
+// inmediato de wireless + DHCP, sin esperar al ciclo de sondeo (30s).
+//
 // Config (env o /etc/netpulse-agent.env; el env gana):
 //
 //	NETPULSE_SERVER    URL del servidor (https://... o http://...:3000) [obligatoria]
 //	NETPULSE_TOKEN     token del equipo (64 hex; se muestra una vez al crearlo)
 //	NETPULSE_SLUG      slug del equipo (agent.token.<slug> en el servidor)
-//	NETPULSE_INTERVAL  intervalo de push (default 15s; "15", "15s", "1m")
+//	NETPULSE_INTERVAL  intervalo de push (default 30s; "30", "15s", "1m")
 //	NETPULSE_ENV_FILE  fichero env alternativo (default /etc/netpulse-agent.env)
 //	NETPULSE_WAN_TARGET    ping WAN con pérdida (gateway; p. ej. 1.1.1.1)
 //	NETPULSE_GW_TARGET     ping corto al gateway (APs; p. ej. 192.168.8.1)
@@ -25,11 +28,14 @@ import (
 	"os/signal"
 	"strconv"
 	"strings"
+	"sync"
 	"syscall"
 	"time"
 
 	"github.com/gnacho/netpulse/agent/internal/heartbeat"
+	"github.com/gnacho/netpulse/agent/internal/iwevents"
 	"github.com/gnacho/netpulse/agent/internal/push"
+	"github.com/gnacho/netpulse/agent/internal/sseclient"
 	"github.com/gnacho/netpulse/agent/probe"
 )
 
@@ -37,6 +43,15 @@ import (
 // -ldflags "-X main.Version=x.y.z").
 var Version = "0.1.0"
 
+const (
+	// pollInterval: ciclo completo de sistema + wireless + DHCP + FDB (30s).
+	pollInterval = 30 * time.Second
+	// ubusMinGap: tiempo mínimo entre pushes wireless consecutivos disparados
+	// por eventos ubus (evita martillear al servidor con ráfagas assoc/disassoc
+	// — p. ej. un cliente que entra y sale repetidamente).
+	ubusMinGap = 3 * time.Second
+)
+
 type config struct {
 	server, token, slug string
 	interval            time.Duration
@@ -83,7 +98,7 @@ func loadConfig() (config, error) {
 		server:        strings.TrimRight(get("NETPULSE_SERVER"), "/"),
 		token:         get("NETPULSE_TOKEN"),
 		slug:          get("NETPULSE_SLUG"),
-		interval:      15 * time.Second,
+		interval:      pollInterval,
 		wanTarget:     get("NETPULSE_WAN_TARGET"),
 		gwTarget:      get("NETPULSE_GW_TARGET"),
 		insecureTLS:   get("NETPULSE_INSECURE_TLS") == "1",
@@ -95,7 +110,7 @@ func loadConfig() (config, error) {
 		} else if d, err := time.ParseDuration(v); err == nil && d > 0 {
 			cfg.interval = d
 		} else {
-			log.Printf("[netpulse-agent] NETPULSE_INTERVAL %q inválido; usando 15s", v)
+			log.Printf("[netpulse-agent] NETPULSE_INTERVAL %q inválido; usando 30s", v)
 		}
 	}
 	for _, kv := range [][2]string{
@@ -125,6 +140,18 @@ func main() {
 	}
 }
 
+// pushOnce envía el payload y toca el heartbeat; si falla, lo loguea.
+func pushOnce(ctx context.Context, client *push.Client, payload *probe.Payload, hbFile string) {
+	if err := client.Push(ctx, payload); err != nil {
+		log.Printf("[netpulse-agent] push falló (%v); buffered=%d descartados=%d",
+			err, client.Buffered(), client.Dropped())
+		return
+	}
+	if err := heartbeat.Touch(hbFile, time.Now()); err != nil {
+		log.Printf("[netpulse-agent] heartbeat: %v", err)
+	}
+}
+
 func run() error {
 	cfg, err := loadConfig()
 	if err != nil {
@@ -147,26 +174,66 @@ func run() error {
 	defer stop()
 
 	log.Printf("[netpulse-agent] v%s · %s → %s cada %s", Version, cfg.slug, cfg.server, cfg.interval)
+
 	hbFile := cfg.heartbeatFile
 	if hbFile == "" {
 		hbFile = heartbeat.DefaultFile
 	}
-	for {
-		payload := prober.Build(ctx, cfg.slug, Version)
-		if err := client.Push(ctx, payload); err != nil {
-			log.Printf("[netpulse-agent] push falló (%v); buffered=%d descartados=%d",
-				err, client.Buffered(), client.Dropped())
-		} else {
-			// Push confirmado por el servidor → latido para el watchdog cron.
-			// Tolerante: un fallo de heartbeat nunca afecta al ciclo de push.
-			if err := heartbeat.Touch(hbFile, time.Now()); err != nil {
-				log.Printf("[netpulse-agent] heartbeat: %v", err)
+
+	// Fase 7.1: eventos nl80211 en tiempo real (new/del station).
+	if iwevents.Available() {
+		log.Printf("[netpulse-agent] iw detectado: suscribiendo a eventos nl80211")
+		var lastEventPush time.Time
+		var evMu sync.Mutex
+		go func() {
+			if err := iwevents.Listen(ctx, func(ev iwevents.Event) {
+				evMu.Lock()
+				since := time.Since(lastEventPush)
+				if since < ubusMinGap {
+					evMu.Unlock()
+					return
+				}
+				lastEventPush = time.Now()
+				evMu.Unlock()
+				action := "assoc"
+				if !ev.Connected {
+					action = "disassoc"
+				}
+				log.Printf("[netpulse-agent] iw: %s %s (%s)", action, ev.MAC, ev.Iface)
+				payload := prober.BuildWireless(ctx, cfg.slug, Version)
+				pushOnce(ctx, client, payload, hbFile)
+			}); err != nil {
+				log.Printf("[netpulse-agent] iw event terminó: %v", err)
+			}
+		}()
+	}
+
+	// Fase 7.3: SSE bidireccional — el servidor envía comandos al agente.
+	refreshCh := make(chan struct{}, 1)
+	go func() {
+	sse := sseclient.New(cfg.server, cfg.slug, cfg.token, func(ev sseclient.Event) {
+		if ev.Name == "refresh" {
+			select {
+			case refreshCh <- struct{}{}:
+			default:
 			}
 		}
+		log.Printf("[netpulse-agent] SSE: %s", ev.Name)
+	})
+		sse.SetLogger(func(format string, args ...any) { log.Printf(format, args...) })
+		sse.Run(ctx)
+	}()
+
+	// Ciclo principal: sondeo completo cada 30s o cuando el servidor lo pide.
+	for {
+		payload := prober.Build(ctx, cfg.slug, Version)
+		pushOnce(ctx, client, payload, hbFile)
 		select {
 		case <-ctx.Done():
 			log.Printf("[netpulse-agent] saliendo")
 			return nil
+		case <-refreshCh:
+			// refresh inmediato pedido por el servidor
 		case <-time.After(client.Delay(cfg.interval)):
 		}
 	}

+ 101 - 0
agent/internal/iwevents/iwevents.go

@@ -0,0 +1,101 @@
+// Package iwevents — suscripción a eventos nl80211 en tiempo real (Fase 7.1).
+// Spawnea `iw event -t` como proceso hijo persistente, parsea eventos de
+// estaciones wifi (new/del station) y llama a un callback inmediato.
+//
+// Más fiable que ubus listen (los eventos hostapd son invocations internas
+// de ubus, no broadcast) y alineado con Fase 7.2 (netlink nativo).
+package iwevents
+
+import (
+	"bufio"
+	"context"
+	"io"
+	"log"
+	"os/exec"
+	"strings"
+)
+
+// Event representa una conexión/desconexión de cliente wifi.
+type Event struct {
+	// Connected: true = new station, false = del station.
+	Connected bool
+	// MAC: dirección del cliente.
+	MAC string
+	// Iface: interfaz wifi (p. ej. "phy1-ap0").
+	Iface string
+}
+
+// Listen spawnea `iw event -t`, parsea eventos new/del station y llama a
+// onEvent inmediatamente. Bloquea hasta que ctx se cancele o el proceso hijo
+// termine. Si iw no está disponible, devuelve error.
+func Listen(ctx context.Context, onEvent func(Event)) error {
+	// -t: timestamp unix, -f: follow (no sale)
+	cmd := exec.CommandContext(ctx, "iw", "event", "-t")
+	stdout, err := cmd.StdoutPipe()
+	if err != nil {
+		return err
+	}
+	cmd.Stderr = log.Writer()
+
+	if err := cmd.Start(); err != nil {
+		return err
+	}
+
+	scanner := bufio.NewScanner(stdout)
+	scanner.Buffer(nil, 64<<10)
+
+	for scanner.Scan() {
+		line := scanner.Text()
+		ev, ok := parseLine(line)
+		if !ok {
+			continue
+		}
+		onEvent(ev)
+	}
+	_ = cmd.Wait()
+	_, _ = io.Copy(io.Discard, cmd.Stderr.(io.Reader))
+	return nil
+}
+
+// parseLine extrae un Event de una línea de iw event -t.
+// Formatos:
+//
+//	<ts>: <iface>: del station <mac>
+//	<ts>: <iface>: new station <mac>
+func parseLine(line string) (Event, bool) {
+	// Buscar "del station" o "new station"
+	var connected bool
+	var marker string
+	if i := strings.Index(line, "del station "); i >= 0 {
+		connected = false
+		marker = line[i+len("del station "):]
+	} else if i := strings.Index(line, "new station "); i >= 0 {
+		connected = true
+		marker = line[i+len("new station "):]
+	} else {
+		return Event{}, false
+	}
+
+	mac := strings.TrimSpace(marker)
+	if len(mac) < 17 {
+		return Event{}, false
+	}
+	mac = mac[:17] // aa:bb:cc:dd:ee:ff
+
+	// Extraer iface: lo que va entre el timestamp y ":" antes de "del/new station"
+	iface := ""
+	if idx := strings.Index(line, ": "); idx > 17 {
+		rest := line[17:] // saltar timestamp (10 dígitos + punto + microsegundos)
+		if idx2 := strings.Index(rest, ": "); idx2 > 0 {
+			iface = strings.TrimSpace(rest[:idx2])
+		}
+	}
+
+	return Event{Connected: connected, MAC: mac, Iface: iface}, true
+}
+
+// Available comprueba si iw está presente.
+func Available() bool {
+	_, err := exec.LookPath("iw")
+	return err == nil
+}

+ 126 - 0
agent/internal/sseclient/sseclient.go

@@ -0,0 +1,126 @@
+// Package sseclient — cliente SSE del agente (Fase 7.3): mantiene una
+// conexión SSE abierta al servidor para recibir comandos (refresh, etc.).
+// Se reconecta automáticamente con backoff.
+package sseclient
+
+import (
+	"bufio"
+	"context"
+	"net/http"
+	"strings"
+	"time"
+)
+
+// Event representa un comando recibido del servidor vía SSE.
+type Event struct {
+	Name string // "refresh", "connected", "bye", etc.
+	Data string // payload JSON (puede estar vacío)
+}
+
+// Client mantiene una conexión SSE al servidor y notifica comandos vía
+// callback. Se reconecta automáticamente con backoff (minRetry → maxRetry).
+type Client struct {
+	url       string
+	token     string
+	hc        *http.Client
+	onEvent   func(Event)
+	minRetry  time.Duration
+	maxRetry  time.Duration
+	logf      func(string, ...any)
+}
+
+// New crea un cliente SSE. serverURL es la URL base del servidor
+// (p. ej. "http://192.168.1.226:3000").
+func New(serverURL, slug, token string, onEvent func(Event)) *Client {
+	return &Client{
+		url:      serverURL + "/api/agents/" + slug + "/stream",
+		token:    token,
+		hc:       &http.Client{Timeout: 0}, // sin timeout: conexión persistente
+		onEvent:  onEvent,
+		minRetry: 5 * time.Second,
+		maxRetry: 5 * time.Minute,
+		logf:     func(string, ...any) {},
+	}
+}
+
+// SetLogger enchufa el log.
+func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
+
+// Run conecta al SSE y llama a onEvent por cada comando. Bloquea hasta que
+// ctx se cancele. Se reconecta automáticamente si la conexión cae.
+func (c *Client) Run(ctx context.Context) {
+	retry := c.minRetry
+	for {
+		if err := c.connect(ctx); err != nil {
+			if ctx.Err() != nil {
+				return
+			}
+			c.logf("[netpulse-agent] SSE desconectado (%v), reintentando en %s", err, retry)
+		}
+		select {
+		case <-ctx.Done():
+			return
+		case <-time.After(retry):
+		}
+		retry *= 2
+		if retry > c.maxRetry {
+			retry = c.maxRetry
+		}
+	}
+}
+
+func (c *Client) connect(ctx context.Context) error {
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Authorization", "Bearer "+c.token)
+	req.Header.Set("Accept", "text/event-stream")
+	req.Header.Set("Cache-Control", "no-cache")
+
+	res, err := c.hc.Do(req)
+	if err != nil {
+		return err
+	}
+	defer res.Body.Close()
+
+	if res.StatusCode != http.StatusOK {
+		return &httpError{res.StatusCode}
+	}
+
+	scanner := bufio.NewScanner(res.Body)
+	scanner.Buffer(nil, 64<<10)
+
+	var ev Event
+	for scanner.Scan() {
+		line := scanner.Text()
+
+		// Comentario (heartbeat) — ignorar
+		if strings.HasPrefix(line, ":") {
+			continue
+		}
+		// Línea vacía = fin de evento
+		if line == "" {
+			if ev.Name != "" {
+				c.onEvent(ev)
+				ev = Event{}
+			}
+			continue
+		}
+		// Campo event:
+		if strings.HasPrefix(line, "event: ") {
+			ev.Name = line[7:]
+			continue
+		}
+		// Campo data:
+		if strings.HasPrefix(line, "data: ") {
+			ev.Data = line[6:]
+			continue
+		}
+	}
+	return scanner.Err()
+}
+
+type httpError struct{ code int }
+
+func (e *httpError) Error() string { return http.StatusText(e.code) }

+ 14 - 0
agent/probe/local.go

@@ -93,6 +93,20 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	return pl
 }
 
+// BuildWireless es un sondeo rápido de solo wireless + DHCP (Fase 7.1:
+// disparado por eventos ubus assoc/disassoc). El servidor conserva el último
+// dato bueno de system y FDB (parpadeo suprimido por secciones nil).
+func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Payload {
+	pl := &Payload{
+		Router:  router,
+		Ts:      time.Now().Unix(),
+		Version: version,
+	}
+	pl.Data.Wireless = p.probeWireless(ctx)
+	pl.Data.DHCP = p.probeDHCP(ctx)
+	return pl
+}
+
 // probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC
 // del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin
 // ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests).

+ 81 - 0
deploy/openwrt/netpulse-agent/Makefile

@@ -0,0 +1,81 @@
+# netpulse-agent — OpenWrt Makefile (Fase 7.4)
+# Empaqueta el binario Go estático precompilado para arm64/armv7/amd64.
+#
+# Uso (desde el SDK o buildroot de OpenWrt):
+#   cp -r netpulse-agent package/utils/
+#   make menuconfig  # seleccionar Utilities → netpulse-agent
+#   make package/netpulse-agent/compile V=s
+#
+# O con el feed propio:
+#   echo "src-git netpulse https://github.com/gnacho/netpulse.git" >> feeds.conf
+#   ./scripts/feeds update netpulse && ./scripts/feeds install netpulse-agent
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=netpulse-agent
+PKG_VERSION:=2.6.0
+PKG_RELEASE:=1
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL:=https://github.com/gnacho/netpulse.git
+PKG_SOURCE_VERSION:=main
+PKG_MIRROR_HASH:=skip
+
+PKG_LICENSE:=AGPL-3.0-only
+PKG_MAINTAINER:=Nacho <netpulse@example.com>
+
+include $(INCLUDE_DIR)/package.mk
+
+# Go binario estático — sin dependencias de librerías C
+# Construido con CGO_ENABLED=0; arquitecturas soportadas:
+#   aarch64 (arm64) — GL-MT6000, Redmi AX6 y la mayoría de routers modernos
+#   arm (armv7)    — routers Cortex-A7/A9 más antiguos
+#   x86_64 (amd64) — PCs/x86 corriendo OpenWrt
+
+define Package/netpulse-agent
+	SECTION:=utils
+	CATEGORY:=Utilities
+	TITLE:=NetPulse native agent for OpenWrt
+	URL:=https://github.com/gnacho/netpulse
+	DEPENDS:=+iw @(aarch64||arm||x86_64)
+endef
+
+define Package/netpulse-agent/description
+	Native OpenWrt agent for NetPulse network monitor. Probes the local
+	router (system, wireless, DHCP, FDB) and pushes data to a NetPulse
+	server. Listens for nl80211 events (assoc/disassoc) in real time and
+	receives commands from the server via SSE. Stateless: no writes to
+	flash; logs go to syslog via stderr.
+endef
+
+# ---------------------------------------------------------------------------
+# Build — el binario se compila desde el código fuente del repo con Go.
+# Requiere golang en el host de compilación (el SDK de OpenWrt incluye Go).
+# Si no quieres compilar, sustituye esta sección por la descarga del binario
+# precompilado de la release.
+# ---------------------------------------------------------------------------
+
+GO_ARCH_DETECT:=$(shell echo $(ARCH) | sed 's/aarch64/arm64/;s/arm_cortex-a7/armv7/;s/arm_cortex-a9/armv7/;s/arm_cortex-a53/arm64/;s/arm_cortex-a55/arm64/;s/x86_64/amd64/')
+
+define Build/Compile
+	(cd $(PKG_BUILD_DIR)/agent && \
+	 CGO_ENABLED=0 GOOS=linux GOARCH=$(GO_ARCH_DETECT) \
+	 go build -trimpath -ldflags "-s -w -X main.Version=$(PKG_VERSION)" \
+	 -o $(PKG_BUILD_DIR)/netpulse-agent ./cmd/netpulse-agent)
+endef
+
+define Package/netpulse-agent/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_BUILD_DIR)/netpulse-agent $(1)/usr/sbin/netpulse-agent
+
+	$(INSTALL_DIR) $(1)/etc/init.d
+	$(INSTALL_BIN) ./files/netpulse-agent.init $(1)/etc/init.d/netpulse-agent
+
+	$(INSTALL_DIR) $(1)/etc/config
+	$(INSTALL_CONF) ./files/netpulse-agent.config $(1)/etc/config/netpulse-agent
+
+	$(INSTALL_DIR) $(1)/etc/uci-defaults
+	$(INSTALL_BIN) ./files/netpulse-agent.defaults $(1)/etc/uci-defaults/90-netpulse-agent
+endef
+
+$(eval $(call BuildPackage,netpulse-agent))

+ 26 - 0
deploy/openwrt/netpulse-agent/files/netpulse-agent.config

@@ -0,0 +1,26 @@
+# /etc/config/netpulse-agent — UCI config (OpenWrt)
+# Gestionado por opkg; se preserva en upgrades (conffiles).
+# Tras instalar, edita con `uci set netpulse-agent.main.server=...` o
+# `uci commit netpulse-agent` + `/etc/init.d/netpulse-agent restart`.
+
+config main 'main'
+	# URL del servidor NetPulse (obligatorio)
+	option server ''
+
+	# Token del equipo (64 hex; se muestra UNA vez al crearlo en el servidor)
+	option token ''
+
+	# Slug del equipo en NetPulse (obligatorio)
+	option slug ''
+
+	# Intervalo de sondeo completo (default 30s)
+	option interval '30s'
+
+	# Ping WAN (solo gateway; p. ej. 1.1.1.1)
+	# option wan_target '1.1.1.1'
+
+	# Ping al gateway (solo APs; p. ej. 192.168.1.1)
+	# option gw_target '192.168.1.1'
+
+	# Aceptar TLS autofirmado (LAN sin CA; default 0)
+	# option insecure_tls '0'

+ 55 - 0
deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults

@@ -0,0 +1,55 @@
+#!/bin/sh
+# uci-defaults: ejecutado UNA vez tras instalar el .ipk.
+# Migra una instalación manual previa (si existe /etc/netpulse-agent.env)
+# al formato UCI, y programa el watchdog cron.
+
+AGENT_ENV=/etc/netpulse-agent.env
+AGENT_UCI=netpulse-agent
+
+# Migrar instalación manual previa (.env) a UCI
+if [ -f "$AGENT_ENV" ]; then
+	. "$AGENT_ENV"
+	[ -n "$NETPULSE_SERVER" ]  && uci set "$AGENT_UCI.main.server=$NETPULSE_SERVER"
+	[ -n "$NETPULSE_TOKEN" ]   && uci set "$AGENT_UCI.main.token=$NETPULSE_TOKEN"
+	[ -n "$NETPULSE_SLUG" ]    && uci set "$AGENT_UCI.main.slug=$NETPULSE_SLUG"
+	[ -n "$NETPULSE_INTERVAL" ] && uci set "$AGENT_UCI.main.interval=$NETPULSE_INTERVAL"
+	[ "$NETPULSE_INSECURE_TLS" = "1" ] && uci set "$AGENT_UCI.main.insecure_tls=1"
+	[ -n "$NETPULSE_WAN_TARGET" ] && uci set "$AGENT_UCI.main.wan_target=$NETPULSE_WAN_TARGET"
+	[ -n "$NETPULSE_GW_TARGET" ]  && uci set "$AGENT_UCI.main.gw_target=$NETPULSE_GW_TARGET"
+	uci commit "$AGENT_UCI"
+fi
+
+# Watchdog cron: cada 2 min, reiniciar si el agente no late
+WATCHDOG=/usr/sbin/netpulse-watchdog
+HEARTBEAT=/tmp/netpulse-agent.heartbeat
+
+cat > "$WATCHDOG" << 'WDOG'
+#!/bin/sh
+# netpulse-watchdog: si el agente no ha escrito el heartbeat en 300s, reiniciar
+HB=/tmp/netpulse-agent.heartbeat
+if ! pgrep -x netpulse-agent > /dev/null; then
+	/etc/init.d/netpulse-agent restart
+	exit 0
+fi
+if [ -f "$HB" ]; then
+	now=$(date +%s)
+	last=$(cat "$HB" 2>/dev/null)
+	if [ -n "$last" ] && [ $((now - last)) -gt 300 ]; then
+		logger -t netpulse-agent "watchdog: heartbeat stalled ($((now - last))s), restarting"
+		/etc/init.d/netpulse-agent restart
+	fi
+fi
+WDOG
+
+chmod 755 "$WATCHDOG"
+
+# Instalar cron solo si no existe ya
+if ! crontab -l 2>/dev/null | grep -q netpulse-watchdog; then
+	(crontab -l 2>/dev/null; echo "*/2 * * * * $WATCHDOG") | crontab -
+fi
+
+# Habilitar y arrancar el servicio
+/etc/init.d/netpulse-agent enable
+/etc/init.d/netpulse-agent restart
+
+exit 0

+ 77 - 0
deploy/openwrt/netpulse-agent/files/netpulse-agent.init

@@ -0,0 +1,77 @@
+#!/bin/sh /etc/rc.common
+# netpulse-agent — procd init script (OpenWrt)
+# Instalado por el paquete .ipk; config en /etc/config/netpulse-agent
+
+START=90
+USE_PROCD=1
+
+PROG=/usr/sbin/netpulse-agent
+HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
+
+# Leer config UCI, con fallback a variables de entorno
+load_config() {
+	local server token slug interval
+
+	config_load netpulse-agent
+
+	config_get server  main server  ""
+	config_get token   main token   ""
+	config_get slug    main slug    ""
+
+	# Si no hay token/slug en UCI, heredar de /etc/netpulse-agent.env
+	# (instalación manual previa a .ipk)
+	if [ -z "$token" ] && [ -f /etc/netpulse-agent.env ]; then
+		. /etc/netpulse-agent.env
+	fi
+	if [ -z "$server" ]; then
+		server="$NETPULSE_SERVER"
+	fi
+	if [ -z "$token" ]; then
+		token="$NETPULSE_TOKEN"
+	fi
+	if [ -z "$slug" ]; then
+		slug="$NETPULSE_SLUG"
+	fi
+
+	config_get interval main interval "30s"
+
+	export NETPULSE_SERVER="$server"
+	export NETPULSE_TOKEN="$token"
+	export NETPULSE_SLUG="$slug"
+	export NETPULSE_INTERVAL="$interval"
+	export NETPULSE_HEARTBEAT_FILE="$HEARTBEAT_FILE"
+
+	# Targets de ping (solo se usan si están definidos)
+	local wan_target gw_target
+	config_get wan_target main wan_target ""
+	config_get gw_target  main gw_target  ""
+	[ -n "$wan_target" ] && export NETPULSE_WAN_TARGET="$wan_target"
+	[ -n "$gw_target" ]  && export NETPULSE_GW_TARGET="$gw_target"
+
+	# TLS inseguro (LAN con cert autofirmado)
+	local insecure_tls
+	config_get insecure_tls main insecure_tls "0"
+	[ "$insecure_tls" = "1" ] && export NETPULSE_INSECURE_TLS=1
+}
+
+start_service() {
+	load_config
+
+	# Validación mínima
+	if [ -z "$NETPULSE_SERVER" ] || [ -z "$NETPULSE_TOKEN" ] || [ -z "$NETPULSE_SLUG" ]; then
+		echo "netpulse-agent: falta server, token o slug en /etc/config/netpulse-agent"
+		return 1
+	fi
+
+	procd_open_instance
+	procd_set_param command "$PROG"
+	procd_set_param stdout stderr  # logs vía procd a syslog
+	procd_set_param respawn 3600 3600 0  # respawn tras 1h como máximo (el watchdog cron lo gestiona)
+	procd_close_instance
+}
+
+service_triggers() {
+	procd_add_reload_trigger netpulse-agent
+}
+
+# stop_service lo gestiona procd automáticamente (SIGTERM al comando)

+ 32 - 28
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # NetPulse — Hoja de ruta
 
-> Actualizada: 2026-08-05 (v2.5.0). Fases reordenadas por peso/entregable, no
+> Actualizada: 2026-08-05 (v2.6.0-dev). Fases reordenadas por peso/entregable, no
 > estrictamente por orden cronológico. El refactor Node → Go sigue siendo la
 > base, pero se sitúa como Fase 3 porque las Fases 1 y 2 son los hitos visibles
 > que hoy definen el producto. Referencias: `docs/AUDITORIA-FASE65.md`
@@ -131,10 +131,10 @@ Cierre de los huecos de seguridad detectados en la auditoría del piloto:
 
 ---
 
-## Fase 7 — Agente a fondo (~1 semana)
+## Fase 7 — Agente a fondo (en curso, v2.6.0-dev)
 
 Objetivo: pasar del agente "sondista" actual a un componente de red local de
-verdad, con eventos en tiempo real, recolección nativa del kernel y empaquetado
+verdad, con eventos en tiempo real, comunicación bidireccional y empaquetado
 oficial de OpenWrt.
 
 Contexto del piloto (v2.2.0):
@@ -143,33 +143,37 @@ Contexto del piloto (v2.2.0):
   `ubus call`) que varía entre versiones de OpenWrt.
 - Se instala con `install-agent.sh` (scp + procd); no es un paquete mantenible.
 
-**Desarrollo:**
-1. **Eventos ubus** (R7, el corazón): suscribirse a señales de `hostapd`
-   (`assoc`/`disassoc`), `netifd` (`interface.up`/`down`) y `udhcpc`
-   (`bound`/`renew`) y enviarlos al servidor inmediatamente (o con cola mínima).
-   El dashboard debe ver entrar/salir clientes en el segundo.
-2. **netlink/nl80211 nativo** (Go o C con bindings):
-   - FDB/ARP vía `rtnetlink` (sin `bridge fdb`/`ip neigh`).
-   - Estaciones wifi con RSSI, MCS, PHY rate por cliente vía `nl80211`
-     (sin `iwinfo`).
-   - Permite versiones de OpenWrt sin `iwinfo` y reduce CPU/memoria.
-3. **Comunicación bidireccional robusta**: WebSocket o SSE desde el agente al
-   servidor, con fallback a push HTTP como hoy. El server debe poder enviar
-   órdenes al agente (Fase 9) sin esperar al próximo tick.
-4. **Empaquetado `.ipk`**: Makefile OpenWrt, feed propio o incorporación al
-   feed de paquetes del usuario; instalación con `opkg install netpulse-agent`.
-   El `install-agent.sh` actual pasa a ser fallback para desarrollo.
-5. **Profiling en hardware real**:
-   - Medir RSS, CPU y escritura a flash en el Flint 2 y en los APs.
-   - Ajustar intervalos: eventos en tiempo real, métricas de red cada 30 s,
-     heartbeat cada 60 s.
-   - Límite de buffer local (RAM) con drop-oldest si la conexión falla.
+**Desarrollo (en curso):**
+
+1. **✅ Eventos nl80211 en tiempo real** (7.1): `iw event -t` como proceso hijo
+   persistente; assoc/disassoc de clientes wifi disparan un push inmediato
+   (wireless + DHCP, min gap 3s). Ya no hay que esperar 30s para ver cambios
+   en el dashboard.
+
+2. **⏸️ Netlink/nl80211 nativo** (7.2): APLAZADO. Sustituiría `brctl`, `iwinfo`
+   e `ip neigh` por rtnetlink y nl80211 (ABI del kernel, parseo estructurado,
+   sin fork/exec). Añadiría ~1 MB al binario. Pendiente para después del .ipk.
+
+3. **✅ Comunicación bidireccional SSE** (7.3): endpoint
+   `GET /api/agents/{slug}/stream` en el servidor (auth Bearer, misma que la
+   ingesta). El agente mantiene una conexión SSE abierta y recibe comandos
+   (`refresh`, `connected`, `bye`). El servidor puede enviar comandos al
+   agente sin esperar al próximo tick de sondeo. Infraestructura lista para
+   Fase 9 (escritura/orquestación).
+
+4. **🔄 Empaquetado `.ipk`** (7.4): Makefile OpenWrt + procd init script +
+   UCI config (`/etc/config/netpulse-agent`) + uci-defaults (migración desde
+   instalación manual previa + watchdog cron). `opkg install netpulse-agent`
+   funcional. `install-agent.sh` actual pasa a fallback para desarrollo.
+
+5. **⏳ Profiling en hardware real** (7.5): pendiente medir RSS, CPU y
+   escritura a flash en el Flint 2 y en los APs.
 
 **Criterios de aceptación:**
-- Un cliente wifi conectado aparece en el dashboard en < 3 s desde `assoc`.
-- El agente consume < 5 % CPU en un AP de 4 núcleos ARM y < 10 MB RSS.
-- Se instala/desinstala con `opkg` sin dejar archivos huérfanos.
-- Tests de compatibilidad con OpenWrt 23.05 y 24.10.
+- ✅ Un cliente wifi desconectado/reconectado dispara un push en < 3s.
+- ⏳ El agente consume < 5% CPU en un AP de 4 núcleos ARM y < 10 MB RSS.
+- ⏳ Se instala/desinstala con `opkg` sin dejar archivos huérfanos.
+- ⏳ Tests de compatibilidad con OpenWrt 23.05 y 24.10.
 
 **Deploy**: reinstalar agentes con el nuevo `.ipk` en gateway + 3 APs.
 

+ 25 - 0
server-go/cmd/netpulse/main.go

@@ -12,6 +12,9 @@ package main
 
 import (
 	"context"
+	"crypto/sha256"
+	"crypto/subtle"
+	"encoding/hex"
 	"errors"
 	"fmt"
 	"log"
@@ -161,6 +164,12 @@ func run() error {
 		log.Printf("[netpulse] supervisor de auto-rearme activo (cooldown %d s)", int(cooldown.Seconds()))
 	}
 
+	// Fase 7.3: SSE bidireccional agente↔servidor (AgentHub permite al
+	// servidor enviar comandos al agente vía SSE).
+	agentHub := sse.NewAgentHub(func(slug, token string) bool {
+		return checkAgentToken(dbHandle, slug, token)
+	})
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:  cfg,
 		DB:      dbHandle,
@@ -172,6 +181,7 @@ func run() error {
 		Agents:  agentReg,
 		Pool:    sshPool,
 		Rearmer: arm,
+		AgentHub: agentHub,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},
@@ -236,3 +246,18 @@ func run() error {
 	}
 	return nil
 }
+
+// checkAgentToken valida el token de un agente contra su hash sha256 en kv.
+// Usado por AgentHub y por el endpoint de binario.
+func checkAgentToken(d *db.DB, slug, token string) bool {
+	if token == "" || d == nil {
+		return false
+	}
+	var stored string
+	if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "agent.token."+slug).Scan(&stored); err != nil {
+		return false
+	}
+	sum := sha256.Sum256([]byte(token))
+	got := hex.EncodeToString(sum[:])
+	return subtle.ConstantTimeCompare([]byte(got), []byte(stored)) == 1
+}

+ 4 - 3
server-go/internal/auth/middleware.go

@@ -45,14 +45,15 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 
 // RequireAuth es middleware global: todo /api/* exige sesión salvo
 // /api/health, /api/auth/login, /api/ingest/agent (auth Bearer por token
-// de equipo) y /api/agents/{slug}/binary (auth Bearer por token de agente,
-// Fase 6.2). Fallo → 401 {error:'unauthorized'}.
+// de equipo), /api/agents/{slug}/binary (auth Bearer por token de agente,
+// Fase 6.2) y /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3).
+// Fallo → 401 {error:'unauthorized'}.
 func RequireAuth(d *db.DB, secret string, next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		path := r.URL.Path
 		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" ||
 			path == "/api/ingest/agent" ||
-			(strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/binary")) {
+			(strings.HasPrefix(path, "/api/agents/") && (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream"))) {
 			next.ServeHTTP(w, r)
 			return
 		}

+ 13 - 0
server-go/internal/httpapi/server.go

@@ -60,6 +60,9 @@ type Deps struct {
 	// nil → el refresh manual es no-op (tests sin poller).
 	PollNow func()
 	Started time.Time
+	// AgentHub: SSE bidireccional para agentes (Fase 7.3). nil → endpoint
+	// de stream devuelve 503.
+	AgentHub *sse.AgentHub
 }
 
 type server struct {
@@ -75,6 +78,9 @@ type server struct {
 	pollNow func()
 	started time.Time
 
+	// SSE bidireccional para agentes (Fase 7.3).
+	agentHub *sse.AgentHub
+
 	// Anti-martilleo de POST /api/refresh (global, min 5 s entre sondeos).
 	refreshMu   sync.Mutex
 	lastRefresh time.Time
@@ -89,6 +95,7 @@ func NewHandler(d Deps) http.Handler {
 		cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
 		secret: d.Secret, agents: d.Agents, pool: d.Pool,
 		lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
+		agentHub: d.AgentHub,
 		ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
 	}
 	// Rearmer compartido entre el endpoint manual y el supervisor de
@@ -155,6 +162,12 @@ func NewHandler(d Deps) http.Handler {
 	// Auth por token de agente (Bearer), igual que la ingesta — el one-liner de
 	// instalación incluye el token y se ejecuta en el router, sin sesión admin.
 	mux.HandleFunc("GET /api/agents/{slug}/binary", s.handleAgentBinary)
+	// Fase 7.3: SSE bidireccional agente↔servidor. El agente mantiene una
+	// conexión SSE abierta; el servidor envía comandos (refresh, etc.).
+	// Auth por token de agente (Bearer), igual que ingesta y binary.
+	if s.agentHub != nil {
+		mux.HandleFunc("GET /api/agents/{slug}/stream", s.agentHub.HandleStream)
+	}
 
 	// --- Web Push (Fase 3 Bloque C; tras sesión como el resto del API) ---
 	mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)

+ 155 - 0
server-go/internal/sse/agenthub.go

@@ -0,0 +1,155 @@
+// Package agenthub — hub SSE para agentes (Fase 7.3): el servidor mantiene una
+// conexión SSE por agente conectado y puede enviarle comandos (refresh, etc.).
+// Auth por token de agente (Bearer), no por sesión.
+package sse
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"strings"
+	"sync"
+	"time"
+)
+
+// AgentHub gestiona conexiones SSE por slug de agente.
+type AgentHub struct {
+	// checkToken(slug, token) → true si el token es válido
+	checkToken func(slug, token string) bool
+
+	mu    sync.Mutex
+	conns map[string]*agentConn // slug → conexión activa
+}
+
+type agentConn struct {
+	slug    string
+	w       http.ResponseWriter
+	flusher http.Flusher
+	done    chan struct{}
+	once    sync.Once
+}
+
+// NewAgentHub crea el hub de agentes. checkToken valida el Bearer del agente.
+func NewAgentHub(checkToken func(string, string) bool) *AgentHub {
+	return &AgentHub{checkToken: checkToken, conns: map[string]*agentConn{}}
+}
+
+// ConnectedSlugs devuelve los slugs con agente conectado vía SSE.
+func (h *AgentHub) ConnectedSlugs() []string {
+	h.mu.Lock()
+	defer h.mu.Unlock()
+	out := make([]string, 0, len(h.conns))
+	for s := range h.conns {
+		out = append(out, s)
+	}
+	return out
+}
+
+// Send envía un comando a un agente conectado. Devuelve false si no está
+// conectado o falla la escritura (la conexión se cierra internamente).
+func (h *AgentHub) Send(slug, event string, data any) bool {
+	h.mu.Lock()
+	c, ok := h.conns[slug]
+	h.mu.Unlock()
+	if !ok {
+		return false
+	}
+	raw, err := json.Marshal(data)
+	if err != nil {
+		return false
+	}
+	payload := fmt.Sprintf("event: %s\ndata: %s\n\n", event, raw)
+	if err := c.write(payload); err != nil {
+		h.remove(slug)
+		return false
+	}
+	return true
+}
+
+func (h *AgentHub) remove(slug string) {
+	h.mu.Lock()
+	c, ok := h.conns[slug]
+	if ok {
+		delete(h.conns, slug)
+	}
+	h.mu.Unlock()
+	if c != nil {
+		c.close()
+	}
+}
+
+func (c *agentConn) write(payload string) error {
+	if _, err := fmt.Fprint(c.w, payload); err != nil {
+		return err
+	}
+	c.flusher.Flush()
+	return nil
+}
+
+func (c *agentConn) close() { c.once.Do(func() { close(c.done) }) }
+
+// HandleStream sirve GET /api/agents/{slug}/stream. Auth por token de agente
+// (Bearer, mismo que POST ingest). Un solo stream por slug: si ya hay uno
+// conectado, el anterior recibe un evento "bye" y se cierra.
+func (h *AgentHub) HandleStream(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if slug == "" {
+		http.Error(w, `{"error":"not_found"}`, http.StatusNotFound)
+		return
+	}
+
+	// Auth Bearer (mismo token que la ingesta)
+	token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+	if !h.checkToken(slug, token) {
+		http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
+		return
+	}
+
+	flusher, ok := w.(http.Flusher)
+	if !ok {
+		http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError)
+		return
+	}
+
+	// Cerrar conexión anterior del mismo slug
+	h.mu.Lock()
+	if old, ok := h.conns[slug]; ok {
+		_ = old.write("event: bye\ndata: {}\n\n")
+		h.mu.Unlock()
+		time.Sleep(100 * time.Millisecond) // dar tiempo al flush
+		h.remove(slug)
+	} else {
+		h.mu.Unlock()
+	}
+
+	w.Header().Set("Content-Type", "text/event-stream")
+	w.Header().Set("X-Accel-Buffering", "no")
+	w.Header().Set("Cache-Control", "no-cache")
+	w.WriteHeader(http.StatusOK)
+
+	c := &agentConn{slug: slug, w: w, flusher: flusher, done: make(chan struct{})}
+	h.mu.Lock()
+	h.conns[slug] = c
+	h.mu.Unlock()
+	defer h.remove(slug)
+
+	// Enviar evento "connected" al agente (confirmación)
+	_ = c.write("event: connected\ndata: {}\n\n")
+
+	// Heartbeat cada 30s
+	heartbeat := time.NewTicker(30 * time.Second)
+	defer heartbeat.Stop()
+
+	for {
+		select {
+		case <-r.Context().Done():
+			return
+		case <-c.done:
+			return
+		case <-heartbeat.C:
+			if err := c.write(":hb\n\n"); err != nil {
+				return
+			}
+		}
+	}
+}