remote_job.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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
  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 new_spec(args):
  72. command = args.command[1:] if args.command and args.command[0] == "--" else args.command
  73. if not command:
  74. raise ValueError("submit requires a nonempty command after --")
  75. for value in (args.snapshot_id, args.target, args.task, args.toolchain_id):
  76. if not value.strip():
  77. raise ValueError("snapshot/target/task/toolchain identifiers must not be empty")
  78. return {**source_binding(args.workspace), "snapshot_id": args.snapshot_id, "target": args.target,
  79. "task": args.task, "toolchain_id": args.toolchain_id, "container": args.container,
  80. "heavy": args.heavy or args.task in ("td", "formal", "build", "full", "package"),
  81. "command": command, "runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
  82. def save_status(folder, state):
  83. if state["status"] in TERMINAL - {"PASS"} and not state.get("failure_bundle") and not state.get("failure_bundle_error"):
  84. if "artifacts" not in state:
  85. state["artifacts"] = artifact_inventory(folder)
  86. try:
  87. state["failure_bundle"] = failure_bundle(folder, state)
  88. state["artifacts"].append({key: state["failure_bundle"][key] for key in ("path", "size", "sha256")})
  89. except Exception as error:
  90. # Diagnostic collection must not replace the original exit/status.
  91. state["failure_bundle_error"] = str(error)
  92. atomic(folder / "RUN-STATUS.json", state)
  93. if state["status"] in TERMINAL:
  94. atomic(folder / "RESULT.json", state)
  95. def artifact_inventory(folder):
  96. artifacts = []
  97. reserved = {"RUN-STATUS.json", "RESULT.json", ".lock", "GO", BUNDLE_NAME, BUNDLE_NAME + ".partial"}
  98. for path in sorted(folder.rglob("*")):
  99. relative = path.relative_to(folder).as_posix()
  100. if path.is_file() and not path.is_symlink() and relative not in reserved:
  101. with path.open("rb") as stream:
  102. sha = hashlib.file_digest(stream, "sha256").hexdigest()
  103. artifacts.append({"path": relative, "size": path.stat().st_size, "sha256": sha})
  104. return artifacts
  105. def failure_bundle(folder, state):
  106. """Collect native reports and small waveforms; index large remote artifacts."""
  107. destination = folder / BUNDLE_NAME
  108. partial = folder / (BUNDLE_NAME + ".partial")
  109. if destination.exists() or partial.exists():
  110. raise RuntimeError("reserved diagnostic archive already exists; retained unchanged")
  111. native = {".log", ".rpt", ".report", ".timing", ".area", ".xml", ".json", ".txt", ".sby"}
  112. rows = []
  113. budget = DIAGNOSTIC_LIMIT
  114. # Collect console failures before optional reports when logs are very large.
  115. artifacts = sorted(state["artifacts"], key=lambda item: (item["path"] not in ("stdout.log", "stderr.log", "SPEC.json"), item["path"]))
  116. with zipfile.ZipFile(partial, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
  117. for item in artifacts:
  118. path = folder / item["path"]
  119. suffix = path.suffix.lower()
  120. row = dict(item)
  121. if suffix in (".vcd", ".fst") and item["size"] > SMALL_WAVE_LIMIT:
  122. row["disposition"] = "remote_large_waveform"
  123. elif suffix not in native | {".vcd", ".fst"}:
  124. row["disposition"] = "remote_non_diagnostic_artifact"
  125. elif item["size"] <= budget:
  126. member = "files/" + item["path"]
  127. archive.write(path, member)
  128. row.update(disposition="complete", member=member, included_bytes=item["size"])
  129. budget -= item["size"]
  130. elif suffix in native and budget:
  131. length = min(budget, 2 * 1024 * 1024)
  132. with path.open("rb") as stream:
  133. stream.seek(-length, os.SEEK_END)
  134. tail = stream.read(length)
  135. member = "tails/" + item["path"]
  136. archive.writestr(member, tail)
  137. row.update(disposition="tail_only", member=member, included_bytes=length,
  138. included_sha256=hashlib.sha256(tail).hexdigest())
  139. budget -= length
  140. else:
  141. row["disposition"] = "remote_bundle_size_limit"
  142. rows.append(row)
  143. index = {"schema": "prod2u-failure-index-v1", "run_id": state.get("run_id", folder.name),
  144. "job_status": state["status"], "exit_code": state.get("exit_code"), "reason": state.get("reason"),
  145. "spec": state.get("spec"), "hardware": "NOT_RUN", "uncompressed_file_limit": DIAGNOSTIC_LIMIT,
  146. "small_waveform_limit": SMALL_WAVE_LIMIT, "artifacts": rows,
  147. "scope": "Included bytes only; large waves and explicitly indexed omissions remain on the remote host."}
  148. archive.writestr("FAILURE-INDEX.json", json.dumps(index, indent=2, ensure_ascii=False).encode())
  149. partial.replace(destination)
  150. with destination.open("rb") as stream:
  151. sha = hashlib.file_digest(stream, "sha256").hexdigest()
  152. return {"path": BUNDLE_NAME, "size": destination.stat().st_size, "sha256": sha,
  153. "complete_files": sum(row["disposition"] == "complete" for row in rows),
  154. "scope": "bounded failed-stage diagnostics; see FAILURE-INDEX.json for omitted/tail-only data"}
  155. def fetch_failure(result, remote_runner, remote_root, local_root=None):
  156. from tools.remote_transfer import SSH, download
  157. bundle = result.get("failure_bundle")
  158. if not bundle:
  159. return {"status": "UNAVAILABLE", "reason": result.get("failure_bundle_error", "this result has no diagnostic archive")}
  160. if bundle["path"] != BUNDLE_NAME or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,95}", result["run_id"]):
  161. raise ValueError("invalid remote diagnostic identity")
  162. root = Path(local_root) if local_root else Path(tempfile.gettempdir()) / "prod2u-thermal/analysis"
  163. folder = (root / ("run-" + result["run_id"])).resolve()
  164. remote = str(PurePosixPath(remote_root) / result["run_id"] / BUNDLE_NAME)
  165. worker = str(PurePosixPath(remote_runner).parent / "remote_transfer.py")
  166. receipt = download(SSH(worker), remote, folder / BUNDLE_NAME, bundle["sha256"])
  167. if receipt["size"] != bundle["size"]:
  168. raise ValueError("diagnostic archive size differs from job result")
  169. atomic(folder / "TRANSFER-RECEIPT.json", receipt)
  170. return {"status": "PASS", "path": receipt["destination"], "sha256": receipt["sha256"],
  171. "transferred_chunks": receipt["transferred_chunks"], "reused_chunks": receipt["reused_chunks"],
  172. "scope": receipt["scope"]}
  173. def populated(group):
  174. path = CGROOT / group.lstrip("/") / "cgroup.events"
  175. try:
  176. return "populated 1" in path.read_text().splitlines()
  177. except FileNotFoundError:
  178. return False
  179. def kill_job_group(state):
  180. group = state.get("job_cgroup")
  181. parent = state.get("container_cgroup")
  182. if not group:
  183. return
  184. name = state.get("cgroup_name", "prod2u-job-" + state["identity"][:24])
  185. if not re.fullmatch(r"prod2u-job-[a-f0-9]{24}", name):
  186. raise RuntimeError("invalid job cgroup name")
  187. expected = str(Path(parent) / name) if parent else None
  188. if state.get("boot_id") != boot_id() or group != expected or ".." in Path(group).parts:
  189. raise RuntimeError("refuse stale or mismatched job cgroup")
  190. target = CGROOT / group.lstrip("/") / "cgroup.kill"
  191. if target.exists():
  192. target.write_text("1")
  193. def refresh(folder):
  194. with lock(folder / ".lock"):
  195. state = read(folder / "RUN-STATUS.json")
  196. if state["status"] in TERMINAL:
  197. return state
  198. reason = None
  199. if state["boot_id"] != boot_id():
  200. reason = "host rebooted; old process identities are invalid"
  201. elif state.get("job_cgroup") and populated(state["job_cgroup"]):
  202. return state
  203. else:
  204. unit = subprocess.run(["systemctl", "show", state["unit"], "-p", "ActiveState", "--value"],
  205. text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  206. if unit.returncode:
  207. raise RuntimeError("cannot inspect job unit: " + unit.stderr.strip())
  208. if unit.stdout.strip() not in ("active", "activating", "reloading", "deactivating"):
  209. reason = "worker unit is inactive and no job processes remain"
  210. if reason:
  211. state.update(status="INTERRUPTED", reason=reason, finished_utc=now(), exit_code=None)
  212. save_status(folder, state)
  213. return state
  214. def submit(args):
  215. folder = job_dir(args.run_root, args.run_id)
  216. folder.parent.mkdir(parents=True, exist_ok=True)
  217. spec = new_spec(args)
  218. with lock(folder.parent / ".submit.lock"):
  219. if folder.exists():
  220. old = read(folder / "SPEC.json")
  221. if old != spec:
  222. raise ValueError("RUN_ID_CONFLICT: existing run has different inputs; use a new run_id")
  223. return refresh(folder)
  224. folder.mkdir()
  225. atomic(folder / "SPEC.json", spec)
  226. state = {"schema": "prod2u-remote-job-v2", "run_id": args.run_id, "identity": digest(spec),
  227. "status": "QUEUED", "phase": "submit", "boot_id": boot_id(), "submitted_utc": now(),
  228. "unit": unit_name(folder), "spec": spec, "logs": ["stdout.log", "stderr.log", "worker.log"],
  229. "hardware": "NOT_RUN"}
  230. save_status(folder, state)
  231. command = ["systemd-run", "--quiet", "--collect", "--service-type=exec", "--unit=" + state["unit"],
  232. "--property=StandardOutput=append:" + str(folder / "worker.log"),
  233. "--property=StandardError=append:" + str(folder / "worker.log"),
  234. sys.executable, str(Path(__file__).resolve()), "_launch", str(folder)]
  235. result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  236. if result.returncode:
  237. with lock(folder / ".lock"):
  238. state.update(status="SUBMIT_FAILED", exit_code=result.returncode, reason=result.stderr.strip(), finished_utc=now())
  239. save_status(folder, state)
  240. return read(folder / "RUN-STATUS.json")
  241. def cancel(folder):
  242. # Serialize with submission so cancellation cannot precede systemd dispatch.
  243. with lock(folder.parent / ".submit.lock"):
  244. return cancel_dispatched(folder)
  245. def cancel_dispatched(folder):
  246. stop_unit = False
  247. with lock(folder / ".lock"):
  248. state = read(folder / "RUN-STATUS.json")
  249. if state["status"] in TERMINAL:
  250. return state
  251. if state["boot_id"] != boot_id():
  252. state.update(status="INTERRUPTED", reason="host rebooted", exit_code=None, finished_utc=now())
  253. else:
  254. stop_unit = state["phase"] == "submit" and not state.get("job_cgroup")
  255. state.update(cancel_requested=True, phase="cancelling")
  256. if stop_unit:
  257. state.update(status="CANCELLED", exit_code=130, finished_utc=now(),
  258. reason="cancelled before command startup")
  259. save_status(folder, state)
  260. kill_job_group(state)
  261. # Before attachment, _launch observes this flag and never opens the gate.
  262. save_status(folder, state)
  263. if stop_unit:
  264. if state["unit"] != unit_name(folder):
  265. raise RuntimeError("job unit identity mismatch")
  266. subprocess.run(["systemctl", "stop", state["unit"]], check=True)
  267. return state
  268. def attach(folder, manager, process):
  269. deadline = time.monotonic() + 30
  270. ready = folder / "PROCESS.json"
  271. while not ready.exists():
  272. if process.poll() is not None:
  273. raise RuntimeError("container worker exited before its startup handshake")
  274. if time.monotonic() > deadline:
  275. raise RuntimeError("container worker startup handshake timed out")
  276. time.sleep(.05)
  277. binding = read(ready)
  278. if binding["boot_id"] != boot_id() or pid_start(binding["pid"]) != binding["start_ticks"]:
  279. raise RuntimeError("container worker process identity mismatch")
  280. with lock(folder / ".lock"):
  281. state = read(folder / "RUN-STATUS.json")
  282. info = manager.inspect()
  283. parent = info["State"]["CgroupPath"]
  284. name = state["unit"].removesuffix(".service")
  285. group = str(Path(parent) / name)
  286. path = CGROOT / group.lstrip("/")
  287. path.mkdir()
  288. state.update(job_cgroup=group, cgroup_name=name, container_cgroup=parent,
  289. process=binding, container_id=info["Id"], container_image_id=info["Image"])
  290. save_status(folder, state)
  291. (path / "cgroup.procs").write_text(str(binding["pid"]))
  292. if binding["pid"] not in [int(x) for x in (path / "cgroup.procs").read_text().split()]:
  293. raise RuntimeError("worker was not attached to its job cgroup")
  294. if state.get("cancel_requested"):
  295. kill_job_group(state)
  296. else:
  297. state.update(status="RUNNING", phase="command", started_utc=now())
  298. save_status(folder, state)
  299. (folder / "GO").touch()
  300. def launch(folder):
  301. spec = read(folder / "SPEC.json")
  302. manager = Controller(spec["container"], Path("/data/prod2u"))
  303. # Same acquisition order as lifecycle changes. Keep these locks through
  304. # failure cleanup so container recreation cannot race cancellation.
  305. with manager.lock(shared=True, heavy=spec["heavy"]):
  306. return launch_locked(folder, manager)
  307. def launch_locked(folder, manager):
  308. spec = read(folder / "SPEC.json")
  309. process = None
  310. result_code = None
  311. reason = None
  312. def interrupted(signum, frame):
  313. raise RuntimeError("worker received signal " + str(signum))
  314. signal.signal(signal.SIGTERM, interrupted)
  315. signal.signal(signal.SIGINT, interrupted)
  316. try:
  317. with lock(folder / ".lock"):
  318. state = read(folder / "RUN-STATUS.json")
  319. if state["status"] in TERMINAL:
  320. return 0 if state["status"] == "PASS" else 1
  321. if state["phase"] != "submit":
  322. return 0 # An existing launcher already owns this immutable run.
  323. if state.get("cancel_requested"):
  324. result_code = 130
  325. else:
  326. state.update(phase="container_start")
  327. save_status(folder, state)
  328. if result_code == 130:
  329. return finish(folder, result_code, None)
  330. info = manager.inspect()
  331. if not info or not info["State"]["Running"] or info["HostConfig"]["PidMode"] != "host":
  332. raise RuntimeError("persistent container must be running with host PID namespace")
  333. if source_binding(spec["workspace"]) != {key: spec[key] for key in ("workspace", "commit", "tree")}:
  334. raise RuntimeError("source snapshot changed after submission")
  335. with (folder / "stdout.log").open("w") as stdout, (folder / "stderr.log").open("w") as stderr:
  336. process = subprocess.Popen(["podman", "exec", "--workdir", spec["workspace"], spec["container"],
  337. "python3", str(Path(__file__).resolve()), "_execute", str(folder)],
  338. stdout=stdout, stderr=stderr)
  339. attach(folder, manager, process)
  340. result_code = process.wait()
  341. with lock(folder / ".lock"):
  342. state = read(folder / "RUN-STATUS.json")
  343. if state.get("job_cgroup") and populated(state["job_cgroup"]):
  344. reason = "command left background processes; all job processes were terminated"
  345. kill_job_group(state)
  346. return finish(folder, result_code, reason)
  347. except Exception as error:
  348. reason = str(error)
  349. with lock(folder / ".lock"):
  350. state = read(folder / "RUN-STATUS.json")
  351. kill_job_group(state)
  352. if not state.get("job_cgroup") and (folder / "PROCESS.json").exists():
  353. binding = read(folder / "PROCESS.json")
  354. if binding["boot_id"] == boot_id() and pid_start(binding["pid"]) == binding["start_ticks"]:
  355. os.kill(binding["pid"], signal.SIGKILL)
  356. if process:
  357. try:
  358. process.wait(timeout=10)
  359. except subprocess.TimeoutExpired:
  360. process.kill()
  361. process.wait()
  362. return finish(folder, result_code, reason)
  363. def finish(folder, code, reason):
  364. with lock(folder / ".lock"):
  365. state = read(folder / "RUN-STATUS.json")
  366. if state["status"] in TERMINAL:
  367. return 0 if state["status"] == "PASS" else 1
  368. status = "CANCELLED" if state.get("cancel_requested") else ("PASS" if code == 0 and not reason else "FAIL")
  369. artifacts = artifact_inventory(folder)
  370. state.update(status=status, phase="finished", exit_code=code, reason=reason,
  371. finished_utc=now(), artifacts=artifacts)
  372. save_status(folder, state)
  373. return 0 if status == "PASS" else 1
  374. def execute(folder):
  375. """Container handshake: no task process starts before host cgroup attachment."""
  376. atomic(folder / "PROCESS.json", {"pid": os.getpid(), "start_ticks": pid_start(os.getpid()), "boot_id": boot_id()})
  377. deadline = time.monotonic() + 40
  378. while not (folder / "GO").exists():
  379. if time.monotonic() > deadline:
  380. raise RuntimeError("host did not grant job execution")
  381. time.sleep(.05)
  382. spec = read(folder / "SPEC.json")
  383. environment = dict(os.environ, PROD2U_RUN_DIR=str(folder), PROD2U_RUN_ID=folder.name)
  384. return subprocess.run(spec["command"], env=environment).returncode
  385. def main(argv=None):
  386. for stream in (sys.stdout, sys.stderr):
  387. if hasattr(stream, "reconfigure"):
  388. stream.reconfigure(encoding="utf-8")
  389. argv = list(sys.argv[1:] if argv is None else argv)
  390. parser = argparse.ArgumentParser(description=__doc__)
  391. parser.add_argument("--run-root", type=Path, default="/data/prod2u/runs")
  392. parser.add_argument("--ssh-runner", help="exact remote remote_job.py path; use the existing edk2-uefi-lab SSH configuration")
  393. parser.add_argument("--fetch-root", type=Path, help="local failed-log directory (default: TEMP/prod2u-thermal/analysis)")
  394. sub = parser.add_subparsers(dest="action", required=True)
  395. entry = sub.add_parser("submit")
  396. entry.add_argument("run_id")
  397. for name in ("snapshot-id", "target", "task", "toolchain-id", "workspace"):
  398. entry.add_argument("--" + name, required=True)
  399. entry.add_argument("--container", default="prod2u-dev")
  400. entry.add_argument("--heavy", action="store_true")
  401. for name in ("status", "cancel", "logs", "fetch"):
  402. sub.add_parser(name).add_argument("run_id")
  403. for name in ("_launch", "_execute"):
  404. sub.add_parser(name).add_argument("folder", type=Path)
  405. boundary = argv.index("--") if "--" in argv else len(argv)
  406. args = parser.parse_args(argv[:boundary])
  407. args.command = argv[boundary+1:]
  408. if args.command and args.action != "submit":
  409. parser.error("only submit accepts a command after --")
  410. try:
  411. if args.ssh_runner:
  412. remaining = argv[:boundary]
  413. for option in ("--ssh-runner", "--fetch-root"):
  414. if option in remaining:
  415. index = remaining.index(option)
  416. del remaining[index:index+2]
  417. else:
  418. remaining = [x for x in remaining if not x.startswith(option + "=")]
  419. remaining += argv[boundary:]
  420. command = shlex.join(["python3", args.ssh_runner, *remaining])
  421. null = "NUL" if sys.platform == "win32" else "/dev/null"
  422. ssh = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=" + null,
  423. "-o", "GlobalKnownHostsFile=" + null, "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10",
  424. "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "edk2-uefi-lab", command]
  425. response = subprocess.run(ssh, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  426. if response.stderr:
  427. sys.stderr.buffer.write(response.stderr)
  428. if response.returncode or args.action == "logs":
  429. sys.stdout.buffer.write(response.stdout)
  430. return response.returncode
  431. result = json.loads(response.stdout)
  432. code = 0
  433. if result.get("status") in TERMINAL - {"PASS"} or args.action == "fetch":
  434. try:
  435. result["failure_download"] = fetch_failure(result, args.ssh_runner, args.run_root.as_posix(), args.fetch_root)
  436. except Exception as error:
  437. result["failure_download"] = {"status": "FAIL", "error": str(error)}
  438. code = 3
  439. print(json.dumps(result, indent=2, ensure_ascii=False))
  440. return code
  441. if sys.platform != "linux" or os.geteuid() != 0:
  442. raise ValueError("execute on the authorized Linux host as root, or use --ssh-runner")
  443. if args.action == "_execute":
  444. return execute(args.folder)
  445. if Path("/run/.containerenv").exists():
  446. raise ValueError("submit/status/cancel require the Linux Podman host")
  447. if args.action == "_launch":
  448. return launch(args.folder)
  449. if args.action == "submit":
  450. result = submit(args)
  451. else:
  452. folder = job_dir(args.run_root, args.run_id)
  453. if args.action == "cancel":
  454. result = cancel(folder)
  455. else:
  456. result = refresh(folder)
  457. if args.action == "logs":
  458. for name in result["logs"]:
  459. path = folder / name
  460. if path.exists():
  461. print("== " + name + " ==")
  462. print(path.read_text(encoding="utf-8", errors="replace"), end="")
  463. return 0
  464. print(json.dumps(result, indent=2, ensure_ascii=False))
  465. return 0
  466. except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as error:
  467. print(str(error), file=sys.stderr)
  468. return 2
  469. if __name__ == "__main__":
  470. raise SystemExit(main())