dev_container.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #!/usr/bin/env python3
  2. """Persistent rootful Podman lifecycle on the Linux host.
  3. stop/up retain a container. down checkpoints before removal. recreate probes a
  4. replacement before removing the stopped original. Use run for shared lifecycle
  5. locking; unmanaged direct Podman exec commands cannot participate in that lock.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. from contextlib import contextmanager
  10. from datetime import datetime, timezone
  11. import hashlib
  12. import json
  13. import os
  14. from pathlib import Path, PurePosixPath
  15. import re
  16. import subprocess
  17. import sys
  18. import uuid
  19. REPO = Path(__file__).resolve().parents[1]
  20. DEFAULT_IMAGE = "localhost/prod2u-6400-dev:locked"
  21. PROTECTED = {"/", "/usr", "/usr/local", "/opt", "/root", "/etc", "/var/lib/dpkg"}
  22. def encode(value):
  23. return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
  24. def validate_spec(spec):
  25. if spec["user"] not in ("0", "0:0", "root") or not spec["privileged"] or spec["network"] != "host":
  26. raise ValueError("container requires existing root, privileged mode and host networking")
  27. if spec["entrypoint"] not in (["/bin/sleep"], ["sleep"]) or spec["command"] != ["infinity"]:
  28. raise ValueError("lifecycle management requires the sleep-infinity development container")
  29. targets = set()
  30. for mount in spec["mounts"]:
  31. source, target = Path(mount["source"]), PurePosixPath(mount["target"])
  32. if not source.is_absolute() or not target.is_absolute() or ".." in target.parts:
  33. raise ValueError("mount paths must be absolute and normalized")
  34. if str(target) in PROTECTED or str(target) in targets:
  35. raise ValueError("unsafe or duplicate mount target: " + str(target))
  36. targets.add(str(target))
  37. def create_args(name, image, spec):
  38. validate_spec(spec)
  39. args = ["podman", "create", "--name", name, "--pull=never", "--user", spec["user"],
  40. "--userns=host", "--privileged", "--network=host",
  41. "--security-opt", "label=disable", "--security-opt", "seccomp=unconfined"]
  42. for key in ("pid", "ipc", "uts"):
  43. if spec.get(key):
  44. args.append("--" + key + "=" + spec[key])
  45. for mount in spec["mounts"]:
  46. args += ["--volume", mount["source"] + ":" + mount["target"] + (":rw" if mount["rw"] else ":ro")]
  47. for key, value in sorted(spec["env"].items()):
  48. args += ["--env", key + "=" + value]
  49. return args + ["--workdir", spec["workdir"], "--entrypoint", json.dumps(spec["entrypoint"]), image, *spec["command"]]
  50. class Controller:
  51. def __init__(self, name, base, state_dir=None, workspace=None, image=DEFAULT_IMAGE):
  52. if not re.fullmatch(r"prod2u-[A-Za-z0-9_.-]+", name):
  53. raise ValueError("name must be in the prod2u- task namespace")
  54. self.name, self.base, self.image = name, Path(base).resolve(), image
  55. self.workspace = Path(workspace).resolve() if workspace else None
  56. self.state_dir = Path(state_dir or os.environ.get("XDG_STATE_HOME", str(self.base / "state"))) / "dev-container"
  57. self.state_dir.mkdir(parents=True, exist_ok=True)
  58. self.state_path = self.state_dir / (name + ".json")
  59. def call(self, args, check=True):
  60. return subprocess.run(args, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=check)
  61. def inspect(self, name=None):
  62. name = name or self.name
  63. found = self.call(["podman", "container", "exists", name], check=False)
  64. if found.returncode == 1:
  65. return None
  66. if found.returncode:
  67. raise RuntimeError(found.stderr.strip() or "podman lookup failed")
  68. return json.loads(self.call(["podman", "inspect", name]).stdout)[0]
  69. def load(self):
  70. return json.loads(self.state_path.read_text()) if self.state_path.exists() else {}
  71. def save(self, image, spec, **extra):
  72. state = {"schema": "prod2u-container-state-v1", "name": self.name, "image_id": image, "spec": spec,
  73. "environment_id": hashlib.sha256(encode({"image": image, "spec": spec})).hexdigest()[:16],
  74. "updated_utc": datetime.now(timezone.utc).isoformat(), **extra}
  75. temporary = self.state_path.with_suffix(".tmp")
  76. temporary.write_text(json.dumps(state, indent=2) + "\n")
  77. temporary.replace(self.state_path)
  78. return state
  79. @contextmanager
  80. def lock(self, shared=False, heavy=False):
  81. import fcntl
  82. self.base.joinpath("cache").mkdir(parents=True, exist_ok=True)
  83. paths = ([self.base / "cache/heavy.lock"] if heavy else []) + [self.state_dir / (self.name + ".lock")]
  84. streams = []
  85. try:
  86. for i, path in enumerate(paths):
  87. stream = path.open("a+")
  88. fcntl.flock(stream, fcntl.LOCK_SH if shared and i == len(paths)-1 else fcntl.LOCK_EX)
  89. streams.append(stream)
  90. yield
  91. finally:
  92. for stream in reversed(streams):
  93. fcntl.flock(stream, fcntl.LOCK_UN)
  94. stream.close()
  95. def spec(self, info):
  96. config, host = info["Config"], info["HostConfig"]
  97. if host.get("AutoRemove"):
  98. raise ValueError("auto-remove containers are not supported")
  99. if any(m["Type"] != "bind" for m in info["Mounts"]):
  100. raise ValueError("only explicit bind mounts are supported")
  101. result = {"user": config.get("User", "0:0"), "privileged": host["Privileged"], "network": host["NetworkMode"],
  102. "pid": host.get("PidMode", ""), "ipc": host.get("IpcMode", ""), "uts": host.get("UTSMode", ""),
  103. "entrypoint": config["Entrypoint"], "command": config["Cmd"], "workdir": config["WorkingDir"],
  104. "env": dict(item.split("=", 1) for item in config.get("Env", []) if "=" in item),
  105. "mounts": [{"source": m["Source"], "target": m["Destination"], "rw": m["RW"]} for m in info["Mounts"]]}
  106. validate_spec(result)
  107. result["mounts"].sort(key=lambda m: m["target"])
  108. return result
  109. def desired(self, original=None):
  110. result = json.loads(json.dumps(original)) if original else {
  111. "user": "0:0", "privileged": True, "network": "host", "pid": "host", "ipc": "host", "uts": "host",
  112. "entrypoint": ["/bin/sleep"], "command": ["infinity"], "workdir": "/workspace", "env": {},
  113. "mounts": [{"source": str(self.base), "target": "/data/prod2u", "rw": True},
  114. {"source": str(self.workspace or REPO), "target": "/workspace", "rw": True}]}
  115. for key, value in {"XDG_CACHE_HOME": "/data/prod2u/cache", "XDG_STATE_HOME": "/data/prod2u/state",
  116. "XDG_RUNTIME_DIR": "/run/prod2u", "TMPDIR": "/data/prod2u/cache/tmp"}.items():
  117. result["env"].setdefault(key, value)
  118. if self.workspace:
  119. result["mounts"] = [m for m in result["mounts"] if m["target"] != "/workspace"]
  120. result["mounts"].append({"source": str(self.workspace), "target": "/workspace", "rw": True})
  121. for mount in result["mounts"]:
  122. if not Path(mount["source"]).is_dir():
  123. raise ValueError("bind source directory is missing: " + mount["source"])
  124. validate_spec(result)
  125. result["mounts"].sort(key=lambda m: m["target"])
  126. return result
  127. def idle(self, info):
  128. if info.get("ExecIDs"):
  129. raise RuntimeError("container has active exec sessions; wait before lifecycle changes")
  130. if info["State"].get("Paused"):
  131. raise RuntimeError("container is paused; resolve that state before lifecycle changes")
  132. if not info["State"]["Running"]:
  133. return
  134. group = info["State"].get("CgroupPath")
  135. if not group or ".." in PurePosixPath(group).parts:
  136. raise RuntimeError("cannot verify container cgroup")
  137. root = Path("/sys/fs/cgroup") / group.lstrip("/")
  138. if not root.is_dir():
  139. raise RuntimeError("container cgroup disappeared; recheck state")
  140. pids = set()
  141. for path in root.rglob("cgroup.procs"):
  142. pids.update(int(x) for x in path.read_text().split())
  143. other = pids - {int(info["State"]["Pid"])}
  144. if other:
  145. raise RuntimeError("container has background work (host PIDs): " + ",".join(map(str, sorted(other))))
  146. def probe(self, name):
  147. self.call(["podman", "exec", name, "python3", "-c",
  148. "import os;from pathlib import Path;assert os.getuid()==0;"
  149. "[Path(os.environ[k]).mkdir(parents=True,exist_ok=True) for k in ('XDG_CACHE_HOME','XDG_STATE_HOME','XDG_RUNTIME_DIR','TMPDIR')]"])
  150. def up_unlocked(self):
  151. info = self.inspect()
  152. if info:
  153. actual = self.spec(info)
  154. if self.workspace and not any(m["target"] == "/workspace" and m["source"] == str(self.workspace) for m in actual["mounts"]):
  155. raise RuntimeError("workspace mount differs; use --workspace PATH recreate before running there")
  156. if not info["State"]["Running"]:
  157. self.call(["podman", "start", info["Id"]])
  158. return self.inspect()
  159. saved = self.load()
  160. image = saved.get("image_id") or json.loads(self.call(["podman", "image", "inspect", self.image]).stdout)[0]["Id"]
  161. spec = self.desired(saved.get("spec"))
  162. self.call(create_args(self.name, image, spec))
  163. self.call(["podman", "start", self.name])
  164. self.probe(self.name)
  165. self.save(image, spec, restored_from=saved.get("checkpoint_tag"))
  166. return self.inspect()
  167. def checkpoint_unlocked(self, restart):
  168. info = self.inspect()
  169. if not info:
  170. raise RuntimeError("container does not exist")
  171. spec = self.desired(self.spec(info))
  172. self.idle(info)
  173. running = info["State"]["Running"]
  174. if running:
  175. self.call(["podman", "stop", "--time", "30", info["Id"]])
  176. tag = "localhost/" + self.name + "-checkpoint:" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:12]
  177. try:
  178. self.call(["podman", "commit", "--pause=false", info["Id"], tag])
  179. image = json.loads(self.call(["podman", "image", "inspect", tag]).stdout)[0]["Id"]
  180. state = self.save(image, spec, checkpoint_tag=tag, checkpoint_container_id=info["Id"])
  181. except Exception:
  182. if running:
  183. self.call(["podman", "start", info["Id"]])
  184. raise
  185. if restart and running:
  186. self.call(["podman", "start", info["Id"]])
  187. return info, state
  188. def recreate_unlocked(self):
  189. if not self.inspect():
  190. return self.up_unlocked()
  191. old, saved = self.checkpoint_unlocked(restart=False)
  192. candidate = self.name + "-candidate-" + uuid.uuid4().hex[:8]
  193. backup = self.name + "-previous-" + uuid.uuid4().hex[:8]
  194. candidate_id = None
  195. renamed = False
  196. try:
  197. candidate_id = self.call(create_args(candidate, saved["image_id"], saved["spec"])).stdout.strip()
  198. self.call(["podman", "start", candidate_id])
  199. self.probe(candidate_id)
  200. new = self.inspect(candidate_id)
  201. if self.spec(new) != saved["spec"]:
  202. raise RuntimeError("replacement settings differ from checkpoint specification")
  203. self.call(["podman", "rename", old["Id"], backup])
  204. renamed = True
  205. self.call(["podman", "rename", candidate_id, self.name])
  206. except Exception:
  207. if candidate_id and self.inspect(candidate_id):
  208. self.call(["podman", "rm", "--force", candidate_id])
  209. if renamed:
  210. self.call(["podman", "rename", old["Id"], self.name])
  211. if old["State"]["Running"]:
  212. self.call(["podman", "start", old["Id"]])
  213. raise
  214. self.call(["podman", "rm", old["Id"]])
  215. return self.inspect()
  216. def summary(self, info):
  217. saved = self.load()
  218. return {"name": self.name, "container_id": info["Id"] if info else None,
  219. "state": info["State"]["Status"] if info else "absent", "image_id": info["Image"] if info else None,
  220. "state_file": str(self.state_path),
  221. "environment_id": hashlib.sha256(encode({"image": info["Image"], "spec": self.spec(info)})).hexdigest()[:16] if info else None,
  222. "checkpoint_environment_id": saved.get("environment_id"), "checkpoint_image_id": saved.get("image_id")}
  223. def action(self, action):
  224. if action == "status":
  225. return self.summary(self.inspect())
  226. with self.lock(heavy=action in ("stop", "down", "checkpoint", "recreate", "build")):
  227. if action == "up":
  228. info = self.up_unlocked()
  229. elif action == "stop":
  230. info = self.inspect()
  231. if info:
  232. self.spec(info)
  233. self.idle(info)
  234. if info["State"]["Running"]:
  235. self.call(["podman", "stop", "--time", "30", info["Id"]])
  236. info = self.inspect()
  237. elif action == "checkpoint":
  238. self.checkpoint_unlocked(restart=True)
  239. info = self.inspect()
  240. elif action == "down":
  241. if self.inspect():
  242. old, _ = self.checkpoint_unlocked(restart=False)
  243. self.call(["podman", "rm", old["Id"]])
  244. info = None
  245. elif action == "recreate":
  246. info = self.recreate_unlocked()
  247. elif action == "build":
  248. result = subprocess.run(["bash", str(REPO / "containers/6400-dev/build-image.sh")])
  249. if result.returncode:
  250. raise RuntimeError("base image build failed")
  251. info = self.inspect()
  252. else:
  253. info = self.inspect()
  254. return self.summary(info)
  255. def execute(self, command, workdir=None, terminal=False):
  256. with self.lock():
  257. self.up_unlocked()
  258. with self.lock(shared=True):
  259. info = self.inspect()
  260. if not info or not info["State"]["Running"]:
  261. raise RuntimeError("container changed during startup; retry before executing the command")
  262. args = ["podman", "exec"] + (["-it"] if terminal else [])
  263. if workdir:
  264. args += ["--workdir", workdir]
  265. return subprocess.run(args + [self.name, *command]).returncode
  266. DOCTOR = '''import json,os,shutil,subprocess,tempfile
  267. from pathlib import Path
  268. assert os.getuid()==0
  269. for name in ('git','python3','iverilog','vvp','verilator','yosys','sby','go'):
  270. assert shutil.which(name),name
  271. import pytest,yaml,cocotb
  272. with tempfile.TemporaryDirectory(prefix='prod2u-doctor-') as folder:
  273. 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')
  274. subprocess.run(['iverilog','-g2012','-s','test','-o',str(p/'test.vvp'),str(p/'test.v')],check=True)
  275. result=subprocess.check_output(['vvp',str(p/'test.vvp')],text=True);assert 'DOCTOR_RTL_PASS' in result
  276. subprocess.run(['verilator','--binary','--timing','-Wno-fatal','-j','2','--top-module','test','--Mdir',str(p/'obj'),str(p/'test.v')],check=True)
  277. result=subprocess.check_output([str(p/'obj/Vtest')],text=True);assert 'DOCTOR_RTL_PASS' in result
  278. print(json.dumps({'uid':os.getuid(),'icarus_smoke':'PASS','verilator_compile_and_run':'PASS','hardware':'NOT_RUN'}))
  279. '''
  280. def main(argv=None):
  281. parser = argparse.ArgumentParser(description=__doc__)
  282. parser.add_argument("--name", default=os.environ.get("PROD2U_CONTAINER", "prod2u-dev"))
  283. parser.add_argument("--base", type=Path, default=os.environ.get("PRODU2_TOOLCHAIN_BASE", "/data/prod2u"))
  284. parser.add_argument("--state-dir", type=Path)
  285. parser.add_argument("--workspace", type=Path, help="bind this exact source directory to /workspace on creation/recreate")
  286. parser.add_argument("--image", default=DEFAULT_IMAGE, help="initial image only; checkpoints use immutable IDs")
  287. sub = parser.add_subparsers(dest="action", required=True)
  288. for name in ("up", "stop", "down", "checkpoint", "recreate", "status", "doctor", "build"):
  289. sub.add_parser(name)
  290. for name in ("run", "shell"):
  291. entry = sub.add_parser(name)
  292. entry.add_argument("--workdir")
  293. entry.add_argument("argv", nargs=argparse.REMAINDER)
  294. args = parser.parse_args(argv)
  295. if sys.platform != "linux" or os.geteuid() != 0 or Path("/run/.containerenv").exists():
  296. parser.error("execute on the authorized Linux Podman host as existing root")
  297. try:
  298. manager = Controller(args.name, args.base, args.state_dir, args.workspace, args.image)
  299. if args.action in ("run", "shell", "doctor"):
  300. command = ["python3", "-c", DOCTOR] if args.action == "doctor" else args.argv
  301. if command and command[0] == "--":
  302. command = command[1:]
  303. if not command and args.action == "run":
  304. parser.error("run requires a command")
  305. return manager.execute(command or ["bash"], getattr(args, "workdir", None), args.action == "shell" and sys.stdin.isatty())
  306. print(json.dumps(manager.action(args.action), indent=2))
  307. return 0
  308. except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error:
  309. print(str(error), file=sys.stderr)
  310. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  311. print(error.stderr.strip(), file=sys.stderr)
  312. return 2
  313. if __name__ == "__main__":
  314. raise SystemExit(main())