Files
RustProxy/docker-agent/containers.go
T
2026-11-14 09:57:21 +01:00

188 lines
5.0 KiB
Go

package main
import (
"context"
"net/url"
"strings"
"sync"
"time"
)
const maxStatContainers = 64
type containerState struct {
State string `json:"state,omitempty"`
Health string `json:"health,omitempty"`
RestartCount *uint64 `json:"restart_count,omitempty"`
CPUPercent *float64 `json:"cpu_percent,omitempty"`
MemoryBytes *uint64 `json:"memory_bytes,omitempty"`
MemoryLimitBytes *uint64 `json:"memory_limit_bytes,omitempty"`
StartedAt string `json:"started_at,omitempty"`
}
type containerInspect struct {
RestartCount uint64 `json:"RestartCount"`
State struct {
Status string `json:"Status"`
StartedAt string `json:"StartedAt"`
Health *struct {
Status string `json:"Status"`
} `json:"Health"`
} `json:"State"`
}
type cpuUsage struct {
CPUUsage struct {
TotalUsage uint64 `json:"total_usage"`
} `json:"cpu_usage"`
SystemCPUUsage uint64 `json:"system_cpu_usage"`
OnlineCPUs uint32 `json:"online_cpus"`
}
type containerStats struct {
CPUStats cpuUsage `json:"cpu_stats"`
PreCPUStats cpuUsage `json:"precpu_stats"`
MemoryStats struct {
Usage uint64 `json:"usage"`
Limit uint64 `json:"limit"`
Stats map[string]uint64 `json:"stats"`
} `json:"memory_stats"`
}
func healthFromStatus(status string) string {
status = strings.ToLower(status)
switch {
case strings.Contains(status, "(unhealthy)"):
return "unhealthy"
case strings.Contains(status, "(healthy)"):
return "healthy"
case strings.Contains(status, "health: starting"):
return "starting"
}
return ""
}
func rustproxyLabels(labels map[string]string) map[string]string {
out := map[string]string{}
for key, value := range labels {
if strings.HasPrefix(key, "rustproxy.") && len(key) <= 64 && len(value) <= 512 && len(out) < 32 {
out[key] = value
}
}
if len(out) == 0 {
return nil
}
return out
}
type cpuSampleKey struct{ total, system uint64 }
type containerCollector struct {
mu sync.Mutex
prev map[string]cpuSampleKey
}
func newContainerCollector() *containerCollector {
return &containerCollector{prev: map[string]cpuSampleKey{}}
}
func memoryWithoutCache(stats containerStats) uint64 {
usage := stats.MemoryStats.Usage
for _, key := range []string{"inactive_file", "total_inactive_file", "cache"} {
if value, ok := stats.MemoryStats.Stats[key]; ok && value < usage {
return usage - value
}
}
return usage
}
func (c *containerCollector) cpuPercent(id string, stats containerStats) *float64 {
c.mu.Lock()
defer c.mu.Unlock()
current := cpuSampleKey{stats.CPUStats.CPUUsage.TotalUsage, stats.CPUStats.SystemCPUUsage}
previous, ok := c.prev[id]
c.prev[id] = current
if !ok && stats.PreCPUStats.SystemCPUUsage > 0 {
previous, ok = cpuSampleKey{stats.PreCPUStats.CPUUsage.TotalUsage, stats.PreCPUStats.SystemCPUUsage}, true
}
if !ok || current.system <= previous.system || current.total < previous.total {
return nil
}
cpus := float64(stats.CPUStats.OnlineCPUs)
if cpus == 0 {
cpus = 1
}
value := round(float64(current.total-previous.total)/float64(current.system-previous.system)*cpus*100, 1)
return &value
}
func (c *containerCollector) enrich(ctx context.Context, sock string, services []service) {
ids := map[string]*containerState{}
order := []string{}
for i := range services {
id := services[i].ContainerID
if id == "" {
continue
}
if _, ok := ids[id]; !ok {
if len(order) >= maxStatContainers {
continue
}
ids[id] = services[i].Container
order = append(order, id)
}
}
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
var wg sync.WaitGroup
limit := make(chan struct{}, 8)
for _, id := range order {
state := ids[id]
if state == nil {
continue
}
wg.Add(1)
go func(id string, state *containerState) {
defer wg.Done()
limit <- struct{}{}
defer func() { <-limit }()
escaped := url.PathEscape(id)
var inspect containerInspect
if err := engineGet(ctx, sock, "/containers/"+escaped+"/json", &inspect); err == nil {
restarts := inspect.RestartCount
state.RestartCount = &restarts
if inspect.State.Status != "" {
state.State = inspect.State.Status
}
state.StartedAt = inspect.State.StartedAt
switch {
case inspect.State.Health != nil && inspect.State.Health.Status != "":
state.Health = strings.ToLower(inspect.State.Health.Status)
case inspect.State.Health == nil:
state.Health = "none"
}
}
var stats containerStats
if err := engineGet(ctx, sock, "/containers/"+escaped+"/stats?stream=false&one-shot=true", &stats); err == nil {
state.CPUPercent = c.cpuPercent(id, stats)
if stats.MemoryStats.Usage > 0 {
memory := memoryWithoutCache(stats)
state.MemoryBytes = &memory
}
if stats.MemoryStats.Limit > 0 && stats.MemoryStats.Limit < 1<<60 {
limitBytes := stats.MemoryStats.Limit
state.MemoryLimitBytes = &limitBytes
}
}
}(id, state)
}
wg.Wait()
c.mu.Lock()
for id := range c.prev {
if _, ok := ids[id]; !ok {
delete(c.prev, id)
}
}
c.mu.Unlock()
}