| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391 |
- #!/usr/bin/env python3
- """Submit/status/logs/cancel for exact-source jobs in the persistent LAN container.
- Run on the Linux host, or pass --ssh-runner with this file's exact remote path
- from Windows. A run ID is immutable: reuse returns its existing state; changed
- input requires a new run ID. PASS means the command succeeded, not product acceptance.
- """
- from __future__ import annotations
- import argparse
- from contextlib import contextmanager
- import hashlib
- import json
- import os
- from pathlib import Path
- import re
- import shlex
- import signal
- import subprocess
- import sys
- import time
- from datetime import datetime, timezone
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tools.dev_container import Controller
- TERMINAL = {"PASS", "FAIL", "CANCELLED", "INTERRUPTED", "SUBMIT_FAILED"}
- CGROOT = Path("/sys/fs/cgroup")
- def now():
- return datetime.now(timezone.utc).isoformat()
- def digest(value):
- return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
- def atomic(path, value):
- temporary = path.with_suffix(path.suffix + ".tmp")
- temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
- temporary.replace(path)
- def read(path):
- return json.loads(path.read_text(encoding="utf-8"))
- def boot_id():
- return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
- def pid_start(pid):
- try:
- # comm may contain spaces and parentheses; starttime is field 22.
- return Path(f"/proc/{int(pid)}/stat").read_text().rsplit(")", 1)[1].split()[19]
- except (FileNotFoundError, ProcessLookupError):
- return None
- @contextmanager
- def lock(path):
- import fcntl
- with path.open("a+") as stream:
- fcntl.flock(stream, fcntl.LOCK_EX)
- yield
- def job_dir(root, run_id):
- if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", run_id):
- raise ValueError("run_id must contain 1..96 letters, digits, dots, hyphens or underscores")
- return Path(root).resolve() / run_id
- def unit_name(folder):
- return "prod2u-job-" + hashlib.sha256(str(folder).encode()).hexdigest()[:24] + ".service"
- def source_binding(workspace):
- workspace = Path(workspace).resolve()
- if not workspace.is_dir():
- raise ValueError("workspace is missing")
- def git(*args):
- return subprocess.check_output(["git", "-C", str(workspace), *args], text=True).strip()
- if git("status", "--porcelain", "--untracked-files=all"):
- raise ValueError("submit requires a clean exact source snapshot")
- return {"workspace": str(workspace), "commit": git("rev-parse", "HEAD"), "tree": git("rev-parse", "HEAD^{tree}")}
- def new_spec(args):
- command = args.command[1:] if args.command and args.command[0] == "--" else args.command
- if not command:
- raise ValueError("submit requires a nonempty command after --")
- for value in (args.snapshot_id, args.target, args.task, args.toolchain_id):
- if not value.strip():
- raise ValueError("snapshot/target/task/toolchain identifiers must not be empty")
- return {**source_binding(args.workspace), "snapshot_id": args.snapshot_id, "target": args.target,
- "task": args.task, "toolchain_id": args.toolchain_id, "container": args.container,
- "heavy": args.heavy or args.task in ("td", "formal", "build", "full", "package"),
- "command": command, "runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
- def save_status(folder, state):
- atomic(folder / "RUN-STATUS.json", state)
- if state["status"] in TERMINAL:
- atomic(folder / "RESULT.json", state)
- def populated(group):
- path = CGROOT / group.lstrip("/") / "cgroup.events"
- try:
- return "populated 1" in path.read_text().splitlines()
- except FileNotFoundError:
- return False
- def kill_job_group(state):
- group = state.get("job_cgroup")
- parent = state.get("container_cgroup")
- if not group:
- return
- name = state.get("cgroup_name", "prod2u-job-" + state["identity"][:24])
- if not re.fullmatch(r"prod2u-job-[a-f0-9]{24}", name):
- raise RuntimeError("invalid job cgroup name")
- expected = str(Path(parent) / name) if parent else None
- if state.get("boot_id") != boot_id() or group != expected or ".." in Path(group).parts:
- raise RuntimeError("refuse stale or mismatched job cgroup")
- target = CGROOT / group.lstrip("/") / "cgroup.kill"
- if target.exists():
- target.write_text("1")
- def refresh(folder):
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- if state["status"] in TERMINAL:
- return state
- reason = None
- if state["boot_id"] != boot_id():
- reason = "host rebooted; old process identities are invalid"
- elif state.get("job_cgroup") and populated(state["job_cgroup"]):
- return state
- else:
- unit = subprocess.run(["systemctl", "show", state["unit"], "-p", "ActiveState", "--value"],
- text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if unit.returncode:
- raise RuntimeError("cannot inspect job unit: " + unit.stderr.strip())
- if unit.stdout.strip() not in ("active", "activating", "reloading", "deactivating"):
- reason = "worker unit is inactive and no job processes remain"
- if reason:
- state.update(status="INTERRUPTED", reason=reason, finished_utc=now(), exit_code=None)
- save_status(folder, state)
- return state
- def submit(args):
- folder = job_dir(args.run_root, args.run_id)
- folder.parent.mkdir(parents=True, exist_ok=True)
- spec = new_spec(args)
- with lock(folder.parent / ".submit.lock"):
- if folder.exists():
- old = read(folder / "SPEC.json")
- if old != spec:
- raise ValueError("RUN_ID_CONFLICT: existing run has different inputs; use a new run_id")
- return refresh(folder)
- folder.mkdir()
- atomic(folder / "SPEC.json", spec)
- state = {"schema": "prod2u-remote-job-v2", "run_id": args.run_id, "identity": digest(spec),
- "status": "QUEUED", "phase": "submit", "boot_id": boot_id(), "submitted_utc": now(),
- "unit": unit_name(folder), "spec": spec, "logs": ["stdout.log", "stderr.log", "worker.log"],
- "hardware": "NOT_RUN"}
- save_status(folder, state)
- command = ["systemd-run", "--quiet", "--collect", "--service-type=exec", "--unit=" + state["unit"],
- "--property=StandardOutput=append:" + str(folder / "worker.log"),
- "--property=StandardError=append:" + str(folder / "worker.log"),
- sys.executable, str(Path(__file__).resolve()), "_launch", str(folder)]
- result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if result.returncode:
- with lock(folder / ".lock"):
- state.update(status="SUBMIT_FAILED", exit_code=result.returncode, reason=result.stderr.strip(), finished_utc=now())
- save_status(folder, state)
- return read(folder / "RUN-STATUS.json")
- def cancel(folder):
- # Serialize with submission so cancellation cannot precede systemd dispatch.
- with lock(folder.parent / ".submit.lock"):
- return cancel_dispatched(folder)
- def cancel_dispatched(folder):
- stop_unit = False
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- if state["status"] in TERMINAL:
- return state
- if state["boot_id"] != boot_id():
- state.update(status="INTERRUPTED", reason="host rebooted", exit_code=None, finished_utc=now())
- else:
- stop_unit = state["phase"] == "submit" and not state.get("job_cgroup")
- state.update(cancel_requested=True, phase="cancelling")
- if stop_unit:
- state.update(status="CANCELLED", exit_code=130, finished_utc=now(),
- reason="cancelled before command startup")
- save_status(folder, state)
- kill_job_group(state)
- # Before attachment, _launch observes this flag and never opens the gate.
- save_status(folder, state)
- if stop_unit:
- if state["unit"] != unit_name(folder):
- raise RuntimeError("job unit identity mismatch")
- subprocess.run(["systemctl", "stop", state["unit"]], check=True)
- return state
- def attach(folder, manager, process):
- deadline = time.monotonic() + 30
- ready = folder / "PROCESS.json"
- while not ready.exists():
- if process.poll() is not None:
- raise RuntimeError("container worker exited before its startup handshake")
- if time.monotonic() > deadline:
- raise RuntimeError("container worker startup handshake timed out")
- time.sleep(.05)
- binding = read(ready)
- if binding["boot_id"] != boot_id() or pid_start(binding["pid"]) != binding["start_ticks"]:
- raise RuntimeError("container worker process identity mismatch")
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- info = manager.inspect()
- parent = info["State"]["CgroupPath"]
- name = state["unit"].removesuffix(".service")
- group = str(Path(parent) / name)
- path = CGROOT / group.lstrip("/")
- path.mkdir()
- state.update(job_cgroup=group, cgroup_name=name, container_cgroup=parent,
- process=binding, container_id=info["Id"], container_image_id=info["Image"])
- save_status(folder, state)
- (path / "cgroup.procs").write_text(str(binding["pid"]))
- if binding["pid"] not in [int(x) for x in (path / "cgroup.procs").read_text().split()]:
- raise RuntimeError("worker was not attached to its job cgroup")
- if state.get("cancel_requested"):
- kill_job_group(state)
- else:
- state.update(status="RUNNING", phase="command", started_utc=now())
- save_status(folder, state)
- (folder / "GO").touch()
- def launch(folder):
- spec = read(folder / "SPEC.json")
- manager = Controller(spec["container"], Path("/data/prod2u"))
- # Same acquisition order as lifecycle changes. Keep these locks through
- # failure cleanup so container recreation cannot race cancellation.
- with manager.lock(shared=True, heavy=spec["heavy"]):
- return launch_locked(folder, manager)
- def launch_locked(folder, manager):
- spec = read(folder / "SPEC.json")
- process = None
- result_code = None
- reason = None
- def interrupted(signum, frame):
- raise RuntimeError("worker received signal " + str(signum))
- signal.signal(signal.SIGTERM, interrupted)
- signal.signal(signal.SIGINT, interrupted)
- try:
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- if state["status"] in TERMINAL:
- return 0 if state["status"] == "PASS" else 1
- if state["phase"] != "submit":
- return 0 # An existing launcher already owns this immutable run.
- if state.get("cancel_requested"):
- result_code = 130
- else:
- state.update(phase="container_start")
- save_status(folder, state)
- if result_code == 130:
- return finish(folder, result_code, None)
- info = manager.inspect()
- if not info or not info["State"]["Running"] or info["HostConfig"]["PidMode"] != "host":
- raise RuntimeError("persistent container must be running with host PID namespace")
- if source_binding(spec["workspace"]) != {key: spec[key] for key in ("workspace", "commit", "tree")}:
- raise RuntimeError("source snapshot changed after submission")
- with (folder / "stdout.log").open("w") as stdout, (folder / "stderr.log").open("w") as stderr:
- process = subprocess.Popen(["podman", "exec", "--workdir", spec["workspace"], spec["container"],
- "python3", str(Path(__file__).resolve()), "_execute", str(folder)],
- stdout=stdout, stderr=stderr)
- attach(folder, manager, process)
- result_code = process.wait()
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- if state.get("job_cgroup") and populated(state["job_cgroup"]):
- reason = "command left background processes; all job processes were terminated"
- kill_job_group(state)
- return finish(folder, result_code, reason)
- except Exception as error:
- reason = str(error)
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- kill_job_group(state)
- if not state.get("job_cgroup") and (folder / "PROCESS.json").exists():
- binding = read(folder / "PROCESS.json")
- if binding["boot_id"] == boot_id() and pid_start(binding["pid"]) == binding["start_ticks"]:
- os.kill(binding["pid"], signal.SIGKILL)
- if process:
- try:
- process.wait(timeout=10)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait()
- return finish(folder, result_code, reason)
- def finish(folder, code, reason):
- with lock(folder / ".lock"):
- state = read(folder / "RUN-STATUS.json")
- if state["status"] in TERMINAL:
- return 0 if state["status"] == "PASS" else 1
- status = "CANCELLED" if state.get("cancel_requested") else ("PASS" if code == 0 and not reason else "FAIL")
- artifacts = []
- for path in sorted(folder.rglob("*")):
- if path.is_file() and not path.is_symlink() and path.name not in ("RUN-STATUS.json", "RESULT.json", ".lock", "GO"):
- # Retain large waveforms remotely; inventory hashes stream without loading them.
- with path.open("rb") as stream:
- sha = hashlib.file_digest(stream, "sha256").hexdigest()
- artifacts.append({"path": path.relative_to(folder).as_posix(), "size": path.stat().st_size, "sha256": sha})
- state.update(status=status, phase="finished", exit_code=code, reason=reason,
- finished_utc=now(), artifacts=artifacts)
- save_status(folder, state)
- return 0 if status == "PASS" else 1
- def execute(folder):
- """Container handshake: no task process starts before host cgroup attachment."""
- atomic(folder / "PROCESS.json", {"pid": os.getpid(), "start_ticks": pid_start(os.getpid()), "boot_id": boot_id()})
- deadline = time.monotonic() + 40
- while not (folder / "GO").exists():
- if time.monotonic() > deadline:
- raise RuntimeError("host did not grant job execution")
- time.sleep(.05)
- spec = read(folder / "SPEC.json")
- environment = dict(os.environ, PROD2U_RUN_DIR=str(folder), PROD2U_RUN_ID=folder.name)
- return subprocess.run(spec["command"], env=environment).returncode
- def main(argv=None):
- argv = list(sys.argv[1:] if argv is None else argv)
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--run-root", type=Path, default="/data/prod2u/runs")
- parser.add_argument("--ssh-runner", help="exact remote remote_job.py path; use the existing edk2-uefi-lab SSH configuration")
- sub = parser.add_subparsers(dest="action", required=True)
- entry = sub.add_parser("submit")
- entry.add_argument("run_id")
- for name in ("snapshot-id", "target", "task", "toolchain-id", "workspace"):
- entry.add_argument("--" + name, required=True)
- entry.add_argument("--container", default="prod2u-dev")
- entry.add_argument("--heavy", action="store_true")
- for name in ("status", "cancel", "logs"):
- sub.add_parser(name).add_argument("run_id")
- for name in ("_launch", "_execute"):
- sub.add_parser(name).add_argument("folder", type=Path)
- boundary = argv.index("--") if "--" in argv else len(argv)
- args = parser.parse_args(argv[:boundary])
- args.command = argv[boundary+1:]
- if args.command and args.action != "submit":
- parser.error("only submit accepts a command after --")
- try:
- if args.ssh_runner:
- remaining = argv.copy()
- if "--ssh-runner" in remaining:
- index = remaining.index("--ssh-runner")
- del remaining[index:index+2]
- else:
- remaining = [x for x in remaining if not x.startswith("--ssh-runner=")]
- command = shlex.join(["python3", args.ssh_runner, *remaining])
- null = "NUL" if sys.platform == "win32" else "/dev/null"
- ssh = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=" + null,
- "-o", "GlobalKnownHostsFile=" + null, "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10",
- "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "edk2-uefi-lab", command]
- return subprocess.run(ssh).returncode
- if sys.platform != "linux" or os.geteuid() != 0:
- raise ValueError("execute on the authorized Linux host as root, or use --ssh-runner")
- if args.action == "_execute":
- return execute(args.folder)
- if Path("/run/.containerenv").exists():
- raise ValueError("submit/status/cancel require the Linux Podman host")
- if args.action == "_launch":
- return launch(args.folder)
- if args.action == "submit":
- result = submit(args)
- else:
- folder = job_dir(args.run_root, args.run_id)
- if args.action == "cancel":
- result = cancel(folder)
- else:
- result = refresh(folder)
- if args.action == "logs":
- for name in result["logs"]:
- path = folder / name
- if path.exists():
- print("== " + name + " ==")
- print(path.read_text(encoding="utf-8", errors="replace"), end="")
- return 0
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return 0
- except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error:
- print(str(error), file=sys.stderr)
- return 2
- if __name__ == "__main__":
- raise SystemExit(main())
|