Sfoglia il codice sorgente

feat: path analysis with mtr results per hop (#343) (#360)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 mesi fa
parent
commit
4158d4336e

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

@@ -40,6 +40,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
 	"github.com/gnacho/netpulse/server-go/internal/poller"
 	"github.com/gnacho/netpulse/server-go/internal/push"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
@@ -210,6 +211,10 @@ func run() error {
 		return fmt.Errorf("wifi sle schema: %w", err)
 	}
 	wifiSLE := wifisle.NewStore(dbHandle)
+	if err := pathanalysis.EnsureSchema(dbHandle); err != nil {
+		return fmt.Errorf("path analysis schema: %w", err)
+	}
+	pathStore := pathanalysis.NewStore(dbHandle)
 
 	// Clave SSH propia para sondear routers (se genera la primera vez)
 	if err := sshkey.EnsureKeypair(cfg.SSHKeyPath); err != nil {
@@ -414,6 +419,7 @@ func run() error {
 		TokenStore:      tokenStore,
 		CollectorReader: collReader,
 		WiFiSLE:         wifiSLE,
+		PathAnalysis:    pathStore,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},

+ 74 - 0
server-go/internal/httpapi/path_api.go

@@ -0,0 +1,74 @@
+package httpapi
+
+import (
+	"net/http"
+)
+
+func (s *server) handlePathSummaries(w http.ResponseWriter, r *http.Request) {
+	if s.pathAnalysis == nil {
+		writeJSON(w, http.StatusOK, map[string]any{"summaries": []any{}, "available": false})
+		return
+	}
+	routerID := r.URL.Query().Get("router")
+	if routerID == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "router required")
+		return
+	}
+	summaries, err := s.pathAnalysis.Summaries(routerID)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "path_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"summaries": summaries, "available": true})
+}
+
+func (s *server) handlePathLatest(w http.ResponseWriter, r *http.Request) {
+	if s.pathAnalysis == nil {
+		writeError(w, http.StatusServiceUnavailable, "path_unavailable")
+		return
+	}
+	routerID := r.URL.Query().Get("router")
+	dest := r.URL.Query().Get("destination")
+	if routerID == "" || dest == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "router and destination required")
+		return
+	}
+	result, err := s.pathAnalysis.Latest(routerID, dest)
+	if err != nil {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	writeJSON(w, http.StatusOK, result)
+}
+
+func (s *server) handlePathHistory(w http.ResponseWriter, r *http.Request) {
+	if s.pathAnalysis == nil {
+		writeError(w, http.StatusServiceUnavailable, "path_unavailable")
+		return
+	}
+	routerID := r.URL.Query().Get("router")
+	dest := r.URL.Query().Get("destination")
+	if routerID == "" || dest == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "router and destination required")
+		return
+	}
+	results, err := s.pathAnalysis.History(routerID, dest, 20)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "path_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"results": results})
+}
+
+func (s *server) handlePathDestinations(w http.ResponseWriter, r *http.Request) {
+	if s.pathAnalysis == nil {
+		writeJSON(w, http.StatusOK, map[string]any{"destinations": []any{}, "available": false})
+		return
+	}
+	dests, err := s.pathAnalysis.AllDestinations()
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "path_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"destinations": dests, "available": true})
+}

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

@@ -32,6 +32,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/internethealth"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
 	"github.com/gnacho/netpulse/server-go/internal/presence"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/security"
