package main import ( "context" "net/url" "strings" "sync" "time" ) const ( maxStatContainers = 64 statWorkers = 8 containerStatsTTL = 15 * time.Second ) 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 cache map[string]containerState cacheSock string cacheUntil time.Time inFlight chan struct{} } func newContainerCollector() *containerCollector { return &containerCollector{prev: make(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) { selected := make(map[string]struct{}) order := make([]string, 0, maxStatContainers) for i := range services { id := services[i].ContainerID if id == "" || services[i].Container == nil { continue } if _, ok := selected[id]; !ok && len(order) < maxStatContainers { selected[id] = struct{}{} order = append(order, id) } } if len(order) == 0 { c.mu.Lock() if c.inFlight == nil { c.prev = make(map[string]cpuSampleKey) c.cache = nil c.cacheUntil = time.Time{} } c.mu.Unlock() return } for { if ctx.Err() != nil { return } c.mu.Lock() hit := c.cacheSock == sock && time.Now().Before(c.cacheUntil) if hit { for _, id := range order { if _, exists := c.cache[id]; !exists { hit = false break } } } if hit { snapshot := c.cache c.mu.Unlock() applyContainerSnapshot(services, snapshot) return } if c.inFlight != nil { done := c.inFlight c.mu.Unlock() select { case <-done: continue case <-ctx.Done(): return } } done := make(chan struct{}) c.inFlight = done c.mu.Unlock() snapshot := c.fetchSnapshot(ctx, sock, order) c.mu.Lock() if ctx.Err() == nil { c.cache, c.cacheSock = snapshot, sock c.cacheUntil = time.Now().Add(containerStatsTTL) for id := range c.prev { if _, exists := selected[id]; !exists { delete(c.prev, id) } } } c.inFlight = nil close(done) c.mu.Unlock() applyContainerSnapshot(services, snapshot) return } } func (c *containerCollector) fetchSnapshot(parent context.Context, sock string, order []string) map[string]containerState { ctx, cancel := context.WithTimeout(parent, 4*time.Second) defer cancel() results := make([]containerState, len(order)) workers := statWorkers if len(order) < workers { workers = len(order) } jobs := make(chan int) var wg sync.WaitGroup wg.Add(workers) for i := 0; i < workers; i++ { go func() { defer wg.Done() for index := range jobs { if ctx.Err() == nil { results[index] = c.inspectContainer(ctx, sock, order[index]) } } }() } queue: for index := range order { select { case jobs <- index: case <-ctx.Done(): break queue } } close(jobs) wg.Wait() snapshot := make(map[string]containerState, len(order)) for i, id := range order { snapshot[id] = results[i] } return snapshot } func (c *containerCollector) inspectContainer(ctx context.Context, sock, id string) containerState { var state containerState escaped := url.PathEscape(id) var inspect containerInspect if err := engineGet(ctx, sock, "/containers/"+escaped+"/json", &inspect); err == nil { state.RestartCount = ptr(inspect.RestartCount) 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 { state.MemoryBytes = ptr(memoryWithoutCache(stats)) } if stats.MemoryStats.Limit > 0 && stats.MemoryStats.Limit < 1<<60 { state.MemoryLimitBytes = ptr(stats.MemoryStats.Limit) } } return state } func applyContainerSnapshot(services []service, snapshot map[string]containerState) { for i := range services { dest := services[i].Container if dest == nil { continue } state, exists := snapshot[services[i].ContainerID] if !exists { continue } if state.State != "" { dest.State = state.State } if state.Health != "" { dest.Health = state.Health } if state.StartedAt != "" { dest.StartedAt = state.StartedAt } if state.RestartCount != nil { dest.RestartCount = ptr(*state.RestartCount) } if state.CPUPercent != nil { dest.CPUPercent = ptr(*state.CPUPercent) } if state.MemoryBytes != nil { dest.MemoryBytes = ptr(*state.MemoryBytes) } if state.MemoryLimitBytes != nil { dest.MemoryLimitBytes = ptr(*state.MemoryLimitBytes) } } }