| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595 |
- #!/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, PurePosixPath
- import re
- import shlex
- import signal
- import subprocess
- import sys
- import time
- import tempfile
- import zipfile
- 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, main as container_main
- TERMINAL = {"PASS", "FAIL", "CANCELLED", "INTERRUPTED", "SUBMIT_FAILED"}
- CGROOT = Path("/sys/fs/cgroup")
- BUNDLE_NAME = "FAILURE-LOGS.zip"
- DIAGNOSTIC_LIMIT = 64 * 1024 * 1024
- SMALL_WAVE_LIMIT = 4 * 1024 * 1024
- 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 snapshot(repository, workspace, commit):
- """Create a self-contained exact clone, or verify an existing one unchanged."""
- if not re.fullmatch(r"[a-fA-F0-9]{40}", commit):
- raise ValueError("snapshot requires a full 40-character commit")
- repository, workspace = Path(repository), Path(workspace)
- if not repository.is_absolute() or not repository.is_dir() or not workspace.is_absolute():
- raise ValueError("snapshot requires a local absolute repository and destination")
- repository, workspace = repository.resolve(), workspace.absolute()
- commit = commit.lower()
- workspace.parent.mkdir(parents=True, exist_ok=True)
- with lock(workspace.parent / ".snapshot.lock"):
- if workspace.exists() or workspace.is_symlink():
- if workspace.is_symlink():
- raise ValueError("snapshot destination is a symlink; retained unchanged")
- if not (workspace / '.git').is_dir():
- raise ValueError("snapshot must own its Git directory; retained unchanged")
- result = source_binding(workspace)
- if result['commit'] != commit:
- raise ValueError("snapshot destination has a different commit; retained unchanged")
- if (workspace / '.git/objects/info/alternates').exists():
- raise ValueError("snapshot depends on alternate Git objects")
- else:
- # The temporary clone belongs to this invocation only. No reset or
- # cleanup of a pre-existing source tree occurs, even after failure.
- with tempfile.TemporaryDirectory(prefix=workspace.name + '.partial-', dir=workspace.parent) as temporary:
- clone = Path(temporary) / 'source'
- subprocess.run(['git', 'clone', '--no-hardlinks', '--no-checkout', str(repository), str(clone)], check=True)
- subprocess.run(['git', '-C', str(clone), 'checkout', '--detach', commit], check=True)
- result = source_binding(clone)
- if result['commit'] != commit:
- raise ValueError("snapshot checkout did not resolve to the requested commit")
- clone.rename(workspace)
- result['workspace'] = str(workspace)
- return dict(result, scope='exact-source-clone', repository=str(repository))
- def prepare_alias(args):
- """Presets only; all execution still goes through submit and its locks."""
- if args.action not in ('quick', 'td', 'full'):
- return
- args.task = args.action
- if args.action == 'full':
- if not args.command:
- raise ValueError("full requires an explicit suite command after --; current regression is not Full acceptance")
- else:
- if args.command:
- raise ValueError("quick/td use the canonical firmware command; use submit for a custom command")
- action = 'diagnose' if args.action == 'quick' else 'build'
- # No shell expansion: the run directory is resolved inside the worker.
- # 1200s measured need: the real-rate 12-axis engine TB (25 Hz Z
- # half-period restored by contract) runs 782s wall in vvp.
- code = ("import os,sys; from pathlib import Path; from tools.fw_cli import main; "
- "raise SystemExit(main([sys.argv[1],sys.argv[2],'--run-root',"
- "str(Path(os.environ['PROD2U_RUN_DIR'])/'native')" +
- (",'--timeout','1200'" if args.action == 'quick' else "") + "]))")
- args.command = ['python3', '-c', code, action, args.target]
- args.action = 'submit'
- 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):
- if state["status"] in TERMINAL - {"PASS"} and not state.get("failure_bundle") and not state.get("failure_bundle_error"):
- if "artifacts" not in state:
- state["artifacts"] = artifact_inventory(folder)
- try:
- state["failure_bundle"] = failure_bundle(folder, state)
- state["artifacts"].append({key: state["failure_bundle"][key] for key in ("path", "size", "sha256")})
- except Exception as error:
- # Diagnostic collection must not replace the original exit/status.
- state["failure_bundle_error"] = str(error)
- atomic(folder / "RUN-STATUS.json", state)
- if state["status"] in TERMINAL:
- atomic(folder / "RESULT.json", state)
- def artifact_inventory(folder):
- artifacts = []
- reserved = {"RUN-STATUS.json", "RESULT.json", ".lock", "GO", BUNDLE_NAME, BUNDLE_NAME + ".partial"}
- for path in sorted(folder.rglob("*")):
- relative = path.relative_to(folder).as_posix()
- if path.is_file() and not path.is_symlink() and relative not in reserved:
- with path.open("rb") as stream:
- sha = hashlib.file_digest(stream, "sha256").hexdigest()
- artifacts.append({"path": relative, "size": path.stat().st_size, "sha256": sha})
- return artifacts
- def failure_bundle(folder, state):
- """Collect native reports and small waveforms; index large remote artifacts."""
- destination = folder / BUNDLE_NAME
- partial = folder / (BUNDLE_NAME + ".partial")
- if destination.exists() or partial.exists():
- raise RuntimeError("reserved diagnostic archive already exists; retained unchanged")
- native = {".log", ".rpt", ".report", ".timing", ".area", ".xml", ".json", ".txt", ".sby"}
- rows = []
- budget = DIAGNOSTIC_LIMIT
- # Collect console failures before optional reports when logs are very large.
- artifacts = sorted(state["artifacts"], key=lambda item: (item["path"] not in ("stdout.log", "stderr.log", "SPEC.json"), item["path"]))
- with zipfile.ZipFile(partial, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
- for item in artifacts:
- path = folder / item["path"]
- suffix = path.suffix.lower()
- row = dict(item)
- if suffix in (".vcd", ".fst") and item["size"] > SMALL_WAVE_LIMIT:
- row["disposition"] = "remote_large_waveform"
- elif suffix not in native | {".vcd", ".fst"}:
- row["disposition"] = "remote_non_diagnostic_artifact"
- elif item["size"] <= budget:
- member = "files/" + item["path"]
- archive.write(path, member)
- row.update(disposition="complete", member=member, included_bytes=item["size"])
- budget -= item["size"]
- elif suffix in native and budget:
- length = min(budget, 2 * 1024 * 1024)
- with path.open("rb") as stream:
- stream.seek(-length, os.SEEK_END)
- tail = stream.read(length)
- member = "tails/" + item["path"]
- archive.writestr(member, tail)
- row.update(disposition="tail_only", member=member, included_bytes=length,
- included_sha256=hashlib.sha256(tail).hexdigest())
- budget -= length
- else:
- row["disposition"] = "remote_bundle_size_limit"
- rows.append(row)
- index = {"schema": "prod2u-failure-index-v1", "run_id": state.get("run_id", folder.name),
- "job_status": state["status"], "exit_code": state.get("exit_code"), "reason": state.get("reason"),
- "spec": state.get("spec"), "hardware": "NOT_RUN", "uncompressed_file_limit": DIAGNOSTIC_LIMIT,
- "small_waveform_limit": SMALL_WAVE_LIMIT, "artifacts": rows,
- "scope": "Included bytes only; large waves and explicitly indexed omissions remain on the remote host."}
- archive.writestr("FAILURE-INDEX.json", json.dumps(index, indent=2, ensure_ascii=False).encode())
- partial.replace(destination)
- with destination.open("rb") as stream:
- sha = hashlib.file_digest(stream, "sha256").hexdigest()
- return {"path": BUNDLE_NAME, "size": destination.stat().st_size, "sha256": sha,
- "complete_files": sum(row["disposition"] == "complete" for row in rows),
- "scope": "bounded failed-stage diagnostics; see FAILURE-INDEX.json for omitted/tail-only data"}
- def fetch_failure(result, remote_runner, remote_root, local_root=None):
- from tools.remote_transfer import SSH, download
- bundle = result.get("failure_bundle")
- if not bundle:
- return {"status": "UNAVAILABLE", "reason": result.get("failure_bundle_error", "this result has no diagnostic archive")}
- if bundle["path"] != BUNDLE_NAME or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", result["run_id"]):
- raise ValueError("invalid remote diagnostic identity")
- root = Path(local_root) if local_root else Path(tempfile.gettempdir()) / "prod2u-thermal/analysis"
- folder = (root / ("run-" + result["run_id"])).resolve()
- remote = str(PurePosixPath(remote_root) / result["run_id"] / BUNDLE_NAME)
- worker = str(PurePosixPath(remote_runner).parent / "remote_transfer.py")
- receipt = download(SSH(worker), remote, folder / BUNDLE_NAME, bundle["sha256"])
- if receipt["size"] != bundle["size"]:
- raise ValueError("diagnostic archive size differs from job result")
- atomic(folder / "TRANSFER-RECEIPT.json", receipt)
- return {"status": "PASS", "path": receipt["destination"], "sha256": receipt["sha256"],
- "transferred_chunks": receipt["transferred_chunks"], "reused_chunks": receipt["reused_chunks"],
- "scope": receipt["scope"]}
- 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 = artifact_inventory(folder)
- 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):
- for stream in (sys.stdout, sys.stderr):
- if hasattr(stream, "reconfigure"):
- stream.reconfigure(encoding="utf-8")
- 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")
- parser.add_argument("--fetch-root", type=Path, help="local failed-log directory (default: TEMP/prod2u-thermal/analysis)")
- sub = parser.add_subparsers(dest="action", required=True)
- for action, help_text in (("submit", "run an explicit command"),
- ("quick", "run current firmware RTL diagnostics; not Full acceptance"),
- ("td", "run native firmware synthesis/place/route/bitgen"),
- ("full", "run an explicit Full suite command under the heavy lock")):
- entry = sub.add_parser(action, help=help_text)
- entry.add_argument("run_id")
- for name in ("snapshot-id", "target", "toolchain-id", "workspace"):
- entry.add_argument("--" + name, required=True)
- if action == 'submit':
- entry.add_argument('--task', required=True)
- entry.add_argument("--container", default="prod2u-dev")
- entry.add_argument("--heavy", action="store_true")
- entry = sub.add_parser('snapshot', help='create or verify a clean self-contained exact Git clone')
- entry.add_argument('--repository', default='/data/prod2u/git/cpld-temperature-control.git')
- entry.add_argument('--workspace', required=True)
- entry.add_argument('--commit', required=True)
- sub.add_parser('sync', help='push local HEAD to the configured LAN Git remote')
- for action in ('doctor', 'container-up', 'container-stop', 'container-down', 'container-recreate', 'container-status'):
- entry = sub.add_parser(action, help='forward to the existing persistent container lifecycle tool')
- entry.add_argument('--container', default='prod2u-dev')
- entry.add_argument('--workspace', help='exact bind source for container creation/recreation')
- for name in ("status", "cancel", "logs", "fetch"):
- 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 not in ("submit", "full"):
- parser.error("only submit/full accept a command after --")
- try:
- if args.action == 'sync':
- if args.ssh_runner:
- raise ValueError('sync runs in the local source tree; omit --ssh-runner')
- environment = dict(os.environ)
- null = 'NUL' if sys.platform == 'win32' else '/dev/null'
- environment['GIT_SSH_COMMAND'] = ('ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=' + null +
- ' -o GlobalKnownHostsFile=' + null + ' -o UpdateHostKeys=no -o ConnectTimeout=10')
- return subprocess.run(['git', '-C', str(ROOT), 'push', 'lan', 'HEAD'], env=environment).returncode
- if args.ssh_runner:
- remaining = argv[:boundary]
- for option in ("--ssh-runner", "--fetch-root"):
- if option in remaining:
- index = remaining.index(option)
- del remaining[index:index+2]
- else:
- remaining = [x for x in remaining if not x.startswith(option + "=")]
- remaining += argv[boundary:]
- command = shlex.join(["python3", args.ssh_runner, *remaining])
- null = "NUL" if sys.platform == "win32" else "/dev/null"
- ssh = ["ssh", "-n", "-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]
- # Windows OpenSSH keeps an inherited stdin pipe handle open after the
- # remote command exits, hanging the caller; never let ssh see our stdin.
- response = subprocess.run(ssh, stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if response.stderr:
- sys.stderr.buffer.write(response.stderr)
- if response.returncode or args.action == "logs" or args.action == 'doctor' or args.action.startswith('container-'):
- sys.stdout.buffer.write(response.stdout)
- return response.returncode
- result = json.loads(response.stdout)
- code = 0
- if result.get("status") in TERMINAL - {"PASS"} or args.action == "fetch":
- try:
- result["failure_download"] = fetch_failure(result, args.ssh_runner, args.run_root.as_posix(), args.fetch_root)
- except Exception as error:
- result["failure_download"] = {"status": "FAIL", "error": str(error)}
- code = 3
- print(json.dumps(result, indent=2, ensure_ascii=False))
- return code
- 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 == 'doctor' or args.action.startswith('container-'):
- command = ['--name', args.container]
- if args.workspace:
- command += ['--workspace', args.workspace]
- return container_main(command + [args.action.removeprefix('container-')])
- if args.action == 'snapshot':
- print(json.dumps(snapshot(args.repository, args.workspace, args.commit), indent=2))
- return 0
- prepare_alias(args)
- 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())
|