浏览代码

fix(snmp): intervalo de polling SNMP configurable y histeresis ghost-port (#414) (#434)

* fix(#404): muestra changelog del release en el asistente de actualización

En modo rolling se busca el body del release asociado al commit cuando el body del commit está vacío. Se añade fallback con enlace a las notas del release si no hay changelog.

* fix(#413,#415,#416): mejora detección de puertos y descubrimiento por hostname

- BuildEthPorts añade interfaces físicas no listadas en board.json (eth0, sfp+, etc.).

- Descubrimiento de routers resuelve hostname por PTR y lo usa al añadir, evitando problemas con IP y known_hosts.

* fix(snmp): intervalo de polling SNMP configurable y histeresis ghost-port (#414)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 月之前
父节点
当前提交
55ac27d64a

+ 11 - 1
CHANGELOG.md

@@ -5,7 +5,17 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
-<<<<<<< HEAD
+## [2.23.6] - 2026-09-01
+
+### Added
+
+- **Intervalo de polling SNMP configurable por switch (#414)**: los routers con SNMP activado ahora usan un `snmp_poll_interval` configurable (10-3600 s, default 60) en lugar de sondear en cada tick de 5 s. Se expone en el formulario de edicion del router (Ajustes > Routers) y en `PUT /api/config/routers/:id`.
+
+### Fixed
+
+- **Falsos positivos ghost-port en switches SNMP (#414)**: el `PortMonitor` aplica una histeresis temporal de 5 minutos de silencio real antes de declarar ghost-port en puertos procedentes de SNMP. Ademas, cuando un router SNMP se cachea entre polls, no se re-observa el mismo snapshot, evitando que el contador de polls sin trafico crezca artificialmente.
+- **Métricas duplicadas para routers SNMP (#414)**: el poller ya no inserta filas repetidas en `metrics` cuando reutiliza el snapshot cacheado de un switch SNMP.
+
 ## [2.23.5] - 2026-09-01
 
 ### Fixed

+ 2 - 2
app/package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "netpulse",
-  "version": "2.23.5",
+  "version": "2.23.6",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "netpulse",
-      "version": "2.23.5",
+      "version": "2.23.6",
       "dependencies": {
         "@hookform/resolvers": "^5.2.2",
         "@radix-ui/react-accordion": "^1.2.12",

+ 1 - 1
app/package.json

@@ -1,7 +1,7 @@
 {
   "name": "netpulse",
   "private": true,
-  "version": "2.23.5",
+  "version": "2.23.6",
   "type": "module",
   "scripts": {
     "dev": "vite",

+ 2 - 1
app/public/locales/en/translation.json

@@ -1065,7 +1065,8 @@
       "firmwareTargetHint": "Optional. If the installed firmware doesn't match this version, NetPulse alerts.",
       "snmpEnabled": "SNMP polling",
       "snmpCommunity": "Community (SNMPv2c)",
-      "snmpPort": "Port"
+      "snmpPort": "Port",
+      "snmpPollInterval": "Interval (s)"
     },
     "overrides": {
       "title": "Topology — manual tagging",

+ 2 - 1
app/public/locales/es/translation.json

@@ -1065,7 +1065,8 @@
       "firmwareTargetHint": "Opcional. Si el firmware instalado no coincide con esta versión, NetPulse lo avisa.",
       "snmpEnabled": "Sondeo SNMP",
       "snmpCommunity": "Comunidad (SNMPv2c)",
-      "snmpPort": "Puerto"
+      "snmpPort": "Puerto",
+      "snmpPollInterval": "Intervalo (s)"
     },
     "overrides": {
       "title": "Topología — etiquetado manual",

+ 34 - 15
app/src/pages/Settings.tsx

@@ -278,6 +278,7 @@ interface ConfigRouter {
   snmp_enabled: boolean
   snmp_community: string
   snmp_port: number
+  snmp_poll_interval: number
 }
 
 interface DiscoverCandidate {
@@ -312,6 +313,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editSnmpEnabled, setEditSnmpEnabled] = useState(false)
   const [editSnmpCommunity, setEditSnmpCommunity] = useState('')
   const [editSnmpPort, setEditSnmpPort] = useState(161)
+  const [editSnmpPollInterval, setEditSnmpPollInterval] = useState(60)
   const [editSubmitting, setEditSubmitting] = useState(false)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [copied, setCopied] = useState(false)
@@ -505,6 +507,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditSnmpEnabled(r.snmp_enabled ?? false)
     setEditSnmpCommunity(r.snmp_community ?? '')
     setEditSnmpPort(r.snmp_port ?? 161)
+    setEditSnmpPollInterval(r.snmp_poll_interval ?? 60)
     setError(null)
   }
 
@@ -527,6 +530,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           snmp_enabled: editSnmpEnabled,
           snmp_community: editSnmpCommunity.trim() || undefined,
           snmp_port: editSnmpPort,
+          snmp_poll_interval: editSnmpPollInterval,
         }),
       })
       if (res.status === 409) {
@@ -856,21 +860,36 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                           className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
                         />
                       </div>
-                      <div>
-                        <label htmlFor="snmp-port" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
-                          {t('settings.routers.snmpPort')}
-                        </label>
-                        <input
-                          id="snmp-port"
-                          type="number"
-                          min={1}
-                          max={65535}
-                          value={editSnmpPort}
-                          onChange={(e) => setEditSnmpPort(Number(e.target.value))}
-                          aria-label={t('settings.routers.snmpPort')}
-                          className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
-                        />
-                      </div>
+                        <div>
+                          <label htmlFor="snmp-port" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                            {t('settings.routers.snmpPort')}
+                          </label>
+                          <input
+                            id="snmp-port"
+                            type="number"
+                            min={1}
+                            max={65535}
+                            value={editSnmpPort}
+                            onChange={(e) => setEditSnmpPort(Number(e.target.value))}
+                            aria-label={t('settings.routers.snmpPort')}
+                            className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                          />
+                        </div>
+                        <div>
+                          <label htmlFor="snmp-poll-interval" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                            {t('settings.routers.snmpPollInterval')}
+                          </label>
+                          <input
+                            id="snmp-poll-interval"
+                            type="number"
+                            min={10}
+                            max={3600}
+                            value={editSnmpPollInterval}
+                            onChange={(e) => setEditSnmpPollInterval(Number(e.target.value))}
+                            aria-label={t('settings.routers.snmpPollInterval')}
+                            className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                          />
+                        </div>
                     </div>
                   )}
                 </div>

+ 1 - 1
server-go/internal/adapters/agent.go

@@ -469,7 +469,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	cached := l.extrasCache[cfg.ID]
 	l.mu.Unlock()
 
-	out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}}
+	out := &routerPolled{cfg: cfg, client: l.clients[cfg.ID], net: &NetDevBps{}, polledAt: time.Now().UnixMilli()}
 	sysInfo := &SysInfo{}
 	ramPct := 0
 

+ 31 - 1
server-go/internal/adapters/live.go

@@ -137,6 +137,9 @@ type routerPolled struct {
 	// dawnDetected: el agente reportó una sección DAWN en el payload. Se
 	// usa para mostrar el aviso de deprecación (#426).
 	dawnDetected bool
+	// polledAt (issue #414): epoch ms en que se realizó el sondeo real. Se
+	// usa para deduplicar filas de métricas cuando SNMP se cachea.
+	polledAt int64
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -207,6 +210,12 @@ type Live struct {
 	// snmpPorts (issue #309): contadores del último poll SNMP por router y
 	// puerto. Se usa para calcular rxBps/txBps entre polls sucesivos.
 	snmpPorts map[string]map[string]snmpPortSample
+	// snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
+	snmpLastPoll map[string]time.Time
+	// snmpLastMetricsTick (issue #414): polledAt del último tick que se persistió
+	// en la tabla metrics, para evitar filas duplicadas cuando se reutiliza el
+	// snapshot cacheado de un router SNMP.
+	snmpLastMetricsTick map[string]int64
 	lastPolled  map[string]*routerPolled
 	failCount   map[string]int
 	lastErr     map[string]error // último error del sondeo (issue #257: distinguir sin-acceso de caído)
@@ -303,6 +312,8 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		lastAgentIf:          map[string]*agentIfSample{},
 		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
+		snmpLastPoll:         map[string]time.Time{},
+		snmpLastMetricsTick:  map[string]int64{},
 		lastPolled:           map[string]*routerPolled{},
 		failCount:            map[string]int{},
 		lastErr:              map[string]error{},
@@ -439,6 +450,16 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.snmpPorts, id)
 		}
 	}
+	for id := range l.snmpLastPoll {
+		if !ids[id] {
+			delete(l.snmpLastPoll, id)
+		}
+	}
+	for id := range l.snmpLastMetricsTick {
+		if !ids[id] {
+			delete(l.snmpLastMetricsTick, id)
+		}
+	}
 	for id := range l.lastPolled {
 		if !ids[id] {
 			delete(l.lastPolled, id)
@@ -943,6 +964,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
 		luci: luciGood, wanInfo: wanInfo, vlans: vlansGood,
+		polledAt: l.now().UnixMilli(),
 	}, nil
 }
 
@@ -2688,9 +2710,13 @@ func (l *Live) AlertsEngine() *alerts.Engine { return l.engine }
 func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
 	l.mu.Lock()
 	polled := l.lastPolled
-	l.mu.Unlock()
 	rows := []MetricsRow{}
 	for id, p := range polled {
+		// issue #414: los routers SNMP cacheados repiten el mismo snapshot
+		// entre polls reales; no se vuelve a persistir la misma fila.
+		if p.cfg.SnmpEnabled && p.polledAt != 0 && p.polledAt <= l.snmpLastMetricsTick[id] {
+			continue
+		}
 		row := MetricsRow{
 			RouterID:  id,
 			CPU:       fptr(float64(p.cpu)),
@@ -2703,7 +2729,11 @@ func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
 			row.TxBps = p.net.TxBps
 		}
 		rows = append(rows, row)
+		if p.cfg.SnmpEnabled {
+			l.snmpLastMetricsTick[id] = p.polledAt
+		}
 	}
+	l.mu.Unlock()
 	return rows
 }
 

