Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/containerenumerator/podinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"log/slog"
"mogenius-operator/src/assert"
"net/url"
"slices"
"strings"
"time"

v1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -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
}

Expand Down
12 changes: 9 additions & 3 deletions src/core/dbstats.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
23 changes: 21 additions & 2 deletions src/core/nodemetricscollector.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package core

import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"mogenius-operator/src/assert"
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/networkmonitor/networkmonitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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{}

Expand Down
63 changes: 31 additions & 32 deletions src/networkmonitor/networkstatsreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -83,36 +83,38 @@ 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)
self.removeRx <- nil
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 {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -191,15 +193,15 @@ func (self *networkStatsReader) startWorker() {
containerInfo.Metrics[baseStartInfo.Interface] = metricSnapshot
}

newMetrics[baseInfo.ContainerId] = containerInfo
newMetrics[baseInfo.PodInfo.NamespaceAndName()] = containerInfo
}
metrics = newMetrics
}
}
}()
}

func (self *networkStatsReader) Metrics() map[ContainerId]ContainerInfo {
func (self *networkStatsReader) Metrics() map[containerenumerator.PodInfoIdentifier]ContainerInfo {
self.Run()

self.metricsTx <- struct{}{}
Expand All @@ -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) {}
Expand Down
Loading
Loading