"""Constants and small helpers shared by the runner, the CLI and the UI.""" import getpass import hashlib import json import os import signal import time VERSION = "2.0" # the launcher the runner is re-executed through (it sets up vendor/ on sys.path) ENTRY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dsflow_tui.py") ME = os.environ.get("USER") or getpass.getuser() JOB_FILE = "tui_job.json" # state of the current/last sanity run JOB_LOCK = "tui_job.lock" # flock held by the runner while it lives JOB_CANCEL = "tui_job.cancel" # touch to ask the runner to stop RUNNER_LOG = "tui_runner.log" # what the runner did, step by step RUNNER_OUT = "tui_runner.out" # runner stdout/stderr (crash traces) HISTORY = "tui_history.json" # last passing duration per config TERMINAL = ("passed", "failed", "cancelled", "error") HEARTBEAT_STALE = 60 # s without a runner heartbeat => runner gone class FlowError(Exception): pass class StepFailed(Exception): pass class Cancelled(Exception): pass def read_json(path, default=None): try: with open(path) as fh: return json.load(fh) except (OSError, ValueError): return default def write_json(path, data): tmp = "%s.%d.tmp" % (path, os.getpid()) with open(tmp, "w") as fh: json.dump(data, fh, indent=1, sort_keys=True) os.replace(tmp, path) def sha1_file(path): h = hashlib.sha1() try: with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) except OSError: return None return h.hexdigest() def norm(path): path = path.strip() while path.startswith("./"): path = path[2:] return path def fmt_dur(sec): if sec is None: return "" sec = int(max(0, sec)) if sec < 60: return "%ds" % sec if sec < 3600: return "%dm%02ds" % (sec // 60, sec % 60) return "%dh%02dm" % (sec // 3600, sec % 3600 // 60) def fmt_ago(epoch): return "%s ago" % fmt_dur(time.time() - epoch) if epoch else "never" def fmt_clock(epoch): return time.strftime("%H:%M:%S", time.localtime(epoch)) if epoch else "--:--:--" def last_line(text): lines = [l for l in (text or "").strip().splitlines() if l.strip()] return lines[-1].strip() if lines else "" def tail_lines(path, max_bytes=256 * 1024): try: with open(path, "rb") as fh: fh.seek(0, os.SEEK_END) size = fh.tell() fh.seek(max(0, size - max_bytes)) data = fh.read() except OSError: return None lines = data.decode("utf-8", "replace").replace("\r", "").expandtabs(4).split("\n") if size > max_bytes: lines = lines[1:] if lines and lines[-1] == "": lines.pop() return lines def job_state(job): """none | active | orphaned | done""" if not job: return "none" if job.get("status") in TERMINAL: return "done" if time.time() - job.get("heartbeat", job.get("created", 0)) > HEARTBEAT_STALE: return "orphaned" return "active" def kill_group(p, grace=10): for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, 5)): try: os.killpg(p.pid, sig) except OSError: return t_end = time.time() + wait while time.time() < t_end: if p.poll() is not None: return time.sleep(0.2)