+ 23 - 13
server-go/internal/adapters/portmonitor.go

@@ -9,12 +9,13 @@ import (
 )
 
 const (
-	flapWindow         = 10 * time.Minute
-	flapThreshold      = 5
-	ghostConsecutive   = 3
-	ghostMinHistory   = 12
-	degradedConsec     = 3
-	degradedMinHistory = 12
+	flapWindow             = 10 * time.Minute
+	flapThreshold          = 5
+	ghostConsecutive       = 3
+	ghostMinHistory        = 12
+	snmpGhostMinDuration   = 5 * time.Minute
+	degradedConsec         = 3
+	degradedMinHistory     = 12
 )
 
 type portKey struct {
@@ -23,13 +24,14 @@ type portKey struct {
 }
 
 type portState struct {
-	up           bool
-	transitions  []time.Time
-	speedMbps    int
-	speedHistory []int
-	trafficTotal uint64
-	zeroStreak   int
-	hadTraffic   bool
+	up             bool
+	transitions    []time.Time
+	speedMbps      int
+	speedHistory   []int
+	trafficTotal   uint64
+	zeroStreak     int
+	hadTraffic     bool
+	lastTrafficAt  time.Time
 	// Incidentes abiertos (issue #366): mientras la condición persiste hay
 	// UNA sola alerta viva por puerto (EmitOrUpdate la refresca in situ);
 	// la flag dispara la alerta de recuperación exactamente una vez.
@@ -148,6 +150,7 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now tim
 		st.zeroStreak = 0
 		st.hadTraffic = false
 		st.trafficTotal = 0
+		st.lastTrafficAt = time.Time{}
 		st.ghostActive = false
 		return
 	}
@@ -158,12 +161,14 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now tim
 		st.trafficTotal = total
 		st.hadTraffic = false
 		st.zeroStreak = 0
+		st.lastTrafficAt = time.Time{}
 		st.ghostActive = false
 		return
 	}
 	if total > st.trafficTotal {
 		st.hadTraffic = true
 		st.zeroStreak = 0
+		st.lastTrafficAt = now
 	} else if st.hadTraffic {
 		st.zeroStreak++
 	}
