Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(metrics): isolate statistics reads from history load

rcourtman02d8165b8b76
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 0404a4e2b7..de4a20b826 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -3151,3 +3151,13 @@ Router initialization no longer launches their five-second cached-metrics loop
or allocates per-resource pre-incident buffers. Explicit legacy archive reads
are lazy and bounded to the existing 16 MiB file limit. Canonical resource
history supplies current diagnostic evidence without a second sampling loop.
+
+Metrics-store operational statistics use one dedicated read-only connection,
+separate from the bounded history/write pool. Saturating history connections
+must not prevent `GetStats` from reading current committed tier counts. This
+is connection-capacity isolation, not cached or estimated statistics. The
+statistics pool belongs to the store and closes on normal or timed-out shutdown.
+The existing 500-node mixed-endpoint workload and latency budgets remain intact.
+`pkg/metrics/store_additional_test.go` holds every history connection to
+prove availability without relying on favourable scheduling, and covers
+committed-data visibility, write rejection, clear and pool shutdown.
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index dfe48f58c9..b478da9c2c 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -194,8 +194,12 @@ var (
// Store provides persistent metrics storage
type Store struct {
- db *pdb.InstrumentedDB
- config StoreConfig
+ db *pdb.InstrumentedDB
+ // Operational statistics must remain readable when history requests occupy
+ // every connection in the main pool. This separate pool has one read-only
+ // connection and reads current committed data, without a result cache.
+ statsDB *pdb.InstrumentedDB
+ config StoreConfig
// Cache compiled read SQL only. Results always come from the current
// database snapshot. Bound the number of parameter-count shapes retained.
@@ -335,6 +339,28 @@ func NewStore(config StoreConfig) (*Store, error) {
return nil, fmt.Errorf("failed to secure metrics db files: %w", err)
}
+ statsPath := filepath.ToSlash(config.DBPath)
+ if !strings.HasPrefix(statsPath, "/") {
+ statsPath = "/" + statsPath // Windows drive paths in a file URI.
+ }
+ statsURI := url.URL{Scheme: "file", Path: statsPath, RawQuery: url.Values{
+ "mode": {"ro"},
+ "_pragma": {"busy_timeout(30000)"},
+ }.Encode()}
+ statsDB, err := sql.Open("sqlite", statsURI.String())
+ if err != nil {
+ db.Close()
+ return nil, fmt.Errorf("failed to open metrics statistics reader: %w", err)
+ }
+ statsDB.SetMaxOpenConns(1)
+ statsDB.SetMaxIdleConns(1)
+ if err := statsDB.Ping(); err != nil {
+ statsDB.Close()
+ db.Close()
+ return nil, fmt.Errorf("failed to initialize metrics statistics reader: %w", err)
+ }
+ store.statsDB = pdb.Wrap(statsDB, "metrics")
+
// Keep metric ingestion independent from rollup, retention, and one-time
// startup maintenance. SQLite remains the write-serialization boundary,
// but long maintenance scheduling no longer prevents the write queue from
@@ -2266,7 +2292,7 @@ func (s *Store) Close() error {
case <-s.doneCh:
case <-shutdownTimer.C:
log.Warn().Msg("Metrics store ingestion shutdown timed out")
- return s.db.Close()
+ return s.closeDatabases()
}
select {
@@ -2275,7 +2301,15 @@ func (s *Store) Close() error {
log.Warn().Msg("Metrics store maintenance shutdown timed out")
}
- return s.db.Close()
+ return s.closeDatabases()
+}
+
+func (s *Store) closeDatabases() error {
+ var statsErr error
+ if s.statsDB != nil {
+ statsErr = s.statsDB.Close()
+ }
+ return errors.Join(statsErr, s.db.Close())
}
func ensureOwnerOnlyDir(dir string) error {
@@ -2381,7 +2415,7 @@ func (s *Store) GetStats() Stats {
stats := Stats{}
// Count by tier
- rows, err := s.db.Query(`SELECT tier, COUNT(*) FROM metrics GROUP BY tier`)
+ rows, err := s.statsDB.Query(`SELECT tier, COUNT(*) FROM metrics GROUP BY tier`)
if err == nil {
defer rows.Close()
for rows.Next() {
diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.go
index 5a3e12d82a..2f8c2d7b79 100644
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@ -2,6 +2,9 @@ package metrics
import (
"bytes"
+ "context"
+ "database/sql"
+ "fmt"
"os"
"path/filepath"
"strconv"
@@ -1346,3 +1349,109 @@ func TestStoreRetainedLargeQueryBindings(t *testing.T) {
}
}
}
+
+// Holding every history connection makes starvation deterministic, independent
+// of machine speed or how database/sql happens to schedule a request burst.
+func TestStoreStatsRemainAvailableWhenHistoryPoolIsSaturated(t *testing.T) {
+ for _, size := range []int{1, 4} {
+ t.Run(fmt.Sprintf("history_connections_%d", size), func(t *testing.T) {
+ cfg := DefaultConfig(t.TempDir())
+ cfg.FlushInterval = time.Hour
+ store, err := NewStore(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { store.Close() })
+ if err := store.WaitForMaintenance(5 * time.Second); err != nil {
+ t.Fatal(err)
+ }
+ store.Write("node", "one", "cpu", 10, time.Now())
+ store.Flush()
+ store.SetMaxOpenConns(size)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ var held []*sql.Conn
+ release := func() {
+ for _, conn := range held {
+ conn.Close()
+ }
+ held = nil
+ }
+ defer release()
+ for i := 0; i < size; i++ {
+ conn, err := store.db.DB.Conn(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ held = append(held, conn)
+ }
+ done := make(chan Stats, 1)
+ go func() { done <- store.GetStats() }()
+ select {
+ case stats := <-done:
+ if stats.RawCount != 1 {
+ t.Fatalf("statistics lost committed data: %+v", stats)
+ }
+ case <-time.After(2 * time.Second):
+ release()
+ <-done
+ t.Fatal("statistics waited for the saturated history connection pool")
+ }
+ })
+ }
+}
+
+func TestStoreStatsReaderObservesCommittedDataAndCloses(t *testing.T) {
+ cfg := DefaultConfig(t.TempDir() + "/metrics with spaces")
+ store, err := NewStore(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { store.Close() })
+ if err := store.WaitForMaintenance(5 * time.Second); err != nil {
+ t.Fatal(err)
+ }
+ store.Write("node", "one", "cpu", 10, time.Now())
+ store.Flush()
+ if stats := store.GetStats(); stats.RawCount != 1 {
+ t.Fatalf("missing flushed sample: %+v", stats)
+ }
+
+ tx, err := store.db.DB.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if _, err := tx.Exec(`INSERT INTO metrics
+ (resource_type, resource_id, metric_type, value, timestamp, tier)
+ VALUES ('node', 'two', 'cpu', 20, ?, 'raw')`, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if stats := store.GetStats(); stats.RawCount != 1 {
+ t.Fatalf("statistics exposed an uncommitted write: %+v", stats)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ if stats := store.GetStats(); stats.RawCount != 2 {
+ t.Fatalf("statistics failed to observe commit: %+v", stats)
+ }
+ if _, err := store.statsDB.Exec(`DELETE FROM metrics`); err == nil {
+ t.Fatal("statistics connection permitted a write")
+ }
+ if err := store.Clear(); err != nil {
+ t.Fatal(err)
+ }
+ if stats := store.GetStats(); stats.RawCount != 0 {
+ t.Fatalf("statistics retained cleared data: %+v", stats)
+ }
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.statsDB.DB.Ping(); err == nil {
+ t.Fatal("statistics pool remained open after store shutdown")
+ }
+ if err := store.db.DB.Ping(); err == nil {
+ t.Fatal("main pool remained open after store shutdown")
+ }
+}