#!/usr/bin/env python3 """Persistent rootful Podman lifecycle on the Linux host. stop/up retain a container. down checkpoints before removal. recreate probes a replacement before removing the stopped original. Use run for shared lifecycle locking; unmanaged direct Podman exec commands cannot participate in that lock. """ from __future__ import annotations import argparse from contextlib import contextmanager from datetime import datetime, timezone import hashlib import json import os from pathlib import Path, PurePosixPath import re import subprocess import sys import uuid REPO = Path(__file__).resolve().parents[1] DEFAULT_IMAGE = "localhost/prod2u-6400-dev:locked" PROTECTED = {"/", "/usr", "/usr/local", "/opt", "/root", "/etc", "/var/lib/dpkg"} def encode(value): return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() def validate_spec(spec): if spec["user"] not in ("0", "0:0", "root") or not spec["privileged"] or spec["network"] != "host": raise ValueError("container requires existing root, privileged mode and host networking") if spec["entrypoint"] not in (["/bin/sleep"], ["sleep"]) or spec["command"] != ["infinity"]: raise ValueError("lifecycle management requires the sleep-infinity development container") targets = set() for mount in spec["mounts"]: source, target = Path(mount["source"]), PurePosixPath(mount["target"]) if not source.is_absolute() or not target.is_absolute() or ".." in target.parts: raise ValueError("mount paths must be absolute and normalized") if str(target) in PROTECTED or str(target) in targets: raise ValueError("unsafe or duplicate mount target: " + str(target)) targets.add(str(target)) def create_args(name, image, spec): validate_spec(spec) args = ["podman", "create", "--name", name, "--pull=never", "--user", spec["user"], "--userns=host", "--privileged", "--network=host", "--security-opt", "label=disable", "--security-opt", "seccomp=unconfined"] for key in ("pid", "ipc", "uts"): if spec.get(key): args.append("--" + key + "=" + spec[key]) for mount in spec["mounts"]: args += ["--volume", mount["source"] + ":" + mount["target"] + (":rw" if mount["rw"] else ":ro")] for key, value in sorted(spec["env"].items()): args += ["--env", key + "=" + value] return args + ["--workdir", spec["workdir"], "--entrypoint", json.dumps(spec["entrypoint"]), image, *spec["command"]] class Controller: def __init__(self, name, base, state_dir=None, workspace=None, image=DEFAULT_IMAGE): if not re.fullmatch(r"prod2u-[A-Za-z0-9_.-]+", name): raise ValueError("name must be in the prod2u- task namespace") self.name, self.base, self.image = name, Path(base).resolve(), image self.workspace = Path(workspace).resolve() if workspace else None self.state_dir = Path(state_dir or os.environ.get("XDG_STATE_HOME", str(self.base / "state"))) / "dev-container" self.state_dir.mkdir(parents=True, exist_ok=True) self.state_path = self.state_dir / (name + ".json") def call(self, args, check=True): return subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=check) def inspect(self, name=None): name = name or self.name found = self.call(["podman", "container", "exists", name], check=False) if found.returncode == 1: return None if found.returncode: raise RuntimeError(found.stderr.strip() or "podman lookup failed") return json.loads(self.call(["podman", "inspect", name]).stdout)[0] def load(self): return json.loads(self.state_path.read_text()) if self.state_path.exists() else {} def save(self, image, spec, **extra): state = {"schema": "prod2u-container-state-v1", "name": self.name, "image_id": image, "spec": spec, "environment_id": hashlib.sha256(encode({"image": image, "spec": spec})).hexdigest()[:16], "updated_utc": datetime.now(timezone.utc).isoformat(), **extra} temporary = self.state_path.with_suffix(".tmp") temporary.write_text(json.dumps(state, indent=2) + "\n") temporary.replace(self.state_path) return state @contextmanager def lock(self, shared=False, heavy=False): import fcntl self.base.joinpath("cache").mkdir(parents=True, exist_ok=True) paths = ([self.base / "cache/heavy.lock"] if heavy else []) + [self.state_dir / (self.name + ".lock")] streams = [] try: for i, path in enumerate(paths): stream = path.open("a+") fcntl.flock(stream, fcntl.LOCK_SH if shared and i == len(paths)-1 else fcntl.LOCK_EX) streams.append(stream) yield finally: for stream in reversed(streams): fcntl.flock(stream, fcntl.LOCK_UN) stream.close() def spec(self, info): config, host = info["Config"], info["HostConfig"] if host.get("AutoRemove"): raise ValueError("auto-remove containers are not supported") if any(m["Type"] != "bind" for m in info["Mounts"]): raise ValueError("only explicit bind mounts are supported") result = {"user": config.get("User", "0:0"), "privileged": host["Privileged"], "network": host["NetworkMode"], "pid": host.get("PidMode", ""), "ipc": host.get("IpcMode", ""), "uts": host.get("UTSMode", ""), "entrypoint": config["Entrypoint"], "command": config["Cmd"], "workdir": config["WorkingDir"], "env": dict(item.split("=", 1) for item in config.get("Env", []) if "=" in item), "mounts": [{"source": m["Source"], "target": m["Destination"], "rw": m["RW"]} for m in info["Mounts"]]} validate_spec(result) result["mounts"].sort(key=lambda m: m["target"]) return result def desired(self, original=None): result = json.loads(json.dumps(original)) if original else { "user": "0:0", "privileged": True, "network": "host", "pid": "host", "ipc": "host", "uts": "host", "entrypoint": ["/bin/sleep"], "command": ["infinity"], "workdir": "/workspace", "env": {}, "mounts": [{"source": str(self.base), "target": "/data/prod2u", "rw": True}, {"source": str(self.workspace or REPO), "target": "/workspace", "rw": True}]} for key, value in {"XDG_CACHE_HOME": "/data/prod2u/cache", "XDG_STATE_HOME": "/data/prod2u/state", "XDG_RUNTIME_DIR": "/run/prod2u", "TMPDIR": "/data/prod2u/cache/tmp"}.items(): result["env"].setdefault(key, value) if self.workspace: result["mounts"] = [m for m in result["mounts"] if m["target"] != "/workspace"] result["mounts"].append({"source": str(self.workspace), "target": "/workspace", "rw": True}) for mount in result["mounts"]: if not Path(mount["source"]).is_dir(): raise ValueError("bind source directory is missing: " + mount["source"]) validate_spec(result) result["mounts"].sort(key=lambda m: m["target"]) return result def idle(self, info): if info.get("ExecIDs"): raise RuntimeError("container has active exec sessions; wait before lifecycle changes") if info["State"].get("Paused"): raise RuntimeError("container is paused; resolve that state before lifecycle changes") if not info["State"]["Running"]: return group = info["State"].get("CgroupPath") if not group or ".." in PurePosixPath(group).parts: raise RuntimeError("cannot verify container cgroup") root = Path("/sys/fs/cgroup") / group.lstrip("/") if not root.is_dir(): raise RuntimeError("container cgroup disappeared; recheck state") pids = set() for path in root.rglob("cgroup.procs"): pids.update(int(x) for x in path.read_text().split()) other = pids - {int(info["State"]["Pid"])} if other: raise RuntimeError("container has background work (host PIDs): " + ",".join(map(str, sorted(other)))) def probe(self, name): self.call(["podman", "exec", name, "python3", "-c", "import os;from pathlib import Path;assert os.getuid()==0;" "[Path(os.environ[k]).mkdir(parents=True,exist_ok=True) for k in ('XDG_CACHE_HOME','XDG_STATE_HOME','XDG_RUNTIME_DIR','TMPDIR')]"]) def up_unlocked(self): info = self.inspect() if info: actual = self.spec(info) if self.workspace and not any(m["target"] == "/workspace" and m["source"] == str(self.workspace) for m in actual["mounts"]): raise RuntimeError("workspace mount differs; use --workspace PATH recreate before running there") if not info["State"]["Running"]: self.call(["podman", "start", info["Id"]]) return self.inspect() saved = self.load() image = saved.get("image_id") or json.loads(self.call(["podman", "image", "inspect", self.image]).stdout)[0]["Id"] spec = self.desired(saved.get("spec")) self.call(create_args(self.name, image, spec)) self.call(["podman", "start", self.name]) self.probe(self.name) self.save(image, spec, restored_from=saved.get("checkpoint_tag")) return self.inspect() def checkpoint_unlocked(self, restart): info = self.inspect() if not info: raise RuntimeError("container does not exist") spec = self.desired(self.spec(info)) self.idle(info) running = info["State"]["Running"] if running: self.call(["podman", "stop", "--time", "30", info["Id"]]) tag = "localhost/" + self.name + "-checkpoint:" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:12] try: self.call(["podman", "commit", "--pause=false", info["Id"], tag]) image = json.loads(self.call(["podman", "image", "inspect", tag]).stdout)[0]["Id"] state = self.save(image, spec, checkpoint_tag=tag, checkpoint_container_id=info["Id"]) except Exception: if running: self.call(["podman", "start", info["Id"]]) raise if restart and running: self.call(["podman", "start", info["Id"]]) return info, state def recreate_unlocked(self): if not self.inspect(): return self.up_unlocked() old, saved = self.checkpoint_unlocked(restart=False) candidate = self.name + "-candidate-" + uuid.uuid4().hex[:8] backup = self.name + "-previous-" + uuid.uuid4().hex[:8] candidate_id = None renamed = False try: candidate_id = self.call(create_args(candidate, saved["image_id"], saved["spec"])).stdout.strip() self.call(["podman", "start", candidate_id]) self.probe(candidate_id) new = self.inspect(candidate_id) if self.spec(new) != saved["spec"]: raise RuntimeError("replacement settings differ from checkpoint specification") self.call(["podman", "rename", old["Id"], backup]) renamed = True self.call(["podman", "rename", candidate_id, self.name]) except Exception: if candidate_id and self.inspect(candidate_id): self.call(["podman", "rm", "--force", candidate_id]) if renamed: self.call(["podman", "rename", old["Id"], self.name]) if old["State"]["Running"]: self.call(["podman", "start", old["Id"]]) raise self.call(["podman", "rm", old["Id"]]) return self.inspect() def summary(self, info): saved = self.load() return {"name": self.name, "container_id": info["Id"] if info else None, "state": info["State"]["Status"] if info else "absent", "image_id": info["Image"] if info else None, "state_file": str(self.state_path), "environment_id": hashlib.sha256(encode({"image": info["Image"], "spec": self.spec(info)})).hexdigest()[:16] if info else None, "checkpoint_environment_id": saved.get("environment_id"), "checkpoint_image_id": saved.get("image_id")} def action(self, action): if action == "status": return self.summary(self.inspect()) with self.lock(heavy=action in ("stop", "down", "checkpoint", "recreate", "build")): if action == "up": info = self.up_unlocked() elif action == "stop": info = self.inspect() if info: self.spec(info) self.idle(info) if info["State"]["Running"]: self.call(["podman", "stop", "--time", "30", info["Id"]]) info = self.inspect() elif action == "checkpoint": self.checkpoint_unlocked(restart=True) info = self.inspect() elif action == "down": if self.inspect(): old, _ = self.checkpoint_unlocked(restart=False) self.call(["podman", "rm", old["Id"]]) info = None elif action == "recreate": info = self.recreate_unlocked() elif action == "build": result = subprocess.run(["bash", str(REPO / "containers/6400-dev/build-image.sh")]) if result.returncode: raise RuntimeError("base image build failed") info = self.inspect() else: info = self.inspect() return self.summary(info) def execute(self, command, workdir=None, terminal=False): with self.lock(): self.up_unlocked() with self.lock(shared=True): info = self.inspect() if not info or not info["State"]["Running"]: raise RuntimeError("container changed during startup; retry before executing the command") args = ["podman", "exec"] + (["-it"] if terminal else []) if workdir: args += ["--workdir", workdir] return subprocess.run(args + [self.name, *command]).returncode DOCTOR = '''import json,os,shutil,subprocess,tempfile from pathlib import Path assert os.getuid()==0 for name in ('git','python3','iverilog','vvp','verilator','yosys','sby','go'): assert shutil.which(name),name import pytest,yaml,cocotb with tempfile.TemporaryDirectory(prefix='prod2u-doctor-') as folder: p=Path(folder);(p/'test.v').write_text('module test; reg clk=0; always #1 clk=~clk; integer n=0; always @(posedge clk) n<=n+1; initial begin #8; if(n!=4) $fatal(1,"counter"); $display("DOCTOR_RTL_PASS"); $finish; end endmodule') subprocess.run(['iverilog','-g2012','-s','test','-o',str(p/'test.vvp'),str(p/'test.v')],check=True) result=subprocess.check_output(['vvp',str(p/'test.vvp')],text=True);assert 'DOCTOR_RTL_PASS' in result subprocess.run(['verilator','--binary','--timing','-Wno-fatal','-j','2','--top-module','test','--Mdir',str(p/'obj'),str(p/'test.v')],check=True) result=subprocess.check_output([str(p/'obj/Vtest')],text=True);assert 'DOCTOR_RTL_PASS' in result print(json.dumps({'uid':os.getuid(),'icarus_smoke':'PASS','verilator_compile_and_run':'PASS','hardware':'NOT_RUN'})) ''' def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--name", default=os.environ.get("PROD2U_CONTAINER", "prod2u-dev")) parser.add_argument("--base", type=Path, default=os.environ.get("PRODU2_TOOLCHAIN_BASE", "/data/prod2u")) parser.add_argument("--state-dir", type=Path) parser.add_argument("--workspace", type=Path, help="bind this exact source directory to /workspace on creation/recreate") parser.add_argument("--image", default=DEFAULT_IMAGE, help="initial image only; checkpoints use immutable IDs") sub = parser.add_subparsers(dest="action", required=True) for name in ("up", "stop", "down", "checkpoint", "recreate", "status", "doctor", "build"): sub.add_parser(name) for name in ("run", "shell"): entry = sub.add_parser(name) entry.add_argument("--workdir") entry.add_argument("argv", nargs=argparse.REMAINDER) args = parser.parse_args(argv) if sys.platform != "linux" or os.geteuid() != 0 or Path("/run/.containerenv").exists(): parser.error("execute on the authorized Linux Podman host as existing root") try: manager = Controller(args.name, args.base, args.state_dir, args.workspace, args.image) if args.action in ("run", "shell", "doctor"): command = ["python3", "-c", DOCTOR] if args.action == "doctor" else args.argv if command and command[0] == "--": command = command[1:] if not command and args.action == "run": parser.error("run requires a command") return manager.execute(command or ["bash"], getattr(args, "workdir", None), args.action == "shell" and sys.stdin.isatty()) print(json.dumps(manager.action(args.action), indent=2)) return 0 except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error: print(str(error), file=sys.stderr) if isinstance(error, subprocess.CalledProcessError) and error.stderr: print(error.stderr.strip(), file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())