فهرست منبع

fix(collector): wait for cancelled probes before purging state (#1628)

Close a per-probe done channel and wait for it before calling onStop or starting the replacement probe, so a cancelled probe cannot write a stale sample after its target is removed or changes host. Also stop runProbe before writing metrics when its context is already cancelled.

Closes #1627
Nacho 1 ماه پیش
والد
کامیت
fb5447f7d5
2فایلهای تغییر یافته به همراه91 افزوده شده و 1 حذف شده
  1. 22 1
      collector/main.go
  2. 69 0
      collector/main_test.go

+ 22 - 1
collector/main.go

@@ -131,10 +131,12 @@ func main() {
 			return
 		}
 		cctx, ccancel := context.WithCancel(ctx)
-		children[t.Name] = childProc{cancel: ccancel, addr: t.Addr}
+		done := make(chan struct{})
+		children[t.Name] = childProc{cancel: ccancel, addr: t.Addr, done: done}
 		wg.Add(1)
 		go func(t Target) {
 			defer wg.Done()
+			defer close(done)
 			runProbe(cctx, ts, t, &mu, last)
 		}(t)
 		slog.Info("target añadido", "name", t.Name, "addr", t.Addr)
@@ -220,6 +222,7 @@ func main() {
 type childProc struct {
 	cancel context.CancelFunc
 	addr   string
+	done   <-chan struct{}
 }
 
 // reconcileTargets arranca sondas nuevas, reinicia las que cambiaron de host y
@@ -235,6 +238,7 @@ func reconcileTargets(children map[string]childProc, targets []Target, onStart f
 				continue // sin cambios
 			}
 			c.cancel()
+			waitChild(t.Name, c)
 			delete(children, t.Name)
 			slog.Warn("target cambió de host: reiniciando sonda",
 				"name", t.Name, "antes", c.addr, "ahora", t.Addr)
@@ -244,12 +248,26 @@ func reconcileTargets(children map[string]childProc, targets []Target, onStart f
 	for name, c := range children {
 		if !seen[name] {
 			c.cancel()
+			waitChild(name, c)
 			delete(children, name)
 			onStop(name)
 		}
 	}
 }
 
+// waitChild espera a que la sonda haya terminado para que no escriba en `last`
+// después de purgarla ni después de arrancar la sonda del host nuevo.
+func waitChild(name string, c childProc) {
+	if c.done == nil {
+		return
+	}
+	select {
+	case <-c.done:
+	case <-time.After(probeTimeout + time.Second):
+		slog.Warn("sonda no terminó tras cancelar", "name", name)
+	}
+}
+
 // loadTargets lee los routers de NetPulse en SOLO LECTURA + targets extra por env
 // (EXTRA_TARGETS="internet=1.1.1.1:443,nas=192.168.1.50:22").
 func loadTargets(netpulseDB string) ([]Target, error) {
@@ -332,6 +350,9 @@ func runProbe(ctx context.Context, ts *timeseries.TimeSeries, t Target, mu *sync
 	defer tick.Stop()
 	for {
 		res := probe(t.Addr)
+		if ctx.Err() != nil {
+			return
+		}
 		if res.OK {
 			ts.Write("tcp_latency_ms."+t.Name, res.LatencyMs)
 		}

+ 69 - 0
collector/main_test.go

@@ -6,6 +6,7 @@ import (
 	"reflect"
 	"strings"
 	"testing"
+	"time"
 )
 
 // Bug C4.3: colisión de slug → sufijo -2, -3… (nunca ignorar el segundo target).
@@ -128,6 +129,74 @@ func TestReconcileRemovePurges(t *testing.T) {
 	}
 }
 
+// F-23: antes de purgar `last` hay que esperar a que la sonda cancelada
+// termine. Si no, la sonda puede resucitar el target eliminado.
+func TestReconcileWaitsForProbeBeforeStop(t *testing.T) {
+	s := &spyReconcile{}
+	done := make(chan struct{})
+	children := map[string]childProc{
+		"ap": {addr: "192.168.1.2:22", cancel: func() {}, done: done},
+	}
+	returned := make(chan struct{})
+	go func() {
+		reconcileTargets(children, nil, s.onStart(children), s.onStop())
+		close(returned)
+	}()
+
+	select {
+	case <-returned:
+		t.Fatal("reconcileTargets terminó antes de que la sonda acabara")
+	case <-time.After(50 * time.Millisecond):
+	}
+	if len(s.stopped) != 0 {
+		t.Fatalf("onStop se llamó con la sonda viva: %v", s.stopped)
+	}
+
+	close(done)
+	select {
+	case <-returned:
+	case <-time.After(2 * time.Second):
+		t.Fatal("reconcileTargets no terminó tras acabar la sonda")
+	}
+	if !reflect.DeepEqual(s.stopped, []string{"ap"}) {
+		t.Errorf("onStop = %v, quiero [ap]", s.stopped)
+	}
+}
+
+// F-23: al cambiar de host, la sonda vieja debe terminar antes de arrancar la
+// nueva, para que no escriba una muestra del endpoint anterior.
+func TestReconcileWaitsForOldProbeBeforeStart(t *testing.T) {
+	s := &spyReconcile{}
+	done := make(chan struct{})
+	children := map[string]childProc{
+		"gw": {addr: "192.168.1.1:22", cancel: func() {}, done: done},
+	}
+	returned := make(chan struct{})
+	go func() {
+		reconcileTargets(children, []Target{{Name: "gw", Addr: "192.168.1.254:22"}}, s.onStart(children), s.onStop())
+		close(returned)
+	}()
+
+	select {
+	case <-returned:
+		t.Fatal("reconcileTargets arrancó la sonda nueva antes de acabar la vieja")
+	case <-time.After(50 * time.Millisecond):
+	}
+	if len(s.started) != 0 {
+		t.Fatalf("onStart se llamó con la sonda vieja viva: %+v", s.started)
+	}
+
+	close(done)
+	select {
+	case <-returned:
+	case <-time.After(2 * time.Second):
+		t.Fatal("reconcileTargets no terminó tras acabar la sonda vieja")
+	}
+	if len(s.started) != 1 || s.started[0].Addr != "192.168.1.254:22" {
+		t.Errorf("arrancadas = %+v, quiero gw con el host nuevo", s.started)
+	}
+}
+
 // El slug base no cambia con la dedup (regresión del helper slug()).
 func TestSlug(t *testing.T) {
 	cases := map[string]string{