@@ -172,6 +177,11 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now tim
 		return
 	}
 	if st.zeroStreak >= ghostConsecutive {
+		// issue #414: los puertos SNMP se sondean con menos frecuencia; exigir
+		// también un tiempo mínimo de silencio para reducir falsos positivos.
+		if p.Snmp && now.Sub(st.lastTrafficAt) < snmpGhostMinDuration {
+			return
+		}
 		st.ghostActive = true
 		engine.EmitOrUpdate(alerts.AlertEvent{
 			ID:          fmt.Sprintf("alert-ghost-%s-%s", key.routerID, key.portID),

+ 26 - 2
server-go/internal/adapters/snmp_live.go

@@ -10,6 +10,21 @@ import (
 )
 
 func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
+	// issue #414: si no ha pasado el intervalo configurado, reutiliza el último
+	// sondeo real para no martillear al switch con SNMP cada 5 s.
+	interval := cfg.SnmpPollInterval
+	if interval <= 0 {
+		interval = 60
+	}
+	now := l.now()
+	l.mu.Lock()
+	last, hasLast := l.lastPolled[cfg.ID]
+	lastPoll := l.snmpLastPoll[cfg.ID]
+	l.mu.Unlock()
+	if hasLast && last != nil && now.Sub(lastPoll) < time.Duration(interval)*time.Second {
+		return last, nil
+	}
+
 	session, err := npsnmp.NewSession(npsnmp.Config{
 		Host:      cfg.Host,
 		Port:      cfg.SnmpPort,
@@ -55,6 +70,10 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		})
 	}
 
+	for i := range ethPorts {
+		ethPorts[i].Snmp = true
+	}
+
 	prevPorts := l.snmpPrevPorts(cfg.ID)
 	l.mu.Lock()
 	l.snmpPortCache(cfg.ID, ethPorts)
@@ -92,12 +111,17 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		uptimeSec = float64(sysInfo.UpTimeSec)
 	}
 
-	return &routerPolled{
+	p := &routerPolled{
 		cfg:       cfg,
 		uptimeSec: uptimeSec,
 		ports:     ethPorts,
 		fdb:       fdbMap,
-	}, nil
+		polledAt:  now.UnixMilli(),
+	}
+	l.mu.Lock()
+	l.snmpLastPoll[cfg.ID] = now
+	l.mu.Unlock()
+	return p, nil
 }
 
 type snmpPortSample struct {

+ 102 - 0
server-go/internal/adapters/snmp_live_test.go

@@ -0,0 +1,102 @@
+package adapters
+
+import (
+	"context"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// issue #414: cuando no ha pasado el intervalo SNMP configurado, pollRouterSNMP
+// devuelve el snapshot cacheado sin tocar la red.
+func TestSNMPCachesWithinInterval(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	l.now = time.Now
+	cfg := RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true, SnmpPollInterval: 60}
+
+	cached := &routerPolled{
+		cfg:       cfg,
+		uptimeSec: 123,
+		ports:     []EthPort{{ID: "snmp-1", Label: "1", Up: true}},
+		polledAt:  time.Now().Add(-30 * time.Second).UnixMilli(),
+	}
+	l.lastPolled[cfg.ID] = cached
+	l.snmpLastPoll[cfg.ID] = time.Now().Add(-30 * time.Second)
+
+	p, err := l.pollRouterSNMP(cfg)
+	if err != nil {
+		t.Fatalf("unexpected error: %v", err)
+	}
+	if p != cached {
+		t.Fatal("expected cached routerPolled pointer")
+	}
+}
+
+// issue #414: un router SNMP cacheado solo genera UNA fila de métricas por
+// poll real; los ticks intermedios se omiten.
+func TestSNMPMetricsRowsDedup(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	cfg := RouterConfig{ID: "sw1", Host: "192.168.1.10", SnmpEnabled: true}
+	rx := 1e6
+	tx := 2e6
+	l.lastPolled["sw1"] = &routerPolled{
+		cfg:       cfg,
+		cpu:       1, ram: 2,
+		polledAt:  1000,
+		net:       &NetDevBps{RxBps: &rx, TxBps: &tx},
+	}
+
+	rows1 := l.GetMetricsRows(context.Background())
+	if len(rows1) != 1 {
+		t.Fatalf("first call rows = %d, want 1", len(rows1))
+	}
+
+	rows2 := l.GetMetricsRows(context.Background())
+	if len(rows2) != 0 {
+		t.Fatalf("second call rows = %d, want 0 (dedup)", len(rows2))
+	}
+}
+
+// issue #414: los puertos SNMP requieren un tiempo mínimo de silencio antes de
+// declarar ghost-port, aunque el contador de polls consecutivos sin tráfico ya
+// supere el umbral normal.
+func TestPortMonitorGhostSnmpHysteresis(t *testing.T) {
+	pm := NewPortMonitor(true)
+	engine := alerts.New(nil, nil)
+	now := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
+	pm.SetClock(func() time.Time { return now })
+
+	port := EthPort{ID: "snmp-1", Label: "Port1", Up: true, Speed: "1 Gbps", Snmp: true}
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	// Historia suficiente con tráfico creciente.
+	for i := 0; i < ghostMinHistory; i++ {
+		port.RxBytes += 1000
+		port.TxBytes += 500
+		now = now.Add(60 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	// Tráfico cero durante 4 minutos: el streak ya supera ghostConsecutive,
+	// pero el puerto es SNMP y aún no han pasado 5 minutos de silencio.
+	for i := 0; i < 4; i++ {
+		now = now.Add(60 * time.Second)
+		pm.SetClock(func() time.Time { return now })
+		pm.Observe("r1", []EthPort{port}, engine)
+	}
+
+	if n, _ := findAlerts(engine, "Ghost port: Port1 went silent"); n != 0 {
+		t.Fatalf("ghost alerts before min silence = %d, want 0", n)
+	}
+
+	// 70 segundos más de silencio: ahora sí se cumple la histeresis temporal.
+	now = now.Add(70 * time.Second)
+	pm.SetClock(func() time.Time { return now })
+	pm.Observe("r1", []EthPort{port}, engine)
+
+	if n, _ := findAlerts(engine, "Ghost port: Port1 went silent"); n != 1 {
+		t.Fatalf("ghost alerts after min silence = %d, want 1", n)
+	}
+}

+ 7 - 3
server-go/internal/adapters/types.go

@@ -451,6 +451,9 @@ type EthPort struct {
 	ConnectedTo string   `json:"connectedTo,omitempty"`
 	DeviceMac   string   `json:"deviceMac,omitempty"`
 	Detail      string   `json:"detail,omitempty"`
+	// Snmp indica que el puerto proviene de un switch gestionado por SNMP
+	// (issue #414). Se usa para aplicar histeresis temporal en ghost-port.
+	Snmp bool `json:"-"`
 	// Health: per-port health score (issue #299). Ausente si no se ha
 	// calculado (demo sin datos, puertos sin muestras).
 	Health *PortHealth `json:"health,omitempty"`
@@ -711,9 +714,10 @@ type RouterConfig struct {
 	// SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
 	// SnmpEnabled activa el poller SNMP; Community es la comunidad SNMPv2c
 	// ("" = "public"); Port es el puerto UDP (0 = 161 por defecto).
-	SnmpEnabled   bool   `json:"snmp_enabled"`
-	SnmpCommunity string `json:"snmp_community,omitempty"`
-	SnmpPort      int    `json:"snmp_port,omitempty"`
+	SnmpEnabled       bool `json:"snmp_enabled"`
+	SnmpCommunity     string `json:"snmp_community,omitempty"`
+	SnmpPort          int    `json:"snmp_port,omitempty"`
+	SnmpPollInterval  int    `json:"snmp_poll_interval,omitempty"` // segundos; 0 → default 60
 }
 
 // ---------------------------------------------------------------------------

+ 2 - 0
server-go/internal/db/db.go

@@ -402,6 +402,8 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
 	migrate(sqldb, "routers", "snmp_community", "ALTER TABLE routers ADD COLUMN snmp_community TEXT")
 	migrate(sqldb, "routers", "snmp_port", "ALTER TABLE routers ADD COLUMN snmp_port INTEGER NOT NULL DEFAULT 0")
+	// issue #414: intervalo de polling SNMP configurable (segundos; default 60).
+	migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
 
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// DB para que el siguiente arranque no dispare una "migración" espuria

+ 23 - 5
server-go/internal/httpapi/config.go

@@ -94,9 +94,10 @@ type routerInput struct {
 	// FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
 	FirmwareTarget *string `json:"firmware_target"`
 	// SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
-	SnmpEnabled   *bool   `json:"snmp_enabled"`
-	SnmpCommunity *string `json:"snmp_community"`
-	SnmpPort      *int    `json:"snmp_port"`
+	SnmpEnabled       *bool   `json:"snmp_enabled"`
+	SnmpCommunity     *string `json:"snmp_community"`
+	SnmpPort          *int    `json:"snmp_port"`
+	SnmpPollInterval  *int    `json:"snmp_poll_interval"` // issue #414; segundos
 }
 
 // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
@@ -198,6 +199,14 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 			return
 		}
 	}
+	snmpInterval := 60
+	if in.SnmpPollInterval != nil {
+		snmpInterval = *in.SnmpPollInterval
+		if snmpInterval < 10 || snmpInterval > 3600 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
+			return
+		}
+	}
 	for _, rt := range routerstore.ListRouters(s.db.DB) {
 		if rt.Host == host {
 			writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
@@ -207,7 +216,7 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 	created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
 		Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
 		FirmwareTarget: firmwareTarget,
-		SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort,
+		SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
 	})
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
@@ -281,6 +290,15 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		v := strings.TrimSpace(*in.FirmwareTarget)
 		firmwareTarget = &v
 	}
