feat: opt-in /api/containers listing running Docker containers and their uptime
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0c9dd7c9b3
commit
10aaa13aeb
3 files changed
+148
-2
No files matched your search
@@ -54,6 +54,26 @@ If `/host/proc` isn't mounted at all, `/api/stats` still returns data, just
|
|||||||
for the container's own near-empty cgroup instead of the host —
|
for the container's own near-empty cgroup instead of the host —
|
||||||
`network.hostNamespace` in the response tells you which one you're getting.
|
`network.hostNamespace` in the response tells you which one you're getting.
|
||||||
|
|
||||||
|
## Containers (optional)
|
||||||
|
|
||||||
|
`GET /api/containers` lists the running Docker containers (name, image, health,
|
||||||
|
restart count, uptime) for the dashboard's Containers block. It is **off by
|
||||||
|
default**, because reaching the Docker API is a much bigger privilege than the
|
||||||
|
read-only host mounts above. Pick one:
|
||||||
|
|
||||||
|
- **Socket proxy (recommended).** Run a read-only proxy such as
|
||||||
|
`tecnativa/docker-socket-proxy` with only `CONTAINERS=1` enabled, and point the
|
||||||
|
agent at it with `DOCKER_HOST=tcp://socket-proxy:2375`. The proxy is the only
|
||||||
|
thing that touches the socket, and it refuses everything but container reads.
|
||||||
|
- **Mount the socket.** `-v /var/run/docker.sock:/var/run/docker.sock:ro` plus
|
||||||
|
`--group-add <the host's docker group id>` (the agent runs as a non-root
|
||||||
|
user). Note that even a `:ro` socket mount gives full control of Docker to
|
||||||
|
anything that can talk to it, so anyone who gets the agent's API key and a bug
|
||||||
|
to exploit is effectively root on the host.
|
||||||
|
|
||||||
|
Without either, the endpoint answers 503 and everything else works as before.
|
||||||
|
Only names, images, state and start times are ever returned.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
Every endpoint except `/api/health` requires an `X-API-Key` header.
|
Every endpoint except `/api/health` requires an `X-API-Key` header.
|
||||||
@@ -62,6 +82,7 @@ Every endpoint except `/api/health` requires an `X-API-Key` header.
|
|||||||
|--------|------|---------|
|
|--------|------|---------|
|
||||||
| GET | `/api/health` | Liveness check, no auth — used by the Docker `HEALTHCHECK` |
|
| GET | `/api/health` | Liveness check, no auth — used by the Docker `HEALTHCHECK` |
|
||||||
| GET | `/api/stats` | A snapshot of CPU/memory/disk/network for the host |
|
| GET | `/api/stats` | A snapshot of CPU/memory/disk/network for the host |
|
||||||
|
| GET | `/api/containers` | Running Docker containers and their uptime (opt-in, see above) |
|
||||||
|
|
||||||
`GET /api/stats` response shape:
|
`GET /api/stats` response shape:
|
||||||
|
|
||||||
@@ -110,4 +131,5 @@ curl -H "X-API-Key: $API_KEY" http://localhost:9090/api/stats
|
|||||||
|----------|---------|---------|
|
|----------|---------|---------|
|
||||||
| `API_KEY` | auto-generated on first run | The key clients must send as `X-API-Key` |
|
| `API_KEY` | auto-generated on first run | The key clients must send as `X-API-Key` |
|
||||||
| `AGENT_DATA_DIR` | `/data` | Where the auto-generated key is persisted |
|
| `AGENT_DATA_DIR` | `/data` | Where the auto-generated key is persisted |
|
||||||
|
| `DOCKER_HOST` | `unix:///var/run/docker.sock` | Where to reach the Docker API for `/api/containers` (`tcp://host:port` for a socket proxy) |
|
||||||
| `AGENT_HOSTNAME` | host's `/etc/hostname`, or the container's | Overrides the reported `hostname` |
|
| `AGENT_HOSTNAME` | host's `/etc/hostname`, or the container's | Overrides the reported `hostname` |
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""Running Docker containers and how long they've been up.
|
||||||
|
|
||||||
|
Needs access to the Docker API, which is opt-in (see README.md): either the
|
||||||
|
Docker socket mounted into the agent, or — safer — a read-only socket proxy
|
||||||
|
whose address is given in DOCKER_HOST. Only GET requests are ever made, and
|
||||||
|
only container names, images, state and start times are reported — never
|
||||||
|
environment variables, mounts or command lines.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
DOCKER_HOST = os.environ.get("DOCKER_HOST", "").strip() or "unix:///var/run/docker.sock"
|
||||||
|
CACHE_SECONDS = 5.0
|
||||||
|
TIMEOUT = 5.0
|
||||||
|
|
||||||
|
_cache: tuple[float, list[dict]] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DockerUnavailable(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class _UnixConnection(http.client.HTTPConnection):
|
||||||
|
def __init__(self, path: str):
|
||||||
|
super().__init__("localhost", timeout=TIMEOUT)
|
||||||
|
self._path = path
|
||||||
|
|
||||||
|
def connect(self) -> None:
|
||||||
|
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
sock.settimeout(TIMEOUT)
|
||||||
|
sock.connect(self._path)
|
||||||
|
self.sock = sock
|
||||||
|
|
||||||
|
|
||||||
|
def _connection() -> http.client.HTTPConnection:
|
||||||
|
parsed = urlparse(DOCKER_HOST)
|
||||||
|
if parsed.scheme == "unix":
|
||||||
|
return _UnixConnection(parsed.path)
|
||||||
|
if parsed.scheme in ("tcp", "http"):
|
||||||
|
return http.client.HTTPConnection(parsed.hostname or "localhost", parsed.port or 2375, timeout=TIMEOUT)
|
||||||
|
raise DockerUnavailable(f"Unsupported DOCKER_HOST: {DOCKER_HOST}")
|
||||||
|
|
||||||
|
|
||||||
|
def _get(conn: http.client.HTTPConnection, path: str):
|
||||||
|
conn.request("GET", path, headers={"Host": "docker"})
|
||||||
|
resp = conn.getresponse()
|
||||||
|
body = resp.read()
|
||||||
|
if resp.status == 404:
|
||||||
|
return None # the container vanished between listing and inspecting
|
||||||
|
if resp.status != 200:
|
||||||
|
raise DockerUnavailable(f"Docker API returned HTTP {resp.status}")
|
||||||
|
return json.loads(body)
|
||||||
|
|
||||||
|
|
||||||
|
def _started_epoch(value: str | None) -> float | None:
|
||||||
|
# Docker reports nanosecond precision ("2026-01-01T00:00:00.123456789Z"); trim to microseconds.
|
||||||
|
if not value or value.startswith("0001"):
|
||||||
|
return None
|
||||||
|
text = value.rstrip("Z")
|
||||||
|
if "." in text:
|
||||||
|
head, frac = text.split(".", 1)
|
||||||
|
text = f"{head}.{frac[:6]}"
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(text).replace(tzinfo=timezone.utc).timestamp()
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _collect() -> list[dict]:
|
||||||
|
try:
|
||||||
|
conn = _connection()
|
||||||
|
try:
|
||||||
|
listed = _get(conn, "/containers/json") or []
|
||||||
|
now = time.time()
|
||||||
|
rows = []
|
||||||
|
for item in listed:
|
||||||
|
info = _get(conn, f"/containers/{item['Id']}/json")
|
||||||
|
if not info:
|
||||||
|
continue
|
||||||
|
state = info.get("State") or {}
|
||||||
|
if not state.get("Running"):
|
||||||
|
continue
|
||||||
|
started = _started_epoch(state.get("StartedAt"))
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"id": str(info.get("Id", ""))[:12],
|
||||||
|
"name": str(info.get("Name") or "").lstrip("/"),
|
||||||
|
"image": str((info.get("Config") or {}).get("Image") or item.get("Image") or ""),
|
||||||
|
"health": (state.get("Health") or {}).get("Status"),
|
||||||
|
"restartCount": int(info.get("RestartCount") or 0),
|
||||||
|
"uptimeSeconds": max(0, int(now - started)) if started else None,
|
||||||
|
"paused": bool(state.get("Paused")),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
except (OSError, ValueError, http.client.HTTPException) as exc:
|
||||||
|
raise DockerUnavailable("Docker isn't reachable from the agent") from exc
|
||||||
|
return sorted(rows, key=lambda r: r["name"].lower())
|
||||||
|
|
||||||
|
|
||||||
|
def collect() -> list[dict]:
|
||||||
|
"""Cached for a few seconds so several dashboards polling don't multiply the inspect calls."""
|
||||||
|
global _cache
|
||||||
|
if _cache and time.monotonic() - _cache[0] < CACHE_SECONDS:
|
||||||
|
return _cache[1]
|
||||||
|
rows = _collect()
|
||||||
|
_cache = (time.monotonic(), rows)
|
||||||
|
return rows
|
||||||
+11
-2
@@ -1,8 +1,8 @@
|
|||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI
|
from fastapi import Depends, FastAPI, HTTPException
|
||||||
|
|
||||||
from . import stats
|
from . import containers, stats
|
||||||
from .security import require_api_key
|
from .security import require_api_key
|
||||||
|
|
||||||
|
|
||||||
@@ -25,3 +25,12 @@ def health():
|
|||||||
@app.get("/api/stats", dependencies=[Depends(require_api_key)])
|
@app.get("/api/stats", dependencies=[Depends(require_api_key)])
|
||||||
def get_stats():
|
def get_stats():
|
||||||
return stats.collect()
|
return stats.collect()
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/containers", dependencies=[Depends(require_api_key)])
|
||||||
|
def get_containers():
|
||||||
|
# Opt-in: only works when the agent can reach the Docker API (see README.md).
|
||||||
|
try:
|
||||||
|
return {"containers": containers.collect()}
|
||||||
|
except containers.DockerUnavailable as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=str(exc))
|
||||||
Reference in new issue
Block a user