diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md index 618f0a644a..50d4380a99 100644 --- a/docs/release-control/v6/internal/subsystems/monitoring.md +++ b/docs/release-control/v6/internal/subsystems/monitoring.md @@ -263,6 +263,17 @@ The affected poll still reports the same grace-adjusted status and does not move its last-online timestamp. These fixtures do not establish an installed outage's cause or recovery. +### History expiry diagnostics do not own the metrics lock + +The in-memory History sweep finishes expiry and snapshots its removed and +remaining counts under the History lock, then releases it before debug output. +A blocked diagnostic may still delay the calling maintenance tick; it must not +prevent independent poll writers from adding samples or charts from reading +them. Retention and chart selection are unchanged. +`TestMetricsHistoryCleanupLoggingDoesNotBlockHistory` gates the cleanup log +after an expired guest is dropped and verifies a live node's retained and newly +written CPU points are readable before the sink returns. + ### Idle poll workers wake when work becomes eligible sooner An empty active queue has no idle recheck timer. If its head is in the diff --git a/internal/monitoring/metrics_history.go b/internal/monitoring/metrics_history.go index 0f23f314f1..a8d2c0f389 100644 --- a/internal/monitoring/metrics_history.go +++ b/internal/monitoring/metrics_history.go @@ -969,7 +969,6 @@ func (mh *MetricsHistory) GetDiskMetrics(resourceID string, metricType string, d // This prevents unbounded memory growth when containers/VMs are deleted. func (mh *MetricsHistory) Cleanup() { mh.mu.Lock() - defer mh.mu.Unlock() cutoffTime := time.Now().Add(-mh.retentionTime) var guestsRemoved, nodesRemoved, storageRemoved, disksRemoved int @@ -1046,19 +1045,26 @@ func (mh *MetricsHistory) Cleanup() { } } - // Log cleanup activity at debug level - if guestsRemoved > 0 || nodesRemoved > 0 || storageRemoved > 0 || disksRemoved > 0 { - log.Debug(). - Int("guestsRemoved", guestsRemoved). - Int("nodesRemoved", nodesRemoved). - Int("storageRemoved", storageRemoved). - Int("disksRemoved", disksRemoved). - Int("guestsRemaining", len(mh.guestMetrics)). - Int("nodesRemaining", len(mh.nodeMetrics)). - Int("storageRemaining", len(mh.storageMetrics)). - Int("disksRemaining", len(mh.diskMetrics)). - Msg("Cleaned up stale metrics history entries") + if guestsRemoved == 0 && nodesRemoved == 0 && storageRemoved == 0 && disksRemoved == 0 { + mh.mu.Unlock() + return } + + // Report counts from the completed sweep, without making chart readers + // or poll writers wait for a slow diagnostic sink. + guestsRemaining, nodesRemaining := len(mh.guestMetrics), len(mh.nodeMetrics) + storageRemaining, disksRemaining := len(mh.storageMetrics), len(mh.diskMetrics) + mh.mu.Unlock() + log.Debug(). + Int("guestsRemoved", guestsRemoved). + Int("nodesRemoved", nodesRemoved). + Int("storageRemoved", storageRemoved). + Int("disksRemoved", disksRemoved). + Int("guestsRemaining", guestsRemaining). + Int("nodesRemaining", nodesRemaining). + Int("storageRemaining", storageRemaining). + Int("disksRemaining", disksRemaining). + Msg("Cleaned up stale metrics history entries") } // cleanupMetrics removes points older than cutoff time. diff --git a/internal/monitoring/metrics_history_concurrency_test.go b/internal/monitoring/metrics_history_concurrency_test.go index f9dc001237..e42d19e86f 100644 --- a/internal/monitoring/metrics_history_concurrency_test.go +++ b/internal/monitoring/metrics_history_concurrency_test.go @@ -4,7 +4,11 @@ import ( "math/rand" "sync" "testing" + "testing/synctest" "time" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" ) func TestMetricsHistoryConcurrentAccess(t *testing.T) { @@ -75,4 +79,68 @@ func TestMetricsHistoryConcurrentAccess(t *testing.T) { } } +func TestMetricsHistoryCleanupLoggingDoesNotBlockHistory(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + now := time.Now() + history := NewMetricsHistory(1000, time.Hour) + // Insert via the real writer while the point is fresh, then age it + // out. An unrelated node still has recent CPU readings. + history.AddGuestMetric("expired", "cpu", 1, now) + time.Sleep(2 * time.Hour) + history.AddNodeMetric("live", "cpu", 7, time.Now()) + time.Sleep(time.Minute) + + // The package logger is shared. Do not run in parallel, and wait + // for all work to exit before restoring it. + saved, level := log.Logger, zerolog.GlobalLevel() + sink := blockedCacheExpiryLog{ + message: "Cleaned up stale metrics history entries", + entered: make(chan struct{}), + resume: make(chan struct{}), + } + log.Logger = zerolog.New(sink).Level(zerolog.DebugLevel) + zerolog.SetGlobalLevel(zerolog.DebugLevel) + done := make(chan struct{}) + go func() { + defer close(done) + history.Cleanup() + }() + defer func() { + close(sink.resume) + <-done + synctest.Wait() + log.Logger = saved + zerolog.SetGlobalLevel(level) + }() + synctest.Wait() + select { + case <-sink.entered: + default: + t.Fatal("cleanup did not emit the expiry diagnostic") + } + + // Trying the lock first also makes the adverse case fail without + // leaving the reader or writer stuck behind the gated logger. + if !history.mu.TryLock() { + t.Fatal("expiry diagnostic still owns the History lock needed by poll writers and chart readers") + } + _, retained := history.guestMetrics["expired"] + history.mu.Unlock() + if retained { + t.Error("expired entry was still present when its removal was logged") + } + + m := &Monitor{metricsHistory: history} + before := m.GetNodeMetricsForChart("live", "cpu", time.Hour) + if len(before) != 1 || before[0].Value != 7 { + t.Error("chart could not read the retained point while cleanup was logging") + } + history.AddNodeMetric("live", "cpu", 42, time.Now()) + after := m.GetNodeMetricsForChart("live", "cpu", time.Hour) + if len(after) != 2 || after[0].Value != 7 || after[1].Value != 42 { + t.Error("node sample write and chart read did not finish while cleanup was logging") + } + }) +} + // rand is automatically seeded in Go 1.20+