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

fix(collector): configure the TCP probe and say what it is (#1893) (#2036)

The latency sidecar is a TCP connect to port 22 every 5 seconds that never authenticates, which is what dropbear logs as Exit before auth. PROBE_PORT and PROBE_INTERVAL are now configurable, the startup line names the cadence and the port, and both READMEs explain the router-side lines.
Nacho 2 недель назад
Родитель
Сommit
a2eba440df
4 измененных файлов с 98 добавлено и 3 удалено
  1. 7 0
      README.es.md
  2. 2 0
      README.md
  3. 45 3
      collector/main.go
  4. 44 0
      collector/main_test.go

+ 7 - 0
README.es.md

@@ -288,6 +288,13 @@ opcionales:
 curl -fsSL --retry 3 -o /tmp/netpulse-install-collector.sh https://raw.githubusercontent.com/gnacho/netpulse/main/install-collector.sh && sh /tmp/netpulse-install-collector.sh
 ```
 
+Cada sonda es una conexión TCP al router que se cierra sin autenticar, así que
+un router con dropbear la registra como `Child connection` seguida de
+`Exit before auth: Exited normally`. Eso es la sonda, no un intento de login.
+`PROBE_PORT` (por defecto `22`) la apunta a un listener que no escriba una
+línea por conexión, por ejemplo la web del router en `80`, y `PROBE_INTERVAL`
+(por defecto `5s`) fija cada cuánto se ejecuta.
+
 **Modo on-box.** ¿Sin caja aparte? El servidor corre en el propio router
 OpenWrt, con config UCI y TLS autofirmado con pinning SPKI.
 

+ 2 - 0
README.md

@@ -278,6 +278,8 @@ generic SSH failure.
 curl -fsSL --retry 3 -o /tmp/netpulse-install-collector.sh https://raw.githubusercontent.com/gnacho/netpulse/main/install-collector.sh && sh /tmp/netpulse-install-collector.sh
 ```
 
+Each probe is a TCP connection to the router that is closed without authenticating, so a router with dropbear logs it as `Child connection` followed by `Exit before auth: Exited normally`. That is the probe, not a failed login. `PROBE_PORT` (default `22`) points it at a listener that does not log every connection, for example the router's web UI on `80`, and `PROBE_INTERVAL` (default `5s`) sets how often it runs.
+
 **On-box mode.** No spare box? The server itself runs on an OpenWrt router,
 with UCI config and self-signed TLS with SPKI pinning.
 

+ 45 - 3
collector/main.go

@@ -22,6 +22,7 @@ import (
 	"os"
 	"os/signal"
 	"path/filepath"
+	"strconv"
 	"strings"
 	"sync"
 	"syscall"
@@ -33,9 +34,17 @@ import (
 )
 
 const (
+	probeTimeout = 2 * time.Second
+	reloadEvery  = 5 * time.Minute
+)
+
+// Defaults de la sonda. Los dos se pueden cambiar por entorno al arrancar
+// (PROBE_INTERVAL y PROBE_PORT): cada sonda abre una conexión TCP contra el
+// router, así que cadencia y puerto deciden cuánto ruido deja en el log del
+// propio router (#1893).
+var (
 	probeInterval = 5 * time.Second
-	probeTimeout  = 2 * time.Second
-	reloadEvery   = 5 * time.Minute
+	probePort     = "22"
 )
 
 // Version del collector (la reporta /healthz y state.json; se fija con
@@ -55,6 +64,16 @@ type probeResult struct {
 
 func main() {
 	slog.Info("netpulse-collector arrancando", "version", Version)
+	if err := applyProbeEnv(os.Getenv); err != nil {
+		slog.Error("config de sonda", "err", err)
+		os.Exit(1)
+	}
+	// La sonda es un dial TCP que se cierra sin autenticar: en un router con
+	// dropbear eso deja "Child connection" + "Exit before auth: Exited
+	// normally" en su log. Se dice al arrancar para que nadie lo confunda con
+	// un intento de login ni con un fallo de SSH (#1893).
+	slog.Info("sonda TCP configurada", "cada", probeInterval.String(), "puerto", probePort,
+		"nota", "cada sonda abre y cierra una conexión TCP sin autenticar; el router la registra como Exit before auth")
 
 	dataDir := envOr("DATA_DIR", "/opt/netpulse-collector/data")
 	// Ruta real donde install.sh del servidor deja netpulse.db
@@ -287,7 +306,7 @@ func loadTargets(netpulseDB string) ([]Target, error) {
 		if err := rows.Scan(&name, &host); err != nil {
 			return nil, err
 		}
-		targets = append(targets, Target{Name: slug(name), Addr: net.JoinHostPort(host, "22")})
+		targets = append(targets, Target{Name: slug(name), Addr: net.JoinHostPort(host, probePort)})
 	}
 	if err := rows.Err(); err != nil {
 		return nil, err
@@ -427,6 +446,29 @@ func envOr(key, def string) string {
 	return def
 }
 
+// applyProbeEnv ajusta cadencia y puerto de la sonda desde el entorno. Ambos
+// son opcionales: sin ellos se mantiene el comportamiento de siempre (puerto
+// 22 cada 5 s). El puerto existe para poder apuntar la sonda a una boca cuyo
+// listener no escriba una línea por conexión (p. ej. la web del router) y
+// dejar el log de dropbear limpio (#1893).
+func applyProbeEnv(getenv func(string) string) error {
+	if raw := strings.TrimSpace(getenv("PROBE_INTERVAL")); raw != "" {
+		d, err := time.ParseDuration(raw)
+		if err != nil || d < time.Second || d > time.Hour {
+			return fmt.Errorf("PROBE_INTERVAL inválido: %q (1s..1h, p. ej. 30s)", raw)
+		}
+		probeInterval = d
+	}
+	if raw := strings.TrimSpace(getenv("PROBE_PORT")); raw != "" {
+		port, err := strconv.Atoi(raw)
+		if err != nil || port < 1 || port > 65535 {
+			return fmt.Errorf("PROBE_PORT inválido: %q (1..65535)", raw)
+		}
+		probePort = strconv.Itoa(port)
+	}
+	return nil
+}
+
 func ptr(f float64) *float64 { return &f }
 
 // hashJitter devuelve un número determinista [0, max) basado en el nombre

+ 44 - 0
collector/main_test.go

@@ -239,3 +239,47 @@ func TestReconcileStartsNew(t *testing.T) {
 		t.Errorf("started=%v children=%d, quiero 2 y 2", started, len(children))
 	}
 }
+
+// #1893: la cadencia y el puerto de la sonda son configurables, porque cada
+// sonda abre una conexión TCP que el router registra en su log.
+func TestApplyProbeEnv(t *testing.T) {
+	restore := func() {
+		probeInterval = 5 * time.Second
+		probePort = "22"
+	}
+	defer restore()
+
+	for _, tc := range []struct {
+		name     string
+		vars     map[string]string
+		interval time.Duration
+		port     string
+		wantErr  bool
+	}{
+		{name: "sin entorno mantiene los defaults", vars: map[string]string{}, interval: 5 * time.Second, port: "22"},
+		{name: "cadencia y puerto", vars: map[string]string{"PROBE_INTERVAL": "30s", "PROBE_PORT": "80"}, interval: 30 * time.Second, port: "80"},
+		{name: "cadencia con espacios", vars: map[string]string{"PROBE_INTERVAL": "  1m  "}, interval: time.Minute, port: "22"},
+		{name: "cadencia invalida", vars: map[string]string{"PROBE_INTERVAL": "pronto"}, wantErr: true},
+		{name: "cadencia demasiado corta", vars: map[string]string{"PROBE_INTERVAL": "100ms"}, wantErr: true},
+		{name: "cadencia demasiado larga", vars: map[string]string{"PROBE_INTERVAL": "2h"}, wantErr: true},
+		{name: "puerto no numerico", vars: map[string]string{"PROBE_PORT": "ssh"}, wantErr: true},
+		{name: "puerto fuera de rango", vars: map[string]string{"PROBE_PORT": "70000"}, wantErr: true},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			restore()
+			err := applyProbeEnv(func(k string) string { return tc.vars[k] })
+			if tc.wantErr {
+				if err == nil {
+					t.Fatalf("applyProbeEnv(%v) sin error", tc.vars)
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("applyProbeEnv(%v): %v", tc.vars, err)
+			}
+			if probeInterval != tc.interval || probePort != tc.port {
+				t.Fatalf("intervalo/puerto = %s/%s, quiero %s/%s", probeInterval, probePort, tc.interval, tc.port)
+			}
+		})
+	}
+}