This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 17:36:53 +01:00
1 parent 5b6d4a7903
commit 4d1087e357
160 files changed
+2407 -1933

No files matched your search

+1 -11
View File
@@ -124,9 +124,6 @@ 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) {
selected := make(map[string]struct{})
order := make([]string, 0, maxStatContainers)
@@ -166,7 +163,7 @@ func (c *containerCollector) enrich(ctx context.Context, sock string, services [
}
}
if hit {
snapshot := c.cache // immutable until replaced; copies are applied below
snapshot := c.cache
c.mu.Unlock()
applyContainerSnapshot(services, snapshot)
return
@@ -187,9 +184,6 @@ func (c *containerCollector) enrich(ctx context.Context, sock string, services [
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)
@@ -207,8 +201,6 @@ func (c *containerCollector) enrich(ctx context.Context, sock string, services [
}
}
// 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()
@@ -276,8 +268,6 @@ func (c *containerCollector) inspectContainer(ctx context.Context, sock, id stri
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
+1 -11
View File
@@ -18,8 +18,6 @@ import (
const defaultEnvFile = "/etc/rustproxy/docker-agent.env"
// requestedEnvFile is handled before other flags so CLI calls can load the same
// configuration as systemd. Both --env-file=X and --env-file X are supported.
func requestedEnvFile(args []string) (string, error) {
path := defaultEnvFile
for i := 0; i < len(args); i++ {
@@ -39,7 +37,6 @@ func requestedEnvFile(args []string) (string, error) {
return path, nil
}
// Read a restricted, plain KEY=VALUE EnvironmentFile. Never execute it as shell.
func readEnvironmentFile(path string) (map[string]string, error) {
result := make(map[string]string)
f, err := os.Open(path)
@@ -91,7 +88,6 @@ func makeToken() (string, error) {
}
func provisionToken(path string, rotate bool) (string, bool, error) {
// Reject symlinks, devices and directories before opening anything.
stat, err := os.Lstat(path)
var raw []byte
if err == nil {
@@ -130,7 +126,6 @@ func provisionToken(path string, rotate bool) (string, bool, error) {
"RUSTPROXY_DOCKER_AGENT_LISTEN=0.0.0.0:9876\n" +
"RUSTPROXY_DOCKER_AGENT_TLS=true\n")
}
// Preserve non-secret settings/comments, remove duplicate token assignments.
lines := strings.Split(strings.TrimRight(string(raw), "\n"), "\n")
filtered := make([]string, 0, len(lines)+1)
for _, line := range lines {
@@ -148,8 +143,6 @@ func provisionToken(path string, rotate bool) (string, bool, error) {
return token, true, nil
}
// Generated keys must be readable by the unprivileged systemd service even
// when 'init' is invoked via sudo during DEB/RPM or manual installation.
func setServiceCertificateOwnership(certFile, keyFile string) error {
if os.Geteuid() != 0 {
return nil
@@ -157,7 +150,7 @@ func setServiceCertificateOwnership(certFile, keyFile string) error {
serviceUser, err := user.Lookup("rustproxy-docker-agent")
if err != nil {
return nil
} // Standalone CLI; warn operators to run init as service user.
}
uid, err := strconv.Atoi(serviceUser.Uid)
if err != nil {
return err
@@ -172,7 +165,6 @@ func setServiceCertificateOwnership(certFile, keyFile string) error {
if err := os.Chown(certFile, uid, gid); err != nil {
return err
}
// Parent generated via atomicWrite must also be traversable by the service.
dir := filepath.Dir(keyFile)
if dir == filepath.Dir(certFile) {
if err := os.Chown(dir, uid, gid); err != nil {
@@ -274,5 +266,3 @@ func printAgentInfo(w io.Writer, cfg config, envFile string, showToken, asJSON b
}
return nil
}
// Compile-time reference: readCertificate returns an x509 parsed certificate.
-4
View File
@@ -14,14 +14,10 @@ type agentHealthMetrics struct {
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())
+1 -4
View File
@@ -16,10 +16,7 @@ import (
type unixRoundTripper struct{ sock string }
// 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
var unixTransports sync.Map
func unixTransport(sock string) *http.Transport {
if existing, ok := unixTransports.Load(sock); ok {
-2
View File
@@ -135,8 +135,6 @@ 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
-1
View File
@@ -36,7 +36,6 @@ install -d -o rustproxy-docker-agent -g docker -m 0750 /var/lib/rustproxy-docker
if [[ ! -f /etc/rustproxy/docker-agent.env ]]; then
install -m 0600 docker-agent.env.example /etc/rustproxy/docker-agent.env
fi
# Provisioning is delegated to the Go CLI, which keeps existing credentials.
/usr/local/bin/rustproxy-docker-agent init
install -m 0644 rustproxy-docker-agent.service /etc/systemd/system/rustproxy-docker-agent.service
systemctl daemon-reload
+2 -6
View File
@@ -39,7 +39,7 @@ func main() {
}
func run(args []string, stdout, stderr io.Writer) error {
command := "serve" // Preserve the legacy invocation used by existing systemd units.
command := "serve"
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
command, args = args[0], args[1:]
}
@@ -58,8 +58,6 @@ func run(args []string, stdout, stderr io.Writer) error {
}
fileValues, err := readEnvironmentFile(envFile)
if err != nil {
// PID 1 already loaded EnvironmentFile for the unprivileged daemon;
// access to the on-disk secret is deliberately restricted to root.
if !errors.Is(err, os.ErrPermission) || os.Getenv("RUSTPROXY_DOCKER_AGENT_TOKEN") == "" {
return err
}
@@ -80,7 +78,6 @@ func run(args []string, stdout, stderr io.Writer) error {
fs.SetOutput(stderr)
fs.StringVar(&envFile, "env-file", envFile, "systemd EnvironmentFile path")
fs.StringVar(&cfg.Listen, "listen", env("RUSTPROXY_DOCKER_AGENT_LISTEN", "127.0.0.1:9876"), "listen address")
// NEVER supply a token as a flag default: `--help` would leak it into output.
tokenOverride := fs.String("token", "", "Bearer token override (prefer the protected environment file)")
fs.StringVar(&cfg.DockerSock, "docker-socket", env("RUSTPROXY_DOCKER_SOCKET", env("RUSTPROXY_CONTAINER_SOCKET", "auto")), "Docker Engine or Podman API unix socket ('auto' detects Docker, then Podman)")
fs.BoolVar(&cfg.DisableSystemInfo, "no-system-info", !envBoolValue(env("RUSTPROXY_DOCKER_SYSTEM_INFO", "true"), true), "do not report host diagnostics (load, memory, network, uptime)")
@@ -133,7 +130,6 @@ func run(args []string, stdout, stderr io.Writer) error {
if created {
fmt.Fprintf(stdout, "Created a random Bearer token in %s\n", envFile)
}
// Reload because a new token was written after the initial environment read.
fresh, err := readEnvironmentFile(envFile)
if err != nil {
return err
@@ -179,7 +175,7 @@ func run(args []string, stdout, stderr io.Writer) error {
if !validToken(cfg.Token) {
return errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'")
}
fmt.Fprintln(stdout, cfg.Token) // Deliberate: an explicit administrative command.
fmt.Fprintln(stdout, cfg.Token)
return nil
case "info":
if err := printAgentInfo(stdout, cfg, envFile, *showToken, *asJSON); err != nil {
+1 -1
View File
@@ -226,7 +226,7 @@ func TestTLSInventoryReportsServingCertificateFingerprint(t *testing.T) {
go func() { _ = server.ServeTLS(listener, certFile, keyFile) }()
t.Cleanup(func() { _ = server.Close() })
transport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} // test-only: verify the endpoint is actually TLS; RustProxy pins it in production.
transport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
client := &http.Client{Transport: transport, Timeout: time.Second}
req, _ := http.NewRequest(http.MethodGet, "https://"+listener.Addr().String()+"/v1/inventory", nil)
req.Header.Set("Authorization", "Bearer "+cfg.Token)
+1 -1
View File
@@ -1,6 +1,6 @@
package main
var version = "0.38.7" // overridden by the package builder using -ldflags -X main.version
var version = "0.38.7"
type config struct {
Listen string
-1
View File
@@ -296,7 +296,6 @@ func (d *ipDetector) public(ctx context.Context, rawURL string) string {
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 {
-2
View File
@@ -66,8 +66,6 @@ func handler(cfg config) http.Handler {
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 }()
-3
View File
@@ -209,7 +209,6 @@ func (c *systemCollector) cpuPercent() *float64 {
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 {
@@ -223,7 +222,6 @@ func (c *systemCollector) cpuPercent() *float64 {
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
@@ -269,7 +267,6 @@ func (c *systemCollector) collect(ctx context.Context, sock string) *systemInfo
info.NetworkRxBytes, info.NetworkTxBytes = ptr(rx), ptr(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}
}