Lightweight server monitoring with historical data, docker stats, and alerts.
fix(agent): prevent network counter underflow on interface removal and container restart (#2574)
Sven van Ginkelb11e3617990b
diff --git a/agent/docker.go b/agent/docker.goindex ee7700497..8b669d14d 100644--- a/agent/docker.go+++ b/agent/docker.go@@ -326,8 +326,8 @@ func (dm *dockerManager) calculateNetworkStats(ctr *container.ApiInfo, apiStatsrecvTracker.Set(ctr.IdShort, total_recv)// Get deltas (bytes since last measurement)- sent_delta_raw := sentTracker.Delta(ctr.IdShort)- recv_delta_raw := recvTracker.Delta(ctr.IdShort)+ sent_delta_raw := counterDelta(sentTracker, ctr.IdShort, total_sent)+ recv_delta_raw := counterDelta(recvTracker, ctr.IdShort, total_recv)// Calculate bytes per second using per-cache-time read time to avoid// interference between different cache intervals (e.g. 1000ms vs 60000ms)@@ -355,6 +355,18 @@ func (dm *dockerManager) calculateNetworkStats(ctr *container.ApiInfo, apiStatsreturn sent_delta, recv_delta}+// counterDelta returns the increase of a cumulative counter since the previous cycle.+// If the counter went down, 0 is returned for this cycle. The counter is summed across+// the container's interfaces, so a decrease may be a restart (all counters reset) or a+// removed interface (others keep their totals), and the current value isn't a safe delta.+func counterDelta(tracker *deltatracker.DeltaTracker[string, uint64], id string, current uint64) uint64 {+ prev, ok := tracker.Previous(id)+ if !ok || current < prev {+ return 0+ }+ return current - prev+}+// validateCpuPercentage checks if CPU percentage is within valid rangefunc validateCpuPercentage(cpuPct float64, containerName string) error {if cpuPct > 100 {diff --git a/agent/docker_test.go b/agent/docker_test.goindex 76484d545..8d182a205 100644--- a/agent/docker_test.go+++ b/agent/docker_test.go@@ -1279,6 +1279,64 @@ func TestNetworkStatsCalculationWithRealData(t *testing.T) {assert.Equal(t, uint64(0), recv3)}+func TestNetworkStatsCounterDecreaseDoesNotUnderflow(t *testing.T) {+ tests := []struct {+ name string+ before map[string]container.NetworkStats+ after map[string]container.NetworkStats+ }{+ {+ name: "container restarted",+ before: map[string]container.NetworkStats{"eth0": {TxBytes: 5_000_000, RxBytes: 8_000_000}},+ after: map[string]container.NetworkStats{"eth0": {TxBytes: 2_000, RxBytes: 3_000}},+ },+ {+ name: "interface removed",+ before: map[string]container.NetworkStats{+ "eth0": {TxBytes: 1_000_000_000, RxBytes: 2_000_000_000},+ "eth1": {TxBytes: 500_000_000, RxBytes: 500_000_000},+ },+ after: map[string]container.NetworkStats{"eth0": {TxBytes: 1_010_000_000, RxBytes: 2_010_000_000}},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ dm := &dockerManager{+ networkSentTrackers: make(map[uint16]*deltatracker.DeltaTracker[string, uint64]),+ networkRecvTrackers: make(map[uint16]*deltatracker.DeltaTracker[string, uint64]),+ lastNetworkReadTime: make(map[uint16]map[string]time.Time),+ }+ ctr := &container.ApiInfo{IdShort: "test-container"}+ cacheTimeMs := uint16(60000)+ nextCycle := func() {+ dm.cycleNetworkDeltasForCacheTime(cacheTimeMs)+ dm.lastNetworkReadTime[cacheTimeMs] = map[string]time.Time{+ "test-container": time.Now().Add(-1000 * time.Millisecond),+ }+ }++ _, _ = dm.calculateNetworkStats(ctr, &container.ApiStats{Networks: tt.before}, "test", cacheTimeMs)+ nextCycle()++ // Summed counters went down: skip this cycle rather than wrap around or report a spike+ sent, recv := dm.calculateNetworkStats(ctr, &container.ApiStats{Networks: tt.after}, "test", cacheTimeMs)+ assert.Equal(t, uint64(0), sent)+ assert.Equal(t, uint64(0), recv)++ // Next cycle measures from the new baseline+ nextCycle()+ grown := make(map[string]container.NetworkStats, len(tt.after))+ for name, v := range tt.after {+ grown[name] = container.NetworkStats{TxBytes: v.TxBytes + 1_000, RxBytes: v.RxBytes + 2_000}+ }+ sent, recv = dm.calculateNetworkStats(ctr, &container.ApiStats{Networks: grown}, "test", cacheTimeMs)+ assert.InDelta(t, 1_000, sent, 10)+ assert.InDelta(t, 2_000, recv, 20)+ })+ }+}+func TestContainerStatsEndToEndWithRealData(t *testing.T) {// Load minimal container statsdata, err := os.ReadFile("test-data/container.json")diff --git a/agent/network.go b/agent/network.goindex c980a277a..d196c74b7 100644--- a/agent/network.go+++ b/agent/network.go@@ -84,9 +84,8 @@ func (a *Agent) updateNetworkStats(cacheTimeMs uint16, systemStats *system.Statsif netIO, err := psutilNet.IOCounters(true); err == nil {nis, msElapsed := a.loadAndTickNetBaseline(cacheTimeMs)- totalBytesSent, totalBytesRecv := a.sumAndTrackPerNicDeltas(cacheTimeMs, msElapsed, netIO, systemStats)- bytesSentPerSecond, bytesRecvPerSecond := a.computeBytesPerSecond(msElapsed, totalBytesSent, totalBytesRecv, nis)- a.applyNetworkTotals(cacheTimeMs, netIO, systemStats, nis, totalBytesSent, totalBytesRecv, bytesSentPerSecond, bytesRecvPerSecond)+ bytesSentPerSecond, bytesRecvPerSecond := a.sumAndTrackPerNicDeltas(cacheTimeMs, msElapsed, netIO, systemStats)+ a.applyNetworkTotals(cacheTimeMs, netIO, systemStats, nis, bytesSentPerSecond, bytesRecvPerSecond)}}@@ -154,8 +153,10 @@ func (a *Agent) loadAndTickNetBaseline(cacheTimeMs uint16) (netIoStat system.Netreturn netIoStat, msElapsed}-// sumAndTrackPerNicDeltas accumulates totals and records per-NIC up/down deltas into systemStats-func (a *Agent) sumAndTrackPerNicDeltas(cacheTimeMs uint16, msElapsed uint64, netIO []psutilNet.IOCountersStat, systemStats *system.Stats) (totalBytesSent, totalBytesRecv uint64) {+// sumAndTrackPerNicDeltas records per-NIC up/down deltas into systemStats and returns their summed rates.+// Summing per-NIC deltas (rather than diffing summed counters) keeps the total from underflowing+// when a tracked interface disappears or its counters reset.+func (a *Agent) sumAndTrackPerNicDeltas(cacheTimeMs uint16, msElapsed uint64, netIO []psutilNet.IOCountersStat, systemStats *system.Stats) (bytesSentPerSecond, bytesRecvPerSecond uint64) {tracker := a.netInterfaceDeltaTrackers[cacheTimeMs]if tracker == nil {tracker = deltatracker.NewDeltaTracker[string, uint64]()@@ -171,9 +172,6 @@ func (a *Agent) sumAndTrackPerNicDeltas(cacheTimeMs uint16, msElapsed uint64, neif useMacCounters {correctNvethernetCounters(&v)}- totalBytesSent += v.BytesSent- totalBytesRecv += v.BytesRecv-var upDelta, downDelta uint64upKey, downKey := fmt.Sprintf("%sup", v.Name), fmt.Sprintf("%sdown", v.Name)tracker.Set(upKey, v.BytesSent)@@ -199,17 +197,10 @@ func (a *Agent) sumAndTrackPerNicDeltas(cacheTimeMs uint16, msElapsed uint64, ne}}systemStats.NetworkInterfaces[v.Name] = [4]uint64{upDelta, downDelta, v.BytesSent, v.BytesRecv}+ bytesSentPerSecond += upDelta+ bytesRecvPerSecond += downDelta}- return totalBytesSent, totalBytesRecv-}--// computeBytesPerSecond calculates per-second totals from elapsed time and totals-func (a *Agent) computeBytesPerSecond(msElapsed, totalBytesSent, totalBytesRecv uint64, nis system.NetIoStats) (bytesSentPerSecond, bytesRecvPerSecond uint64) {- if msElapsed > 0 {- bytesSentPerSecond = (totalBytesSent - nis.BytesSent) * 1000 / msElapsed- bytesRecvPerSecond = (totalBytesRecv - nis.BytesRecv) * 1000 / msElapsed- }return bytesSentPerSecond, bytesRecvPerSecond}@@ -219,7 +210,6 @@ func (a *Agent) applyNetworkTotals(netIO []psutilNet.IOCountersStat,systemStats *system.Stats,nis system.NetIoStats,- totalBytesSent, totalBytesRecv uint64,bytesSentPerSecond, bytesRecvPerSecond uint64,) {if bytesSentPerSecond > 10_000_000_000 || bytesRecvPerSecond > 10_000_000_000 {@@ -238,8 +228,6 @@ func (a *Agent) applyNetworkTotals(}systemStats.Bandwidth[0], systemStats.Bandwidth[1] = bytesSentPerSecond, bytesRecvPerSecond- nis.BytesSent = totalBytesSent- nis.BytesRecv = totalBytesRecva.netIoStats[cacheTimeMs] = nis}diff --git a/agent/network_test.go b/agent/network_test.goindex f04910992..6d3a1ce0f 100644--- a/agent/network_test.go+++ b/agent/network_test.go@@ -327,21 +327,6 @@ func TestLoadAndTickNetBaseline(t *testing.T) {assert.False(t, ni2.Time.IsZero())}-func TestComputeBytesPerSecond(t *testing.T) {- a := &Agent{}-- // No elapsed -> zero rate- bytesUp, bytesDown := a.computeBytesPerSecond(0, 2000, 3000, system.NetIoStats{BytesSent: 1000, BytesRecv: 1000})- assert.Equal(t, uint64(0), bytesUp)- assert.Equal(t, uint64(0), bytesDown)-- // With elapsed -> per-second calculation- bytesUp, bytesDown = a.computeBytesPerSecond(500, 6000, 11000, system.NetIoStats{BytesSent: 1000, BytesRecv: 1000})- // (6000-1000)*1000/500 = 10000; (11000-1000)*1000/500 = 20000- assert.Equal(t, uint64(10000), bytesUp)- assert.Equal(t, uint64(20000), bytesDown)-}-func TestSumAndTrackPerNicDeltas(t *testing.T) {a := &Agent{netInterfaces: map[string]bool{"eth0": false, "wlan0": false},@@ -354,16 +339,17 @@ func TestSumAndTrackPerNicDeltas(t *testing.T) {stats1 := &system.Stats{}a.ensureNetworkInterfacesMap(stats1)tx1, rx1 := a.sumAndTrackPerNicDeltas(cache, 0, net1, stats1)- assert.Equal(t, uint64(1000), tx1)- assert.Equal(t, uint64(2000), rx1)+ // No elapsed time yet -> zero rate+ assert.Equal(t, uint64(0), tx1)+ assert.Equal(t, uint64(0), rx1)// Second cycle with elapsed, larger counters -> deltas computed insidenet2 := []psutilNet.IOCountersStat{{Name: "eth0", BytesSent: 4000, BytesRecv: 9000}}stats := &system.Stats{}a.ensureNetworkInterfacesMap(stats)tx2, rx2 := a.sumAndTrackPerNicDeltas(cache, 1000, net2, stats)- assert.Equal(t, uint64(4000), tx2)- assert.Equal(t, uint64(9000), rx2)+ assert.Equal(t, uint64(3000), tx2)+ assert.Equal(t, uint64(7000), rx2)// Up/Down deltas per second should be (4000-1000)/1s = 3000 and (9000-2000)/1s = 7000ni, ok := stats.NetworkInterfaces["eth0"]assert.True(t, ok)@@ -408,13 +394,39 @@ func TestSumAndTrackPerNicDeltasHandlesCounterReset(t *testing.T) {assert.Equal(t, uint64(1_500), niReset[1], "download delta should match new counter value after reset")}+func TestSumAndTrackPerNicDeltasInterfaceDisappears(t *testing.T) {+ a := &Agent{+ netInterfaces: map[string]bool{"eth0": false, "wpan0": false},+ netInterfaceDeltaTrackers: make(map[uint16]*deltatracker.DeltaTracker[string, uint64]),+ }+ cache := uint16(60000)++ before := []psutilNet.IOCountersStat{+ {Name: "eth0", BytesSent: 10_000_000, BytesRecv: 50_000_000},+ {Name: "wpan0", BytesSent: 40_000, BytesRecv: 300_000},+ }+ statsBefore := &system.Stats{}+ a.ensureNetworkInterfacesMap(statsBefore)+ _, _ = a.sumAndTrackPerNicDeltas(cache, 0, before, statsBefore)++ // wpan0 is gone and eth0 grew less than wpan0's counters, so the summed counters drop+ after := []psutilNet.IOCountersStat{+ {Name: "eth0", BytesSent: 10_030_000, BytesRecv: 50_060_000},+ }+ statsAfter := &system.Stats{}+ a.ensureNetworkInterfacesMap(statsAfter)+ tx, rx := a.sumAndTrackPerNicDeltas(cache, 60_000, after, statsAfter)++ assert.Equal(t, uint64(500), tx, "total should only reflect eth0 growth, not underflow")+ assert.Equal(t, uint64(1_000), rx, "total should only reflect eth0 growth, not underflow")+ assert.NotContains(t, statsAfter.NetworkInterfaces, "wpan0")+}+func TestApplyNetworkTotals(t *testing.T) {tests := []struct {name stringbytesSentPerSecond uint64bytesRecvPerSecond uint64- totalBytesSent uint64- totalBytesRecv uint64expectReset boolexpectedBandwidthSent uint64expectedBandwidthRecv uint64@@ -423,8 +435,6 @@ func TestApplyNetworkTotals(t *testing.T) {name: "Valid network stats - normal values",bytesSentPerSecond: 1000000, // 1 MB/sbytesRecvPerSecond: 2000000, // 2 MB/s- totalBytesSent: 10000000,- totalBytesRecv: 20000000,expectReset: false,expectedBandwidthSent: 1000000,expectedBandwidthRecv: 2000000,@@ -433,32 +443,24 @@ func TestApplyNetworkTotals(t *testing.T) {name: "Invalid network stats - sent exceeds threshold",bytesSentPerSecond: 11000000000, // ~10.5 GB/s > 10 GB/s thresholdbytesRecvPerSecond: 1000000, // 1 MB/s- totalBytesSent: 10000000,- totalBytesRecv: 20000000,expectReset: true,},{name: "Invalid network stats - recv exceeds threshold",bytesSentPerSecond: 1000000, // 1 MB/sbytesRecvPerSecond: 11000000000, // ~10.5 GB/s > 10 GB/s threshold- totalBytesSent: 10000000,- totalBytesRecv: 20000000,expectReset: true,},{name: "Invalid network stats - both exceed threshold",bytesSentPerSecond: 12000000000, // ~11.4 GB/sbytesRecvPerSecond: 13000000000, // ~12.4 GB/s- totalBytesSent: 10000000,- totalBytesRecv: 20000000,expectReset: true,},{name: "Zero values",bytesSentPerSecond: 0,bytesRecvPerSecond: 0,- totalBytesSent: 0,- totalBytesRecv: 0,expectReset: false,expectedBandwidthSent: 0,expectedBandwidthRecv: 0,@@ -486,8 +488,6 @@ func TestApplyNetworkTotals(t *testing.T) {netIO,systemStats,nis,- tt.totalBytesSent,- tt.totalBytesRecv,tt.bytesSentPerSecond,tt.bytesRecvPerSecond,)@@ -502,11 +502,7 @@ func TestApplyNetworkTotals(t *testing.T) {// Should have applied statsassert.Equal(t, tt.expectedBandwidthSent, systemStats.Bandwidth[0])assert.Equal(t, tt.expectedBandwidthRecv, systemStats.Bandwidth[1])-- // Should have updated NetIoStats- updatedNis := a.netIoStats[cacheTimeMs]- assert.Equal(t, tt.totalBytesSent, updatedNis.BytesSent)- assert.Equal(t, tt.totalBytesRecv, updatedNis.BytesRecv)+ assert.Contains(t, a.netIoStats, cacheTimeMs, "baseline should be stored")}})}@@ -525,8 +521,6 @@ func TestSumAndTrackPerNicDeltasKeepsCountersWhenMacReadFails(t *testing.T) {stats := &system.Stats{}a.ensureNetworkInterfacesMap(stats)- tx, rx := a.sumAndTrackPerNicDeltas(1, 0, netIO, stats)- assert.Equal(t, uint64(400), tx)- assert.Equal(t, uint64(600), rx)+ _, _ = a.sumAndTrackPerNicDeltas(1, 0, netIO, stats)assert.Equal(t, [4]uint64{0, 0, 300, 400}, stats.NetworkInterfaces["missing0"])}