0.38.6_agent_hotfix

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-19 08:53:34 +01:00
1 parent 1239ff524d
commit d4a604970e
14 files changed
+478 -162

No files matched your search

+184 -58
View File
@@ -8,7 +8,11 @@ import (
"time"
)
const maxStatContainers = 64
const (
maxStatContainers = 64
statWorkers = 8
containerStatsTTL = 15 * time.Second
)
type containerState struct {
State string `json:"state,omitempty"`
@@ -78,12 +82,16 @@ func rustproxyLabels(labels map[string]string) map[string]string {
type cpuSampleKey struct{ total, system uint64 }
type containerCollector struct {
mu sync.Mutex
prev map[string]cpuSampleKey
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: map[string]cpuSampleKey{}}
return &containerCollector{prev: make(map[string]cpuSampleKey)}
}
func memoryWithoutCache(stats containerStats) uint64 {
@@ -116,72 +124,190 @@ func (c *containerCollector) cpuPercent(id string, stats containerStats) *float6
return &value
}
// enrich applies a bounded, short-lived snapshot to every service, including
// multiple published ports belonging to the same container. It coalesces
// concurrent polls without holding a mutex during Docker API requests.
func (c *containerCollector) enrich(ctx context.Context, sock string, services []service) {
ids := map[string]*containerState{}
order := []string{}
selected := make(map[string]struct{})
order := make([]string, 0, maxStatContainers)
for i := range services {
id := services[i].ContainerID
if id == "" {
if id == "" || services[i].Container == nil {
continue
}
if _, ok := ids[id]; !ok {
if len(order) >= maxStatContainers {
continue
}
ids[id] = services[i].Container
if _, ok := selected[id]; !ok && len(order) < maxStatContainers {
selected[id] = struct{}{}
order = append(order, id)
}
}
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
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 // immutable until replaced; copies are applied below
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()
// A disconnected client must not replace a complete cache with an
// incomplete snapshot. Docker API timeouts still produce a bounded,
// temporarily cached partial snapshot to avoid repeated heavy polling.
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
}
}
// fetchSnapshot uses a fixed worker pool rather than a goroutine per container.
// Results are indexed so workers never write concurrently into a Go map.
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
limit := make(chan struct{}, 8)
for _, id := range order {
state := ids[id]
if state == nil {
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
}
// Each request owns its service structs. Never hand out pointers to cached
// values: a caller modifying an inventory must not mutate a later response.
func applyContainerSnapshot(services []service, snapshot map[string]containerState) {
for i := range services {
dest := services[i].Container
if dest == 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)
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)
}
}
c.mu.Unlock()
}