0.38.6_agent_hotfix
This commit is contained in:
1 parent
1239ff524d
commit
d4a604970e
14 files changed
+478
-162
No files matched your search
@@ -131,8 +131,10 @@ RustProxy 0.37.0 and newer request `GET /v1/inventory?system=1`; the agent then
|
||||
|
||||
## API and troubleshooting
|
||||
|
||||
The API is `GET /v1/inventory` with `Authorization: Bearer <token>`; `GET /healthz` has no inventory and requires no token. Both use HTTPS by default. Plain HTTP is possible with `RUSTPROXY_DOCKER_AGENT_TLS=false` but exposes credentials in transit; use it only in a secured network and never across the public Internet.
|
||||
The API is `GET /v1/inventory` with `Authorization: Bearer <token>`; `GET /healthz` has no inventory and requires no token. Both use HTTPS by default. Up to **two authenticated inventory requests** are processed at once; additional polls immediately receive HTTP **503** and `Retry-After: 1`. Clients should retry with backoff. `POST /v1/enroll` allows a burst of six attempts, refilling at one attempt per second, across all clients. Excess attempts receive HTTP **429** and `Retry-After: 1`; one-time codes are not consumed on 429. Use firewall allowlists to prevent untrusted clients from exhausting the shared rate limit. Plain HTTP is possible with `RUSTPROXY_DOCKER_AGENT_TLS=false` but exposes credentials in transit; use it only in a secured network and never across the public Internet.
|
||||
|
||||
- **Agent process diagnostics:** authenticated `GET /v1/diagnostics` (same Bearer token) returns JSON with `rss_bytes` (resident memory), `go_heap_alloc_bytes`, `goroutines` and `open_fds` (RSS and FD counts use Linux `/proc` and are omitted where unavailable). This is an on-demand process snapshot, not Prometheus metrics and not stored over time. `GET /healthz` intentionally contains no sensitive diagnostics. Sample repeatedly to determine whether resident memory or descriptor counts grow after the cache warms up.
|
||||
- **Busy inventory or provisioning:** HTTP 503 on `/v1/inventory` or HTTP 429 on `/v1/enroll` means the bounded work/rate limits are active; honor `Retry-After: 1` before retrying. The systemd agent accepts request headers for up to 3 seconds, request reads for up to 5 seconds and response writes for up to 12 seconds.
|
||||
- `no valid token`: execute `sudo rustproxy-docker-agent init`; check env file permissions and `EnvironmentFile`.
|
||||
- `container socket unavailable`: install/start Docker Engine (or `podman.socket`), check `/var/run/docker.sock` / `/run/podman/podman.sock`, the `docker` group and membership of `rustproxy-docker-agent`.
|
||||
- `TLS certificate/key`: inspect ownership of `/var/lib/rustproxy-docker-agent/`, mode `0600` on the private key, and both certificate/key paths. Refuse partially missing pairs rather than overwriting them.
|
||||
|
||||
+184
-58
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type agentHealthMetrics struct {
|
||||
RSSBytes *uint64 `json:"rss_bytes,omitempty"`
|
||||
HeapAllocBytes uint64 `json:"go_heap_alloc_bytes"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
OpenFDs *int `json:"open_fds,omitempty"`
|
||||
}
|
||||
|
||||
// agentDiagnostics is an authenticated, on-demand snapshot. No background
|
||||
// goroutine, accumulating history, or extra public health endpoint is needed.
|
||||
func agentDiagnostics() agentHealthMetrics {
|
||||
var memory runtime.MemStats
|
||||
runtime.ReadMemStats(&memory)
|
||||
result := agentHealthMetrics{HeapAllocBytes: memory.HeapAlloc, Goroutines: runtime.NumGoroutine()}
|
||||
// Linux agents expose RSS and descriptor counts in /proc. On unsupported
|
||||
// platforms omit these fields instead of incorrectly calling heap RSS.
|
||||
if fields := strings.Fields(readTrimmed("/proc/self/statm")); len(fields) >= 2 {
|
||||
if resident, err := strconv.ParseUint(fields[1], 10, 64); err == nil {
|
||||
rss := resident * uint64(os.Getpagesize())
|
||||
result.RSSBytes = &rss
|
||||
}
|
||||
}
|
||||
if entries, err := os.ReadDir("/proc/self/fd"); err == nil {
|
||||
count := len(entries)
|
||||
result.OpenFDs = &count
|
||||
}
|
||||
return result
|
||||
}
|
||||
+24
-4
@@ -10,23 +10,43 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type unixRoundTripper struct{ sock string }
|
||||
|
||||
func (u unixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// Each Docker socket gets one shared transport. Creating one per RoundTrip
|
||||
// leaks idle connections and their goroutines when keep-alive is enabled.
|
||||
// The configured socket is stable during the lifetime of the agent.
|
||||
var unixTransports sync.Map // map[string]*http.Transport
|
||||
|
||||
func unixTransport(sock string) *http.Transport {
|
||||
if existing, ok := unixTransports.Load(sock); ok {
|
||||
return existing.(*http.Transport)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
var d net.Dialer
|
||||
return d.DialContext(ctx, "unix", u.sock)
|
||||
return d.DialContext(ctx, "unix", sock)
|
||||
},
|
||||
DisableKeepAlives: false,
|
||||
MaxIdleConns: 16,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
MaxConnsPerHost: 32,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
}
|
||||
actual, loaded := unixTransports.LoadOrStore(sock, transport)
|
||||
if loaded {
|
||||
transport.CloseIdleConnections()
|
||||
}
|
||||
return actual.(*http.Transport)
|
||||
}
|
||||
|
||||
func (u unixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
clone := req.Clone(req.Context())
|
||||
clone.URL.Scheme = "http"
|
||||
clone.URL.Host = "docker"
|
||||
return transport.RoundTrip(clone)
|
||||
return unixTransport(u.sock).RoundTrip(clone)
|
||||
}
|
||||
|
||||
func dockerContainers(ctx context.Context, sock string) ([]dockerContainer, error) {
|
||||
|
||||
+41
-1
@@ -18,7 +18,11 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxEnrollments = 8
|
||||
const (
|
||||
maxEnrollments = 8
|
||||
enrollBurst = 6
|
||||
enrollRefillPerSecond = 1.0
|
||||
)
|
||||
|
||||
type enrollment struct {
|
||||
TokenSHA256 string `json:"token_sha256"`
|
||||
@@ -131,8 +135,38 @@ func (e *enroller) redeem(cfg config, presented string, now time.Time) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// The limiter is deliberately global: it has constant memory usage even if
|
||||
// callers rotate source IPs. Enrollment is a rare administrative operation.
|
||||
type enrollLimiter struct {
|
||||
mu sync.Mutex
|
||||
tokens float64
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (l *enrollLimiter) allow(now time.Time) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.last.IsZero() {
|
||||
l.tokens = enrollBurst
|
||||
l.last = now
|
||||
}
|
||||
if elapsed := now.Sub(l.last).Seconds(); elapsed > 0 {
|
||||
l.tokens += elapsed * enrollRefillPerSecond
|
||||
if l.tokens > enrollBurst {
|
||||
l.tokens = enrollBurst
|
||||
}
|
||||
l.last = now
|
||||
}
|
||||
if l.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
l.tokens--
|
||||
return true
|
||||
}
|
||||
|
||||
func enrollHandler(cfg config) http.HandlerFunc {
|
||||
state := &enroller{}
|
||||
limiter := &enrollLimiter{}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
@@ -142,6 +176,12 @@ func enrollHandler(cfg config) http.HandlerFunc {
|
||||
http.Error(w, "enrollment requires HTTPS", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if !limiter.allow(time.Now()) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
http.Error(w, "too many enrollment attempts", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
presented, ok := strings.CutPrefix(auth, "Bearer ")
|
||||
if !ok || !state.redeem(cfg, strings.TrimSpace(presented), time.Now()) {
|
||||
|
||||
@@ -256,7 +256,7 @@ func serve(cfg config) error {
|
||||
log.Printf("TLS certificate: subject=%s valid_until=%s SHA-256=%s", details.Subject, details.NotAfter, details.SHA256)
|
||||
}
|
||||
}
|
||||
server := &http.Server{Addr: cfg.Listen, Handler: handler(cfg), ReadHeaderTimeout: 3 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||
server := &http.Server{Addr: cfg.Listen, Handler: handler(cfg), ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 12 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
go func() {
|
||||
|
||||
+37
-10
@@ -268,23 +268,50 @@ type ipDetector struct {
|
||||
mu sync.Mutex
|
||||
publicIP string
|
||||
expires time.Time
|
||||
fetching chan struct{}
|
||||
}
|
||||
|
||||
func (d *ipDetector) public(ctx context.Context, rawURL string) string {
|
||||
if rawURL == "" {
|
||||
return ""
|
||||
}
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if time.Now().Before(d.expires) {
|
||||
return d.publicIP
|
||||
for {
|
||||
d.mu.Lock()
|
||||
if time.Now().Before(d.expires) {
|
||||
ip := d.publicIP
|
||||
d.mu.Unlock()
|
||||
return ip
|
||||
}
|
||||
if d.fetching != nil {
|
||||
done := d.fetching
|
||||
d.mu.Unlock()
|
||||
select {
|
||||
case <-done:
|
||||
continue
|
||||
case <-ctx.Done():
|
||||
return ""
|
||||
}
|
||||
}
|
||||
done := make(chan struct{})
|
||||
d.fetching = done
|
||||
d.mu.Unlock()
|
||||
|
||||
// Do not hold the cache mutex across the external HTTP lookup.
|
||||
ip := publicIPFromURL(ctx, rawURL)
|
||||
d.mu.Lock()
|
||||
if ctx.Err() == nil {
|
||||
d.publicIP = ip
|
||||
ttl := 5 * time.Minute
|
||||
if ip == "" {
|
||||
ttl = 30 * time.Second
|
||||
}
|
||||
d.expires = time.Now().Add(ttl)
|
||||
}
|
||||
d.fetching = nil
|
||||
close(done)
|
||||
d.mu.Unlock()
|
||||
return ip
|
||||
}
|
||||
d.publicIP = publicIPFromURL(ctx, rawURL)
|
||||
d.expires = time.Now().Add(5 * time.Minute)
|
||||
if d.publicIP == "" {
|
||||
d.expires = time.Now().Add(30 * time.Second)
|
||||
}
|
||||
return d.publicIP
|
||||
}
|
||||
|
||||
func mergeHostAddress(out *[]hostAddress, index map[string]int, candidate hostAddress) {
|
||||
|
||||
+35
-5
@@ -16,12 +16,36 @@ func tokenOK(got, expected string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1
|
||||
}
|
||||
|
||||
func requireToken(w http.ResponseWriter, r *http.Request, expected string) bool {
|
||||
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
const prefix = "Bearer "
|
||||
if strings.HasPrefix(auth, prefix) && tokenOK(strings.TrimSpace(strings.TrimPrefix(auth, prefix)), expected) {
|
||||
return true
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
|
||||
func handler(cfg config) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
detector := &ipDetector{}
|
||||
collector := newSystemCollector()
|
||||
stats := newContainerCollector()
|
||||
inventorySlots := make(chan struct{}, 2)
|
||||
mux.HandleFunc("/v1/enroll", enrollHandler(cfg))
|
||||
mux.HandleFunc("/v1/diagnostics", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if !requireToken(w, r, cfg.Token) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(agentDiagnostics())
|
||||
})
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
@@ -39,11 +63,17 @@ func handler(cfg config) http.Handler {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(auth, prefix) || !tokenOK(strings.TrimSpace(strings.TrimPrefix(auth, prefix)), cfg.Token) {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
if !requireToken(w, r, cfg.Token) {
|
||||
return
|
||||
}
|
||||
// No waiter queue: excess authenticated polls fail fast, so a
|
||||
// stalled Docker socket cannot accumulate unbounded request work.
|
||||
select {
|
||||
case inventorySlots <- struct{}{}:
|
||||
defer func() { <-inventorySlots }()
|
||||
default:
|
||||
w.Header().Set("Retry-After", "1")
|
||||
http.Error(w, "inventory busy", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
containers, err := dockerContainers(r.Context(), cfg.DockerSock)
|
||||
|
||||
+24
-5
@@ -205,16 +205,31 @@ func (c *systemCollector) cpuPercent() *float64 {
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
previous := c.cpu
|
||||
c.mu.Unlock()
|
||||
if previous == nil {
|
||||
// Initial sample takes time, but no collector mutex is held.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
next, ok := parseCPUStat(readTrimmed(c.procDir + "/stat"))
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
previous, sample = &sample, next
|
||||
initial := sample
|
||||
sample = next
|
||||
previous = &initial
|
||||
}
|
||||
c.mu.Lock()
|
||||
if c.cpu != nil {
|
||||
previous = c.cpu
|
||||
}
|
||||
// Concurrent collection must never roll the baseline backwards.
|
||||
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
|
||||
}
|
||||
@@ -225,8 +240,6 @@ func (c *systemCollector) cpuPercent() *float64 {
|
||||
}
|
||||
|
||||
func (c *systemCollector) collect(ctx context.Context, sock string) *systemInfo {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
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 {
|
||||
@@ -254,13 +267,19 @@ func (c *systemCollector) collect(ctx context.Context, sock string) *systemInfo
|
||||
if rx, tx, ok := parseNetDev(readTrimmed(c.procDir + "/net/dev")); ok {
|
||||
now := time.Now()
|
||||
info.NetworkRxBytes, info.NetworkTxBytes = ptr(rx), ptr(tx)
|
||||
if previous := c.net; previous != nil && rx >= previous.rx && tx >= previous.tx {
|
||||
c.mu.Lock()
|
||||
previous := c.net
|
||||
// Do not let an older concurrent poll overwrite a newer sample.
|
||||
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))
|
||||
}
|
||||
}
|
||||
c.net = &netSample{rx: rx, tx: tx, at: now}
|
||||
}
|
||||
diskPath := "/"
|
||||
if sock != "" {
|
||||
|
||||
Reference in new issue
Block a user