+	var snmpPollInterval *int
+	if in.SnmpPollInterval != nil {
+		v := *in.SnmpPollInterval
+		if v < 10 || v > 3600 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
+			return
+		}
+		snmpPollInterval = &v
+	}
 	var snmpPort *int
 	if in.SnmpPort != nil {
 		p := *in.SnmpPort
@@ -299,7 +317,7 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		Name: name, Host: host, Type: typ,
 		IsGateway: &gw, AgentOnly: &ao,
 		FirmwareTarget: firmwareTarget,
-		SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort,
+		SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
 	})
 	if !ok {
 		writeError(w, http.StatusNotFound, "not_found")

+ 1 - 1
server-go/internal/httpapi/server.go

@@ -49,7 +49,7 @@ import (
 // Version es la versión del backend (app.js:18). Es una var (no const) para
 // que goreleaser la inyecte con -X httpapi.Version={{.Version}} y el health
 // reporte la versión del tag; los builds locales caen al fallback.
-var Version = "2.23.5"
+var Version = "2.23.6"
 
 // Deps son las dependencias del servidor API (como createApp de app.js).
 type Deps struct {

+ 30 - 11
server-go/internal/routerstore/routerstore.go

@@ -27,7 +27,7 @@ const probeTimeout = 4 * time.Second
 // ListRouters devuelve la tabla routers ordenada is_gateway DESC,
 // created_at ASC, con is_gateway como booleano.
 func ListRouters(db *sql.DB) []adapters.RouterConfig {
-	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval FROM routers ORDER BY is_gateway DESC, created_at ASC")
 	if err != nil {
 		return []adapters.RouterConfig{}
 	}
@@ -35,9 +35,9 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 	out := []adapters.RouterConfig{}
 	for rows.Next() {
 		var r adapters.RouterConfig
-		var gw, ao, snmpEn, snmpPort int
+		var gw, ao, snmpEn, snmpPort, snmpInterval int
 		var name, ft, snmpComm sql.NullString
-		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort); err != nil {
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval); err != nil {
 			continue
 		}
 		r.Name = name.String
@@ -47,6 +47,7 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 		r.SnmpEnabled = snmpEn == 1
 		r.SnmpCommunity = snmpComm.String
 		r.SnmpPort = snmpPort
+		r.SnmpPollInterval = snmpInterval
 		out = append(out, r)
 	}
 	return out
@@ -126,9 +127,10 @@ type AddInput struct {
 	// FirmwareTarget: versión objetivo (issue #241). "" = sin comprobar.
 	FirmwareTarget string
 	// SNMP (issue #309): credenciales para sondeo SNMP.
-	SnmpEnabled   bool
-	SnmpCommunity string
-	SnmpPort      int
+	SnmpEnabled       bool
+	SnmpCommunity     string
+	SnmpPort          int
+	SnmpPollInterval  int // issue #414; 0 = default 60
 }
 
 // AddRouter inserta un router (si IsGateway, el resto pierde el flag —
@@ -165,9 +167,17 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 	if in.SnmpEnabled {
 		snmpEn = 1
 	}
+	snmpInterval := in.SnmpPollInterval
+	if snmpInterval <= 0 {
+		snmpInterval = 60
+	}
+	snmpPort := in.SnmpPort
+	if snmpPort <= 0 {
+		snmpPort = 161
+	}
 	if _, err := tx.Exec(
-		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
-		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, in.SnmpPort,
+		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval,
 	); err != nil {
 		return adapters.RouterConfig{}, err
 	}
@@ -203,9 +213,10 @@ type UpdateInput struct {
 	// FirmwareTarget: versión objetivo (issue #241). nil = no tocar; "" = limpiar.
 	FirmwareTarget *string
 	// SNMP (issue #309): nil = no tocar; puntero a bool/string/int = aplicar.
-	SnmpEnabled   *bool
-	SnmpCommunity *string
-	SnmpPort      *int
+	SnmpEnabled       *bool
+	SnmpCommunity     *string
+	SnmpPort          *int
+	SnmpPollInterval  *int // issue #414
 }
 
 // UpdateRouter actualiza un router existente por id. Si IsGateway pasa a true,
@@ -279,6 +290,14 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 		sets = append(sets, "snmp_port = ?")
 		args = append(args, *in.SnmpPort)
 	}
+	if in.SnmpPollInterval != nil {
+		v := *in.SnmpPollInterval
+		if v <= 0 {
+			v = 60
+		}
+		sets = append(sets, "snmp_poll_interval = ?")
+		args = append(args, v)
+	}
 	if len(sets) > 0 {
 		args = append(args, id)
 		if _, err := tx.Exec("UPDATE routers SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...); err != nil {