#!/usr/bin/env python3 """Отчёт по контейнерам Docker или Podman.""" from __future__ import annotations import argparse import json import shutil import subprocess from dataclasses import asdict, dataclass from pathlib import Path @dataclass class Container: name: str image: str state: str health: str restarts: int restart_policy: str ports: str problems: str def run(argv: list[str]) -> subprocess.CompletedProcess[str]: return subprocess.run(argv, capture_output=True, text=True, check=False) def detect_runtime(preferred: str | None) -> str | None: for name in ([preferred] if preferred else ["docker", "podman"]): if name and shutil.which(name): return name return None def inspect_containers(runtime: str) -> list[dict]: ids = run([runtime, "ps", "-aq"]).stdout.split() if not ids: return [] result = run([runtime, "inspect", *ids]) if result.returncode != 0: return [] try: data = json.loads(result.stdout) except json.JSONDecodeError: return [] return data if isinstance(data, list) else [] def parse(item: dict) -> Container: name = str(item.get("Name", "")).lstrip("/") or "?" config = item.get("Config") or {} state = item.get("State") or {} host = item.get("HostConfig") or {} restart_policy = (host.get("RestartPolicy") or {}).get("Name", "-") health = ((state.get("Health") or {}).get("Status")) or "-" status = str(state.get("Status", "unknown")) exit_code = int(state.get("ExitCode") or 0) oom = bool(state.get("OOMKilled")) restarts = int(item.get("RestartCount") or 0) ports_data = (item.get("NetworkSettings") or {}).get("Ports") or {} ports = [] for container_port, bindings in ports_data.items(): if not bindings: ports.append(str(container_port)) continue for binding in bindings: host_ip = binding.get("HostIp") or "0.0.0.0" host_port = binding.get("HostPort") or "?" ports.append(f"{host_ip}:{host_port}->{container_port}") notes = [] if health == "unhealthy": notes.append("unhealthy") if status in {"restarting", "dead", "paused"}: notes.append(status) if status == "exited" and exit_code != 0: notes.append(f"exit={exit_code}") if oom: notes.append("oom") if restarts > 5: notes.append(f"restarts={restarts}") return Container( name=name, image=str(config.get("Image", "-")), state=status, health=health, restarts=restarts, restart_policy=str(restart_policy), ports=",".join(sorted(ports)) or "-", problems=", ".join(notes), ) def main() -> int: parser = argparse.ArgumentParser(description="Отчёт по контейнерам") parser.add_argument("--runtime", choices=("docker", "podman"), help="Явно выбрать runtime") parser.add_argument("--only-problems", action="store_true", help="Только проблемные контейнеры") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() runtime = detect_runtime(args.runtime) if runtime is None: print("Не найден docker или podman.") return 2 info_result = run([runtime, "info", "--format", "{{json .}}"]) info = {} if info_result.returncode != 0: print(f"{runtime} info: {info_result.stderr.strip()[:300]}") return 2 try: info = json.loads(info_result.stdout) except json.JSONDecodeError: info = {} items = inspect_containers(runtime) containers = [parse(item) for item in items] if args.only_problems: containers = [item for item in containers if item.problems] print(f"Runtime: {runtime}") if info: print(f"Сервер: {info.get('ServerVersion', info.get('version', '-'))}, контейнеров: {info.get('Containers', len(items))}, запущено: {info.get('ContainersRunning', '-')}") print(f"{'ИМЯ':<28} {'СОСТОЯНИЕ':<12} {'HEALTH':<10} {'RESTARTS':>8} {'ПОЛИТИКА':<12} ПОРТЫ") print("-" * 120) for item in containers: print(f"{item.name:<28} {item.state:<12} {item.health:<10} {item.restarts:>8} {item.restart_policy:<12} {item.ports}") if item.problems: print(f"{'':<28} [WARN] {item.problems}") problems = sum(1 for item in containers if item.problems) print(f"\nКонтейнеров: {len(containers)}, проблемных: {problems}") if args.json: args.json.write_text( json.dumps({"runtime": runtime, "info": info, "containers": [asdict(item) for item in containers]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"JSON сохранён: {args.json}") return 1 if problems else 0 if __name__ == "__main__": raise SystemExit(main())