From 5b8003c54458991f9d22072e5352e3b1ea840552 Mon Sep 17 00:00:00 2001 From: Benedikt Iltisberger Date: Fri, 13 Nov 2026 12:34:55 +0100 Subject: [PATCH] fix(node-metrics): one snoopy per pod, graceful stop, eBPF-attached fallback - start one snoopy per pod instead of per container: all containers of a pod share the sandbox netns, so extra instances stacked a TC program per container on every packet and Metrics() flipped between handles in random map order; the procdev reader also reported a pod once per container - stop snoopy with SIGTERM and only SIGKILL after 5s, so it can detach its programs (netlink TC filters outlive a killed process on <6.6) - read eBPF values once snoopy attached both counters, even while zero; the all-zero heuristic read /proc/net/dev every second for every idle pod, and lo is no longer read at all - hand out a copy of the snoopy status: the handler mutated the slices in place while the collector marshaled them; stale handles are now removed from the status and errors are stored as text instead of {} - write status::snoopy on change (refresh every 5 min) instead of every second - key traffic deltas by namespace/pod: equal pod names in different namespaces mixed their counters Co-Authored-By: Claude Opus 5.5 --- src/containerenumerator/podinfo.go | 21 +- src/core/dbstats.go | 12 +- src/core/nodemetricscollector.go | 23 +- src/networkmonitor/networkmonitor.go | 4 +- src/networkmonitor/networkstatsreader.go | 63 ++-- src/networkmonitor/snoopy.go | 428 ++++++++++++++--------- 6 files changed, 340 insertions(+), 211 deletions(-) diff --git a/src/containerenumerator/podinfo.go b/src/containerenumerator/podinfo.go index acff67207..57185c575 100644 --- a/src/containerenumerator/podinfo.go +++ b/src/containerenumerator/podinfo.go @@ -4,6 +4,8 @@ import ( "log/slog" "mogenius-operator/src/assert" "net/url" + "slices" + "strings" "time" v1 "k8s.io/api/core/v1" @@ -73,12 +75,25 @@ func (self *PodInfo) NamespaceAndName() PodInfoIdentifier { return self.Namespace + "/" + self.Name } -func (self *PodInfo) ContainersWithFirstPid() map[ContainerId]ProcessId { - data := map[ContainerId]ProcessId{} +// ContainerFirstPid pairs a container with the first process running in it. +type ContainerFirstPid struct { + ContainerId ContainerId + Pid ProcessId +} + +// SortedContainersWithFirstPid returns every container with its first pid, +// ordered by container id. All containers of a pod share the network +// namespace of the pod sandbox, so traffic collectors attach to one of them; +// the stable order keeps that choice the same across calls. +func (self *PodInfo) SortedContainersWithFirstPid() []ContainerFirstPid { + data := make([]ContainerFirstPid, 0, len(self.Containers)) for containerId, pids := range self.Containers { assert.Assert(len(pids) > 0, "podinfo should never contain information about containers with 0 processes") - data[containerId] = pids[0] + data = append(data, ContainerFirstPid{ContainerId: containerId, Pid: pids[0]}) } + slices.SortFunc(data, func(a, b ContainerFirstPid) int { + return strings.Compare(a.ContainerId, b.ContainerId) + }) return data } diff --git a/src/core/dbstats.go b/src/core/dbstats.go index 8d33bb2b1..4c57c7964 100644 --- a/src/core/dbstats.go +++ b/src/core/dbstats.go @@ -125,10 +125,16 @@ func (self *valkeyStatsDb) AddInterfaceStatsToDb(currentStats []networkmonitor.P self.lastPodNetworkStats = currentStats self.lastPodNetworkStatsLock.Unlock() - // Build a map for O(1) lookup instead of O(n) linear search + // Build a map for O(1) lookup instead of O(n) linear search. The key + // includes the namespace: pod names repeat across namespaces (e.g. a + // StatefulSet "postgres-0" in two workspaces), and a name-only key mixed + // their counters into each other's deltas. + podKey := func(stat networkmonitor.PodNetworkStats) string { + return stat.Namespace + "/" + stat.Pod + } lastStatsMap := make(map[string]networkmonitor.PodNetworkStats, len(lastStats)) for _, e := range lastStats { - lastStatsMap[e.Pod] = e + lastStatsMap[podKey(e)] = e } for _, currentStat := range currentStats { @@ -147,7 +153,7 @@ func (self *valkeyStatsDb) AddInterfaceStatsToDb(currentStats []networkmonitor.P // Strip before persisting; readers refill from the query context. deltaStat.Namespace = "" - if lastEntry, ok := lastStatsMap[currentStat.Pod]; ok { + if lastEntry, ok := lastStatsMap[podKey(currentStat)]; ok { // Guard against uint64 underflow: if the current counter is smaller than the // last known value, the snoopy process or pod was restarted and the BPF counter // reset to 0. In that case we skip this interval (delta = 0) rather than diff --git a/src/core/nodemetricscollector.go b/src/core/nodemetricscollector.go index 3d01005d6..d505aa590 100644 --- a/src/core/nodemetricscollector.go +++ b/src/core/nodemetricscollector.go @@ -2,7 +2,9 @@ package core import ( "bufio" + "bytes" "context" + "encoding/json" "fmt" "log/slog" "mogenius-operator/src/assert" @@ -19,6 +21,10 @@ import ( "time" ) +// snoopyStatusRefreshInterval rewrites an unchanged snoopy status so its key +// (liveStatsTTL) never expires while the node-metrics pod is running. +const snoopyStatusRefreshInterval = 5 * time.Minute + // sleepCtx returns false when ctx is done so the caller can exit its loop. func sleepCtx(ctx context.Context, d time.Duration) bool { t := time.NewTimer(d) @@ -212,11 +218,24 @@ func (self *nodeMetricsCollector) Run() { if !sleepCtx(ctx, 200*time.Millisecond) { return } + // The status only changes when pods or interfaces come and go; + // rewriting the same JSON every second was pure Valkey write + // load. Write on change, and refresh well before the key's TTL. + var lastStatus []byte + var lastWrite time.Time for { status := self.networkMonitor.Snoopy().Status() - err := self.statsDb.AddSnoopyStatusToDb(nodeName, status) + encoded, err := json.Marshal(status) if err != nil { - self.logger.Error("failed to store snoopy status", "error", err) + self.logger.Error("failed to encode snoopy status", "error", err) + } else if !bytes.Equal(encoded, lastStatus) || time.Since(lastWrite) >= snoopyStatusRefreshInterval { + err := self.statsDb.AddSnoopyStatusToDb(nodeName, status) + if err != nil { + self.logger.Error("failed to store snoopy status", "error", err) + } else { + lastStatus = encoded + lastWrite = time.Now() + } } if !sleepCtx(ctx, 1*time.Second) { return diff --git a/src/networkmonitor/networkmonitor.go b/src/networkmonitor/networkmonitor.go index 999c441ef..d6a8a3f7c 100644 --- a/src/networkmonitor/networkmonitor.go +++ b/src/networkmonitor/networkmonitor.go @@ -107,7 +107,7 @@ func (self *networkMonitor) Run() { } // get initial collected stats - var metrics map[ContainerId]ContainerInfo + var metrics map[containerenumerator.PodInfoIdentifier]ContainerInfo var collectedStats []PodNetworkStats metrics = self.snoopy.Metrics() collectedStats = self.metricsToPodstats(metrics) @@ -192,7 +192,7 @@ func (self *networkMonitor) Snoopy() SnoopyManager { } func (self *networkMonitor) metricsToPodstats( - metrics map[ContainerId]ContainerInfo, + metrics map[containerenumerator.PodInfoIdentifier]ContainerInfo, ) []PodNetworkStats { data := []PodNetworkStats{} diff --git a/src/networkmonitor/networkstatsreader.go b/src/networkmonitor/networkstatsreader.go index e8df5bdf9..67364ae04 100644 --- a/src/networkmonitor/networkstatsreader.go +++ b/src/networkmonitor/networkstatsreader.go @@ -17,12 +17,12 @@ type networkStatsReader struct { procPath string metricsTx chan struct{} - metricsRx chan map[ContainerId]ContainerInfo + metricsRx chan map[containerenumerator.PodInfoIdentifier]ContainerInfo registerTx chan networkStatsReaderDeviceBaseInfo registerRx chan error - removeTx chan ContainerId + removeTx chan containerenumerator.PodInfoIdentifier removeRx chan error running atomic.Bool @@ -46,10 +46,10 @@ func NewNetworkStatsReader(logger *slog.Logger, cne containerenumerator.Containe self.running = atomic.Bool{} self.metricsTx = make(chan struct{}) - self.metricsRx = make(chan map[ContainerId]ContainerInfo) + self.metricsRx = make(chan map[containerenumerator.PodInfoIdentifier]ContainerInfo) self.registerTx = make(chan networkStatsReaderDeviceBaseInfo) self.registerRx = make(chan error) - self.removeTx = make(chan ContainerId) + self.removeTx = make(chan containerenumerator.PodInfoIdentifier) self.removeRx = make(chan error) self.cne = cne @@ -70,7 +70,7 @@ func (self *networkStatsReader) startWorker() { go func() { baseDeviceInfos := []networkStatsReaderDeviceBaseInfo{} - metrics := map[ContainerId]ContainerInfo{} + metrics := map[containerenumerator.PodInfoIdentifier]ContainerInfo{} containers := self.cne.GetProcessesWithContainerIds() networkEnumeratorTicker := time.NewTicker(5 * time.Second) @@ -83,28 +83,30 @@ func (self *networkStatsReader) startWorker() { case <-self.metricsTx: self.metricsRx <- metrics case newDeviceInfo := <-self.registerTx: + newPodId := newDeviceInfo.PodInfo.NamespaceAndName() alreadyRegistered := false for _, info := range baseDeviceInfos { - if info.ContainerId == newDeviceInfo.ContainerId { + if info.PodInfo.NamespaceAndName() == newPodId { alreadyRegistered = true break } } if alreadyRegistered { - self.registerRx <- fmt.Errorf("network device is already registered: %s", newDeviceInfo.ContainerId) + self.registerRx <- fmt.Errorf("pod network is already registered: %s", newPodId) continue } baseDeviceInfos = append(baseDeviceInfos, newDeviceInfo) self.registerRx <- nil - case containerId := <-self.removeTx: + case podId := <-self.removeTx: removeIdx := -1 for idx, info := range baseDeviceInfos { - if info.ContainerId == containerId { + if info.PodInfo.NamespaceAndName() == podId { removeIdx = idx + break } } if removeIdx == -1 { - self.removeRx <- fmt.Errorf("failed to find containerId in tracked container list: %s", containerId) + self.removeRx <- fmt.Errorf("failed to find pod in tracked pod list: %s", podId) continue } baseDeviceInfos = slices.Delete(baseDeviceInfos, removeIdx, removeIdx+1) @@ -112,7 +114,7 @@ func (self *networkStatsReader) startWorker() { case <-networkEnumeratorTicker.C: containers = self.cne.GetProcessesWithContainerIds() case <-updateTicker.C: - newMetrics := map[ContainerId]ContainerInfo{} + newMetrics := map[containerenumerator.PodInfoIdentifier]ContainerInfo{} baseDeviceIdsWithBrokenPid := []int{} for idx, baseInfo := range baseDeviceInfos { @@ -163,7 +165,7 @@ func (self *networkStatsReader) startWorker() { metricSnapshot.Egress.Packets = 0 containerInfo.Metrics[baseStartInfo.Interface] = metricSnapshot } - newMetrics[baseInfo.ContainerId] = containerInfo + newMetrics[baseInfo.PodInfo.NamespaceAndName()] = containerInfo continue } @@ -191,7 +193,7 @@ func (self *networkStatsReader) startWorker() { containerInfo.Metrics[baseStartInfo.Interface] = metricSnapshot } - newMetrics[baseInfo.ContainerId] = containerInfo + newMetrics[baseInfo.PodInfo.NamespaceAndName()] = containerInfo } metrics = newMetrics } @@ -199,7 +201,7 @@ func (self *networkStatsReader) startWorker() { }() } -func (self *networkStatsReader) Metrics() map[ContainerId]ContainerInfo { +func (self *networkStatsReader) Metrics() map[containerenumerator.PodInfoIdentifier]ContainerInfo { self.Run() self.metricsTx <- struct{}{} @@ -208,43 +210,40 @@ func (self *networkStatsReader) Metrics() map[ContainerId]ContainerInfo { return metrics } +// Register tracks the pod's network namespace once: all containers of a pod +// share it, so reading /proc/$pid/net/dev per container counted the same +// interfaces several times and reported the pod once per container. func (self *networkStatsReader) Register(podInfo containerenumerator.PodInfo) []error { errors := []error{} - for containerId, pid := range podInfo.ContainersWithFirstPid() { - kernelNetworkInterfaceInfos, err := getNetworkInterfaceInfo(self.procPath, strconv.FormatUint(pid, 10)) + for _, container := range podInfo.SortedContainersWithFirstPid() { + kernelNetworkInterfaceInfos, err := getNetworkInterfaceInfo(self.procPath, strconv.FormatUint(container.Pid, 10)) if err != nil { + // the first process may already be gone; try the next container errors = append(errors, err) continue } self.registerTx <- networkStatsReaderDeviceBaseInfo{ PodInfo: podInfo, - ContainerId: containerId, - Pid: pid, + ContainerId: container.ContainerId, + Pid: container.Pid, StartInfos: kernelNetworkInterfaceInfos, } - err = <-self.registerRx - if err != nil { - errors = append(errors, err) - continue + if err := <-self.registerRx; err != nil { + return []error{err} } + return nil } return errors } func (self *networkStatsReader) Remove(podInfo containerenumerator.PodInfo) []error { - errors := []error{} - for containerId := range podInfo.ContainersWithFirstPid() { - self.removeTx <- containerId - err := <-self.removeRx - if err != nil { - errors = append(errors, err) - continue - } + self.removeTx <- podInfo.NamespaceAndName() + if err := <-self.removeRx; err != nil { + return []error{err} } - - return errors + return nil } func (self *networkStatsReader) SetArgs(args SnoopyArgs) {} diff --git a/src/networkmonitor/snoopy.go b/src/networkmonitor/snoopy.go index d60e43e7d..6120b8405 100644 --- a/src/networkmonitor/snoopy.go +++ b/src/networkmonitor/snoopy.go @@ -11,11 +11,15 @@ import ( "mogenius-operator/src/config" "mogenius-operator/src/containerenumerator" "mogenius-operator/src/shutdown" + "os" "os/exec" + "slices" "strconv" "strings" "sync" "sync/atomic" + "syscall" + "time" "encoding/json" ) @@ -102,7 +106,8 @@ type SnoopyStatusEventRegisterFailure struct { PodName string `json:"podName"` ContainerId ContainerId `json:"containerId"` NsProcessPid ProcessId `json:"NsProcessId"` - Err error `json:"error"` + // Error is the message text: an error value marshals to `{}`. + Error string `json:"error"` } type SnoopyStatusEventRemove struct { @@ -153,12 +158,12 @@ type SnoopyHandle struct { SnoopyPid ProcessId ContainerPid ProcessId // PID of the monitored container process (for procdev fallback) - StartBytesLock *sync.RWMutex - IngressStartBytes map[InterfaceName]uint64 - EgressStartBytes map[InterfaceName]uint64 - IngressStartPackets map[InterfaceName]uint64 // protected by StartBytesLock - EgressStartPackets map[InterfaceName]uint64 // protected by StartBytesLock - BpfFailedInterfaces map[InterfaceName]bool // interfaces where eBPF init failed; protected by StartBytesLock + StartBytesLock *sync.RWMutex + IngressStartBytes map[InterfaceName]uint64 + EgressStartBytes map[InterfaceName]uint64 + IngressStartPackets map[InterfaceName]uint64 // protected by StartBytesLock + EgressStartPackets map[InterfaceName]uint64 // protected by StartBytesLock + BpfAttachedInterfaces map[InterfaceName]bool // interfaces with both eBPF counters attached; protected by StartBytesLock LastMetricsLock *sync.RWMutex LastMetrics map[InterfaceName]SnoopyInterfaceMetrics @@ -340,6 +345,21 @@ func (self *snoopyManager) Run() { go self.startStatusEventHandler() } +func (self SnoopyStatus) clone() SnoopyStatus { + processes := make([]SnoopyStatusProcess, len(self.SnoopyProcesses)) + for idx, process := range self.SnoopyProcesses { + processes[idx] = SnoopyStatusProcess{ + Pid: process.Pid, + Interfaces: slices.Clone(process.Interfaces), + } + } + return SnoopyStatus{ + Initializing: slices.Clone(self.Initializing), + Failure: slices.Clone(self.Failure), + SnoopyProcesses: processes, + } +} + func (self *snoopyManager) startStatusEventHandler() { status := SnoopyStatus{ Initializing: []SnoopyStatusEventRegisterRequest{}, @@ -353,7 +373,9 @@ func (self *snoopyManager) startStatusEventHandler() { case <-ctx.Done(): return case <-self.statusTx: - self.statusRx <- status + // The handler keeps mutating these slices in place; the caller + // marshals the status concurrently, so it gets its own copy. + self.statusRx <- status.clone() case event := <-self.statusEventTx: switch event.Type { case SnoopyStatusEventTypeRegisterRequest: @@ -550,8 +572,18 @@ type metricsSnapshot struct { ingressStartPackets map[InterfaceName]uint64 egressStartPackets map[InterfaceName]uint64 last map[InterfaceName]SnoopyInterfaceMetrics + bpfAttached map[InterfaceName]bool } +// snoopyImplementationNone is what snoopy reports for a direction it could +// not attach a counter to. +const snoopyImplementationNone = "none" + +// loopbackInterface is never reported: its traffic stays inside the pod. +// snoopy does not attach to it, and reading its /proc/net/dev counters on +// every tick was wasted I/O. +const loopbackInterface = "lo" + func (self *snoopyManager) Metrics() map[containerenumerator.PodInfoIdentifier]ContainerInfo { // Snapshot phase: under the outer handlesLock, collect pointers to // all current handles. Release the lock immediately so Register and @@ -579,12 +611,14 @@ func (self *snoopyManager) Metrics() map[containerenumerator.PodInfoIdentifier]C ingressStartPackets: make(map[InterfaceName]uint64), egressStartPackets: make(map[InterfaceName]uint64), last: make(map[InterfaceName]SnoopyInterfaceMetrics), + bpfAttached: make(map[InterfaceName]bool), } handle.StartBytesLock.RLock() maps.Copy(snap.ingressStart, handle.IngressStartBytes) maps.Copy(snap.egressStart, handle.EgressStartBytes) maps.Copy(snap.ingressStartPackets, handle.IngressStartPackets) maps.Copy(snap.egressStartPackets, handle.EgressStartPackets) + maps.Copy(snap.bpfAttached, handle.BpfAttachedInterfaces) handle.StartBytesLock.RUnlock() handle.LastMetricsLock.RLock() @@ -608,16 +642,20 @@ func (self *snoopyManager) Metrics() map[containerenumerator.PodInfoIdentifier]C var procFetched bool for interfaceName := range snap.ingressStart { + if interfaceName == loopbackInterface { + continue + } interfaceInfo := MetricSnapshot{} interfaceInfo.Ingress.StartBytes = snap.ingressStart[interfaceName] interfaceInfo.Egress.StartBytes = snap.egressStart[interfaceName] - // Use eBPF metrics if they have reported any data. - // If LastMetrics is all-zero the eBPF program either failed to - // initialize (explicitly or silently, e.g. after removing - // privileged:true) or snoopy just started. Fall back to - // /proc/net/dev so that traffic is always captured. + // Use eBPF metrics once snoopy attached both counters, even + // while they are still zero (an idle pod). Otherwise the eBPF + // program failed or is not attached yet: fall back to + // /proc/net/dev so that traffic is always captured. Deciding + // by "all-zero" instead read /proc/net/dev every second for + // every idle pod. lastM := snap.last[interfaceName] - if lastM.Ingress.Bytes > 0 || lastM.Egress.Bytes > 0 || lastM.Ingress.Packets > 0 || lastM.Egress.Packets > 0 { + if snap.bpfAttached[interfaceName] { interfaceInfo.Ingress.Bytes = lastM.Ingress.Bytes interfaceInfo.Ingress.Packets = lastM.Ingress.Packets interfaceInfo.Egress.Bytes = lastM.Egress.Bytes @@ -664,183 +702,235 @@ func (self *snoopyManager) SetArgs(args SnoopyArgs) { self.args = args } +// Register starts one snoopy instance for the pod. All containers of a pod +// share the network namespace of the pod sandbox; one snoopy per container +// attached the same counters to the same interfaces several times (stacking +// a TC program per extra container on every packet) and the per-pod metrics +// then flipped between those instances. func (self *snoopyManager) Register(podInfo containerenumerator.PodInfo) []error { - errors := []error{} - for containerId, pid := range podInfo.ContainersWithFirstPid() { - self.statusEventTx <- SnoopyStatusEvent{ - Type: SnoopyStatusEventTypeRegisterRequest, - RegisterRequest: &SnoopyStatusEventRegisterRequest{ - podInfo.Namespace, - podInfo.Name, - containerId, - pid, - }, - } - handle, err := self.attachToPidNamespace(pid) - if err != nil { - self.statusEventTx <- SnoopyStatusEvent{ - Type: SnoopyStatusEventTypeRegisterFailure, - RegisterFailure: &SnoopyStatusEventRegisterFailure{ - podInfo.Namespace, - podInfo.Name, - containerId, - pid, - err, - }, - } - errors = append(errors, fmt.Errorf("failed to attach snoopy to containerId(%s) pid(%d): %w", containerId, pid, err)) - continue - } + target, err := podNetnsTarget(self.procPath, podInfo) + if err != nil { + return []error{err} + } + containerId := target.ContainerId + pid := target.Pid + + self.statusEventTx <- SnoopyStatusEvent{ + Type: SnoopyStatusEventTypeRegisterRequest, + RegisterRequest: &SnoopyStatusEventRegisterRequest{ + PodNamespace: podInfo.Namespace, + PodName: podInfo.Name, + ContainerId: containerId, + NsProcessPid: pid, + }, + } + handle, err := self.attachToPidNamespace(pid) + if err != nil { self.statusEventTx <- SnoopyStatusEvent{ - Type: SnoopyStatusEventTypeRegisterSuccess, - RegisterSuccess: &SnoopyStatusEventRegisterSuccess{ - podInfo.Namespace, - podInfo.Name, - containerId, - pid, - handle.SnoopyPid, + Type: SnoopyStatusEventTypeRegisterFailure, + RegisterFailure: &SnoopyStatusEventRegisterFailure{ + PodNamespace: podInfo.Namespace, + PodName: podInfo.Name, + ContainerId: containerId, + NsProcessPid: pid, + Error: err.Error(), }, } + return []error{fmt.Errorf("failed to attach snoopy to containerId(%s) pid(%d): %w", containerId, pid, err)} + } + self.statusEventTx <- SnoopyStatusEvent{ + Type: SnoopyStatusEventTypeRegisterSuccess, + RegisterSuccess: &SnoopyStatusEventRegisterSuccess{ + PodNamespace: podInfo.Namespace, + PodName: podInfo.Name, + ContainerId: containerId, + NsProcessPid: pid, + SnoopyPid: handle.SnoopyPid, + }, + } - handle.PodInfo = podInfo - - go func() { - for { - select { - case <-handle.Ctx.Done(): - return - case logMessage := <-handle.Stderr: - switch logMessage.Level { - case "DEBUG": - self.logger.Debug("snoppy debug", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) - case "INFO": - self.logger.Info("snoppy info", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) - case "WARN": - // The Rust snoopy binary logs the setrlimit(RLIMIT_MEMLOCK) failure - // as WARN, but its own message says "this is fine on kernels >=5.11" - // because eBPF on modern kernels uses cgroup-v2 memory accounting - // instead of locked memory. Demote to Debug so it doesn't pollute - // operator telemetry on every snoopy attach. - if strings.Contains(logMessage.Message, "running without raised memlock limit") { - self.logger.Debug("snoppy warning", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) - break - } - self.logger.Warn("snoppy warning", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) - case "ERROR": - self.logger.Error("snoppy error", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + handle.PodInfo = podInfo + + go func() { + for { + select { + case <-handle.Ctx.Done(): + return + case logMessage := <-handle.Stderr: + switch logMessage.Level { + case "DEBUG": + self.logger.Debug("snoppy debug", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + case "INFO": + self.logger.Info("snoppy info", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + case "WARN": + // The Rust snoopy binary logs the setrlimit(RLIMIT_MEMLOCK) failure + // as WARN, but its own message says "this is fine on kernels >=5.11" + // because eBPF on modern kernels uses cgroup-v2 memory accounting + // instead of locked memory. Demote to Debug so it doesn't pollute + // operator telemetry on every snoopy attach. + if strings.Contains(logMessage.Message, "running without raised memlock limit") { + self.logger.Debug("snoppy warning", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + break } - case metrics := <-handle.Stdout: - // InterfaceMetrics (the most frequent event) and - // InterfaceChanged are ignored by the status handler; - // don't funnel them through the serial status channel - // just to be dropped there. - if metrics.Type != SnoopyEventTypeInterfaceMetrics && metrics.Type != SnoopyEventTypeInterfaceChanged { - self.statusEventTx <- SnoopyStatusEvent{ - Type: SnoopyStatusEventTypeSnoopyEvent, - SnoopyEvent: &SnoopyStatusEventSnoopyEvent{ - SnoopyPid: handle.SnoopyPid, - SnoopyEvent: metrics, - }, - } + self.logger.Warn("snoppy warning", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + case "ERROR": + self.logger.Error("snoppy error", "containerId", containerId, "snoopyPid", handle.SnoopyPid, "attachedProcessPid", pid, "level", logMessage.Level, "target", logMessage.Target, "msg", logMessage.Message) + } + case metrics := <-handle.Stdout: + // InterfaceMetrics (the most frequent event) and + // InterfaceChanged are ignored by the status handler; + // don't funnel them through the serial status channel + // just to be dropped there. + if metrics.Type != SnoopyEventTypeInterfaceMetrics && metrics.Type != SnoopyEventTypeInterfaceChanged { + self.statusEventTx <- SnoopyStatusEvent{ + Type: SnoopyStatusEventTypeSnoopyEvent, + SnoopyEvent: &SnoopyStatusEventSnoopyEvent{ + SnoopyPid: handle.SnoopyPid, + SnoopyEvent: metrics, + }, } - switch metrics.Type { - case SnoopyEventTypeInterfaceAdded: - iface := metrics.InterfaceAdded.Interface.Name - rxBytes, txBytes, rxPkts, txPkts := self.readStartMetricsFromPidAndInterface(pid, iface) - handle.StartBytesLock.Lock() - handle.IngressStartBytes[iface] = rxBytes - handle.EgressStartBytes[iface] = txBytes - handle.IngressStartPackets[iface] = rxPkts - handle.EgressStartPackets[iface] = txPkts - handle.StartBytesLock.Unlock() - case SnoopyEventTypeInterfaceRemoved: - iface := metrics.InterfaceRemoved.Interface.Name - handle.StartBytesLock.Lock() - delete(handle.IngressStartBytes, iface) - delete(handle.EgressStartBytes, iface) - delete(handle.IngressStartPackets, iface) - delete(handle.EgressStartPackets, iface) - delete(handle.BpfFailedInterfaces, iface) - handle.StartBytesLock.Unlock() - case SnoopyEventTypeInterfaceChanged: - // ignore - case SnoopyEventTypeInterfaceMetrics: - handle.LastMetricsLock.Lock() - handle.LastMetrics[metrics.InterfaceMetric.Interface] = *metrics.InterfaceMetric - handle.LastMetricsLock.Unlock() - case SnoopyEventTypeInterfaceBpfInitialized: - // ignore - case SnoopyEventTypeInterfaceBpfInitializationFailed: - // eBPF failed for this interface; mark it so Metrics() can fall back to /proc/net/dev - handle.StartBytesLock.Lock() - handle.BpfFailedInterfaces[metrics.InterfaceBpfInitializationFailed.Interface] = true - handle.StartBytesLock.Unlock() - default: - self.logger.Warn("unknown metric type", "type", metrics.Type, "metric", metrics) + } + switch metrics.Type { + case SnoopyEventTypeInterfaceAdded: + iface := metrics.InterfaceAdded.Interface.Name + rxBytes, txBytes, rxPkts, txPkts := self.readStartMetricsFromPidAndInterface(pid, iface) + handle.StartBytesLock.Lock() + handle.IngressStartBytes[iface] = rxBytes + handle.EgressStartBytes[iface] = txBytes + handle.IngressStartPackets[iface] = rxPkts + handle.EgressStartPackets[iface] = txPkts + handle.StartBytesLock.Unlock() + case SnoopyEventTypeInterfaceRemoved: + iface := metrics.InterfaceRemoved.Interface.Name + handle.StartBytesLock.Lock() + delete(handle.IngressStartBytes, iface) + delete(handle.EgressStartBytes, iface) + delete(handle.IngressStartPackets, iface) + delete(handle.EgressStartPackets, iface) + delete(handle.BpfAttachedInterfaces, iface) + handle.StartBytesLock.Unlock() + case SnoopyEventTypeInterfaceChanged: + // ignore + case SnoopyEventTypeInterfaceMetrics: + handle.LastMetricsLock.Lock() + handle.LastMetrics[metrics.InterfaceMetric.Interface] = *metrics.InterfaceMetric + handle.LastMetricsLock.Unlock() + case SnoopyEventTypeInterfaceBpfInitialized: + // Only an interface with both counters attached reports + // eBPF values; anything else is read from /proc/net/dev. + payload := metrics.InterfaceBpfInitialized + attached := payload.IngressImplementation != snoopyImplementationNone && payload.EgressImplementation != snoopyImplementationNone + handle.StartBytesLock.Lock() + if attached { + handle.BpfAttachedInterfaces[payload.Interface] = true + } else { + delete(handle.BpfAttachedInterfaces, payload.Interface) } + handle.StartBytesLock.Unlock() + case SnoopyEventTypeInterfaceBpfInitializationFailed: + // eBPF failed for this interface; Metrics() falls back to /proc/net/dev + handle.StartBytesLock.Lock() + delete(handle.BpfAttachedInterfaces, metrics.InterfaceBpfInitializationFailed.Interface) + handle.StartBytesLock.Unlock() + default: + self.logger.Warn("unknown metric type", "type", metrics.Type, "metric", metrics) } } - }() - - handleId := self.formatHandleId(podInfo.Namespace, podInfo.Name, containerId) - self.handlesLock.Lock() - if old, exists := self.handles[handleId]; exists { - // Stale handle from a previous registration of the same - // container; kill it so its snoopy child doesn't leak. - self.logger.Warn("replacing stale snoopy handle", "handleId", handleId, "snoopyPid", old.SnoopyPid) - go func() { - if err := old.Cmd.Process.Kill(); err == nil { - _, _ = old.Cmd.Process.Wait() - } - }() } - self.handles[handleId] = handle - self.handlesLock.Unlock() + }() + + // The key is the pod, not a pid or container: a container's first PID + // can change during its lifetime while PodInfo.Equals treats the pod as + // unchanged, and Remove() has to find the handle again from the pod. + handleId := podInfo.NamespaceAndName() + self.handlesLock.Lock() + if old, exists := self.handles[handleId]; exists { + // Stale handle from a previous registration of the same pod; stop + // it so its snoopy child doesn't leak. + self.logger.Warn("replacing stale snoopy handle", "handleId", handleId, "snoopyPid", old.SnoopyPid) + self.statusEventTx <- SnoopyStatusEvent{ + Type: SnoopyStatusEventTypeRemove, + Remove: &SnoopyStatusEventRemove{SnoopyPid: old.SnoopyPid}, + } + go self.stopSnoopy(old) } + self.handles[handleId] = handle + self.handlesLock.Unlock() - return errors + return nil } -// formatHandleId deliberately excludes the PID: a container's first PID can -// change during its lifetime (init/wrapper process exits) while PodInfo.Equals -// treats the pod as unchanged. With the PID in the key, Remove() could no -// longer find the handle and the snoopy child process leaked forever. -func (self *snoopyManager) formatHandleId(namespace string, name string, containerId string) string { - return namespace + "/" + name + "/" + containerId +// podNetnsTarget picks the container whose first process is used to enter +// the pod's network namespace: the first one, in stable order, whose +// namespace handle still exists. Short-lived first processes can vanish +// between enumeration and attach; trying the next container avoids a failed +// registration in that case. +func podNetnsTarget(procPath string, podInfo containerenumerator.PodInfo) (containerenumerator.ContainerFirstPid, error) { + containers := podInfo.SortedContainersWithFirstPid() + for _, container := range containers { + netnsPath := procPath + "/" + strconv.FormatUint(container.Pid, 10) + "/ns/net" + if _, err := os.Stat(netnsPath); err == nil { + return container, nil + } + } + return containerenumerator.ContainerFirstPid{}, fmt.Errorf("no container of pod %s has a reachable network namespace (%d containers)", podInfo.NamespaceAndName(), len(containers)) } func (self *snoopyManager) Remove(podInfo containerenumerator.PodInfo) []error { - errors := []error{} + handleId := podInfo.NamespaceAndName() self.handlesLock.Lock() defer self.handlesLock.Unlock() - for containerId := range podInfo.ContainersWithFirstPid() { - handleId := self.formatHandleId(podInfo.Namespace, podInfo.Name, containerId) - handle, ok := self.handles[handleId] - if ok { - delete(self.handles, handleId) - self.statusEventTx <- SnoopyStatusEvent{ - Type: SnoopyStatusEventTypeRemove, - Remove: &SnoopyStatusEventRemove{ - SnoopyPid: handle.SnoopyPid, - }, - } - go func() { - err := handle.Cmd.Process.Kill() - if err != nil { - self.logger.Debug("failed to kill process", "process", handle.Cmd.Process, "error", err) - return - } - _, err = handle.Cmd.Process.Wait() - if err != nil { - self.logger.Debug("failed to wait for process", "process", handle.Cmd.Process, "error", err) - return - } - }() - } + handle, ok := self.handles[handleId] + if !ok { + return nil + } + delete(self.handles, handleId) + self.statusEventTx <- SnoopyStatusEvent{ + Type: SnoopyStatusEventTypeRemove, + Remove: &SnoopyStatusEventRemove{ + SnoopyPid: handle.SnoopyPid, + }, + } + go self.stopSnoopy(handle) + + return nil +} + +// snoopyStopTimeout bounds how long a snoopy instance gets to detach its +// eBPF programs after SIGTERM before it is killed. +const snoopyStopTimeout = 5 * time.Second + +// stopSnoopy asks the snoopy process to exit and reaps it. SIGTERM comes +// first because SIGKILL gives the process no chance to detach: on kernels +// without tcx (<6.6) the TC filters are attached through netlink and outlive +// the process, so every re-registration added another filter to a pod +// network namespace that survives container restarts. +func (self *snoopyManager) stopSnoopy(handle *SnoopyHandle) { + process := handle.Cmd.Process + if err := process.Signal(syscall.SIGTERM); err != nil { + self.logger.Debug("failed to send SIGTERM to snoopy", "snoopyPid", handle.SnoopyPid, "error", err) } - return errors + exited := make(chan struct{}) + go func() { + defer close(exited) + if _, err := process.Wait(); err != nil { + self.logger.Debug("failed to wait for snoopy", "snoopyPid", handle.SnoopyPid, "error", err) + } + }() + + timer := time.NewTimer(snoopyStopTimeout) + defer timer.Stop() + select { + case <-exited: + case <-timer.C: + self.logger.Warn("snoopy did not exit after SIGTERM, killing it", "snoopyPid", handle.SnoopyPid, "timeout", snoopyStopTimeout) + if err := process.Kill(); err != nil { + self.logger.Debug("failed to kill snoopy", "snoopyPid", handle.SnoopyPid, "error", err) + } + <-exited + } } // readStartMetricsFromPidAndInterface reads the current byte and packet counters from @@ -902,7 +992,7 @@ func (self *snoopyManager) attachToPidNamespace(pid ProcessId) (*SnoopyHandle, e snoopy.EgressStartBytes = map[InterfaceName]uint64{} snoopy.IngressStartPackets = map[InterfaceName]uint64{} snoopy.EgressStartPackets = map[InterfaceName]uint64{} - snoopy.BpfFailedInterfaces = map[InterfaceName]bool{} + snoopy.BpfAttachedInterfaces = map[InterfaceName]bool{} snoopy.LastMetricsLock = &sync.RWMutex{} snoopy.LastMetrics = map[InterfaceName]SnoopyInterfaceMetrics{}