remote_job.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. #!/usr/bin/env python3
  2. """Submit/status/logs/cancel for exact-source jobs in the persistent LAN container.
  3. Run on the Linux host, or pass --ssh-runner with this file's exact remote path
  4. from Windows. A run ID is immutable: reuse returns its existing state; changed
  5. input requires a new run ID. PASS means the command succeeded, not product acceptance.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. from contextlib import contextmanager
  10. import hashlib
  11. import json
  12. import os
  13. from pathlib import Path, PurePosixPath
  14. import re
  15. import shlex
  16. import signal
  17. import subprocess
  18. import sys
  19. import time
  20. import tempfile
  21. import zipfile
  22. from datetime import datetime, timezone
  23. ROOT = Path(__file__).resolve().parents[1]
  24. if str(ROOT) not in sys.path:
  25. sys.path.insert(0, str(ROOT))
  26. from tools.dev_container import Controller, main as container_main
  27. TERMINAL = {"PASS", "FAIL", "CANCELLED", "INTERRUPTED", "SUBMIT_FAILED"}
  28. CGROOT = Path("/sys/fs/cgroup")
  29. BUNDLE_NAME = "FAILURE-LOGS.zip"
  30. DIAGNOSTIC_LIMIT = 64 * 1024 * 1024
  31. SMALL_WAVE_LIMIT = 4 * 1024 * 1024
  32. def now():
  33. return datetime.now(timezone.utc).isoformat()
  34. def digest(value):
  35. return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
  36. def atomic(path, value):
  37. temporary = path.with_suffix(path.suffix + ".tmp")
  38. temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  39. temporary.replace(path)
  40. def read(path):
  41. return json.loads(path.read_text(encoding="utf-8"))
  42. def boot_id():
  43. return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
  44. def pid_start(pid):
  45. try:
  46. # comm may contain spaces and parentheses; starttime is field 22.
  47. return Path(f"/proc/{int(pid)}/stat").read_text().rsplit(")", 1)[1].split()[19]
  48. except (FileNotFoundError, ProcessLookupError):
  49. return None
  50. @contextmanager
  51. def lock(path):
  52. import fcntl
  53. with path.open("a+") as stream:
  54. fcntl.flock(stream, fcntl.LOCK_EX)
  55. yield
  56. def job_dir(root, run_id):
  57. if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", run_id):
  58. raise ValueError("run_id must contain 1..96 letters, digits, dots, hyphens or underscores")
  59. return Path(root).resolve() / run_id
  60. def unit_name(folder):
  61. return "prod2u-job-" + hashlib.sha256(str(folder).encode()).hexdigest()[:24] + ".service"
  62. def source_binding(workspace):
  63. workspace = Path(workspace).resolve()
  64. if not workspace.is_dir():
  65. raise ValueError("workspace is missing")
  66. def git(*args):
  67. return subprocess.check_output(["git", "-C", str(workspace), *args], text=True).strip()
  68. if git("status", "--porcelain", "--untracked-files=all"):
  69. raise ValueError("submit requires a clean exact source snapshot")
  70. return {"workspace": str(workspace), "commit": git("rev-parse", "HEAD"), "tree": git("rev-parse", "HEAD^{tree}")}
  71. def snapshot(repository, workspace, commit):
  72. """Create a self-contained exact clone, or verify an existing one unchanged."""
  73. if not re.fullmatch(r"[a-fA-F0-9]{40}", commit):
  74. raise ValueError("snapshot requires a full 40-character commit")
  75. repository, workspace = Path(repository), Path(workspace)
  76. if not repository.is_absolute() or not repository.is_dir() or not workspace.is_absolute():
  77. raise ValueError("snapshot requires a local absolute repository and destination")
  78. repository, workspace = repository.resolve(), workspace.absolute()
  79. commit = commit.lower()
  80. workspace.parent.mkdir(parents=True, exist_ok=True)
  81. with lock(workspace.parent / ".snapshot.lock"):
  82. if workspace.exists() or workspace.is_symlink():
  83. if workspace.is_symlink():
  84. raise ValueError("snapshot destination is a symlink; retained unchanged")
  85. if not (workspace / '.git').is_dir():
  86. raise ValueError("snapshot must own its Git directory; retained unchanged")
  87. result = source_binding(workspace)
  88. if result['commit'] != commit:
  89. raise ValueError("snapshot destination has a different commit; retained unchanged")
  90. if (workspace / '.git/objects/info/alternates').exists():
  91. raise ValueError("snapshot depends on alternate Git objects")
  92. else:
  93. # The temporary clone belongs to this invocation only. No reset or
  94. # cleanup of a pre-existing source tree occurs, even after failure.
  95. with tempfile.TemporaryDirectory(prefix=workspace.name + '.partial-', dir=workspace.parent) as temporary:
  96. clone = Path(temporary) / 'source'
  97. subprocess.run(['git', 'clone', '--no-hardlinks', '--no-checkout', str(repository), str(clone)], check=True)
  98. subprocess.run(['git', '-C', str(clone), 'checkout', '--detach', commit], check=True)
  99. result = source_binding(clone)
  100. if result['commit'] != commit:
  101. raise ValueError("snapshot checkout did not resolve to the requested commit")
  102. clone.rename(workspace)
  103. result['workspace'] = str(workspace)
  104. return dict(result, scope='exact-source-clone', repository=str(repository))
  105. def prepare_alias(args):
  106. """Presets only; all execution still goes through submit and its locks."""
  107. if args.action not in ('quick', 'td', 'full'):
  108. return
  109. args.task = args.action
  110. if args.action == 'full':
  111. if not args.command:
  112. raise ValueError("full requires an explicit suite command after --; current regression is not Full acceptance")
  113. else:
  114. if args.command:
  115. raise ValueError("quick/td use the canonical firmware command; use submit for a custom command")
  116. action = 'diagnose' if args.action == 'quick' else 'build'
  117. # No shell expansion: the run directory is resolved inside the worker.
  118. # 1200s measured need: the real-rate 12-axis engine TB (25 Hz Z
  119. # half-period restored by contract) runs 782s wall in vvp.
  120. code = ("import os,sys; from pathlib import Path; from tools.fw_cli import main; "
  121. "raise SystemExit(main([sys.argv[1],sys.argv[2],'--run-root',"
  122. "str(Path(os.environ['PROD2U_RUN_DIR'])/'native')" +
  123. (",'--timeout','1200'" if args.action == 'quick' else "") + "]))")
  124. args.command = ['python3', '-c', code, action, args.target]
  125. args.action = 'submit'
  126. def new_spec(args):
  127. command = args.command[1:] if args.command and args.command[0] == "--" else args.command
  128. if not command:
  129. raise ValueError("submit requires a nonempty command after --")
  130. for value in (args.snapshot_id, args.target, args.task, args.toolchain_id):
  131. if not value.strip():
  132. raise ValueError("snapshot/target/task/toolchain identifiers must not be empty")
  133. return {**source_binding(args.workspace), "snapshot_id": args.snapshot_id, "target": args.target,
  134. "task": args.task, "toolchain_id": args.toolchain_id, "container": args.container,
  135. "heavy": args.heavy or args.task in ("td", "formal", "build", "full", "package"),
  136. "command": command, "runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
  137. def save_status(folder, state):
  138. if state["status"] in TERMINAL - {"PASS"} and not state.get("failure_bundle") and not state.get("failure_bundle_error"):
  139. if "artifacts" not in state:
  140. state["artifacts"] = artifact_inventory(folder)
  141. try:
  142. state["failure_bundle"] = failure_bundle(folder, state)
  143. state["artifacts"].append({key: state["failure_bundle"][key] for key in ("path", "size", "sha256")})
  144. except Exception as error:
  145. # Diagnostic collection must not replace the original exit/status.
  146. state["failure_bundle_error"] = str(error)
  147. atomic(folder / "RUN-STATUS.json", state)
  148. if state["status"] in TERMINAL:
  149. atomic(folder / "RESULT.json", state)
  150. def artifact_inventory(folder):
  151. artifacts = []
  152. reserved = {"RUN-STATUS.json", "RESULT.json", ".lock", "GO", BUNDLE_NAME, BUNDLE_NAME + ".partial"}
  153. for path in sorted(folder.rglob("*")):
  154. relative = path.relative_to(folder).as_posix()
  155. if path.is_file() and not path.is_symlink() and relative not in reserved:
  156. with path.open("rb") as stream:
  157. sha = hashlib.file_digest(stream, "sha256").hexdigest()
  158. artifacts.append({"path": relative, "size": path.stat().st_size, "sha256": sha})
  159. return artifacts
  160. def failure_bundle(folder, state):
  161. """Collect native reports and small waveforms; index large remote artifacts."""
  162. destination = folder / BUNDLE_NAME
  163. partial = folder / (BUNDLE_NAME + ".partial")
  164. if destination.exists() or partial.exists():
  165. raise RuntimeError("reserved diagnostic archive already exists; retained unchanged")
  166. native = {".log", ".rpt", ".report", ".timing", ".area", ".xml", ".json", ".txt", ".sby"}
  167. rows = []
  168. budget = DIAGNOSTIC_LIMIT
  169. # Collect console failures before optional reports when logs are very large.
  170. artifacts = sorted(state["artifacts"], key=lambda item: (item["path"] not in ("stdout.log", "stderr.log", "SPEC.json"), item["path"]))
  171. with zipfile.ZipFile(partial, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
  172. for item in artifacts:
  173. path = folder / item["path"]
  174. suffix = path.suffix.lower()
  175. row = dict(item)
  176. if suffix in (".vcd", ".fst") and item["size"] > SMALL_WAVE_LIMIT:
  177. row["disposition"] = "remote_large_waveform"
  178. elif suffix not in native | {".vcd", ".fst"}:
  179. row["disposition"] = "remote_non_diagnostic_artifact"
  180. elif item["size"] <= budget:
  181. member = "files/" + item["path"]
  182. archive.write(path, member)
  183. row.update(disposition="complete", member=member, included_bytes=item["size"])
  184. budget -= item["size"]
  185. elif suffix in native and budget:
  186. length = min(budget, 2 * 1024 * 1024)
  187. with path.open("rb") as stream:
  188. stream.seek(-length, os.SEEK_END)
  189. tail = stream.read(length)
  190. member = "tails/" + item["path"]
  191. archive.writestr(member, tail)
  192. row.update(disposition="tail_only", member=member, included_bytes=length,
  193. included_sha256=hashlib.sha256(tail).hexdigest())
  194. budget -= length
  195. else:
  196. row["disposition"] = "remote_bundle_size_limit"
  197. rows.append(row)
  198. index = {"schema": "prod2u-failure-index-v1", "run_id": state.get("run_id", folder.name),
  199. "job_status": state["status"], "exit_code": state.get("exit_code"), "reason": state.get("reason"),
  200. "spec": state.get("spec"), "hardware": "NOT_RUN", "uncompressed_file_limit": DIAGNOSTIC_LIMIT,
  201. "small_waveform_limit": SMALL_WAVE_LIMIT, "artifacts": rows,
  202. "scope": "Included bytes only; large waves and explicitly indexed omissions remain on the remote host."}
  203. archive.writestr("FAILURE-INDEX.json", json.dumps(index, indent=2, ensure_ascii=False).encode())
  204. partial.replace(destination)
  205. with destination.open("rb") as stream:
  206. sha = hashlib.file_digest(stream, "sha256").hexdigest()
  207. return {"path": BUNDLE_NAME, "size": destination.stat().st_size, "sha256": sha,
  208. "complete_files": sum(row["disposition"] == "complete" for row in rows),
  209. "scope": "bounded failed-stage diagnostics; see FAILURE-INDEX.json for omitted/tail-only data"}
  210. def fetch_failure(result, remote_runner, remote_root, local_root=None):
  211. from tools.remote_transfer import SSH, download
  212. bundle = result.get("failure_bundle")
  213. if not bundle:
  214. return {"status": "UNAVAILABLE", "reason": result.get("failure_bundle_error", "this result has no diagnostic archive")}
  215. if bundle["path"] != BUNDLE_NAME or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", result["run_id"]):
  216. raise ValueError("invalid remote diagnostic identity")
  217. root = Path(local_root) if local_root else Path(tempfile.gettempdir()) / "prod2u-thermal/analysis"
  218. folder = (root / ("run-" + result["run_id"])).resolve()
  219. remote = str(PurePosixPath(remote_root) / result["run_id"] / BUNDLE_NAME)
  220. worker = str(PurePosixPath(remote_runner).parent / "remote_transfer.py")
  221. receipt = download(SSH(worker), remote, folder / BUNDLE_NAME, bundle["sha256"])
  222. if receipt["size"] != bundle["size"]:
  223. raise ValueError("diagnostic archive size differs from job result")
  224. atomic(folder / "TRANSFER-RECEIPT.json", receipt)
  225. return {"status": "PASS", "path": receipt["destination"], "sha256": receipt["sha256"],
  226. "transferred_chunks": receipt["transferred_chunks"], "reused_chunks": receipt["reused_chunks"],
  227. "scope": receipt["scope"]}
  228. def populated(group):
  229. path = CGROOT / group.lstrip("/") / "cgroup.events"
  230. try:
  231. return "populated 1" in path.read_text().splitlines()
  232. except FileNotFoundError:
  233. return False
  234. def kill_job_group(state):
  235. group = state.get("job_cgroup")
  236. parent = state.get("container_cgroup")
  237. if not group:
  238. return
  239. name = state.get("cgroup_name", "prod2u-job-" + state["identity"][:24])
  240. if not re.fullmatch(r"prod2u-job-[a-f0-9]{24}", name):
  241. raise RuntimeError("invalid job cgroup name")
  242. expected = str(Path(parent) / name) if parent else None
  243. if state.get("boot_id") != boot_id() or group != expected or ".." in Path(group).parts:
  244. raise RuntimeError("refuse stale or mismatched job cgroup")
  245. target = CGROOT / group.lstrip("/") / "cgroup.kill"
  246. if target.exists():
  247. target.write_text("1")
  248. def refresh(folder):
  249. with lock(folder / ".lock"):
  250. state = read(folder / "RUN-STATUS.json")
  251. if state["status"] in TERMINAL:
  252. return state
  253. reason = None
  254. if state["boot_id"] != boot_id():
  255. reason = "host rebooted; old process identities are invalid"
  256. elif state.get("job_cgroup") and populated(state["job_cgroup"]):
  257. return state
  258. else:
  259. unit = subprocess.run(["systemctl", "show", state["unit"], "-p", "ActiveState", "--value"],
  260. text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  261. if unit.returncode:
  262. raise RuntimeError("cannot inspect job unit: " + unit.stderr.strip())
  263. if unit.stdout.strip() not in ("active", "activating", "reloading", "deactivating"):
  264. reason = "worker unit is inactive and no job processes remain"
  265. if reason:
  266. state.update(status="INTERRUPTED", reason=reason, finished_utc=now(), exit_code=None)
  267. save_status(folder, state)
  268. return state
  269. def submit(args):
  270. folder = job_dir(args.run_root, args.run_id)
  271. folder.parent.mkdir(parents=True, exist_ok=True)
  272. spec = new_spec(args)
  273. with lock(folder.parent / ".submit.lock"):
  274. if folder.exists():
  275. old = read(folder / "SPEC.json")
  276. if old != spec:
  277. raise ValueError("RUN_ID_CONFLICT: existing run has different inputs; use a new run_id")
  278. return refresh(folder)
  279. folder.mkdir()
  280. atomic(folder / "SPEC.json", spec)
  281. state = {"schema": "prod2u-remote-job-v2", "run_id": args.run_id, "identity": digest(spec),
  282. "status": "QUEUED", "phase": "submit", "boot_id": boot_id(), "submitted_utc": now(),
  283. "unit": unit_name(folder), "spec": spec, "logs": ["stdout.log", "stderr.log", "worker.log"],
  284. "hardware": "NOT_RUN"}
  285. save_status(folder, state)
  286. command = ["systemd-run", "--quiet", "--collect", "--service-type=exec", "--unit=" + state["unit"],
  287. "--property=StandardOutput=append:" + str(folder / "worker.log"),
  288. "--property=StandardError=append:" + str(folder / "worker.log"),
  289. sys.executable, str(Path(__file__).resolve()), "_launch", str(folder)]
  290. result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  291. if result.returncode:
  292. with lock(folder / ".lock"):
  293. state.update(status="SUBMIT_FAILED", exit_code=result.returncode, reason=result.stderr.strip(), finished_utc=now())
  294. save_status(folder, state)
  295. return read(folder / "RUN-STATUS.json")
  296. def cancel(folder):
  297. # Serialize with submission so cancellation cannot precede systemd dispatch.
  298. with lock(folder.parent / ".submit.lock"):
  299. return cancel_dispatched(folder)
  300. def cancel_dispatched(folder):
  301. stop_unit = False
  302. with lock(folder / ".lock"):
  303. state = read(folder / "RUN-STATUS.json")
  304. if state["status"] in TERMINAL:
  305. return state
  306. if state["boot_id"] != boot_id():
  307. state.update(status="INTERRUPTED", reason="host rebooted", exit_code=None, finished_utc=now())
  308. else:
  309. stop_unit = state["phase"] == "submit" and not state.get("job_cgroup")
  310. state.update(cancel_requested=True, phase="cancelling")
  311. if stop_unit:
  312. state.update(status="CANCELLED", exit_code=130, finished_utc=now(),
  313. reason="cancelled before command startup")
  314. save_status(folder, state)
  315. kill_job_group(state)
  316. # Before attachment, _launch observes this flag and never opens the gate.
  317. save_status(folder, state)
  318. if stop_unit:
  319. if state["unit"] != unit_name(folder):
  320. raise RuntimeError("job unit identity mismatch")
  321. subprocess.run(["systemctl", "stop", state["unit"]], check=True)
  322. return state
  323. def attach(folder, manager, process):
  324. deadline = time.monotonic() + 30
  325. ready = folder / "PROCESS.json"
  326. while not ready.exists():
  327. if process.poll() is not None:
  328. raise RuntimeError("container worker exited before its startup handshake")
  329. if time.monotonic() > deadline:
  330. raise RuntimeError("container worker startup handshake timed out")
  331. time.sleep(.05)
  332. binding = read(ready)
  333. if binding["boot_id"] != boot_id() or pid_start(binding["pid"]) != binding["start_ticks"]:
  334. raise RuntimeError("container worker process identity mismatch")
  335. with lock(folder / ".lock"):
  336. state = read(folder / "RUN-STATUS.json")
  337. info = manager.inspect()
  338. parent = info["State"]["CgroupPath"]
  339. name = state["unit"].removesuffix(".service")
  340. group = str(Path(parent) / name)
  341. path = CGROOT / group.lstrip("/")
  342. path.mkdir()
  343. state.update(job_cgroup=group, cgroup_name=name, container_cgroup=parent,
  344. process=binding, container_id=info["Id"], container_image_id=info["Image"])
  345. save_status(folder, state)
  346. (path / "cgroup.procs").write_text(str(binding["pid"]))
  347. if binding["pid"] not in [int(x) for x in (path / "cgroup.procs").read_text().split()]:
  348. raise RuntimeError("worker was not attached to its job cgroup")
  349. if state.get("cancel_requested"):
  350. kill_job_group(state)
  351. else:
  352. state.update(status="RUNNING", phase="command", started_utc=now())
  353. save_status(folder, state)
  354. (folder / "GO").touch()
  355. def launch(folder):
  356. spec = read(folder / "SPEC.json")
  357. manager = Controller(spec["container"], Path("/data/prod2u"))
  358. # Same acquisition order as lifecycle changes. Keep these locks through
  359. # failure cleanup so container recreation cannot race cancellation.
  360. with manager.lock(shared=True, heavy=spec["heavy"]):
  361. return launch_locked(folder, manager)
  362. def launch_locked(folder, manager):
  363. spec = read(folder / "SPEC.json")
  364. process = None
  365. result_code = None
  366. reason = None
  367. def interrupted(signum, frame):
  368. raise RuntimeError("worker received signal " + str(signum))
  369. signal.signal(signal.SIGTERM, interrupted)
  370. signal.signal(signal.SIGINT, interrupted)
  371. try:
  372. with lock(folder / ".lock"):
  373. state = read(folder / "RUN-STATUS.json")
  374. if state["status"] in TERMINAL:
  375. return 0 if state["status"] == "PASS" else 1
  376. if state["phase"] != "submit":
  377. return 0 # An existing launcher already owns this immutable run.
  378. if state.get("cancel_requested"):
  379. result_code = 130
  380. else:
  381. state.update(phase="container_start")
  382. save_status(folder, state)
  383. if result_code == 130:
  384. return finish(folder, result_code, None)
  385. info = manager.inspect()
  386. if not info or not info["State"]["Running"] or info["HostConfig"]["PidMode"] != "host":
  387. raise RuntimeError("persistent container must be running with host PID namespace")
  388. if source_binding(spec["workspace"]) != {key: spec[key] for key in ("workspace", "commit", "tree")}:
  389. raise RuntimeError("source snapshot changed after submission")
  390. with (folder / "stdout.log").open("w") as stdout, (folder / "stderr.log").open("w") as stderr:
  391. process = subprocess.Popen(["podman", "exec", "--workdir", spec["workspace"], spec["container"],
  392. "python3", str(Path(__file__).resolve()), "_execute", str(folder)],
  393. stdout=stdout, stderr=stderr)
  394. attach(folder, manager, process)
  395. result_code = process.wait()
  396. with lock(folder / ".lock"):
  397. state = read(folder / "RUN-STATUS.json")
  398. if state.get("job_cgroup") and populated(state["job_cgroup"]):
  399. reason = "command left background processes; all job processes were terminated"
  400. kill_job_group(state)
  401. return finish(folder, result_code, reason)
  402. except Exception as error:
  403. reason = str(error)
  404. with lock(folder / ".lock"):
  405. state = read(folder / "RUN-STATUS.json")
  406. kill_job_group(state)
  407. if not state.get("job_cgroup") and (folder / "PROCESS.json").exists():
  408. binding = read(folder / "PROCESS.json")
  409. if binding["boot_id"] == boot_id() and pid_start(binding["pid"]) == binding["start_ticks"]:
  410. os.kill(binding["pid"], signal.SIGKILL)
  411. if process:
  412. try:
  413. process.wait(timeout=10)
  414. except subprocess.TimeoutExpired:
  415. process.kill()
  416. process.wait()
  417. return finish(folder, result_code, reason)
  418. def finish(folder, code, reason):
  419. with lock(folder / ".lock"):
  420. state = read(folder / "RUN-STATUS.json")
  421. if state["status"] in TERMINAL:
  422. return 0 if state["status"] == "PASS" else 1
  423. status = "CANCELLED" if state.get("cancel_requested") else ("PASS" if code == 0 and not reason else "FAIL")
  424. artifacts = artifact_inventory(folder)
  425. state.update(status=status, phase="finished", exit_code=code, reason=reason,
  426. finished_utc=now(), artifacts=artifacts)
  427. save_status(folder, state)
  428. return 0 if status == "PASS" else 1
  429. def execute(folder):
  430. """Container handshake: no task process starts before host cgroup attachment."""
  431. atomic(folder / "PROCESS.json", {"pid": os.getpid(), "start_ticks": pid_start(os.getpid()), "boot_id": boot_id()})
  432. deadline = time.monotonic() + 40
  433. while not (folder / "GO").exists():
  434. if time.monotonic() > deadline:
  435. raise RuntimeError("host did not grant job execution")
  436. time.sleep(.05)
  437. spec = read(folder / "SPEC.json")
  438. environment = dict(os.environ, PROD2U_RUN_DIR=str(folder), PROD2U_RUN_ID=folder.name)
  439. return subprocess.run(spec["command"], env=environment).returncode
  440. def main(argv=None):
  441. for stream in (sys.stdout, sys.stderr):
  442. if hasattr(stream, "reconfigure"):
  443. stream.reconfigure(encoding="utf-8")
  444. argv = list(sys.argv[1:] if argv is None else argv)
  445. parser = argparse.ArgumentParser(description=__doc__)
  446. parser.add_argument("--run-root", type=Path, default="/data/prod2u/runs")
  447. parser.add_argument("--ssh-runner", help="exact remote remote_job.py path; use the existing edk2-uefi-lab SSH configuration")
  448. parser.add_argument("--fetch-root", type=Path, help="local failed-log directory (default: TEMP/prod2u-thermal/analysis)")
  449. sub = parser.add_subparsers(dest="action", required=True)
  450. for action, help_text in (("submit", "run an explicit command"),
  451. ("quick", "run current firmware RTL diagnostics; not Full acceptance"),
  452. ("td", "run native firmware synthesis/place/route/bitgen"),
  453. ("full", "run an explicit Full suite command under the heavy lock")):
  454. entry = sub.add_parser(action, help=help_text)
  455. entry.add_argument("run_id")
  456. for name in ("snapshot-id", "target", "toolchain-id", "workspace"):
  457. entry.add_argument("--" + name, required=True)
  458. if action == 'submit':
  459. entry.add_argument('--task', required=True)
  460. entry.add_argument("--container", default="prod2u-dev")
  461. entry.add_argument("--heavy", action="store_true")
  462. entry = sub.add_parser('snapshot', help='create or verify a clean self-contained exact Git clone')
  463. entry.add_argument('--repository', default='/data/prod2u/git/cpld-temperature-control.git')
  464. entry.add_argument('--workspace', required=True)
  465. entry.add_argument('--commit', required=True)
  466. sub.add_parser('sync', help='push local HEAD to the configured LAN Git remote')
  467. for action in ('doctor', 'container-up', 'container-stop', 'container-down', 'container-recreate', 'container-status'):
  468. entry = sub.add_parser(action, help='forward to the existing persistent container lifecycle tool')
  469. entry.add_argument('--container', default='prod2u-dev')
  470. entry.add_argument('--workspace', help='exact bind source for container creation/recreation')
  471. for name in ("status", "cancel", "logs", "fetch"):
  472. sub.add_parser(name).add_argument("run_id")
  473. for name in ("_launch", "_execute"):
  474. sub.add_parser(name).add_argument("folder", type=Path)
  475. boundary = argv.index("--") if "--" in argv else len(argv)
  476. args = parser.parse_args(argv[:boundary])
  477. args.command = argv[boundary+1:]
  478. if args.command and args.action not in ("submit", "full"):
  479. parser.error("only submit/full accept a command after --")
  480. try:
  481. if args.action == 'sync':
  482. if args.ssh_runner:
  483. raise ValueError('sync runs in the local source tree; omit --ssh-runner')
  484. environment = dict(os.environ)
  485. null = 'NUL' if sys.platform == 'win32' else '/dev/null'
  486. environment['GIT_SSH_COMMAND'] = ('ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=' + null +
  487. ' -o GlobalKnownHostsFile=' + null + ' -o UpdateHostKeys=no -o ConnectTimeout=10')
  488. return subprocess.run(['git', '-C', str(ROOT), 'push', 'lan', 'HEAD'], env=environment).returncode
  489. if args.ssh_runner:
  490. remaining = argv[:boundary]
  491. for option in ("--ssh-runner", "--fetch-root"):
  492. if option in remaining:
  493. index = remaining.index(option)
  494. del remaining[index:index+2]
  495. else:
  496. remaining = [x for x in remaining if not x.startswith(option + "=")]
  497. remaining += argv[boundary:]
  498. command = shlex.join(["python3", args.ssh_runner, *remaining])
  499. null = "NUL" if sys.platform == "win32" else "/dev/null"
  500. ssh = ["ssh", "-n", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=" + null,
  501. "-o", "GlobalKnownHostsFile=" + null, "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10",
  502. "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "edk2-uefi-lab", command]
  503. # Windows OpenSSH keeps an inherited stdin pipe handle open after the
  504. # remote command exits, hanging the caller; never let ssh see our stdin.
  505. response = subprocess.run(ssh, stdin=subprocess.DEVNULL,
  506. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  507. if response.stderr:
  508. sys.stderr.buffer.write(response.stderr)
  509. if response.returncode or args.action == "logs" or args.action == 'doctor' or args.action.startswith('container-'):
  510. sys.stdout.buffer.write(response.stdout)
  511. return response.returncode
  512. result = json.loads(response.stdout)
  513. code = 0
  514. if result.get("status") in TERMINAL - {"PASS"} or args.action == "fetch":
  515. try:
  516. result["failure_download"] = fetch_failure(result, args.ssh_runner, args.run_root.as_posix(), args.fetch_root)
  517. except Exception as error:
  518. result["failure_download"] = {"status": "FAIL", "error": str(error)}
  519. code = 3
  520. print(json.dumps(result, indent=2, ensure_ascii=False))
  521. return code
  522. if sys.platform != "linux" or os.geteuid() != 0:
  523. raise ValueError("execute on the authorized Linux host as root, or use --ssh-runner")
  524. if args.action == "_execute":
  525. return execute(args.folder)
  526. if Path("/run/.containerenv").exists():
  527. raise ValueError("submit/status/cancel require the Linux Podman host")
  528. if args.action == 'doctor' or args.action.startswith('container-'):
  529. command = ['--name', args.container]
  530. if args.workspace:
  531. command += ['--workspace', args.workspace]
  532. return container_main(command + [args.action.removeprefix('container-')])
  533. if args.action == 'snapshot':
  534. print(json.dumps(snapshot(args.repository, args.workspace, args.commit), indent=2))
  535. return 0
  536. prepare_alias(args)
  537. if args.action == "_launch":
  538. return launch(args.folder)
  539. if args.action == "submit":
  540. result = submit(args)
  541. else:
  542. folder = job_dir(args.run_root, args.run_id)
  543. if args.action == "cancel":
  544. result = cancel(folder)
  545. else:
  546. result = refresh(folder)
  547. if args.action == "logs":
  548. for name in result["logs"]:
  549. path = folder / name
  550. if path.exists():
  551. print("== " + name + " ==")
  552. print(path.read_text(encoding="utf-8", errors="replace"), end="")
  553. return 0
  554. print(json.dumps(result, indent=2, ensure_ascii=False))
  555. return 0
  556. except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error:
  557. print(str(error), file=sys.stderr)
  558. return 2
  559. if __name__ == "__main__":
  560. raise SystemExit(main())