@@ -94,6 +95,8 @@ type Deps struct {
 	Presence *presence.Store
 	// WiFiSLE: WiFi Service Level Expectations (#342). nil → sin SLEs.
 	WiFiSLE *wifisle.Store
+	// PathAnalysis: mtr path analysis (#343). nil → sin path data.
+	PathAnalysis *pathanalysis.Store
 }
 
 type server struct {
@@ -154,6 +157,9 @@ type server struct {
 
 	// WiFiSLE: WiFi Service Level Expectations (#342). nil = sin SLEs.
 	wifiSLE *wifisle.Store
+
+	// PathAnalysis: mtr path analysis (#343). nil = sin path data.
+	pathAnalysis *pathanalysis.Store
 }
 
 // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
@@ -172,6 +178,7 @@ func NewHandler(d Deps) http.Handler {
 		internetHealth:  d.InternetHealth,
 		presence:        d.Presence,
 		wifiSLE:         d.WiFiSLE,
+		pathAnalysis:    d.PathAnalysis,
 	}
 	// Rearmer compartido entre el endpoint manual y el supervisor de
 	// auto-rearme (cmd/netpulse lo construye y lo pasa para que ambos
@@ -245,6 +252,10 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/presence/people", s.handlePresencePeople)
 	mux.HandleFunc("GET /api/wifi-sles", s.handleWiFiSLESummary)
 	mux.HandleFunc("GET /api/wifi-sles/series", s.handleWiFiSLESeries)
+	mux.HandleFunc("GET /api/path/summaries", s.handlePathSummaries)
+	mux.HandleFunc("GET /api/path/latest", s.handlePathLatest)
+	mux.HandleFunc("GET /api/path/history", s.handlePathHistory)
+	mux.HandleFunc("GET /api/path/destinations", s.handlePathDestinations)
 	mux.HandleFunc("GET /api/metrics", s.handleMetrics)
 	mux.HandleFunc("GET /api/topology", s.handleTopology)
 	mux.HandleFunc("GET /api/dawn", s.handleDawn)

+ 190 - 0
server-go/internal/pathanalysis/store.go

@@ -0,0 +1,190 @@
+package pathanalysis
+
+import (
+	"database/sql"
+	"encoding/json"
+	"fmt"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+type Hop struct {
+	Index    int     `json:"index"`
+	Host     string  `json:"host"`
+	LossPct  float64 `json:"lossPct"`
+	AvgMs    float64 `json:"avgMs"`
+	BestMs   float64 `json:"bestMs"`
+	WorstMs  float64 `json:"worstMs"`
+	StdevMs  float64 `json:"stdevMs"`
+}
+
+type PathResult struct {
+	ID          int64  `json:"id"`
+	RouterID    string `json:"routerId"`
+	Destination string `json:"destination"`
+	TS          int64  `json:"ts"`
+	Hops        []Hop  `json:"hops"`
+	HopCount    int    `json:"hopCount"`
+	TotalMs     float64 `json:"totalMs"`
+}
+
+type PathSummary struct {
+	Destination string  `json:"destination"`
+	LastRun     int64   `json:"lastRun"`
+	HopCount    int     `json:"hopCount"`
+	TotalMs     float64 `json:"totalMs"`
+	WorstHop    int     `json:"worstHop"`
+	WorstLoss   float64 `json:"worstLoss"`
+}
+
+type Store struct {
+	db *db.DB
+}
+
+func NewStore(d *db.DB) *Store {
+	return &Store{db: d}
+}
+
+func EnsureSchema(d *db.DB) error {
+	_, err := d.Exec(`
+		CREATE TABLE IF NOT EXISTS path_results (
+			id INTEGER PRIMARY KEY AUTOINCREMENT,
+			router_id TEXT NOT NULL,
+			destination TEXT NOT NULL,
+			ts INTEGER NOT NULL,
+			hops_json TEXT NOT NULL,
+			hop_count INTEGER NOT NULL,
+			total_ms REAL NOT NULL DEFAULT 0
+		);
+		CREATE INDEX IF NOT EXISTS idx_path_results_lookup ON path_results(router_id, destination, ts DESC);
+	`)
+	return err
+}
+
+func (s *Store) Insert(r PathResult) error {
+	hopsJSON, err := json.Marshal(r.Hops)
+	if err != nil {
+		return err
+	}
+	_, err = s.db.Exec(
+		`INSERT INTO path_results (router_id, destination, ts, hops_json, hop_count, total_ms)
+		 VALUES (?, ?, ?, ?, ?, ?)`,
+		r.RouterID, r.Destination, r.TS, string(hopsJSON), r.HopCount, r.TotalMs,
+	)
+	return err
+}
+
+func (s *Store) Latest(routerID, destination string) (*PathResult, error) {
+	var r PathResult
+	var hopsJSON string
+	err := s.db.QueryRow(
+		`SELECT id, router_id, destination, ts, hops_json, hop_count, total_ms
+		 FROM path_results WHERE router_id = ? AND destination = ?
+		 ORDER BY ts DESC LIMIT 1`,
+		routerID, destination,
+	).Scan(&r.ID, &r.RouterID, &r.Destination, &r.TS, &hopsJSON, &r.HopCount, &r.TotalMs)
+	if err != nil {
+		return nil, err
+	}
+	if err := json.Unmarshal([]byte(hopsJSON), &r.Hops); err != nil {
+		return nil, err
+	}
+	return &r, nil
+}
+
+func (s *Store) History(routerID, destination string, limit int) ([]PathResult, error) {
+	if limit <= 0 || limit > 100 {
+		limit = 20
+	}
+	rows, err := s.db.Query(
+		`SELECT id, router_id, destination, ts, hops_json, hop_count, total_ms
+		 FROM path_results WHERE router_id = ? AND destination = ?
+		 ORDER BY ts DESC LIMIT ?`,
+		routerID, destination, limit,
+	)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []PathResult
+	for rows.Next() {
+		var r PathResult
+		var hopsJSON string
+		if err := rows.Scan(&r.ID, &r.RouterID, &r.Destination, &r.TS, &hopsJSON, &r.HopCount, &r.TotalMs); err != nil {
+			return nil, err
+		}
+		if err := json.Unmarshal([]byte(hopsJSON), &r.Hops); err != nil {
+			continue
+		}
+		out = append(out, r)
+	}
+	return out, rows.Err()
+}
+
+func (s *Store) Summaries(routerID string) ([]PathSummary, error) {
+	rows, err := s.db.Query(
+		`SELECT destination, MAX(ts), hop_count, total_ms
+		 FROM path_results WHERE router_id = ?
+		 GROUP BY destination ORDER BY destination`,
+		routerID,
+	)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []PathSummary
+	for rows.Next() {
+		var ps PathSummary
+		if err := rows.Scan(&ps.Destination, &ps.LastRun, &ps.HopCount, &ps.TotalMs); err != nil {
+			continue
+		}
+		var hopsJSON string
+		err := s.db.QueryRow(
+			`SELECT hops_json FROM path_results WHERE router_id = ? AND destination = ? ORDER BY ts DESC LIMIT 1`,
+			routerID, ps.Destination,
+		).Scan(&hopsJSON)
+		if err == nil {
+			var hops []Hop
+			if json.Unmarshal([]byte(hopsJSON), &hops) == nil {
+				for _, h := range hops {
+					if h.LossPct > ps.WorstLoss {
+						ps.WorstLoss = h.LossPct
+						ps.WorstHop = h.Index
+					}
+				}
+			}
+		}
+		out = append(out, ps)
+	}
+	return out, rows.Err()
+}
+
+func (s *Store) AllDestinations() ([]string, error) {
+	rows, err := s.db.Query("SELECT DISTINCT destination FROM path_results ORDER BY destination")
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []string
+	for rows.Next() {
+		var d string
+		if err := rows.Scan(&d); err != nil {
+			continue
+		}
+		out = append(out, d)
+	}
+	return out, rows.Err()
+}
+
+func (s *Store) Purge(olderThan time.Duration) (int64, error) {
+	cutoff := db.NowMS() - olderThan.Milliseconds()
+	res, err := s.db.Exec("DELETE FROM path_results WHERE ts < ?", cutoff)
+	if err != nil {
+		return 0, err
+	}
+	return res.RowsAffected()
+}
+
+var _ = sql.ErrNoRows
+var _ = fmt.Sprintf

+ 117 - 0
server-go/internal/pathanalysis/store_test.go

@@ -0,0 +1,117 @@
+package pathanalysis
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func setup(t *testing.T) *Store {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	if err := EnsureSchema(d); err != nil {
+		t.Fatal(err)
+	}
+	return NewStore(d)
+}
+
+func TestInsertAndLatest(t *testing.T) {
+	s := setup(t)
+	err := s.Insert(PathResult{
+		RouterID: "patio", Destination: "8.8.8.8", TS: db.NowMS(),
+		HopCount: 5, TotalMs: 25.3,
+		Hops: []Hop{
+			{Index: 1, Host: "192.168.1.1", AvgMs: 1.2, LossPct: 0},
+			{Index: 2, Host: "10.0.0.1", AvgMs: 5.1, LossPct: 0},
+			{Index: 3, Host: "172.16.0.1", AvgMs: 8.4, LossPct: 2.5},
+			{Index: 4, Host: "216.239.0.1", AvgMs: 15.2, LossPct: 0},
+			{Index: 5, Host: "8.8.8.8", AvgMs: 25.3, LossPct: 0},
+		},
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	r, err := s.Latest("patio", "8.8.8.8")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if r.HopCount != 5 || r.TotalMs != 25.3 {
+		t.Fatalf("unexpected result: %+v", r)
+	}
+	if len(r.Hops) != 5 {
+		t.Fatalf("expected 5 hops, got %d", len(r.Hops))
+	}
+	if r.Hops[2].LossPct != 2.5 {
+		t.Fatalf("hop 3 loss should be 2.5, got %.1f", r.Hops[2].LossPct)
+	}
+}
+
+func TestLatestNotFound(t *testing.T) {
+	s := setup(t)
+	_, err := s.Latest("nonexistent", "8.8.8.8")
+	if err == nil {
+		t.Fatal("expected error for nonexistent path")
+	}
+}
+
+func TestHistory(t *testing.T) {
+	s := setup(t)
+	now := db.NowMS()
+	for i := 0; i < 5; i++ {
+		_ = s.Insert(PathResult{
+			RouterID: "patio", Destination: "1.1.1.1",
+			TS: now - int64(i)*3600000, HopCount: 3, TotalMs: 10 + float64(i),
+			Hops: []Hop{{Index: 1, Host: "gw", AvgMs: 1}},
+		})
+	}
+	results, err := s.History("patio", "1.1.1.1", 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(results) != 5 {
+		t.Fatalf("expected 5 results, got %d", len(results))
+	}
+}
+
+func TestSummaries(t *testing.T) {
+	s := setup(t)
+	_ = s.Insert(PathResult{
+		RouterID: "patio", Destination: "8.8.8.8", TS: db.NowMS(),
+		HopCount: 4, TotalMs: 20,
+		Hops: []Hop{
+			{Index: 1, Host: "gw", LossPct: 0},
+			{Index: 2, Host: "isp", LossPct: 5.0},
+			{Index: 3, Host: "google", LossPct: 0},
+		},
+	})
+	_ = s.Insert(PathResult{
+		RouterID: "patio", Destination: "1.1.1.1", TS: db.NowMS(),
+		HopCount: 3, TotalMs: 15,
+		Hops: []Hop{{Index: 1, Host: "gw", LossPct: 0}},
+	})
+	summaries, err := s.Summaries("patio")
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(summaries) != 2 {
+		t.Fatalf("expected 2 summaries, got %d", len(summaries))
+	}
+}
+
+func TestPurge(t *testing.T) {
+	s := setup(t)
+	_ = s.Insert(PathResult{RouterID: "r1", Destination: "d1", TS: db.NowMS() - 86400000*30, HopCount: 1, Hops: []Hop{}})
+	_ = s.Insert(PathResult{RouterID: "r1", Destination: "d1", TS: db.NowMS(), HopCount: 1, Hops: []Hop{}})
+	n, err := s.Purge(7 * 24 * time.Hour)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if n != 1 {
+		t.Fatalf("expected 1 purged, got %d", n)
+	}
+}