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

feat(telemetry): anonymous daily instance ping (#822) (#824)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
0bf1f2ba0f

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

@@ -57,6 +57,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
 	"github.com/gnacho/netpulse/server-go/internal/telegram"
+	"github.com/gnacho/netpulse/server-go/internal/telemetry"
 	"github.com/gnacho/netpulse/server-go/internal/tlscert"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
 	"github.com/gnacho/netpulse/server-go/internal/webhook"
@@ -657,6 +658,8 @@ func run() error {
 			staticDesc = "(embed)"
 		}
 		log.Printf("[netpulse] datos: %s · estáticos: %s", cfg.DataDir, staticDesc)
+		// Aviso anónimo diario de instancia activa (#822). Fail-silent.
+		telemetry.New(dbHandle, httpapi.Version, cfg.DemoMode).Start(context.Background())
 		p.Start()
 		upd.Start()
 		go fwScheduler.Start()

+ 202 - 0
server-go/internal/telemetry/telemetry.go

@@ -0,0 +1,202 @@
+// Package telemetry: aviso diario ANÓNIMO de instancia activa (#822).
+//
+// Manda, como mucho una vez al día, un GET a un endpoint del proyecto con un
+// identificador aleatorio de instalación (generado en local y guardado en kv),
+// la versión y el os/arch. No envía ni IPs, ni MACs, ni hostnames, ni datos de
+// red, y no guarda nada fuera de su propia instalación. Es fail-silent (un
+// fallo no afecta a la app) y se desactiva con NETPULSE_TELEMETRY=0.
+package telemetry
+
+import (
+	"context"
+	"crypto/rand"
+	"database/sql"
+	"encoding/hex"
+	"fmt"
+	"net/http"
+	"net/url"
+	"os"
+	"runtime"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+const (
+	defaultURL  = "https://netpulse.cloudless.club/instances"
+	kvInstallID = "telemetry.install_id"
+	kvLastSent  = "telemetry.last_sent"
+
+	// minGap: no reenviar antes de 23 h (el objetivo es ~1/día; el margen
+	// evita reenvíos por reinicios con reloj ligeramente distinto).
+	minGap     = 23 * time.Hour
+	checkEvery = time.Hour
+	maxJitter  = 3 * time.Minute
+)
+
+// Agent envía el ping anónimo diario.
+type Agent struct {
+	db      *db.DB
+	url     string
+	version string
+	enabled bool
+
+	client *http.Client
+	now    func() time.Time
+	newID  func() (string, error)
+}
+
+// New construye el agente desde el entorno. Queda desactivado si DEMO_MODE=1
+// (una demo no es una instancia real) o si NETPULSE_TELEMETRY es 0/false/off/no.
+// NETPULSE_TELEMETRY_URL permite cambiar el endpoint (por defecto, el del proyecto).
+func New(d *db.DB, version string, demo bool) *Agent {
+	a := &Agent{
+		db:      d,
+		url:     defaultURL,
+		version: version,
+		enabled: !demo,
+		client:  &http.Client{Timeout: 10 * time.Second},
+		now:     time.Now,
+		newID:   randomID,
+	}
+	if v := strings.TrimSpace(os.Getenv("NETPULSE_TELEMETRY_URL")); v != "" {
+		a.url = strings.TrimRight(v, "/")
+	}
+	if v, ok := os.LookupEnv("NETPULSE_TELEMETRY"); ok {
+		switch strings.ToLower(strings.TrimSpace(v)) {
+		case "0", "false", "off", "no":
+			a.enabled = false
+		}
+	}
+	return a
+}
+
+// Enabled indica si el aviso está activo.
+func (a *Agent) Enabled() bool { return a.enabled }
+
+func randomID() (string, error) {
+	b := make([]byte, 16)
+	if _, err := rand.Read(b); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(b), nil
+}
+
+// installID devuelve el id de instalación, creándolo (una vez) si no existe.
+func (a *Agent) installID() (string, error) {
+	var v string
+	err := a.db.QueryRow("SELECT value FROM kv WHERE key = ?", kvInstallID).Scan(&v)
+	if err == nil && v != "" {
+		return v, nil
+	}
+	if err != nil && err != sql.ErrNoRows {
+		return "", err
+	}
+	id, idErr := a.newID()
+	if idErr != nil {
+		return "", idErr
+	}
+	if _, err := a.setKV(kvInstallID, id); err != nil {
+		return "", err
+	}
+	return id, nil
+}
+
+func (a *Agent) setKV(key, value string) (sql.Result, error) {
+	return a.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		key, value)
+}
+
+func (a *Agent) lastSent() time.Time {
+	var v string
+	if err := a.db.QueryRow("SELECT value FROM kv WHERE key = ?", kvLastSent).Scan(&v); err != nil {
+		return time.Time{}
+	}
+	t, err := time.Parse(time.RFC3339, v)
+	if err != nil {
+		return time.Time{}
+	}
+	return t
+}
+
+// Due indica si toca enviar: nunca se envió o hace más de minGap.
+func (a *Agent) Due() bool {
+	last := a.lastSent()
+	if last.IsZero() {
+		return true
+	}
+	return a.now().Sub(last) >= minGap
+}
+
+// pingURL construye la URL del ping. Solo lleva id, versión y os/arch.
+func (a *Agent) pingURL(id string) string {
+	q := url.Values{}
+	q.Set("v", a.version)
+	q.Set("os", runtime.GOOS+"-"+runtime.GOARCH)
+	return a.url + "/" + url.PathEscape(id) + "?" + q.Encode()
+}
+
+// SendOnce envía el ping si está activo y toca, y persiste last_sent. Nunca
+// devuelve error al llamante en el bucle: es fail-silent por diseño.
+func (a *Agent) SendOnce(ctx context.Context) error {
+	if !a.enabled || !a.Due() {
+		return nil
+	}
+	id, err := a.installID()
+	if err != nil {
+		return err
+	}
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.pingURL(id), nil)
+	if err != nil {
+		return err
+	}
+	req.Header.Set("User-Agent", "netpulse-instance")
+	res, err := a.client.Do(req)
+	if err != nil {
+		return err
+	}
+	res.Body.Close()
+	if res.StatusCode >= 400 {
+		return fmt.Errorf("telemetry: HTTP %d", res.StatusCode)
+	}
+	_, _ = a.setKV(kvLastSent, a.now().UTC().Format(time.RFC3339))
+	return nil
+}
+
+// Start lanza el bucle en segundo plano (jitter inicial + chequeo horario).
+// No hace nada si el aviso está desactivado.
+func (a *Agent) Start(ctx context.Context) {
+	if !a.enabled {
+		return
+	}
+	go func() {
+		select {
+		case <-ctx.Done():
+			return
+		case <-time.After(jitter()):
+		}
+		_ = a.SendOnce(ctx)
+		t := time.NewTicker(checkEvery)
+		defer t.Stop()
+		for {
+			select {
+			case <-ctx.Done():
+				return
+			case <-t.C:
+				_ = a.SendOnce(ctx)
+			}
+		}
+	}()
+}
+
+// jitter reparte los envíos para no sincronizar todas las instancias.
+func jitter() time.Duration {
+	b := make([]byte, 4)
+	if _, err := rand.Read(b); err != nil {
+		return 0
+	}
+	ms := int64(b[0])<<24 | int64(b[1])<<16 | int64(b[2])<<8 | int64(b[3])
+	return time.Duration(ms%int64(maxJitter/time.Millisecond)) * time.Millisecond
+}

