#!/usr/bin/env python3 """A session's tape recorded by one build of pardes and replayed by another (docs/next-daemon.md, the remote bugs): a window's build replaying a terminal's session, a terminal's build a window's, a Linux build a FreeBSD one's. A replica of another build reads its session's units as this replay reads the tape, so what the tape carries must mean the same to both. python3 -B test/cross_replay.py ... a session of recorded here, replayed by it and by each replayer (a pardes-gui records in a hidden window) python3 -B test/cross_replay.py --record the session alone, its tapes left in (on the box, say) python3 -B test/cross_replay.py --replay ... each tape replayed alone The session meets the host's failures, whose errors cross by name: a Look of a fifo (a read the host refuses) and of a directory, a stat and a read under /os over 9P, a Save into a file as if it were a directory and a Restore of a dump that is not there (errors the host reports, anyerrors). """ import os import shutil import signal import subprocess import sys import tempfile import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from daemon import Window, alive, processes, wait_for # noqa: E402 from ninep import Client # noqa: E402 def record(binary, out): """One session of `binary`, recording into `out`: its tapes' paths.""" out = Path(out).resolve() out.mkdir(parents=True, exist_ok=True) # A short runtime directory: a socket's path holds 108 bytes at most. root = Path(tempfile.mkdtemp(prefix='xr-', dir=os.environ.get('TMPDIR', '/tmp'))) env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_STATE_HOME=str(root / 'state'), XDG_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/sh') (root / 'config' / 'pardes').mkdir(parents=True) (root / 'a.txt').write_text('hello\n') (root / 'dir').mkdir() (root / 'dir' / 'b.txt').write_text('in a directory\n') os.mkfifo(root / 'fifo') # No `MessageLinger 0` (test/daemon.py's sessions have it): with it, now # and then, a tape does not replay even by its own build, on main too # (pane 0's message differs a step after a failure is said). (root / 'config' / 'pardes' / 'init').write_text('') stem = Path(binary).name env['PARDES_RECORD'] = str(out / f'{stem}-') window = 'gui' in stem started = [] win = None try: if window: win = Window(root, 'rec', [binary, '--9p=xr', str(root / 'a.txt')], env) started.append(win.pid) else: started.append(subprocess.Popen([binary, '--detach=xr', str(root / 'a.txt')], env=env, cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True).pid) sock = root / 'pardes-9p-xr.sock' wait_for('the session\'s 9P socket', sock.exists, timeout=30) with Client(sock) as c: status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines()) started.append(int(status['pid'])) pane = next(int(row.split()[0]) for row in c.read('/index').splitlines() if row.split()[1] == b'text') for line in (f'Look {root / "fifo"}', f'Look {root / "dir"}', f'Save {root / "a.txt" / "x"}', f'Restore {root / "nothing.dump"}'): try: c.write(f'/pane/{pane}/exec', line.encode() + b'\n') except Exception: pass # said as the write's error: a failure is what is wanted time.sleep(.3) c.stat(f'/os{root / "a.txt"}') assert c.read(f'/os{root / "a.txt"}') == b'hello\n' for _ in range(2): # the failed Save left the text edited: Exit asks again try: c.write(f'/pane/{pane}/exec', b'Exit\n') except Exception: pass if win: win.close() wait_for('the session\'s end', lambda: not any(alive(p) for p in started), timeout=20) finally: for pid in started + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass shutil.rmtree(root, ignore_errors=True) tapes = sorted(out.glob(f'{stem}-*.tape')) assert tapes, f'{binary} wrote no tape into {out}' taped = b''.join(t.read_bytes() for t in tapes) for name in (b'NotAFile', b'NotDir', b'FileNotFound'): # the fifo's, the Save's, the Restore's assert name in taped, f'no {name} in the tapes' return tapes def replay(binary, tape): """`binary`'s replay of `tape`: its replicas' digests agree. A replica client never draws its session's frames, and only the replica that draws none (`headless`) must agree with another frontend's tape: the two that draw meet the other build's drawing (a window's, a terminal's).""" env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')} env['PARDES_REPLAY'] = str(tape) got = subprocess.run([binary], env=env, capture_output=True, timeout=600) said = got.stderr.decode(errors='replace') alike = ('gui' in Path(tape).name) == ('gui' in Path(binary).name) agreed = [line for line in said.splitlines() if line.endswith('digests agree')] assert ('headless replica' in ''.join(agreed)) and (not alike or (got.returncode == 0 and len(agreed) == 3)), \ f'{binary} replaying {tape}:\n{said[-3000:]}' print(f'cross_replay: {Path(binary).name} replayed {Path(tape).name}: ' + '; '.join(line.split(': ', 1)[1] for line in said.splitlines() if 'replica' in line)) if __name__ == '__main__': if sys.argv[1:2] == ['--record']: for t in record(sys.argv[2], sys.argv[3]): print(t) elif sys.argv[1:2] == ['--replay']: for t in sys.argv[3:]: replay(sys.argv[2], t) else: out = Path(tempfile.mkdtemp(prefix='xr-tapes-', dir=os.environ.get('TMPDIR', '/tmp'))) try: for t in record(sys.argv[1], out): for b in sys.argv[1:]: replay(b, t) finally: shutil.rmtree(out, ignore_errors=True)