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.

Isolate host and Docker CPU sampling baselines (#1894)

pulse-triage[bot]0f972f42f23a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e74911e30e..58c4ba25cc 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -7728,3 +7728,21 @@ counts projected from existing action audit records.
The `patrol_digest` report schedule kind in `internal/api/report_schedules.go`
only reads the digest and sends an email. It issues no agent commands, plans
no actions, and changes no capability, token, or binding state.
+
+### Independent module CPU sampling baselines
+
+The host default system collector retains its own `hostmetrics.Collector` for
+its lifetime. `Metrics` and `MetricsWithDiskFilters` use that same retained
+baseline; independent host collectors and the Docker module do not consume
+one another's CPU counters. Docker retains a separate module-scoped collector,
+not one per arbitrary Docker Agent instance. The first observation keeps the
+existing spot-sample fallback; subsequent observations measure the owning
+collector's reporting interval. Package-level hostmetrics convenience calls
+remain shared and must not be used for independent module reporting loops.
+
+`TestDefaultCollectorIndependentCPUBaselines` in
+`internal/hostagent/agent_metrics_test.go` exercises both host entry points
+against interleaved Linux procfs counters.
+`internal/hostmetrics/issue1894_interleaved_collectors_test.go` independently
+pins isolated collector deltas and startup fallback. This changes telemetry
+sampling only, not report schemas, identity, enrollment or command authority.
diff --git a/internal/dockeragent/deps.go b/internal/dockeragent/deps.go
index 4405da2768..8ab815cbe5 100644
--- a/internal/dockeragent/deps.go
+++ b/internal/dockeragent/deps.go
@@ -14,15 +14,18 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"
)
+// Docker reporting must not consume the host module or package-level CPU baseline.
+var dockerHostMetrics hostmetrics.Collector
+
var (
connectRuntimeFn = connectRuntime
connectCollectorRuntimeFn = connectCollectorOwnedRootlessRuntime
- hostmetricsCollect = hostmetrics.Collect
+ hostmetricsCollect = dockerHostMetrics.Collect
hostmetricsCollectWithDiskFilters = func(ctx context.Context, exclude, include []string) (hostmetrics.Snapshot, error) {
if len(include) == 0 {
return hostmetricsCollect(ctx, exclude)
}
- return hostmetrics.CollectWithDiskFilters(ctx, exclude, include)
+ return dockerHostMetrics.CollectWithDiskFilters(ctx, exclude, include)
}
newTickerFn = time.NewTicker
randomDurationFn = randomDuration
diff --git a/internal/hostagent/agent_metrics_test.go b/internal/hostagent/agent_metrics_test.go
index dd895994e3..854aa0b159 100644
--- a/internal/hostagent/agent_metrics_test.go
+++ b/internal/hostagent/agent_metrics_test.go
@@ -4,9 +4,12 @@ import (
"context"
"errors"
"fmt"
+ "math"
"net/http"
"net/http/httptest"
"os"
+ "path/filepath"
+ "runtime"
"strings"
"testing"
"time"
@@ -927,3 +930,45 @@ func TestCollectCommandOutputLimitedKeepsLegacyCollectorsCompatible(t *testing.T
t.Fatalf("bounded output = %q, want %q", output, "1234")
}
}
+
+// Pin the production SystemCollector routing, not just hostmetrics.Collector:
+// both entry points must retain one baseline per default collector (#1894).
+func TestDefaultCollectorIndependentCPUBaselines(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("uses Linux procfs counter fixtures")
+ }
+ proc := t.TempDir()
+ write := func(name, data string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(proc, name), []byte(data), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write("meminfo", "MemTotal: 8192 kB\nMemFree: 4096 kB\nMemAvailable: 4096 kB\n")
+ write("mountinfo", "")
+ t.Setenv("HOST_PROC", proc)
+ t.Setenv("HOST_PROC_MOUNTINFO", filepath.Join(proc, "mountinfo"))
+ a, b := NewDefaultCollector(), NewDefaultCollector()
+ samples := [][2]int{{10000, 100000}, {10080, 100020}, {10300, 105700}, {10380, 105720}, {10600, 111400}, {10680, 111420}}
+ for i, sample := range samples {
+ write("stat", fmt.Sprintf("cpu %d 0 0 %d 0 0 0 0 0 0\ncpu0 %d 0 0 %d 0 0 0 0 0 0\n", sample[0], sample[1], sample[0], sample[1]))
+ collector := a
+ if i%2 == 1 {
+ collector = b
+ }
+ var snapshot hostmetrics.Snapshot
+ var err error
+ // Alternate APIs on each instance to verify they share its retained state.
+ if (i/2)%2 == 0 {
+ snapshot, err = collector.Metrics(context.Background(), nil)
+ } else {
+ snapshot, err = collectMetricsWithDiskFilters(context.Background(), collector, nil, nil)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if i >= 2 && math.Abs(snapshot.CPUUsagePercent-5) > 1e-8 {
+ t.Fatalf("sample %d: CPU = %v, want full-interval 5%%", i, snapshot.CPUUsagePercent)
+ }
+ }
+}
diff --git a/internal/hostagent/sysinfo.go b/internal/hostagent/sysinfo.go
index 3bab6561a4..652a077df2 100644
--- a/internal/hostagent/sysinfo.go
+++ b/internal/hostagent/sysinfo.go
@@ -60,7 +60,9 @@ func NewDefaultCollector() SystemCollector {
return &defaultCollector{}
}
-type defaultCollector struct{}
+type defaultCollector struct {
+ metrics hostmetrics.Collector
+}
func (c *defaultCollector) HostInfo(ctx context.Context) (*gohost.InfoStat, error) {
return gohost.InfoWithContext(ctx)
@@ -71,11 +73,11 @@ func (c *defaultCollector) HostUptime(ctx context.Context) (uint64, error) {
}
func (c *defaultCollector) Metrics(ctx context.Context, exclude []string) (hostmetrics.Snapshot, error) {
- return hostmetrics.Collect(ctx, exclude)
+ return c.metrics.Collect(ctx, exclude)
}
func (c *defaultCollector) MetricsWithDiskFilters(ctx context.Context, exclude, include []string) (hostmetrics.Snapshot, error) {
- return hostmetrics.CollectWithDiskFilters(ctx, exclude, include)
+ return c.metrics.CollectWithDiskFilters(ctx, exclude, include)
}
func (c *defaultCollector) SensorsLocal(ctx context.Context) (string, error) {
diff --git a/internal/hostmetrics/collector.go b/internal/hostmetrics/collector.go
index ec0769d929..8267f63b7a 100644
--- a/internal/hostmetrics/collector.go
+++ b/internal/hostmetrics/collector.go
@@ -131,9 +131,24 @@ type Snapshot struct {
Network []agentshost.NetworkInterface
}
+// Collector owns the CPU baseline for one reporting loop. Its zero value is
+// ready to use. Retain it across reports; do not copy it after first use.
+type Collector struct {
+ cpu cpuUsageTracker
+}
+
+// Collect gathers metrics using this reporting loop's CPU baseline.
+func (c *Collector) Collect(ctx context.Context, diskExclude []string) (Snapshot, error) {
+ return c.CollectWithDiskFilters(ctx, diskExclude, nil)
+}
+
+var defaultCollector Collector
+
// Collect gathers a point-in-time snapshot of host resource utilisation.
// diskExclude contains user-defined patterns for devices or mount points to
// exclude. It preserves the original API for callers that do not need includes.
+// Package-level calls share a baseline; independent reporting loops must use
+// their own retained Collector.
func Collect(ctx context.Context, diskExclude []string) (Snapshot, error) {
return CollectWithDiskFilters(ctx, diskExclude, nil)
}
@@ -142,6 +157,12 @@ func Collect(ctx context.Context, diskExclude []string) (Snapshot, error) {
// and includes. Includes opt matching filesystems back in after Pulse's
// automatic pseudo-filesystem filtering. Explicit exclusions always win.
func CollectWithDiskFilters(ctx context.Context, diskExclude, diskInclude []string) (Snapshot, error) {
+ return defaultCollector.CollectWithDiskFilters(ctx, diskExclude, diskInclude)
+}
+
+// CollectWithDiskFilters gathers metrics with this loop's CPU baseline and
+// applies the same disk filtering as the package-level convenience function.
+func (c *Collector) CollectWithDiskFilters(ctx context.Context, diskExclude, diskInclude []string) (Snapshot, error) {
collectCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
@@ -153,7 +174,7 @@ func CollectWithDiskFilters(ctx context.Context, diskExclude, diskInclude []stri
log.Debug().Err(err).Msg("hostmetrics: failed to collect cpu count")
}
- if cpuUsage, err := collectCPUUsage(collectCtx); err == nil {
+ if cpuUsage, err := c.cpu.collect(collectCtx); err == nil {
snapshot.CPUUsagePercent = cpuUsage
} else {
log.Debug().Err(err).Msg("hostmetrics: failed to collect cpu usage")
@@ -255,13 +276,10 @@ type cpuUsageTracker struct {
hasPrev bool
}
-// defaultCPUUsage backs Collect. The state is process-wide by design: every
-// consumer of Collect reports a busy average over the window since the
-// previous collection, which stays correct even if collections interleave.
-var defaultCPUUsage = &cpuUsageTracker{}
-
+// collectCPUUsage preserves the package-level convenience path. Independent
+// reporting loops must retain their own Collector instead.
func collectCPUUsage(ctx context.Context) (float64, error) {
- return defaultCPUUsage.collect(ctx)
+ return defaultCollector.cpu.collect(ctx)
}
func (t *cpuUsageTracker) collect(ctx context.Context) (float64, error) {
diff --git a/internal/hostmetrics/issue1894_interleaved_collectors_test.go b/internal/hostmetrics/issue1894_interleaved_collectors_test.go
new file mode 100644
index 0000000000..9821f95084
--- /dev/null
+++ b/internal/hostmetrics/issue1894_interleaved_collectors_test.go
@@ -0,0 +1,134 @@
+package hostmetrics
+
+import (
+ "context"
+ "math"
+ "testing"
+ "time"
+
+ gocpu "github.com/shirou/gopsutil/v4/cpu"
+ godisk "github.com/shirou/gopsutil/v4/disk"
+ goload "github.com/shirou/gopsutil/v4/load"
+ gomem "github.com/shirou/gopsutil/v4/mem"
+ gonet "github.com/shirou/gopsutil/v4/net"
+)
+
+// Two near-synchronous reporting loops must each retain a full-interval
+// baseline, not measure the brief busy burst between their reports (#1894).
+func TestIssue1894InterleavedCollectors(t *testing.T) {
+ origCPUCounts := cpuCounts
+ origCPUPercent := cpuPercent
+ origCPUTimes := cpuTimes
+ origLoadAvg := loadAvg
+ origVirtualMemory := virtualMemory
+ origDiskPartitions := diskPartitions
+ origDiskUsage := diskUsage
+ origDiskIOCounters := diskIOCounters
+ origNetInterfaces := netInterfaces
+ origNetIOCounters := netIOCounters
+
+ cpuCounts = func(ctx context.Context, logical bool) (int, error) { return 4, nil }
+ cpuPercent = func(ctx context.Context, interval time.Duration, percpu bool) ([]float64, error) {
+ return []float64{5.0}, nil
+ }
+ cpuTimes = func(ctx context.Context, percpu bool) ([]gocpu.TimesStat, error) {
+ return []gocpu.TimesStat{{CPU: "cpu-total", User: 100, System: 50, Idle: 1000}}, nil
+ }
+ loadAvg = func(ctx context.Context) (*goload.AvgStat, error) {
+ return &goload.AvgStat{Load1: 0.1, Load5: 0.2, Load15: 0.3}, nil
+ }
+ virtualMemory = func(ctx context.Context) (*gomem.VirtualMemoryStat, error) {
+ return &gomem.VirtualMemoryStat{
+ Total: 8 * 1024 * 1024 * 1024,
+ Used: 4 * 1024 * 1024 * 1024,
+ Free: 4 * 1024 * 1024 * 1024,
+ UsedPercent: 50,
+ SwapTotal: 1024 * 1024 * 1024,
+ SwapFree: 512 * 1024 * 1024,
+ }, nil
+ }
+ diskPartitions = func(ctx context.Context, all bool) ([]godisk.PartitionStat, error) {
+ return []godisk.PartitionStat{{Device: "/dev/sda", Mountpoint: "/", Fstype: "ext4"}}, nil
+ }
+ diskUsage = func(ctx context.Context, path string) (*godisk.UsageStat, error) {
+ return &godisk.UsageStat{Total: 100, Used: 50, Free: 50, UsedPercent: 50}, nil
+ }
+ diskIOCounters = func(ctx context.Context, names ...string) (map[string]godisk.IOCountersStat, error) {
+ return map[string]godisk.IOCountersStat{
+ "sda": {
+ ReadBytes: 1,
+ WriteBytes: 2,
+ ReadCount: 1,
+ WriteCount: 2,
+ },
+ }, nil
+ }
+ netInterfaces = func(ctx context.Context) (gonet.InterfaceStatList, error) {
+ return gonet.InterfaceStatList{
+ {
+ Name: "eth0",
+ HardwareAddr: "00:11:22:33:44:55",
+ Flags: []string{"up"},
+ Addrs: []gonet.InterfaceAddr{{Addr: "192.168.1.10/24"}},
+ },
+ }, nil
+ }
+ netIOCounters = func(ctx context.Context, pernic bool) ([]gonet.IOCountersStat, error) {
+ return []gonet.IOCountersStat{{Name: "eth0", BytesRecv: 1, BytesSent: 2}}, nil
+ }
+
+ t.Cleanup(func() {
+ cpuCounts = origCPUCounts
+ cpuPercent = origCPUPercent
+ cpuTimes = origCPUTimes
+ loadAvg = origLoadAvg
+ virtualMemory = origVirtualMemory
+ diskPartitions = origDiskPartitions
+ diskUsage = origDiskUsage
+ diskIOCounters = origDiskIOCounters
+ netInterfaces = origNetInterfaces
+ netIOCounters = origNetIOCounters
+ })
+
+ samples := []gocpu.TimesStat{
+ {User: 100, Idle: 1000},
+ {User: 100.8, Idle: 1000.2},
+ {User: 103, Idle: 1057},
+ {User: 103.8, Idle: 1057.2},
+ {User: 106, Idle: 1114},
+ {User: 106.8, Idle: 1114.2},
+ }
+ index, spots := 0, 0
+ cpuTimes = func(context.Context, bool) ([]gocpu.TimesStat, error) {
+ sample := samples[index]
+ index++
+ return []gocpu.TimesStat{sample}, nil
+ }
+ cpuPercent = func(context.Context, time.Duration, bool) ([]float64, error) {
+ spots++
+ return []float64{80}, nil
+ }
+ var host, docker Collector
+ for cycle := 0; cycle < 3; cycle++ {
+ a, err := host.Collect(context.Background(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := docker.CollectWithDiskFilters(context.Background(), nil, []string{"/"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := 5.0
+ if cycle == 0 {
+ want = 80
+ }
+ for _, got := range []float64{a.CPUUsagePercent, b.CPUUsagePercent} {
+ if math.Abs(got-want) > 1e-9 {
+ t.Fatalf("cycle %d: CPU = %v, want %v", cycle, got, want)
+ }
+ }
+ }
+ if spots != 2 {
+ t.Fatalf("spot samples = %d, want startup only (2)", spots)
+ }
+}