+ 132 - 0
server-go/internal/telemetry/telemetry_test.go

@@ -0,0 +1,132 @@
+// telemetry_test.go — #822: el ping anónimo solo lleva id+versión+os/arch,
+// se desactiva con NETPULSE_TELEMETRY=0 y no reenvía antes de 23 h.
+package telemetry
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func openTestDB(t *testing.T) *db.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d
+}
+
+func TestDisabledByEnvAndDemo(t *testing.T) {
+	t.Setenv("NETPULSE_TELEMETRY", "0")
+	if New(openTestDB(t), "v1", false).Enabled() {
+		t.Fatal("NETPULSE_TELEMETRY=0 debería desactivar el aviso")
+	}
+	t.Setenv("NETPULSE_TELEMETRY", "1")
+	if New(openTestDB(t), "v1", true).Enabled() {
+		t.Fatal("DEMO_MODE debería desactivar el aviso")
+	}
+}
+
+func TestSendOncePayloadAndLastSent(t *testing.T) {
+	var gotPath, gotQuery, gotUA string
+	var hits int
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		hits++
+		gotPath, gotQuery, gotUA = r.URL.Path, r.URL.RawQuery, r.UserAgent()
+		w.WriteHeader(http.StatusNoContent)
+	}))
+	defer srv.Close()
+
+	t.Setenv("NETPULSE_TELEMETRY", "1")
+	t.Setenv("NETPULSE_TELEMETRY_URL", srv.URL+"/instances")
+	d := openTestDB(t)
+	a := New(d, "v9.9.9", false)
+	a.newID = func() (string, error) { return "abc123", nil }
+	fixed := time.Date(2026, 9, 22, 12, 0, 0, 0, time.UTC)
+	a.now = func() time.Time { return fixed }
+
+	if err := a.SendOnce(context.Background()); err != nil {
+		t.Fatalf("SendOnce: %v", err)
+	}
+	if hits != 1 {
+		t.Fatalf("hits = %d, esperaba 1", hits)
+	}
+	if gotPath != "/instances/abc123" {
+		t.Fatalf("path = %q", gotPath)
+	}
+	if gotUA != "netpulse-instance" {
+		t.Fatalf("ua = %q", gotUA)
+	}
+	// El query solo puede llevar v y os.
+	for _, kv := range strings.Split(gotQuery, "&") {
+		if kv == "" {
+			continue
+		}
+		k := strings.SplitN(kv, "=", 2)[0]
+		if k != "v" && k != "os" {
+			t.Fatalf("parámetro inesperado en el ping: %q", k)
+		}
+	}
+	if !strings.Contains(gotQuery, "v=v9.9.9") {
+		t.Fatalf("falta la versión: %q", gotQuery)
+	}
+	// Tras enviar, no vuelve a tocar hasta pasadas 23 h.
+	if a.Due() {
+		t.Fatal("no debería tocar reenviar justo después")
+	}
+	a.now = func() time.Time { return fixed.Add(24 * time.Hour) }
+	if !a.Due() {
+		t.Fatal("debería tocar reenviar a las 24 h")
+	}
+	if err := a.SendOnce(context.Background()); err != nil {
+		t.Fatalf("SendOnce 2: %v", err)
+	}
+	if hits != 2 {
+		t.Fatalf("hits = %d, esperaba 2", hits)
+	}
+}
+
+func TestInstallIDStableAndPersisted(t *testing.T) {
+	t.Setenv("NETPULSE_TELEMETRY", "1")
+	d := openTestDB(t)
+	a := New(d, "v1", false)
+	id1, err := a.installID()
+	if err != nil || len(id1) != 32 {
+		t.Fatalf("installID = %q, %v", id1, err)
+	}
+	id2, _ := a.installID()
+	if id1 != id2 {
+		t.Fatalf("el id no es estable: %q != %q", id1, id2)
+	}
+	// Un agente nuevo sobre la misma BD reutiliza el id.
+	a2 := New(d, "v1", false)
+	id3, _ := a2.installID()
+	if id3 != id1 {
+		t.Fatalf("el id debería persistir entre arranques: %q != %q", id3, id1)
+	}
+}
+
+func TestHTTPErrorDoesNotMarkSent(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusNotFound)
+	}))
+	defer srv.Close()
+
+	t.Setenv("NETPULSE_TELEMETRY", "1")
+	t.Setenv("NETPULSE_TELEMETRY_URL", srv.URL+"/instances")
+	d := openTestDB(t)
+	a := New(d, "v1", false)
+	if err := a.SendOnce(context.Background()); err == nil {
+		t.Fatal("un 404 debería devolver error")
+	}
+	if !a.Due() {
+		t.Fatal("un fallo no debe marcar como enviado (se reintentará)")
+	}
+}