0.37.0
This commit is contained in:
1 parent
ad0ff60632
commit
6b59434ffa
60 files changed
+7418
-732
No files matched your search
+37
-3
@@ -4,7 +4,7 @@ The optional `rustproxy-docker-agent` runs **on a Docker host**, not on the Rust
|
||||
|
||||
## Requirements and security
|
||||
|
||||
- Linux amd64/x86_64 with **systemd and Docker Engine** (including a usable `/var/run/docker.sock`). No FreeBSD `pkg` is built for this agent.
|
||||
- Linux amd64/x86_64 with **systemd and Docker Engine or Podman** (a usable `/var/run/docker.sock` or Podman API socket, see [Podman](#podman)). No FreeBSD `pkg` is built for this agent.
|
||||
- Restrict inbound port `9876` to the RustProxy server through a firewall. The example binds `0.0.0.0:9876`; this is reachable from other machines when the firewall permits it.
|
||||
- Access to `docker.sock` grants substantial **host-level privilege**, regardless of the agent's read-only HTTP API. The service uses a dedicated unprivileged identity granted access to the `docker` group.
|
||||
- Self-signed ECDSA P-256 HTTPS is enabled by default; the certificate and private key persist under `/var/lib/rustproxy-docker-agent/` and are **not** regenerated on upgrades/restarts. The key is `0600`.
|
||||
@@ -44,7 +44,16 @@ sudo systemctl status rustproxy-docker-agent
|
||||
sudo journalctl -u rustproxy-docker-agent -n 100 --no-pager
|
||||
```
|
||||
|
||||
Configure **RustProxy → Settings → Docker agents** with the host's `https://host:9876` URL, the full Bearer token, and the printed certificate SHA-256 fingerprint. The RustProxy server pins the certificate when a fingerprint is configured; a replaced certificate requires updating the fingerprint in the panel.
|
||||
The quickest way to connect RustProxy is the **provisioning code**:
|
||||
|
||||
```bash
|
||||
sudo rustproxy-docker-agent provision-code
|
||||
# RPDA1-eyJ2IjoxLCJuYW1lIjoiZG9ja2VyMSIsImVuZHBvaW50Ijoi...
|
||||
```
|
||||
|
||||
Paste it into **RustProxy → Settings → Docker agents → Paste provisioning code**. The panel fills in the agent name and ID, the `https://IP:port` endpoint, the Bearer token and the pinned certificate SHA-256 fingerprint. By default the code is **one-time**: `RPDA1-` + base64url JSON with the endpoint, the certificate fingerprint and an enrollment secret valid for 15 minutes (`--ttl`). RustProxy redeems it at `POST /v1/enroll` over the pinned HTTPS connection and receives the permanent token; the secret is stored hashed in `enrollment.json` next to the TLS key and removed on use. `--static` prints the older reusable code, which **contains the secret token**. The endpoint host is `RUSTPROXY_DOCKER_ADVERTISE_IP`, a concrete listen address or the routed IP; override it with `--endpoint-host docker1.example.net` (or `RUSTPROXY_DOCKER_ENDPOINT_HOST`). `info --show-token` also prints the code.
|
||||
|
||||
Alternatively configure **RustProxy → Settings → Docker agents** manually with the host's `https://host:9876` URL, the full Bearer token, and the printed certificate SHA-256 fingerprint. The RustProxy server pins the certificate when a fingerprint is configured; a replaced certificate requires updating the fingerprint in the panel.
|
||||
|
||||
## CLI commands
|
||||
|
||||
@@ -55,6 +64,8 @@ Configure **RustProxy → Settings → Docker agents** with the host's `https://
|
||||
| `sudo rustproxy-docker-agent info` | Show listening endpoint, hostname, Docker socket, token status/length, TLS certificate paths, SHA-256, issuer, subject, SAN, serial, algorithms and validity |
|
||||
| `sudo rustproxy-docker-agent info --show-token` | Explicitly reveal the full Bearer token in addition to metadata |
|
||||
| `sudo rustproxy-docker-agent show-token` | Print **only** the full secret token (protect stdout) |
|
||||
| `sudo rustproxy-docker-agent provision-code [--ttl 15m] [--endpoint-host HOST]` | Print a one-time `RPDA1-…` code (endpoint, certificate fingerprint, single-use enrollment secret) for the RustProxy panel; HTTPS only |
|
||||
| `sudo rustproxy-docker-agent provision-code --static` | Print a reusable code that contains the Bearer token (**sensitive**) |
|
||||
| `sudo rustproxy-docker-agent rotate-token` | Create a new token without replacing the certificate; **restart the service and update RustProxy** before continuing |
|
||||
| `sudo rustproxy-docker-agent cert-init` | Create a missing certificate/key and print SHA-256; never overwrites existing valid certificate/key |
|
||||
| `sudo rustproxy-docker-agent print-fingerprint` | Print current SHA-256 certificate fingerprint |
|
||||
@@ -93,12 +104,35 @@ Both installation types use the **same** config and certificate paths, but diffe
|
||||
|
||||
Upgrades do not reset credentials or private state. The environment file is installed with `config|noreplace`; local edits remain in place according to package-manager conffile behavior. Removal does not delete `/etc/rustproxy/docker-agent.env` or `/var/lib/rustproxy-docker-agent` (back these up separately).
|
||||
|
||||
## Container labels and state
|
||||
|
||||
With **Publish from container labels** enabled in RustProxy, containers with `rustproxy.enable=true` are published automatically (see `docs/DOCKER_DISCOVERY.md`). The agent forwards only `rustproxy.*` labels. For every published container it also reports state, health check, restart count, CPU and memory (`GET /containers/{id}/json` and `/stats?stream=false&one-shot=true`, at most 64 containers per poll). Labels and container state are sent only to RustProxy 0.37.0+ (`?system=1`); `RUSTPROXY_DOCKER_SYSTEM_INFO=false` also disables container statistics.
|
||||
|
||||
## Podman
|
||||
|
||||
The agent speaks the Docker Engine API, which Podman also serves on its API socket. With `RUSTPROXY_DOCKER_SOCKET=auto` (the default) the agent uses `/var/run/docker.sock` when present, then `/run/podman/podman.sock`, then `$XDG_RUNTIME_DIR/podman/podman.sock` (rootless). Set an explicit path or `unix://` URL to choose one.
|
||||
|
||||
Rootful Podman:
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now podman.socket
|
||||
# Give the service group access to the socket (the installer creates a 'docker' group when Podman is found):
|
||||
sudo systemctl edit podman.socket # [Socket] SocketGroup=docker SocketMode=0660
|
||||
sudo systemctl restart podman.socket rustproxy-docker-agent
|
||||
```
|
||||
|
||||
Containers started by `podman-compose` are grouped by their `com.docker.compose.*` or `io.podman.compose.*` labels exactly like Docker Compose services. Ports published by a Podman **pod** belong to the pod's infra container and are reported under that container name. The agent details in RustProxy show `podman` as the runtime.
|
||||
|
||||
## Host diagnostics
|
||||
|
||||
RustProxy 0.37.0 and newer request `GET /v1/inventory?system=1`; the agent then adds a `system` object with the OS name, kernel, architecture, uptime, load average, CPU count and usage, memory/swap, disk usage of the container data directory, host network totals and rates (container and virtual interfaces excluded), the runtime (`docker`/`podman`) with its version and running/total container and image counts. Older RustProxy versions never receive the block. Values the agent cannot read are omitted. Set `RUSTPROXY_DOCKER_SYSTEM_INFO=false` (or `--no-system-info`) to stop reporting it.
|
||||
|
||||
## 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.
|
||||
|
||||
- `no valid token`: execute `sudo rustproxy-docker-agent init`; check env file permissions and `EnvironmentFile`.
|
||||
- `Docker socket unavailable`: install/start Docker Engine, check `/var/run/docker.sock`, the `docker` group and membership of `rustproxy-docker-agent`.
|
||||
- `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.
|
||||
- `x509` or fingerprint mismatch in RustProxy: compare `sudo rustproxy-docker-agent print-fingerprint` with the pin configured in Settings.
|
||||
- Cannot reach port `9876`: check `RUSTPROXY_DOCKER_AGENT_LISTEN`, listening socket, firewall, and that HTTPS is used.
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import "syscall"
|
||||
|
||||
func diskUsage(path string) (uint64, uint64, bool) {
|
||||
var stat syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &stat); err != nil || stat.Blocks == 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
size := uint64(stat.Bsize)
|
||||
return stat.Blocks * size, stat.Bavail * size, true
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
func diskUsage(string) (uint64, uint64, bool) { return 0, 0, false }
|
||||
@@ -4,6 +4,9 @@ RUSTPROXY_DOCKER_AGENT_TOKEN=replace-with-at-least-24-random-characters
|
||||
RUSTPROXY_DOCKER_AGENT_TLS=true
|
||||
RUSTPROXY_DOCKER_AGENT_CERT_FILE=/var/lib/rustproxy-docker-agent/agent.crt
|
||||
RUSTPROXY_DOCKER_AGENT_KEY_FILE=/var/lib/rustproxy-docker-agent/agent.key
|
||||
RUSTPROXY_DOCKER_SOCKET=auto
|
||||
RUSTPROXY_DOCKER_SYSTEM_INFO=true
|
||||
RUSTPROXY_DOCKER_ENDPOINT_HOST=
|
||||
# Optional preferred address. Other usable host addresses are still auto-detected and reported.
|
||||
RUSTPROXY_DOCKER_ADVERTISE_IP=
|
||||
# Optional external/public address lookup. Set empty to disable.
|
||||
|
||||
+14
-3
@@ -80,11 +80,20 @@ func dnsLabel(value string) string {
|
||||
return out
|
||||
}
|
||||
|
||||
func firstLabel(labels map[string]string, names ...string) string {
|
||||
for _, name := range names {
|
||||
if value := strings.TrimSpace(labels[name]); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func serviceIdentity(c dockerContainer, p dockerPort) (key, technical string) {
|
||||
name := cleanName(c.Names)
|
||||
project := c.Labels["com.docker.compose.project"]
|
||||
composeService := c.Labels["com.docker.compose.service"]
|
||||
replica := c.Labels["com.docker.compose.container-number"]
|
||||
project := firstLabel(c.Labels, "com.docker.compose.project", "io.podman.compose.project")
|
||||
composeService := firstLabel(c.Labels, "com.docker.compose.service", "io.podman.compose.service")
|
||||
replica := firstLabel(c.Labels, "com.docker.compose.container-number", "io.podman.compose.container-number")
|
||||
if project != "" && composeService != "" {
|
||||
if replica == "" {
|
||||
replica = name
|
||||
@@ -121,6 +130,8 @@ func servicesFrom(containers []dockerContainer) []service {
|
||||
item = &service{
|
||||
Key: key, TechnicalName: technical, ContainerID: id, ContainerName: name,
|
||||
Image: c.Image, PrivatePort: p.PrivatePort, Protocol: p.Type,
|
||||
Labels: rustproxyLabels(c.Labels),
|
||||
Container: &containerState{State: strings.ToLower(c.State), Health: healthFromStatus(c.Status)},
|
||||
}
|
||||
byKey[key] = item
|
||||
bindingSeen[key] = make(map[string]struct{})
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxEnrollments = 8
|
||||
|
||||
type enrollment struct {
|
||||
TokenSHA256 string `json:"token_sha256"`
|
||||
Expires int64 `json:"expires"`
|
||||
}
|
||||
|
||||
func enrollmentPath(cfg config) string {
|
||||
return filepath.Join(filepath.Dir(cfg.KeyFile), "enrollment.json")
|
||||
}
|
||||
|
||||
func readEnrollments(path string) ([]enrollment, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var items []enrollment
|
||||
if err := json.Unmarshal(data, &items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func writeEnrollments(path string, items []enrollment) error {
|
||||
data, err := json.Marshal(items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := atomicWrite(path, data, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Geteuid() == 0 {
|
||||
if serviceUser, err := user.Lookup("rustproxy-docker-agent"); err == nil {
|
||||
uid, _ := strconv.Atoi(serviceUser.Uid)
|
||||
gid, _ := strconv.Atoi(serviceUser.Gid)
|
||||
_ = os.Chown(path, uid, gid)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func createEnrollment(cfg config, ttl time.Duration, now time.Time) (string, time.Time, error) {
|
||||
if ttl < time.Minute || ttl > 7*24*time.Hour {
|
||||
return "", time.Time{}, errors.New("enrollment code lifetime must be between 1m and 168h")
|
||||
}
|
||||
token, err := makeToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
path := enrollmentPath(cfg)
|
||||
items, err := readEnrollments(path)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
fresh := items[:0]
|
||||
for _, item := range items {
|
||||
if item.Expires > now.Unix() {
|
||||
fresh = append(fresh, item)
|
||||
}
|
||||
}
|
||||
if len(fresh) >= maxEnrollments {
|
||||
fresh = fresh[len(fresh)-maxEnrollments+1:]
|
||||
}
|
||||
expires := now.Add(ttl)
|
||||
fresh = append(fresh, enrollment{TokenSHA256: hashToken(token), Expires: expires.Unix()})
|
||||
if err := writeEnrollments(path, fresh); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
type enroller struct {
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (e *enroller) redeem(cfg config, presented string, now time.Time) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
path := enrollmentPath(cfg)
|
||||
items, err := readEnrollments(path)
|
||||
if err != nil || presented == "" {
|
||||
return false
|
||||
}
|
||||
want := hashToken(presented)
|
||||
matched := -1
|
||||
kept := make([]enrollment, 0, len(items))
|
||||
for index, item := range items {
|
||||
if item.Expires <= now.Unix() {
|
||||
continue
|
||||
}
|
||||
if matched < 0 && subtle.ConstantTimeCompare([]byte(item.TokenSHA256), []byte(want)) == 1 {
|
||||
matched = index
|
||||
continue
|
||||
}
|
||||
kept = append(kept, item)
|
||||
}
|
||||
if matched < 0 {
|
||||
return false
|
||||
}
|
||||
if err := writeEnrollments(path, kept); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func enrollHandler(cfg config) http.HandlerFunc {
|
||||
state := &enroller{}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if !cfg.TLS || cfg.Fingerprint == "" {
|
||||
http.Error(w, "enrollment requires HTTPS", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||
presented, ok := strings.CutPrefix(auth, "Bearer ")
|
||||
if !ok || !state.redeem(cfg, strings.TrimSpace(presented), time.Now()) {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
http.Error(w, "unknown, expired or used enrollment code", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"token": cfg.Token, "certificate_sha256": cfg.Fingerprint})
|
||||
}
|
||||
}
|
||||
|
||||
type enrollmentPayload struct {
|
||||
Version int `json:"v"`
|
||||
Name string `json:"name"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Enroll string `json:"enroll"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Expires int64 `json:"expires"`
|
||||
Agent string `json:"agent"`
|
||||
}
|
||||
|
||||
func enrollmentCode(cfg config, hostOverride string, ttl time.Duration, now time.Time) (string, time.Time, error) {
|
||||
if !cfg.TLS {
|
||||
return "", time.Time{}, errors.New("one-time codes require HTTPS; use --static with plain HTTP")
|
||||
}
|
||||
if !validToken(cfg.Token) {
|
||||
return "", time.Time{}, errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'")
|
||||
}
|
||||
endpoint, err := provisionEndpoint(cfg, hostOverride)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
fingerprint, err := certificateFingerprint(cfg.CertFile)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("TLS certificate: %w (run 'sudo rustproxy-docker-agent init')", err)
|
||||
}
|
||||
token, expires, err := createEnrollment(cfg, ttl, now)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
raw, err := json.Marshal(enrollmentPayload{Version: 2, Name: cfg.Hostname, Endpoint: endpoint, Enroll: token,
|
||||
Fingerprint: strings.ToLower(strings.ReplaceAll(fingerprint, ":", "")), Expires: expires.Unix(), Agent: version})
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
return provisionPrefix + base64.RawURLEncoding.EncodeToString(raw), expires, nil
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEnrollmentCodeIsOneTimeAndExpires(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config{Listen: "0.0.0.0:9876", Token: strings.Repeat("p", 32), TLS: true, AdvertiseIP: "192.0.2.10", Hostname: "dock1",
|
||||
CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")}
|
||||
fingerprint, _, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Fingerprint = fingerprint
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
code, expires, err := enrollmentCode(cfg, "", 10*time.Minute, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(code, provisionPrefix))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload enrollmentPayload
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Version != 2 || payload.Enroll == "" || strings.Contains(string(raw), cfg.Token) || payload.Expires != expires.Unix() || payload.Fingerprint != fingerprint {
|
||||
t.Fatalf("payload %s", raw)
|
||||
}
|
||||
state := &enroller{}
|
||||
if state.redeem(cfg, "wrong-token-value-0123456789", now) {
|
||||
t.Fatal("wrong token redeemed")
|
||||
}
|
||||
if !state.redeem(cfg, payload.Enroll, now.Add(time.Minute)) {
|
||||
t.Fatal("valid code rejected")
|
||||
}
|
||||
if state.redeem(cfg, payload.Enroll, now.Add(time.Minute)) {
|
||||
t.Fatal("code redeemed twice")
|
||||
}
|
||||
code2, _, err := enrollmentCode(cfg, "", time.Minute, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ = base64.RawURLEncoding.DecodeString(strings.TrimPrefix(code2, provisionPrefix))
|
||||
_ = json.Unmarshal(raw, &payload)
|
||||
if state.redeem(cfg, payload.Enroll, now.Add(2*time.Minute)) {
|
||||
t.Fatal("expired code redeemed")
|
||||
}
|
||||
if _, _, err := enrollmentCode(config{TLS: false, Token: cfg.Token}, "", time.Minute, now); err == nil {
|
||||
t.Fatal("plain HTTP one-time code allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollHandlerReturnsTokenOnlyOnce(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config{Listen: "127.0.0.1:9876", Token: strings.Repeat("q", 32), TLS: true, Hostname: "dock1", Fingerprint: strings.Repeat("a", 64),
|
||||
CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")}
|
||||
secret, _, err := createEnrollment(cfg, time.Minute, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(enrollHandler(cfg))
|
||||
defer srv.Close()
|
||||
post := func() (int, map[string]string) {
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+secret)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
out := map[string]string{}
|
||||
_ = json.NewDecoder(res.Body).Decode(&out)
|
||||
return res.StatusCode, out
|
||||
}
|
||||
if status, body := post(); status != 200 || body["token"] != cfg.Token {
|
||||
t.Fatalf("first %d %v", status, body)
|
||||
}
|
||||
if status, _ := post(); status != http.StatusUnauthorized {
|
||||
t.Fatalf("second %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerLabelsHealthAndStats(t *testing.T) {
|
||||
got := servicesFrom([]dockerContainer{{ID: "abcdef1234567890", Names: []string{"/web"}, Image: "nginx", State: "Running", Status: "Up 3 minutes (unhealthy)",
|
||||
Labels: map[string]string{"rustproxy.enable": "true", "rustproxy.host": "shop", "com.example": "x"},
|
||||
Ports: []dockerPort{{IP: "0.0.0.0", PrivatePort: 80, PublicPort: 8080, Type: "tcp"}}}})
|
||||
if len(got) != 1 || got[0].Labels["rustproxy.host"] != "shop" || got[0].Labels["com.example"] != "" || got[0].Container.Health != "unhealthy" || got[0].Container.State != "running" {
|
||||
t.Fatalf("service %#v %#v", got, got[0].Container)
|
||||
}
|
||||
sock := fakeEngine(t, "docker.sock", map[string]string{
|
||||
"/containers/abcdef123456/json": `{"RestartCount":3,"State":{"Status":"running","StartedAt":"2026-11-13T10:00:00Z","Health":{"Status":"unhealthy"}}}`,
|
||||
"/containers/abcdef123456/stats": `{"cpu_stats":{"cpu_usage":{"total_usage":2000},"system_cpu_usage":20000,"online_cpus":2},"precpu_stats":{"cpu_usage":{"total_usage":1000},"system_cpu_usage":10000},"memory_stats":{"usage":5000,"limit":100000,"stats":{"inactive_file":1000}}}`,
|
||||
})
|
||||
collector := newContainerCollector()
|
||||
collector.enrich(context.Background(), sock, got)
|
||||
if got[0].Container.Health != "unhealthy" {
|
||||
t.Fatalf("health %q", got[0].Container.Health)
|
||||
}
|
||||
c := got[0].Container
|
||||
if c.RestartCount == nil || *c.RestartCount != 3 || c.CPUPercent == nil || *c.CPUPercent != 20 || *c.MemoryBytes != 4000 || *c.MemoryLimitBytes != 100000 {
|
||||
t.Fatalf("container %#v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyInventoryOmitsLabelsAndContainerState(t *testing.T) {
|
||||
sock := fakeEngine(t, "docker.sock", map[string]string{
|
||||
"/containers/json": `[{"Id":"abcdef1234567890","Names":["/web"],"Image":"nginx","State":"running","Status":"Up","Labels":{"rustproxy.enable":"true"},"Ports":[{"IP":"0.0.0.0","PrivatePort":80,"PublicPort":8080,"Type":"tcp"}]}]`,
|
||||
})
|
||||
cfg := config{Token: strings.Repeat("x", 24), DockerSock: sock, Hostname: "docker-a"}
|
||||
srv := httptest.NewServer(handler(cfg))
|
||||
defer srv.Close()
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/inventory", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var raw map[string]any
|
||||
_ = json.NewDecoder(res.Body).Decode(&raw)
|
||||
service := raw["services"].([]any)[0].(map[string]any)
|
||||
if _, ok := service["labels"]; ok {
|
||||
t.Fatal("labels sent to legacy server")
|
||||
}
|
||||
if _, ok := service["container"]; ok {
|
||||
t.Fatal("container state sent to legacy server")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerWithoutHealthcheckIsReportedAsNone(t *testing.T) {
|
||||
got := servicesFrom([]dockerContainer{{ID: "fedcba9876543210", Names: []string{"/plain"}, Image: "nginx", State: "running", Status: "Up 3 minutes",
|
||||
Ports: []dockerPort{{IP: "0.0.0.0", PrivatePort: 80, PublicPort: 8081, Type: "tcp"}}}})
|
||||
if got[0].Container.Health != "" {
|
||||
t.Fatalf("health before inspect %q", got[0].Container.Health)
|
||||
}
|
||||
sock := fakeEngine(t, "docker.sock", map[string]string{
|
||||
"/containers/fedcba987654/json": `{"RestartCount":0,"State":{"Status":"running","StartedAt":"2026-11-13T10:00:00Z"}}`,
|
||||
})
|
||||
newContainerCollector().enrich(context.Background(), sock, got)
|
||||
c := got[0].Container
|
||||
if c.Health != "none" || c.State != "running" || c.CPUPercent != nil || c.MemoryBytes != nil {
|
||||
t.Fatalf("container %#v", c)
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -7,7 +7,15 @@ if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
|
||||
fi
|
||||
command -v go >/dev/null 2>&1 || { echo "Go is required to build the agent." >&2; exit 2; }
|
||||
command -v systemctl >/dev/null 2>&1 || { echo "systemd is required." >&2; exit 2; }
|
||||
getent group docker >/dev/null 2>&1 || { echo "Docker group not found; install Docker first." >&2; exit 2; }
|
||||
if ! getent group docker >/dev/null 2>&1; then
|
||||
if command -v podman >/dev/null 2>&1; then
|
||||
groupadd --system docker
|
||||
echo "Created the 'docker' group for Podman socket access; see README.md (Podman) to grant it access to podman.sock." >&2
|
||||
else
|
||||
echo "Neither Docker (docker group) nor Podman found; install a container runtime first." >&2
|
||||
exit 2
|
||||
fi
|
||||
fi
|
||||
|
||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
TMP=$(mktemp -d)
|
||||
@@ -37,4 +45,4 @@ systemctl --no-pager --full status rustproxy-docker-agent.service || true
|
||||
|
||||
printf '\nAgent endpoint, TLS certificate details and Bearer token (sensitive):\n'
|
||||
/usr/local/bin/rustproxy-docker-agent info --show-token
|
||||
printf '\nInstalled. Configure RustProxy -> Settings -> Docker agents with the HTTPS endpoint, token and SHA-256 fingerprint above.\n'
|
||||
printf '\nInstalled. In RustProxy -> Settings -> Docker agents choose "Paste provisioning code" and paste the RPDA1-... code above\n(or enter the HTTPS endpoint, token and SHA-256 fingerprint manually).\n'
|
||||
+36
-4
@@ -82,7 +82,11 @@ func run(args []string, stdout, stderr io.Writer) error {
|
||||
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", "/var/run/docker.sock"), "Docker Engine unix socket")
|
||||
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)")
|
||||
staticCode := fs.Bool("static", false, "provision-code: print a reusable code with the permanent token instead of a one-time code")
|
||||
codeTTL := fs.Duration("ttl", 15*time.Minute, "provision-code: lifetime of a one-time code")
|
||||
endpointOverride := fs.String("endpoint-host", env("RUSTPROXY_DOCKER_ENDPOINT_HOST", ""), "host or IP placed in the provisioning code (default: advertised/route IP)")
|
||||
fs.StringVar(&cfg.AdvertiseIP, "advertise-ip", env("RUSTPROXY_DOCKER_ADVERTISE_IP", ""), "preferred host IP")
|
||||
fs.StringVar(&cfg.PublicIPURL, "public-ip-url", env("RUSTPROXY_DOCKER_PUBLIC_IP_URL", "https://api.ipify.org"), "public IP lookup URL")
|
||||
fs.StringVar(&cfg.Hostname, "hostname", env("RUSTPROXY_DOCKER_HOSTNAME", hostname), "reported host name")
|
||||
@@ -114,6 +118,7 @@ func run(args []string, stdout, stderr io.Writer) error {
|
||||
if *printFingerprint {
|
||||
command = "print-fingerprint"
|
||||
}
|
||||
cfg.DockerSock = resolveSocket(cfg.DockerSock)
|
||||
cfg.Token = env("RUSTPROXY_DOCKER_AGENT_TOKEN", "")
|
||||
if *tokenOverride != "" {
|
||||
cfg.Token = *tokenOverride
|
||||
@@ -146,7 +151,23 @@ func run(args []string, stdout, stderr io.Writer) error {
|
||||
}
|
||||
fmt.Fprintf(stdout, "Certificate SHA-256: %s\n", fingerprint)
|
||||
}
|
||||
fmt.Fprintf(stdout, "Provisioning complete. Run 'sudo rustproxy-docker-agent info --show-token' to configure RustProxy.\n")
|
||||
fmt.Fprintf(stdout, "Provisioning complete. Run 'sudo rustproxy-docker-agent provision-code' and paste the code into RustProxy -> Settings -> Docker agents.\n")
|
||||
return nil
|
||||
case "provision-code":
|
||||
if *staticCode {
|
||||
code, err := provisionCode(cfg, *endpointOverride)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stdout, code)
|
||||
return nil
|
||||
}
|
||||
code, expires, err := enrollmentCode(cfg, *endpointOverride, *codeTTL, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stdout, code)
|
||||
fmt.Fprintf(stderr, "One-time code, valid until %s. The agent service must be running to redeem it.\n", expires.Local().Format(time.RFC3339))
|
||||
return nil
|
||||
case "rotate-token":
|
||||
if _, _, err := provisionToken(envFile, true); err != nil {
|
||||
@@ -161,7 +182,15 @@ func run(args []string, stdout, stderr io.Writer) error {
|
||||
fmt.Fprintln(stdout, cfg.Token) // Deliberate: an explicit administrative command.
|
||||
return nil
|
||||
case "info":
|
||||
return printAgentInfo(stdout, cfg, envFile, *showToken, *asJSON)
|
||||
if err := printAgentInfo(stdout, cfg, envFile, *showToken, *asJSON); err != nil {
|
||||
return err
|
||||
}
|
||||
if *showToken && !*asJSON {
|
||||
if code, err := provisionCode(cfg, *endpointOverride); err == nil {
|
||||
fmt.Fprintf(stdout, "Provisioning code (sensitive, paste into RustProxy -> Settings -> Docker agents):\n%s\n", code)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case "cert-init":
|
||||
fingerprint, created, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname)
|
||||
if err != nil {
|
||||
@@ -194,6 +223,8 @@ func printUsage(w io.Writer) {
|
||||
fmt.Fprintln(w, " init Generate missing token and certificate, preserve existing secrets")
|
||||
fmt.Fprintln(w, " info [--show-token] Show endpoint, TLS certificate details and token status")
|
||||
fmt.Fprintln(w, " show-token Print the full Bearer token (sensitive)")
|
||||
fmt.Fprintln(w, " provision-code Print a one-time code (endpoint, fingerprint, enrollment secret) for the RustProxy panel")
|
||||
fmt.Fprintln(w, " --ttl 15m sets its lifetime, --static prints a reusable code with the token")
|
||||
fmt.Fprintln(w, " rotate-token Replace the Bearer token (service restart required)")
|
||||
fmt.Fprintln(w, " cert-init Create a missing TLS certificate and key")
|
||||
fmt.Fprintln(w, " print-fingerprint Print current TLS certificate SHA-256 fingerprint")
|
||||
@@ -207,7 +238,7 @@ func serve(cfg config) error {
|
||||
return errors.New("RUSTPROXY_DOCKER_AGENT_TOKEN must be a non-placeholder value with at least 24 characters; run 'sudo rustproxy-docker-agent init'")
|
||||
}
|
||||
if _, err := os.Stat(cfg.DockerSock); err != nil {
|
||||
return fmt.Errorf("Docker socket unavailable: %w", err)
|
||||
return fmt.Errorf("container socket unavailable (Docker or Podman): %w", err)
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(cfg.Listen); err != nil {
|
||||
return fmt.Errorf("invalid listen address: %w", err)
|
||||
@@ -239,6 +270,7 @@ func serve(cfg config) error {
|
||||
scheme = "https"
|
||||
}
|
||||
log.Printf("RustProxy Docker Agent %s listening on %s://%s; Bearer token configured (%d chars, redacted)", version, scheme, cfg.Listen, len(cfg.Token))
|
||||
log.Printf("container API socket: %s", cfg.DockerSock)
|
||||
var err error
|
||||
if cfg.TLS {
|
||||
err = server.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile)
|
||||
|
||||
+25
-19
@@ -1,18 +1,19 @@
|
||||
package main
|
||||
|
||||
var version = "1.0.1" // overridden by the package builder using -ldflags -X main.version
|
||||
var version = "1.1.0" // overridden by the package builder using -ldflags -X main.version
|
||||
|
||||
type config struct {
|
||||
Listen string
|
||||
Token string
|
||||
DockerSock string
|
||||
AdvertiseIP string
|
||||
PublicIPURL string
|
||||
Hostname string
|
||||
TLS bool
|
||||
CertFile string
|
||||
KeyFile string
|
||||
Fingerprint string
|
||||
Listen string
|
||||
Token string
|
||||
DockerSock string
|
||||
AdvertiseIP string
|
||||
PublicIPURL string
|
||||
Hostname string
|
||||
TLS bool
|
||||
CertFile string
|
||||
KeyFile string
|
||||
Fingerprint string
|
||||
DisableSystemInfo bool
|
||||
}
|
||||
|
||||
type dockerPort struct {
|
||||
@@ -28,6 +29,8 @@ type dockerContainer struct {
|
||||
Image string `json:"Image"`
|
||||
Labels map[string]string `json:"Labels"`
|
||||
Ports []dockerPort `json:"Ports"`
|
||||
State string `json:"State"`
|
||||
Status string `json:"Status"`
|
||||
}
|
||||
|
||||
type binding struct {
|
||||
@@ -36,14 +39,16 @@ type binding struct {
|
||||
}
|
||||
|
||||
type service struct {
|
||||
Key string `json:"key"`
|
||||
TechnicalName string `json:"technical_name"`
|
||||
ContainerID string `json:"container_id"`
|
||||
ContainerName string `json:"container_name"`
|
||||
Image string `json:"image"`
|
||||
PrivatePort uint16 `json:"private_port"`
|
||||
Protocol string `json:"protocol"`
|
||||
Bindings []binding `json:"bindings"`
|
||||
Key string `json:"key"`
|
||||
TechnicalName string `json:"technical_name"`
|
||||
ContainerID string `json:"container_id"`
|
||||
ContainerName string `json:"container_name"`
|
||||
Image string `json:"image"`
|
||||
PrivatePort uint16 `json:"private_port"`
|
||||
Protocol string `json:"protocol"`
|
||||
Bindings []binding `json:"bindings"`
|
||||
Labels map[string]string `json:"labels,omitempty"`
|
||||
Container *containerState `json:"container,omitempty"`
|
||||
}
|
||||
|
||||
type hostAddress struct {
|
||||
@@ -62,4 +67,5 @@ type inventory struct {
|
||||
Addresses []hostAddress `json:"addresses"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Services []service `json:"services"`
|
||||
System *systemInfo `json:"system,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const provisionPrefix = "RPDA1-"
|
||||
|
||||
type provisionPayload struct {
|
||||
Version int `json:"v"`
|
||||
Name string `json:"name"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Token string `json:"token"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
Agent string `json:"agent"`
|
||||
}
|
||||
|
||||
func endpointHost(cfg config, override string) string {
|
||||
if host := strings.TrimSpace(override); host != "" {
|
||||
return host
|
||||
}
|
||||
if ip := validIP(cfg.AdvertiseIP); ip != "" {
|
||||
return ip
|
||||
}
|
||||
if host, _, err := net.SplitHostPort(cfg.Listen); err == nil {
|
||||
if ip := net.ParseIP(host); ip != nil && !ip.IsUnspecified() && !ip.IsLoopback() {
|
||||
return ip.String()
|
||||
}
|
||||
if ip := net.ParseIP(host); ip == nil && host != "" && host != "localhost" {
|
||||
return host
|
||||
}
|
||||
}
|
||||
if ip := routeIP(); ip != "" {
|
||||
return ip
|
||||
}
|
||||
return "127.0.0.1"
|
||||
}
|
||||
|
||||
func provisionEndpoint(cfg config, hostOverride string) (string, error) {
|
||||
_, port, err := net.SplitHostPort(cfg.Listen)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid listen address: %w", err)
|
||||
}
|
||||
scheme := "http"
|
||||
if cfg.TLS {
|
||||
scheme = "https"
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(endpointHost(cfg, hostOverride), port)), nil
|
||||
}
|
||||
|
||||
func provisionCode(cfg config, hostOverride string) (string, error) {
|
||||
if !validToken(cfg.Token) {
|
||||
return "", errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'")
|
||||
}
|
||||
endpoint, err := provisionEndpoint(cfg, hostOverride)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
payload := provisionPayload{Version: 1, Name: cfg.Hostname, Endpoint: endpoint, Token: cfg.Token, Agent: version}
|
||||
if cfg.TLS {
|
||||
fingerprint, err := certificateFingerprint(cfg.CertFile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("TLS certificate: %w (run 'sudo rustproxy-docker-agent init')", err)
|
||||
}
|
||||
payload.Fingerprint = strings.ToLower(strings.ReplaceAll(fingerprint, ":", ""))
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return provisionPrefix + base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
func decodeProvisionCode(code string) (provisionPayload, error) {
|
||||
var payload provisionPayload
|
||||
body, ok := strings.CutPrefix(strings.TrimSpace(code), provisionPrefix)
|
||||
if !ok {
|
||||
return payload, errors.New("not a RustProxy agent provisioning code")
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(body)
|
||||
if err != nil {
|
||||
return payload, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return payload, err
|
||||
}
|
||||
if payload.Version != 1 || payload.Endpoint == "" || !validToken(payload.Token) {
|
||||
return payload, errors.New("incomplete provisioning code")
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultDockerSocket = "/var/run/docker.sock"
|
||||
|
||||
func socketCandidates() []string {
|
||||
out := []string{defaultDockerSocket, "/run/docker.sock", "/run/podman/podman.sock", "/var/run/podman/podman.sock"}
|
||||
if runtimeDir := strings.TrimSpace(os.Getenv("XDG_RUNTIME_DIR")); runtimeDir != "" {
|
||||
out = append(out, filepath.Join(runtimeDir, "podman", "podman.sock"), filepath.Join(runtimeDir, "docker.sock"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeSocket(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if strings.HasPrefix(raw, "unix://") {
|
||||
raw = strings.TrimPrefix(raw, "unix://")
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func resolveSocket(configured string) string {
|
||||
configured = normalizeSocket(configured)
|
||||
if configured != "" && !strings.EqualFold(configured, "auto") {
|
||||
return configured
|
||||
}
|
||||
for _, candidate := range socketCandidates() {
|
||||
if info, err := os.Stat(candidate); err == nil && info.Mode()&os.ModeSocket != 0 {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return defaultDockerSocket
|
||||
}
|
||||
|
||||
type engineInfo struct {
|
||||
Containers uint64 `json:"Containers"`
|
||||
ContainersRunning uint64 `json:"ContainersRunning"`
|
||||
Images uint64 `json:"Images"`
|
||||
ServerVersion string `json:"ServerVersion"`
|
||||
OperatingSystem string `json:"OperatingSystem"`
|
||||
KernelVersion string `json:"KernelVersion"`
|
||||
Architecture string `json:"Architecture"`
|
||||
NCPU uint32 `json:"NCPU"`
|
||||
MemTotal uint64 `json:"MemTotal"`
|
||||
DockerRootDir string `json:"DockerRootDir"`
|
||||
}
|
||||
|
||||
type engineVersion struct {
|
||||
Version string `json:"Version"`
|
||||
Components []struct {
|
||||
Name string `json:"Name"`
|
||||
Version string `json:"Version"`
|
||||
} `json:"Components"`
|
||||
}
|
||||
|
||||
func engineGet(ctx context.Context, sock, path string, target any) error {
|
||||
client := &http.Client{Transport: unixRoundTripper{sock: sock}, Timeout: 3 * time.Second}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker"+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("container API %s returned %s", path, resp.Status)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(target)
|
||||
}
|
||||
|
||||
func runtimeName(version engineVersion, sock string) string {
|
||||
for _, component := range version.Components {
|
||||
if strings.Contains(strings.ToLower(component.Name), "podman") {
|
||||
return "podman"
|
||||
}
|
||||
}
|
||||
if strings.Contains(strings.ToLower(sock), "podman") {
|
||||
return "podman"
|
||||
}
|
||||
return "docker"
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
[Unit]
|
||||
Description=RustProxy Docker discovery agent
|
||||
After=docker.service network-online.target
|
||||
After=docker.service podman.socket podman.service network-online.target
|
||||
Wants=network-online.target
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
|
||||
+19
-2
@@ -19,6 +19,9 @@ func tokenOK(got, expected string) bool {
|
||||
func handler(cfg config) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
detector := &ipDetector{}
|
||||
collector := newSystemCollector()
|
||||
stats := newContainerCollector()
|
||||
mux.HandleFunc("/v1/enroll", enrollHandler(cfg))
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
@@ -54,10 +57,24 @@ func handler(cfg config) http.Handler {
|
||||
if cfg.Fingerprint != "" {
|
||||
w.Header().Set("X-RustProxy-Agent-Certificate-SHA256", cfg.Fingerprint)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(inventory{
|
||||
result := inventory{
|
||||
AgentVersion: version, Hostname: cfg.Hostname, PublicIP: primaryIP, PublicIPSource: primarySource, CertificateSHA256: cfg.Fingerprint,
|
||||
Addresses: addresses, ObservedAt: time.Now().UTC().Format(time.RFC3339), Services: servicesFrom(containers),
|
||||
})
|
||||
}
|
||||
extended := r.URL.Query().Get("system") == "1"
|
||||
if extended && !cfg.DisableSystemInfo {
|
||||
result.System = collector.collect(r.Context(), cfg.DockerSock)
|
||||
stats.enrich(r.Context(), cfg.DockerSock, result.Services)
|
||||
}
|
||||
if !extended || cfg.DisableSystemInfo {
|
||||
for i := range result.Services {
|
||||
if !extended {
|
||||
result.Services[i].Labels = nil
|
||||
}
|
||||
result.Services[i].Container = nil
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(result)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"math"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type systemInfo struct {
|
||||
OS string `json:"os,omitempty"`
|
||||
Kernel string `json:"kernel,omitempty"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
Runtime string `json:"runtime,omitempty"`
|
||||
RuntimeVersion string `json:"runtime_version,omitempty"`
|
||||
UptimeSeconds *uint64 `json:"uptime_seconds,omitempty"`
|
||||
Load1 *float64 `json:"load1,omitempty"`
|
||||
Load5 *float64 `json:"load5,omitempty"`
|
||||
Load15 *float64 `json:"load15,omitempty"`
|
||||
CPUCount *uint32 `json:"cpu_count,omitempty"`
|
||||
CPUPercent *float64 `json:"cpu_percent,omitempty"`
|
||||
MemoryTotalBytes *uint64 `json:"memory_total_bytes,omitempty"`
|
||||
MemoryAvailableBytes *uint64 `json:"memory_available_bytes,omitempty"`
|
||||
SwapTotalBytes *uint64 `json:"swap_total_bytes,omitempty"`
|
||||
SwapFreeBytes *uint64 `json:"swap_free_bytes,omitempty"`
|
||||
DiskTotalBytes *uint64 `json:"disk_total_bytes,omitempty"`
|
||||
DiskFreeBytes *uint64 `json:"disk_free_bytes,omitempty"`
|
||||
NetworkRxBytes *uint64 `json:"network_rx_bytes,omitempty"`
|
||||
NetworkTxBytes *uint64 `json:"network_tx_bytes,omitempty"`
|
||||
NetworkRxBytesPerSecond *float64 `json:"network_rx_bytes_per_second,omitempty"`
|
||||
NetworkTxBytesPerSecond *float64 `json:"network_tx_bytes_per_second,omitempty"`
|
||||
ContainersRunning *uint64 `json:"containers_running,omitempty"`
|
||||
ContainersTotal *uint64 `json:"containers_total,omitempty"`
|
||||
Images *uint64 `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
type cpuSample struct{ idle, total uint64 }
|
||||
type netSample struct {
|
||||
rx, tx uint64
|
||||
at time.Time
|
||||
}
|
||||
|
||||
type systemCollector struct {
|
||||
mu sync.Mutex
|
||||
procDir string
|
||||
etcDir string
|
||||
cpu *cpuSample
|
||||
net *netSample
|
||||
}
|
||||
|
||||
func newSystemCollector() *systemCollector {
|
||||
return &systemCollector{procDir: "/proc", etcDir: "/etc"}
|
||||
}
|
||||
|
||||
func ptr[T any](value T) *T { return &value }
|
||||
|
||||
func round(value float64, places int) float64 {
|
||||
scale := math.Pow(10, float64(places))
|
||||
return math.Round(value*scale) / scale
|
||||
}
|
||||
|
||||
func readTrimmed(path string) string {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func osPrettyName(etcDir string) string {
|
||||
for _, path := range []string{etcDir + "/os-release", "/usr/lib/os-release"} {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
scanner := bufio.NewScanner(file)
|
||||
name := ""
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if value, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok {
|
||||
name = strings.Trim(value, `"'`)
|
||||
break
|
||||
}
|
||||
if value, ok := strings.CutPrefix(line, "NAME="); ok && name == "" {
|
||||
name = strings.Trim(value, `"'`)
|
||||
}
|
||||
}
|
||||
file.Close()
|
||||
if name != "" {
|
||||
return name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseLoadavg(raw string) (float64, float64, float64, bool) {
|
||||
fields := strings.Fields(raw)
|
||||
if len(fields) < 3 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
var values [3]float64
|
||||
for i := range values {
|
||||
value, err := strconv.ParseFloat(fields[i], 64)
|
||||
if err != nil || value < 0 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
values[i] = value
|
||||
}
|
||||
return values[0], values[1], values[2], true
|
||||
}
|
||||
|
||||
func parseMeminfo(raw string) map[string]uint64 {
|
||||
out := map[string]uint64{}
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
key, rest, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(rest)
|
||||
if len(fields) == 0 {
|
||||
continue
|
||||
}
|
||||
value, err := strconv.ParseUint(fields[0], 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if len(fields) > 1 && strings.EqualFold(fields[1], "kB") {
|
||||
value *= 1024
|
||||
}
|
||||
out[strings.TrimSpace(key)] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parseCPUStat(raw string) (cpuSample, bool) {
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 5 || fields[0] != "cpu" {
|
||||
continue
|
||||
}
|
||||
var total, idle uint64
|
||||
for index, field := range fields[1:] {
|
||||
value, err := strconv.ParseUint(field, 10, 64)
|
||||
if err != nil {
|
||||
return cpuSample{}, false
|
||||
}
|
||||
if index >= 8 {
|
||||
break
|
||||
}
|
||||
total += value
|
||||
if index == 3 || index == 4 {
|
||||
idle += value
|
||||
}
|
||||
}
|
||||
return cpuSample{idle: idle, total: total}, total > 0
|
||||
}
|
||||
return cpuSample{}, false
|
||||
}
|
||||
|
||||
func skipTrafficInterface(name string) bool {
|
||||
name = strings.ToLower(name)
|
||||
if name == "lo" || skipInterface(name) {
|
||||
return true
|
||||
}
|
||||
for _, prefix := range []string{"cni", "flannel", "cali", "podman", "vxlan", "kube-", "weave", "tunl0"} {
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parseNetDev(raw string) (uint64, uint64, bool) {
|
||||
var rx, tx uint64
|
||||
found := false
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
name, rest, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
name = strings.TrimSpace(name)
|
||||
fields := strings.Fields(rest)
|
||||
if len(fields) < 9 || skipTrafficInterface(name) {
|
||||
continue
|
||||
}
|
||||
in, err1 := strconv.ParseUint(fields[0], 10, 64)
|
||||
out, err2 := strconv.ParseUint(fields[8], 10, 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
continue
|
||||
}
|
||||
rx += in
|
||||
tx += out
|
||||
found = true
|
||||
}
|
||||
return rx, tx, found
|
||||
}
|
||||
|
||||
func (c *systemCollector) cpuPercent() *float64 {
|
||||
sample, ok := parseCPUStat(readTrimmed(c.procDir + "/stat"))
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
previous := c.cpu
|
||||
if previous == nil {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
next, ok := parseCPUStat(readTrimmed(c.procDir + "/stat"))
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
previous, sample = &sample, next
|
||||
}
|
||||
c.cpu = &cpuSample{idle: sample.idle, total: sample.total}
|
||||
if sample.total <= previous.total || sample.idle < previous.idle {
|
||||
return nil
|
||||
}
|
||||
totalDelta := float64(sample.total - previous.total)
|
||||
idleDelta := float64(sample.idle - previous.idle)
|
||||
value := round(math.Max(0, math.Min(100, (1-idleDelta/totalDelta)*100)), 1)
|
||||
return &value
|
||||
}
|
||||
|
||||
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 {
|
||||
info.UptimeSeconds = ptr(uint64(value))
|
||||
}
|
||||
}
|
||||
if l1, l5, l15, ok := parseLoadavg(readTrimmed(c.procDir + "/loadavg")); ok {
|
||||
info.Load1, info.Load5, info.Load15 = ptr(l1), ptr(l5), ptr(l15)
|
||||
}
|
||||
info.CPUCount = ptr(uint32(runtime.NumCPU()))
|
||||
info.CPUPercent = c.cpuPercent()
|
||||
memory := parseMeminfo(readTrimmed(c.procDir + "/meminfo"))
|
||||
if value, ok := memory["MemTotal"]; ok {
|
||||
info.MemoryTotalBytes = ptr(value)
|
||||
}
|
||||
if value, ok := memory["MemAvailable"]; ok {
|
||||
info.MemoryAvailableBytes = ptr(value)
|
||||
}
|
||||
if value, ok := memory["SwapTotal"]; ok {
|
||||
info.SwapTotalBytes = ptr(value)
|
||||
}
|
||||
if value, ok := memory["SwapFree"]; ok {
|
||||
info.SwapFreeBytes = ptr(value)
|
||||
}
|
||||
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 {
|
||||
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 != "" {
|
||||
var engine engineInfo
|
||||
if err := engineGet(ctx, sock, "/info", &engine); err == nil {
|
||||
info.ContainersRunning = ptr(engine.ContainersRunning)
|
||||
info.ContainersTotal = ptr(engine.Containers)
|
||||
info.Images = ptr(engine.Images)
|
||||
if info.OS == "" {
|
||||
info.OS = engine.OperatingSystem
|
||||
}
|
||||
if info.Kernel == "" {
|
||||
info.Kernel = engine.KernelVersion
|
||||
}
|
||||
if engine.DockerRootDir != "" {
|
||||
diskPath = engine.DockerRootDir
|
||||
}
|
||||
info.RuntimeVersion = engine.ServerVersion
|
||||
}
|
||||
var version engineVersion
|
||||
if err := engineGet(ctx, sock, "/version", &version); err == nil {
|
||||
info.Runtime = runtimeName(version, sock)
|
||||
if version.Version != "" {
|
||||
info.RuntimeVersion = version.Version
|
||||
}
|
||||
} else if info.RuntimeVersion != "" {
|
||||
info.Runtime = runtimeName(engineVersion{}, sock)
|
||||
}
|
||||
}
|
||||
if total, free, ok := diskUsage(diskPath); ok {
|
||||
info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free)
|
||||
} else if diskPath != "/" {
|
||||
if total, free, ok := diskUsage("/"); ok {
|
||||
info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free)
|
||||
}
|
||||
}
|
||||
return info
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fakeEngine(t *testing.T, name string, routes map[string]string) string {
|
||||
t.Helper()
|
||||
sock := filepath.Join(t.TempDir(), name)
|
||||
ln, err := net.Listen("unix", sock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, ok := routes[r.URL.Path]
|
||||
if !ok {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(body))
|
||||
})}
|
||||
go srv.Serve(ln)
|
||||
t.Cleanup(func() { _ = srv.Close(); _ = os.Remove(sock) })
|
||||
return sock
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, path, data string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemParsers(t *testing.T) {
|
||||
l1, l5, l15, ok := parseLoadavg("0.52 0.40 0.31 2/345 6789")
|
||||
if !ok || l1 != 0.52 || l5 != 0.40 || l15 != 0.31 {
|
||||
t.Fatalf("loadavg %v %v %v %v", l1, l5, l15, ok)
|
||||
}
|
||||
memory := parseMeminfo("MemTotal: 16384 kB\nMemAvailable: 8192 kB\nSwapTotal: 0 kB\n")
|
||||
if memory["MemTotal"] != 16384*1024 || memory["MemAvailable"] != 8192*1024 {
|
||||
t.Fatalf("meminfo %#v", memory)
|
||||
}
|
||||
sample, ok := parseCPUStat("cpu 100 0 100 700 100 0 0 0 50 0\ncpu0 1 2 3 4\n")
|
||||
if !ok || sample.total != 1000 || sample.idle != 800 {
|
||||
t.Fatalf("cpu %#v", sample)
|
||||
}
|
||||
rx, tx, ok := parseNetDev("Inter-| Receive\n face |bytes\n lo: 100 1 0 0 0 0 0 0 100 1 0 0 0 0 0 0\n eth0: 2000 10 0 0 0 0 0 0 3000 10 0 0 0 0 0 0\ndocker0: 50 1 0 0 0 0 0 0 60 1 0 0 0 0 0 0\nvethab12: 5 1 0 0 0 0 0 0 6 1 0 0 0 0 0 0\n wlan0: 1 1 0 0 0 0 0 0 2 1 0 0 0 0 0 0\n")
|
||||
if !ok || rx != 2001 || tx != 3002 {
|
||||
t.Fatalf("netdev %d %d %v", rx, tx, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemCollectorReadsProcAndPodmanEngine(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeFile(t, root+"/proc/loadavg", "1.00 0.50 0.25 1/100 42\n")
|
||||
writeFile(t, root+"/proc/uptime", "3600.55 100.00\n")
|
||||
writeFile(t, root+"/proc/meminfo", "MemTotal: 2048 kB\nMemAvailable: 1024 kB\nSwapTotal: 512 kB\nSwapFree: 256 kB\n")
|
||||
writeFile(t, root+"/proc/stat", "cpu 10 0 10 80 0 0 0 0 0 0\n")
|
||||
writeFile(t, root+"/proc/net/dev", "eth0: 1000 1 0 0 0 0 0 0 2000 1 0 0 0 0 0 0\n")
|
||||
writeFile(t, root+"/proc/sys/kernel/osrelease", "6.12.0-test\n")
|
||||
writeFile(t, root+"/etc/os-release", "NAME=Test\nPRETTY_NAME=\"Test Linux 1\"\n")
|
||||
sock := fakeEngine(t, "podman.sock", map[string]string{
|
||||
"/info": `{"Containers":5,"ContainersRunning":3,"Images":7,"ServerVersion":"5.4.0"}`,
|
||||
"/version": `{"Version":"5.4.0","Components":[{"Name":"Podman Engine","Version":"5.4.0"}]}`,
|
||||
})
|
||||
collector := &systemCollector{procDir: root + "/proc", etcDir: root + "/etc"}
|
||||
info := collector.collect(context.Background(), sock)
|
||||
if info.OS != "Test Linux 1" || info.Kernel != "6.12.0-test" || info.Runtime != "podman" || info.RuntimeVersion != "5.4.0" {
|
||||
t.Fatalf("identity %#v", info)
|
||||
}
|
||||
if *info.UptimeSeconds != 3600 || *info.Load1 != 1 || *info.MemoryTotalBytes != 2048*1024 || *info.ContainersRunning != 3 || *info.ContainersTotal != 5 || *info.Images != 7 {
|
||||
t.Fatalf("values %#v", info)
|
||||
}
|
||||
if info.NetworkRxBytesPerSecond != nil {
|
||||
t.Fatal("first sample must not report a rate")
|
||||
}
|
||||
collector.net.at = time.Now().Add(-2 * time.Second)
|
||||
writeFile(t, root+"/proc/net/dev", "eth0: 3000 1 0 0 0 0 0 0 2000 1 0 0 0 0 0 0\n")
|
||||
info = collector.collect(context.Background(), "")
|
||||
if info.NetworkRxBytesPerSecond == nil || *info.NetworkRxBytesPerSecond < 900 || *info.NetworkRxBytesPerSecond > 1100 || *info.NetworkTxBytesPerSecond != 0 {
|
||||
t.Fatalf("rates %#v", info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInventorySystemInfoIsOptIn(t *testing.T) {
|
||||
sock := fakeEngine(t, "docker.sock", map[string]string{
|
||||
"/containers/json": `[]`,
|
||||
"/info": `{"Containers":1,"ContainersRunning":1,"Images":1,"ServerVersion":"27.0.1"}`,
|
||||
"/version": `{"Version":"27.0.1","Components":[{"Name":"Engine","Version":"27.0.1"}]}`,
|
||||
})
|
||||
cfg := config{Token: strings.Repeat("x", 24), DockerSock: sock, Hostname: "docker-a"}
|
||||
srv := httptest.NewServer(handler(cfg))
|
||||
defer srv.Close()
|
||||
get := func(path string) map[string]any {
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+path, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+cfg.Token)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var out map[string]any
|
||||
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if _, ok := get("/v1/inventory")["system"]; ok {
|
||||
t.Fatal("legacy request must not receive system info")
|
||||
}
|
||||
system, ok := get("/v1/inventory?system=1")["system"].(map[string]any)
|
||||
if !ok || system["runtime"] != "docker" || system["containers_running"] != float64(1) {
|
||||
t.Fatalf("system %#v", system)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSocketAndPodmanComposeLabels(t *testing.T) {
|
||||
if got := resolveSocket("unix:///run/custom.sock"); got != "/run/custom.sock" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
runtimeDir := t.TempDir()
|
||||
t.Setenv("XDG_RUNTIME_DIR", runtimeDir)
|
||||
if err := os.MkdirAll(filepath.Join(runtimeDir, "podman"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("unix", filepath.Join(runtimeDir, "podman", "podman.sock"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
if _, err := os.Stat(defaultDockerSocket); err != nil {
|
||||
if got := resolveSocket("auto"); !strings.HasSuffix(got, "podman/podman.sock") {
|
||||
t.Fatalf("auto socket %s", got)
|
||||
}
|
||||
}
|
||||
c := dockerContainer{Names: []string{"/web_1"}, Labels: map[string]string{"io.podman.compose.project": "shop", "io.podman.compose.service": "web"}}
|
||||
key, _ := serviceIdentity(c, dockerPort{PrivatePort: 80, Type: "tcp"})
|
||||
if key != "compose:shop/web/web_1:80/tcp" {
|
||||
t.Fatal(key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvisionCodeRoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config{Listen: "0.0.0.0:9876", Token: strings.Repeat("a", 32), TLS: true, AdvertiseIP: "192.0.2.10", Hostname: "dock1",
|
||||
CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")}
|
||||
fingerprint, _, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := provisionCode(cfg, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(code, provisionPrefix) || strings.ContainsAny(code, "+/= \n") {
|
||||
t.Fatalf("code %q", code)
|
||||
}
|
||||
payload, err := decodeProvisionCode(code)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Endpoint != "https://192.0.2.10:9876" || payload.Token != cfg.Token || payload.Fingerprint != fingerprint || payload.Name != "dock1" {
|
||||
t.Fatalf("payload %#v", payload)
|
||||
}
|
||||
if code, _ := provisionCode(cfg, "2001:db8::5"); !strings.HasPrefix(code, provisionPrefix) {
|
||||
t.Fatal("ipv6 override")
|
||||
} else if payload, _ := decodeProvisionCode(code); payload.Endpoint != "https://[2001:db8::5]:9876" {
|
||||
t.Fatalf("ipv6 endpoint %s", payload.Endpoint)
|
||||
}
|
||||
cfg.Token = "short"
|
||||
if _, err := provisionCode(cfg, ""); err == nil {
|
||||
t.Fatal("short token accepted")
|
||||
}
|
||||
if _, err := decodeProvisionCode("garbage"); err == nil {
|
||||
t.Fatal("garbage accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user