"""The rules behind each UI action, kept free of Textual so they can be tested directly. Every function takes plain rows from a Snapshot and returns data or (ok, message); the UI decides how to show it. """ import os import signal import socket import time from .common import JOB_CANCEL, JOB_FILE, ME, fmt_dur, last_line, sha1_file, write_json def sanity_blockers(rows): """Reasons the marked changes can't go into a sanity run (empty list = fine).""" out = [] for r in rows: if r["stale"]: out.append("%s: %s -> %s on Trunk - rebase first (m)" % (r["path"], r["base"], r["latest"])) if r["holder"] and r["holder"] != ME: out.append("%s: locked by %s" % (r["path"], r["holder"])) if not r["exists"]: out.append("%s: registered as new but missing on disk" % r["path"]) return out def split_kinds(rows): """(modified paths, new paths) of Changes rows.""" return ([r["path"] for r in rows if r.get("kind") == "M"], [r["path"] for r in rows if r.get("kind") == "A"]) def sanity_form_error(values, all_configs): """Validation for the Run sanity dialog; None when the values are usable.""" if not values["configs"]: return "pick at least one config" if values["mode"] == "checkin": if not values["msg"].strip(): return "a check-in comment is required" if list(values["configs"]) != list(all_configs): return "check-in needs every config (%s)" % " ".join(all_configs) elif values["tag"]: return "tagging needs 'check in' (tagging now would tag the old vault versions)" return None def stamp_problems(flow, job, rows): """Why the last run does not cover these files as they are now (empty list = ok).""" if not job or job.get("status") != "passed" or not job.get("sanity_ok"): return ["no passing sanity run on record"] probs = [] if list(job["configs"]) != flow.configs: probs.append("last run covered %s, check-in needs %s" % (" ".join(job["configs"]), " ".join(flow.configs))) age = time.time() - job.get("sanity_epoch", 0) if age > flow.max_age: probs.append("last pass is %s old (limit %s)" % (fmt_dur(age), fmt_dur(flow.max_age))) for r in rows: h = job.get("hashes", {}).get(r["path"]) if h is None: probs.append("%s was not part of the last run" % r["path"]) elif sha1_file(flow.wpath(r["path"])) != h: probs.append("%s changed since the last run" % r["path"]) return probs def checkin_now(flow, job, rows, msg, tag, log): """Check in files a passing run covers, re-checking freshness and contents first.""" mods, news = split_kinds(rows) stale = flow.stale_of(mods) if stale: return False, "went stale on Trunk: %s - rebase first" % ", ".join(sorted(stale)) probs = stamp_problems(flow, job, rows) if probs: return False, probs[0] ok, text = flow.checkin(msg, mods, news, log) if ok and tag: rc, out = flow.act("ds_tag", tag, *(mods + news)) ok = rc == 0 text += " and tagged %s" % tag if ok else "; tagging failed: %s" % last_line(out) return ok, text def run_action(flow, fn, paths, label, log, lead=()): """One batch ds_* call (lock, unlock, tag, rebase) with its output logged; `lead` args go first (the tag).""" rc, out = flow.act(fn, *(list(lead) + list(paths))) for line in out.splitlines(): log(" " + line) if rc == 0: return True, "%s %d file(s): done" % (label, len(paths)) return False, "%s failed: %s" % (label, last_line(out) or "rc=%d" % rc) def request_cancel(flow): """Ask the runner to stop; it kills sanity and releases its locks itself.""" with open(flow.path(JOB_CANCEL), "w") as fh: fh.write(ME) def release_orphan(flow, job): """Clean up after a runner that stopped heart-beating: stop its sanity, release its locks.""" if job.get("child_pid") and job.get("host") == socket.gethostname(): try: os.killpg(job["child_pid"], signal.SIGTERM) except OSError: pass locked = job.get("locked_by_job", []) holders = flow.holders(locked) mine = [f for f in locked if holders.get(f) == ME] rc, out = flow.act("ds_unlock", *mine) if mine else (0, "") for s in job["steps"]: if s["status"] == "running": s.update(status="failed", t1=time.time(), detail="runner lost") elif s["status"] == "pending": s["status"] = "skipped" if s["key"] == "unlock" and rc == 0: s.update(status="done", detail="%d released from the TUI" % len(mine)) job.update(status="error", finished=time.time(), phase="finished", summary="runner lost; %d lock(s) released from the TUI" % len(mine)) write_json(flow.path(JOB_FILE), job) return rc == 0, job["summary"] if rc == 0 else "unlock failed: %s" % last_line(out)