Files
RustProxy/docker-agent/system.go
T
2026-11-28 17:36:53 +01:00

318 lines
8.8 KiB
Go

package main
import (
"bufio"
"context"
"math"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
type systemInfo struct {
OS string `json:"os,omitempty"`
Kernel string `json:"kernel,omitempty"`
Arch string `json:"arch,omitempty"`
Runtime string `json:"runtime,omitempty"`
RuntimeVersion string `json:"runtime_version,omitempty"`
UptimeSeconds *uint64 `json:"uptime_seconds,omitempty"`
Load1 *float64 `json:"load1,omitempty"`
Load5 *float64 `json:"load5,omitempty"`
Load15 *float64 `json:"load15,omitempty"`
CPUCount *uint32 `json:"cpu_count,omitempty"`
CPUPercent *float64 `json:"cpu_percent,omitempty"`
MemoryTotalBytes *uint64 `json:"memory_total_bytes,omitempty"`
MemoryAvailableBytes *uint64 `json:"memory_available_bytes,omitempty"`
SwapTotalBytes *uint64 `json:"swap_total_bytes,omitempty"`
SwapFreeBytes *uint64 `json:"swap_free_bytes,omitempty"`
DiskTotalBytes *uint64 `json:"disk_total_bytes,omitempty"`
DiskFreeBytes *uint64 `json:"disk_free_bytes,omitempty"`
NetworkRxBytes *uint64 `json:"network_rx_bytes,omitempty"`
NetworkTxBytes *uint64 `json:"network_tx_bytes,omitempty"`
NetworkRxBytesPerSecond *float64 `json:"network_rx_bytes_per_second,omitempty"`
NetworkTxBytesPerSecond *float64 `json:"network_tx_bytes_per_second,omitempty"`
ContainersRunning *uint64 `json:"containers_running,omitempty"`
ContainersTotal *uint64 `json:"containers_total,omitempty"`
Images *uint64 `json:"images,omitempty"`
}
type cpuSample struct{ idle, total uint64 }
type netSample struct {
rx, tx uint64
at time.Time
}
type systemCollector struct {
mu sync.Mutex
procDir string
etcDir string
cpu *cpuSample
net *netSample
}
func newSystemCollector() *systemCollector {
return &systemCollector{procDir: "/proc", etcDir: "/etc"}
}
func ptr[T any](value T) *T { return &value }
func round(value float64, places int) float64 {
scale := math.Pow(10, float64(places))
return math.Round(value*scale) / scale
}
func readTrimmed(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
func osPrettyName(etcDir string) string {
for _, path := range []string{etcDir + "/os-release", "/usr/lib/os-release"} {
file, err := os.Open(path)
if err != nil {
continue
}
scanner := bufio.NewScanner(file)
name := ""
for scanner.Scan() {
line := scanner.Text()
if value, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok {
name = strings.Trim(value, `"'`)
break
}
if value, ok := strings.CutPrefix(line, "NAME="); ok && name == "" {
name = strings.Trim(value, `"'`)
}
}
file.Close()
if name != "" {
return name
}
}
return ""
}
func parseLoadavg(raw string) (float64, float64, float64, bool) {
fields := strings.Fields(raw)
if len(fields) < 3 {
return 0, 0, 0, false
}
var values [3]float64
for i := range values {
value, err := strconv.ParseFloat(fields[i], 64)
if err != nil || value < 0 {
return 0, 0, 0, false
}
values[i] = value
}
return values[0], values[1], values[2], true
}
func parseMeminfo(raw string) map[string]uint64 {
out := map[string]uint64{}
for _, line := range strings.Split(raw, "\n") {
key, rest, ok := strings.Cut(line, ":")
if !ok {
continue
}
fields := strings.Fields(rest)
if len(fields) == 0 {
continue
}
value, err := strconv.ParseUint(fields[0], 10, 64)
if err != nil {
continue
}
if len(fields) > 1 && strings.EqualFold(fields[1], "kB") {
value *= 1024
}
out[strings.TrimSpace(key)] = value
}
return out
}
func parseCPUStat(raw string) (cpuSample, bool) {
for _, line := range strings.Split(raw, "\n") {
fields := strings.Fields(line)
if len(fields) < 5 || fields[0] != "cpu" {
continue
}
var total, idle uint64
for index, field := range fields[1:] {
value, err := strconv.ParseUint(field, 10, 64)
if err != nil {
return cpuSample{}, false
}
if index >= 8 {
break
}
total += value
if index == 3 || index == 4 {
idle += value
}
}
return cpuSample{idle: idle, total: total}, total > 0
}
return cpuSample{}, false
}
func skipTrafficInterface(name string) bool {
name = strings.ToLower(name)
if name == "lo" || skipInterface(name) {
return true
}
for _, prefix := range []string{"cni", "flannel", "cali", "podman", "vxlan", "kube-", "weave", "tunl0"} {
if strings.HasPrefix(name, prefix) {
return true
}
}
return false
}
func parseNetDev(raw string) (uint64, uint64, bool) {
var rx, tx uint64
found := false
for _, line := range strings.Split(raw, "\n") {
name, rest, ok := strings.Cut(line, ":")
if !ok {
continue
}
name = strings.TrimSpace(name)
fields := strings.Fields(rest)
if len(fields) < 9 || skipTrafficInterface(name) {
continue
}
in, err1 := strconv.ParseUint(fields[0], 10, 64)
out, err2 := strconv.ParseUint(fields[8], 10, 64)
if err1 != nil || err2 != nil {
continue
}
rx += in
tx += out
found = true
}
return rx, tx, found
}
func (c *systemCollector) cpuPercent() *float64 {
sample, ok := parseCPUStat(readTrimmed(c.procDir + "/stat"))
if !ok {
return nil
}
c.mu.Lock()
previous := c.cpu
c.mu.Unlock()
if previous == nil {
time.Sleep(200 * time.Millisecond)
next, ok := parseCPUStat(readTrimmed(c.procDir + "/stat"))
if !ok {
return nil
}
initial := sample
sample = next
previous = &initial
}
c.mu.Lock()
if c.cpu != nil {
previous = c.cpu
}
if c.cpu != nil && sample.total < c.cpu.total {
c.mu.Unlock()
return nil
}
c.cpu = &cpuSample{idle: sample.idle, total: sample.total}
c.mu.Unlock()
if sample.total <= previous.total || sample.idle < previous.idle {
return nil
}
totalDelta := float64(sample.total - previous.total)
idleDelta := float64(sample.idle - previous.idle)
value := round(math.Max(0, math.Min(100, (1-idleDelta/totalDelta)*100)), 1)
return &value
}
func (c *systemCollector) collect(ctx context.Context, sock string) *systemInfo {
info := &systemInfo{OS: osPrettyName(c.etcDir), Kernel: readTrimmed(c.procDir + "/sys/kernel/osrelease"), Arch: runtime.GOARCH}
if fields := strings.Fields(readTrimmed(c.procDir + "/uptime")); len(fields) > 0 {
if value, err := strconv.ParseFloat(fields[0], 64); err == nil && value >= 0 {
info.UptimeSeconds = ptr(uint64(value))
}
}
if l1, l5, l15, ok := parseLoadavg(readTrimmed(c.procDir + "/loadavg")); ok {
info.Load1, info.Load5, info.Load15 = ptr(l1), ptr(l5), ptr(l15)
}
info.CPUCount = ptr(uint32(runtime.NumCPU()))
info.CPUPercent = c.cpuPercent()
memory := parseMeminfo(readTrimmed(c.procDir + "/meminfo"))
if value, ok := memory["MemTotal"]; ok {
info.MemoryTotalBytes = ptr(value)
}
if value, ok := memory["MemAvailable"]; ok {
info.MemoryAvailableBytes = ptr(value)
}
if value, ok := memory["SwapTotal"]; ok {
info.SwapTotalBytes = ptr(value)
}
if value, ok := memory["SwapFree"]; ok {
info.SwapFreeBytes = ptr(value)
}
if rx, tx, ok := parseNetDev(readTrimmed(c.procDir + "/net/dev")); ok {
now := time.Now()
info.NetworkRxBytes, info.NetworkTxBytes = ptr(rx), ptr(tx)
c.mu.Lock()
previous := c.net
if previous == nil || !now.Before(previous.at) {
c.net = &netSample{rx: rx, tx: tx, at: now}
}
c.mu.Unlock()
if previous != nil && rx >= previous.rx && tx >= previous.tx {
if seconds := now.Sub(previous.at).Seconds(); seconds >= 0.5 {
info.NetworkRxBytesPerSecond = ptr(round(float64(rx-previous.rx)/seconds, 1))
info.NetworkTxBytesPerSecond = ptr(round(float64(tx-previous.tx)/seconds, 1))
}
}
}
diskPath := "/"
if sock != "" {
var engine engineInfo
if err := engineGet(ctx, sock, "/info", &engine); err == nil {
info.ContainersRunning = ptr(engine.ContainersRunning)
info.ContainersTotal = ptr(engine.Containers)
info.Images = ptr(engine.Images)
if info.OS == "" {
info.OS = engine.OperatingSystem
}
if info.Kernel == "" {
info.Kernel = engine.KernelVersion
}
if engine.DockerRootDir != "" {
diskPath = engine.DockerRootDir
}
info.RuntimeVersion = engine.ServerVersion
}
var version engineVersion
if err := engineGet(ctx, sock, "/version", &version); err == nil {
info.Runtime = runtimeName(version, sock)
if version.Version != "" {
info.RuntimeVersion = version.Version
}
} else if info.RuntimeVersion != "" {
info.Runtime = runtimeName(engineVersion{}, sock)
}
}
if total, free, ok := diskUsage(diskPath); ok {
info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free)
} else if diskPath != "/" {
if total, free, ok := diskUsage("/"); ok {
info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free)
}
}
return info
}