Recover monitoring cache-lock repair on fixed FAQ CI base

Preserve the reviewed #5376 commit. Main now contains #5375, which aligns the FAQ test with the shipped article.

Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-28 10:32:19 +00:00
2 changed files with 192 additions and 23 deletions

View File

@@ -0,0 +1,143 @@
package monitoring
import (
"bytes"
"testing"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type blockedCacheExpiryLog struct {
message string
entered chan struct{}
resume chan struct{}
}
func (w blockedCacheExpiryLog) Write(p []byte) (int, error) {
if bytes.Contains(p, []byte(w.message)) {
close(w.entered)
<-w.resume
}
return len(p), nil
}
func TestCacheExpiryLoggingDoesNotHoldPollCacheLocks(t *testing.T) {
now := time.Now()
stale := now.Add(-2 * time.Hour)
const deadKey = "expired"
const instance, node, vmid = "live", "node", 105
guestKey := guestMetadataCacheKey(instance, node, vmid)
for _, kind := range []string{"metadata", "limiter", "node-snapshot", "guest-snapshot", "rrd"} {
t.Run(kind, func(t *testing.T) {
var message string
var sweep func(time.Time)
var checkLive func()
m := &Monitor{}
switch kind {
case "metadata", "limiter":
sweep = m.cleanupGuestMetadataCache
m.guestMetadataCache = map[string]guestMetadataCacheEntry{guestKey: metadataObservationFixture(now)}
if kind == "metadata" {
m.guestMetadataCache[deadKey] = metadataObservationFixture(stale)
message = "Cleaned up stale guest metadata cache entry"
} else {
m.guestMetadataLimiter = map[string]time.Time{deadKey: stale}
message = "Cleaned up stale guest metadata limiter entry"
}
checkLive = func() {
if !m.guestMetadataMu.TryRLock() {
t.Error("expiry logging held the guest metadata cache lock")
} else {
_, retained := m.guestMetadataCache[deadKey]
m.guestMetadataMu.RUnlock()
if retained {
t.Error("expired metadata was still present when its removal was logged")
}
if !m.hasRecentGuestMetadataEvidence(instance, node, vmid, now) {
t.Error("live guest lost its metadata observation")
}
}
if !m.guestMetadataLimiterMu.TryLock() {
t.Fatal("expiry logging held the guest metadata limiter lock")
}
_, retained := m.guestMetadataLimiter[deadKey]
m.guestMetadataLimiterMu.Unlock()
if retained {
t.Error("expired limiter was still present when its removal was logged")
}
if !m.tryReserveGuestMetadataFetch(guestKey, now) {
t.Fatal("live guest could not reserve its next read")
}
m.releaseGuestMetadataFetch(guestKey)
}
case "node-snapshot", "guest-snapshot":
sweep = m.cleanupDiagnosticSnapshots
m.guestSnapshots = map[string]GuestMemorySnapshot{guestKey: {Instance: instance, RetrievedAt: now}}
if kind == "node-snapshot" {
m.nodeSnapshots = map[string]NodeMemorySnapshot{deadKey: {RetrievedAt: stale}}
message = "Cleaned up stale node snapshot"
} else {
m.guestSnapshots[deadKey] = GuestMemorySnapshot{RetrievedAt: stale}
message = "Cleaned up stale guest snapshot"
}
checkLive = func() {
if !m.diagMu.TryRLock() {
t.Fatal("expiry logging held the diagnostic snapshots lock")
}
m.diagMu.RUnlock()
got := m.GetDiagnosticSnapshots()
if len(got.Nodes) != 0 || len(got.Guests) != 1 || got.Guests[0].Instance != instance || !got.Guests[0].RetrievedAt.Equal(now) {
t.Fatalf("diagnostic read did not preserve the live guest alone: %+v", got)
}
}
case "rrd":
sweep = m.cleanupRRDCache
message = "Cleaned up stale RRD cache entry"
m.nodeRRDMemCache = map[string]rrdMemCacheEntry{deadKey: {fetchedAt: stale}}
m.guestAgentFSInfoCacheTTL = vmFSInfoCacheTTL
m.storeVMFSInfo(instance, node, vmid, 100, nil, now)
checkLive = func() {
if !m.rrdCacheMu.TryLock() {
t.Fatal("expiry logging held the guest memory and filesystem cache lock")
}
_, retained := m.nodeRRDMemCache[deadKey]
m.rrdCacheMu.Unlock()
if retained {
t.Error("expired RRD sample was still present when its removal was logged")
}
if got, ok := m.cachedVMFSInfo(instance, node, vmid, 101, now); !ok || !got.fetchedAt.Equal(now) {
t.Fatal("poll lost its independent filesystem observation or changed its age")
}
}
}
// No parallel execution: the monitor writes through the package logger.
saved, level := log.Logger, zerolog.GlobalLevel()
sink := blockedCacheExpiryLog{message, make(chan struct{}), make(chan struct{})}
log.Logger = zerolog.New(sink).Level(zerolog.DebugLevel)
zerolog.SetGlobalLevel(zerolog.DebugLevel)
done := make(chan struct{})
go func() {
defer close(done)
sweep(now)
}()
defer func() {
close(sink.resume)
<-done
log.Logger = saved
zerolog.SetGlobalLevel(level)
}()
select {
case <-sink.entered:
checkLive()
case <-done:
t.Fatal("sweep did not emit its expiry diagnostic")
case <-time.After(5 * time.Second):
t.Fatal("sweep did not reach the gated logger")
}
})
}
}

View File

@@ -5478,6 +5478,23 @@ func (m *Monitor) cleanupRemovedHostAgents(now time.Time) {
}
}
type cacheExpiryLog struct {
key string
at time.Time
}
func cacheExpiryDebugEnabled() bool {
return logging.IsLevelEnabled(zerolog.DebugLevel) && log.Logger.GetLevel() <= zerolog.DebugLevel
}
// Write only after releasing the cache locks: the log sink can block even
// though live polls still need these caches to read and publish observations.
func logCacheExpiries(entries []cacheExpiryLog, keyField, timeField, message string) {
for _, entry := range entries {
log.Debug().Str(keyField, entry.key).Time(timeField, entry.at).Msg(message)
}
}
// cleanupGuestMetadataCache removes stale guest metadata cache and limiter entries.
// Idle entries older than 2x the cache TTL (10 minutes) are removed to prevent
// unbounded growth when VMs are deleted or moved. A successful observation's age
@@ -5485,12 +5502,13 @@ func (m *Monitor) cleanupRemovedHostAgents(now time.Time) {
// OS-info failure counter or known-unsupported command suppression.
func (m *Monitor) cleanupGuestMetadataCache(now time.Time) {
const maxAge = 2 * guestMetadataCacheTTL // 10 minutes
debug := cacheExpiryDebugEnabled()
var expiredCache, expiredLimiter []cacheExpiryLog
// Serialize the activity check with touches and reservations. No caller holds
// the metadata lock while acquiring the limiter lock; this order also keeps
// in-flight ownership intact throughout a sweep.
m.guestMetadataLimiterMu.Lock()
defer m.guestMetadataLimiterMu.Unlock()
m.guestMetadataMu.Lock()
for key, entry := range m.guestMetadataCache {
activityAt := m.guestMetadataLastAccess[key]
@@ -5499,10 +5517,9 @@ func (m *Monitor) cleanupGuestMetadataCache(now time.Time) {
}
if m.guestMetadataInFlight[key] == nil && now.Sub(activityAt) > maxAge {
delete(m.guestMetadataCache, key)
log.Debug().
Str("key", key).
Time("fetchedAt", entry.fetchedAt).
Msg("Cleaned up stale guest metadata cache entry")
if debug {
expiredCache = append(expiredCache, cacheExpiryLog{key, entry.fetchedAt})
}
}
}
m.guestMetadataMu.Unlock()
@@ -5516,12 +5533,15 @@ func (m *Monitor) cleanupGuestMetadataCache(now time.Time) {
// Keep near-term limiter state; remove long-idle keys.
if m.guestMetadataInFlight[key] == nil && now.Sub(nextAllowed) > maxAge {
delete(m.guestMetadataLimiter, key)
log.Debug().
Str("key", key).
Time("nextAllowed", nextAllowed).
Msg("Cleaned up stale guest metadata limiter entry")
if debug {
expiredLimiter = append(expiredLimiter, cacheExpiryLog{key, nextAllowed})
}
}
}
m.guestMetadataLimiterMu.Unlock()
logCacheExpiries(expiredCache, "key", "fetchedAt", "Cleaned up stale guest metadata cache entry")
logCacheExpiries(expiredLimiter, "key", "nextAllowed", "Cleaned up stale guest metadata limiter entry")
}
// cleanupTrackingMaps removes stale entries from various tracking maps to prevent unbounded memory growth.
@@ -5651,29 +5671,32 @@ func (m *Monitor) cleanupTrackingMaps(now time.Time) {
// when nodes/VMs are deleted or reconfigured.
func (m *Monitor) cleanupDiagnosticSnapshots(now time.Time) {
const maxAge = 1 * time.Hour
debug := cacheExpiryDebugEnabled()
var expiredNodes, expiredGuests []cacheExpiryLog
m.diagMu.Lock()
defer m.diagMu.Unlock()
for key, snapshot := range m.nodeSnapshots {
if now.Sub(snapshot.RetrievedAt) > maxAge {
delete(m.nodeSnapshots, key)
log.Debug().
Str("key", key).
Time("retrievedAt", snapshot.RetrievedAt).
Msg("Cleaned up stale node snapshot")
if debug {
expiredNodes = append(expiredNodes, cacheExpiryLog{key, snapshot.RetrievedAt})
}
}
}
for key, snapshot := range m.guestSnapshots {
if now.Sub(snapshot.RetrievedAt) > maxAge {
delete(m.guestSnapshots, key)
log.Debug().
Str("key", key).
Time("retrievedAt", snapshot.RetrievedAt).
Msg("Cleaned up stale guest snapshot")
if debug {
expiredGuests = append(expiredGuests, cacheExpiryLog{key, snapshot.RetrievedAt})
}
}
}
m.diagMu.Unlock()
logCacheExpiries(expiredNodes, "key", "retrievedAt", "Cleaned up stale node snapshot")
logCacheExpiries(expiredGuests, "key", "retrievedAt", "Cleaned up stale guest snapshot")
}
// cleanupRRDCache removes stale RRD memory cache entries.
@@ -5681,17 +5704,17 @@ func (m *Monitor) cleanupDiagnosticSnapshots(now time.Time) {
// unbounded growth when nodes or guests disappear from the poll set.
func (m *Monitor) cleanupRRDCache(now time.Time) {
const maxAge = 2 * nodeRRDCacheTTL // 1 minute
debug := cacheExpiryDebugEnabled()
var expiredNodes []cacheExpiryLog
m.rrdCacheMu.Lock()
defer m.rrdCacheMu.Unlock()
for key, entry := range m.nodeRRDMemCache {
if now.Sub(entry.fetchedAt) > maxAge {
delete(m.nodeRRDMemCache, key)
log.Debug().
Str("node", key).
Time("fetchedAt", entry.fetchedAt).
Msg("Cleaned up stale RRD cache entry")
if debug {
expiredNodes = append(expiredNodes, cacheExpiryLog{key, entry.fetchedAt})
}
}
}
@@ -5710,6 +5733,9 @@ func (m *Monitor) cleanupRRDCache(now time.Time) {
delete(m.vmFSInfoCache, key)
}
}
m.rrdCacheMu.Unlock()
logCacheExpiries(expiredNodes, "node", "fetchedAt", "Cleaned up stale RRD cache entry")
}
// cleanupMetricsHistory removes stale entries from the metrics history.