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
@@ -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 fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
|
||||
from . import stats
|
||||
from . import containers, stats
|
||||
from .security import require_api_key
|
||||
|
||||
|
||||
@@ -25,3 +25,12 @@ def health():
|
||||
@app.get("/api/stats", dependencies=[Depends(require_api_key)])
|
||||
def get_stats():
|
||||
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