"""Runner: the detached process that owns one sanity run, and the helpers that start it.""" import fcntl import os import shlex import signal import socket import subprocess import sys import threading import time import traceback from .common import (ENTRY, HISTORY, JOB_CANCEL, JOB_FILE, JOB_LOCK, ME, RUNNER_LOG, RUNNER_OUT, Cancelled, StepFailed, fmt_dur, kill_group, last_line, read_json, sha1_file, write_json) class Runner(object): def __init__(self, flow): self.flow = flow self.jp = flow.path(JOB_FILE) self.lk = threading.RLock() self.job = None self.child = None self.stop = False self.done = False def log(self, msg): line = "%s %s" % (time.strftime("%H:%M:%S"), msg) with open(self.flow.path(RUNNER_LOG), "a") as fh: fh.write(line + "\n") def save(self): with self.lk: self.job["heartbeat"] = time.time() write_json(self.jp, self.job) def step(self, key): for s in self.job["steps"]: if s["key"] == key: return s return {} def begin(self, key, detail=""): with self.lk: s = self.step(key) s.update(status="running", t0=time.time(), detail=detail) self.job["phase"] = key self.log(">> %s" % s.get("label", key)) self.save() def end(self, key, status="done", detail=None): with self.lk: s = self.step(key) s.update(status=status, t1=time.time()) if detail is not None: s["detail"] = detail self.log("<< %s: %s%s" % (s.get("label", key), status, " (%s)" % detail if detail else "")) self.save() def fail(self, key, detail): self.end(key, "failed", detail) raise StepFailed(detail) def cancelled(self): return self.stop or os.path.exists(self.flow.path(JOB_CANCEL)) def check_cancel(self): if self.cancelled(): raise Cancelled() def cmd(self, fn, *args, **kw): self.log(" $ %s %s" % (fn, " ".join(shlex.quote(a) for a in args))) rc, out = self.flow.act(fn, *args, **kw) for line in out.splitlines(): self.log(" " + line) return rc, out def _signal(self, signum, frame): self.stop = True if self.child is not None: try: os.killpg(self.child.pid, signal.SIGTERM) except OSError: pass def _heartbeat(self): while not self.done: time.sleep(5) if not self.done: try: self.save() except OSError: pass def main(self): lockfh = open(self.flow.path(JOB_LOCK), "a") try: fcntl.flock(lockfh, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: print("dsflow_tui: another sanity runner is active in this workspace") return 1 self.job = read_json(self.jp) if not self.job or self.job.get("status") != "queued": print("dsflow_tui: no queued job in %s" % self.jp) return 1 for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): signal.signal(sig, self._signal) open(self.flow.path(RUNNER_LOG), "w").close() self.job.update(status="running", pid=os.getpid(), host=socket.gethostname(), started=time.time()) self.log("run %s by %s on %s" % (self.job["id"], ME, socket.gethostname())) self.save() threading.Thread(target=self._heartbeat, daemon=True).start() # The terminal status is saved last: readers treat it as "locks are settled". final = "error" try: self.execute() final = "passed" except Cancelled: final, self.job["summary"] = "cancelled", "cancelled by user" except StepFailed as e: final, self.job["summary"] = "failed", str(e) except Exception as e: # noqa - the runner must always release locks self.job["summary"] = "runner error: %s" % e self.log(traceback.format_exc()) finally: with self.lk: for s in self.job["steps"]: if s["status"] == "running": s.update(status="cancelled" if final == "cancelled" else "failed", t1=time.time()) self.release_locks() with self.lk: for s in self.job["steps"]: if s["status"] == "pending": s["status"] = "skipped" self.job["finished"] = time.time() self.job["phase"] = "finished" self.job["status"] = final self.done = True self.log("finished: %s - %s" % (final, self.job.get("summary", ""))) self.save() try: os.remove(self.flow.path(JOB_CANCEL)) except OSError: pass return 0 if final == "passed" else 1 def execute(self): j, flow = self.job, self.flow mods, news = j["files"], j["new_files"] self.begin("validate") missing = [f for f in news if not os.path.exists(flow.wpath(f))] if missing: self.fail("validate", "new file(s) missing: %s" % ", ".join(missing)) if mods: stale = flow.stale_of(mods) if stale: self.fail("validate", "checked in by someone else since you started (dsflow rebase): %s" % ", ".join("%s %s->%s" % (f, v[0], v[1]) for f, v in sorted(stale.items()))) holders = flow.holders(mods) others = dict((f, h) for f, h in holders.items() if h and h != ME) if others: self.fail("validate", "locked by others: %s" % ", ".join("%s (%s)" % i for i in sorted(others.items()))) j["preheld"] = sorted(f for f, h in holders.items() if h == ME) self.end("validate", detail="%d modified, %d new" % (len(mods), len(news))) if mods: self.begin("lock") for f in mods: self.check_cancel() if f in j["preheld"]: continue rc, out = self.cmd("ds_lock", f) if rc != 0: self.fail("lock", "could not lock %s: %s" % (f, last_line(out) or "rc=%d" % rc)) with self.lk: j["locked_by_job"].append(f) self.save() self.end("lock", detail="%d locked, %d already yours" % (len(j["locked_by_job"]), len(j["preheld"]))) if j.get("refresh"): self.check_cancel() self.begin("refresh") rc, out = self.cmd("ds_refresh", timeout=7200) if rc != 0: self.fail("refresh", "refresh to %s failed: %s" % (flow.trunk, last_line(out))) self.end("refresh") j["hashes"] = dict((f, sha1_file(flow.wpath(f))) for f in mods + news) self.save() hist = read_json(flow.path(HISTORY), {}) for cfg in j["configs"]: self.check_cancel() key = "sanity:" + cfg logp = flow.path("sanity_%s.log" % cfg) self.step(key)["log"] = logp self.begin(key) rc = self.run_sanity(cfg, logp) if rc is None: raise Cancelled() if rc != 0: self.fail(key, "sanity FAILED for %s (exit %d) - see %s" % (cfg, rc, os.path.relpath(logp, flow.ws))) dur = time.time() - self.step(key)["t0"] hist[cfg] = dur write_json(flow.path(HISTORY), hist) self.end(key, detail="passed in %s" % fmt_dur(dur)) j["sanity_ok"] = True j["sanity_epoch"] = time.time() self.save() try: if flow.write_bash_stamp(mods + news, j["configs"]): self.log("wrote .dsflow/sanity.stamp - `dsflow checkin` will accept this run too") except OSError as e: self.log("could not write sanity.stamp: %s" % e) if j["mode"] != "checkin": j["summary"] = "sanity passed on %s - locks released; check in within %s (key c)" % ( " ".join(j["configs"]), fmt_dur(flow.max_age)) return self.begin("verify") changed = [f for f in mods + news if sha1_file(flow.wpath(f)) != j["hashes"].get(f)] if changed: self.fail("verify", "edited while sanity ran, NOT checked in: %s" % ", ".join(changed)) stale = flow.stale_of(mods) if stale: self.fail("verify", "went stale on Trunk during the run, NOT checked in: %s" % ", ".join(sorted(stale))) self.end("verify") self.begin("checkin") ok, msg = flow.checkin(j["msg"], mods, news, self.log) if not ok: self.fail("checkin", msg) self.end("checkin", detail=msg) j["checked_in"] = True if j.get("tag"): self.begin("tag") rc, out = self.cmd("ds_tag", j["tag"], *(mods + news)) if rc != 0: self.fail("tag", "checked in, but tagging '%s' failed: %s" % (j["tag"], last_line(out))) self.end("tag", detail="%d file(s)" % len(mods + news)) j["summary"] = "sanity passed on %s - checked in %d file(s)%s" % ( " ".join(j["configs"]), len(mods + news), " and tagged %s" % j["tag"] if j.get("tag") else "") def run_sanity(self, cfg, logp): """Returns the exit code, or None if the run was cancelled.""" flow, cmd = self.flow, self.job.get("sanity_cmd") if cmd: snippet, args = 'eval "$1"', [cmd.replace("{cfg}", shlex.quote(cfg)).replace("{ws}", shlex.quote(flow.ws))] else: snippet, args = 'run_sanity "$1"', [cfg] with open(logp, "w") as fh: fh.write("# dsflow_tui sanity [%s] %s by %s\n# %s\n" % ( cfg, time.strftime("%Y-%m-%d %H:%M:%S"), ME, args[0] if cmd else "run_sanity %s" % cfg)) self.log(" sanity [%s] -> %s" % (cfg, logp)) with open(logp, "ab") as out: self.child = subprocess.Popen(flow.argv(snippet, args), stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, cwd=flow.ws, env=flow.env({"DSFLOW_CFG": cfg}), start_new_session=True) with self.lk: self.job["child_pid"] = self.child.pid # lets the TUI stop it if this runner dies self.save() try: while True: rc = self.child.poll() if rc is not None: return rc if self.cancelled(): self.log(" cancelling sanity [%s]" % cfg) kill_group(self.child) return None time.sleep(0.5) finally: self.child = None with self.lk: self.job.pop("child_pid", None) def release_locks(self): j = self.job mine = [] if j.get("locked_by_job"): self.begin("unlock") holders = self.flow.holders(j["locked_by_job"]) mine = [f for f in j["locked_by_job"] if holders.get(f) == ME] if mine: rc, out = self.cmd("ds_unlock", *mine) if rc != 0: j["summary"] = "%s | WARNING: could not release locks on %s: %s" % ( j.get("summary", ""), ", ".join(mine), last_line(out)) self.end("unlock", "failed", "release by hand: dsflow release %s" % " ".join(mine)) return j["released"] = mine self.end("unlock", detail="%d released" % len(mine) if mine else "already released by check-in") else: with self.lk: s = self.step("unlock") s.update(status="skipped", detail="run took no locks") def new_job(flow, mods, news, configs, mode, msg, tag, refresh): hist = read_json(flow.path(HISTORY), {}) steps = [dict(key="validate", label="Check freshness & locks")] if mods: steps.append(dict(key="lock", label="Lock %d file(s)" % len(mods))) if refresh: steps.append(dict(key="refresh", label="Refresh to %s" % flow.trunk)) for cfg in configs: steps.append(dict(key="sanity:" + cfg, label="Sanity %s" % cfg, kind="sanity", est=hist.get(cfg))) if mode == "checkin": steps.append(dict(key="verify", label="Verify files unchanged")) steps.append(dict(key="checkin", label="Check in %d file(s)" % (len(mods) + len(news)))) if tag: steps.append(dict(key="tag", label="Tag %s" % tag)) steps.append(dict(key="unlock", label="Release run locks")) for s in steps: s.setdefault("kind", "action") s.update(status="pending", detail="", t0=None, t1=None) now = time.time() return dict(id=time.strftime("%Y%m%d-%H%M%S"), user=ME, host=socket.gethostname(), created=now, heartbeat=now, status="queued", phase="queued", mode=mode, msg=msg, tag=tag, refresh=refresh, files=mods, new_files=news, configs=configs, sanity_cmd=flow.sanity_cmd, locked_by_job=[], preheld=[], hashes={}, steps=steps, summary="") def spawn_runner(flow, job): try: os.remove(flow.path(JOB_CANCEL)) except OSError: pass write_json(flow.path(JOB_FILE), job) argv = [sys.executable, ENTRY, "--ws", flow.ws, "--conf", flow.conf] if flow.cli_sanity_cmd: argv += ["--sanity-cmd", flow.cli_sanity_cmd] argv.append("_runjob") with open(flow.path(RUNNER_OUT), "ab") as out: subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, cwd=flow.ws, env=flow.env(), start_new_session=True, close_fds=True) def runner_alive(flow): """True if some process holds the runner flock (same host / working NFS locks).""" try: with open(flow.path(JOB_LOCK), "a") as fh: fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.flock(fh, fcntl.LOCK_UN) return False except OSError: return True