"""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