diff options
Diffstat (limited to 'test/daemon.py')
| -rw-r--r-- | test/daemon.py | 394 |
1 files changed, 388 insertions, 6 deletions
diff --git a/test/daemon.py b/test/daemon.py index acfa4896..2c86c04f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -29,6 +29,9 @@ private HOME and runtime directory: `pardes new --detach` returns once its session runs python3 -B test/daemon.py --pair <pardes> PARDES_PAIR: a terminal's session and its first client + python3 -B test/daemon.py --attach-upgrading <pardes> + an attach started as its session upgrades, and two clients' views + across an Upgrade (in plain and --pair too) python3 -B test/daemon.py --relink <pardes> the daemon killed: its sessions register again with the next; and one stopped: an Adopt waits for its answer to the hello @@ -43,6 +46,7 @@ private HOME and runtime directory: at 0/30/80/207 ms, and a window's session serving replicas """ import fcntl +import json import os import random import re @@ -242,7 +246,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 26 + WIRE = 27 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout @@ -749,9 +753,12 @@ def pair_rows(binary): def upgraded(name, nine, session): """An Upgrade to the same build: the session exec'd under its pid, its - 9P again.""" + 9P again: its socket made anew (a second Upgrade's command line says + `--upgraded=` before its exec too).""" + sock = root / f'pardes-9p-{name}.sock' + before = sock.stat().st_ino nine.write('/ctl', b'Upgrade\n') - wait_for('the session exec\'d', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(session)), timeout=60) + wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60) nine.socket.close() again = reconnect(root / f'pardes-9p-{name}.sock') assert alive(session) @@ -864,6 +871,369 @@ def pair_rows(binary): shutil.rmtree(root, ignore_errors=True) +def attach_upgrading(binary, rounds=6): + """`pardes attach` as its session upgrades: started at once after the + Upgrade's word, it is handed to the session before the exec; told the + session is upgrading (never cut by the exec unanswered: "hung up before + the dump was whole", exit 1), it dials again and joins the new process. + A `new --detach` session, without the variable and with it.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='ru-', dir=scratch)) + 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'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + for e in (env, dict(env, PARDES_PAIR='1')): + name = 'up' + e.get('PARDES_PAIR', '') + out = subprocess.run([binary, 'new', f'--detach={name}', str(notes)], env=e, cwd=root, capture_output=True, + timeout=30, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + sock = root / f'pardes-9p-{name}.sock' + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + for k in range(rounds): + before = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + time.sleep(k * .005) + t = Term(30, 100) + terms.append(t) + a = t.spawn([binary, 'attach', name], e) + wait_for('the client drawn, or gone', lambda: b'line 3 of the notes' in t.text() or a.poll() is not None, timeout=40) + assert a.poll() is None, (k, a.returncode, t.text()[-120:]) + os.kill(a.pid, signal.SIGKILL) + a.wait(timeout=10) + wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60) + nine.socket.close() + nine = reconnect(sock) + assert alive(session) + nine.socket.close() + assert subprocess.run([binary, 'kill', name], env=e, capture_output=True, timeout=30).returncode == 0 + wait_for('the session ended', lambda: not alive(session), timeout=30) + print(f'attach upgrading: an attach started as its session upgrades joins the new process ({rounds} of {rounds}, ' + 'without the variable and with it)') + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + +def pair_upgrade_views(binary): + """PARDES_PAIR, two clients each in its own view (the pair's own terminal + and an attach), each with its own scroll and focus: the pair's scrolled + down a long file a page at a time, the attach's focus on a pane of its + own (New); an Upgrade lets both go and each joins again for its view + (views.away): the same lines shown, the cursor where it was, in each.""" + import pyte + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rv-', dir=scratch)) + 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'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + terms = [] + + def screen(t): + s = pyte.Screen(100, 30) + # Its colours (SGR with colons, which pyte misreads) left out. + pyte.ByteStream(s).feed(re.sub(rb'\x1b\[[0-9:;]*m', b'', t.text())) + return s + + def shown(t): + """The notes' lines it shows, and its cursor.""" + s = screen(t) + return sorted(int(m.group(1)) for row in s.display for m in re.finditer(r'line (\d+) of the notes', row)), (s.cursor.x, s.cursor.y) + + def settled(t): + last = [None, 0] + + def same(): + now = shown(t) + if now != last[0]: + last[0], last[1] = now, time.monotonic() + return time.monotonic() - last[1] > 1.5 and now + return wait_for('its screen settled', same, timeout=30) + + try: + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, '--9p=pv', str(notes)], env) + sock = root / 'pardes-9p-pv.sock' + wait_for('the socket', sock.exists) + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + for _ in range(3): + os.write(t.master, b'\x1b[6~') + time.sleep(.2) + tt = Term(30, 100) + terms.append(tt) + a = tt.spawn([binary, 'attach', 'pv'], env) + wait_for('the attach drawn', lambda: b'\x1b[?1049h' in tt.text(), timeout=30) + os.write(tt.master, b'j') + time.sleep(.3) + before_panes = view_panes(nine) + nine.write('/exec', b'New\n') + wait_for('a pane in the attach\'s view', lambda: view_panes(nine) - before_panes) + + def focus(): + """Each client's focus: its view live (a key that moves nothing).""" + got = [] + for term in (t, tt): + os.write(term.master, b'\x1b') + time.sleep(.6) + got.append(nine.read('/focus')) + return got + focused = focus() + before = settled(t), settled(tt) + assert before[0][0] and before[0][0][0] >= 40, ('the pair scrolled', before[0]) + marks = len(t.text()), len(tt.text()) + ino = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + nine.socket.close() + wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) + nine = reconnect(sock) + for term, mark in zip((t, tt), marks): + wait_for('joined again', lambda: b'joined again' in term.text()[mark:], timeout=30) + after = settled(t), settled(tt) + assert after == before, ('each client\'s lines and cursor as they were', before, after) + # Its focus: what it types lands in the pane it had the keyboard in + # (/focus, read after a key, is which view is live then: not a + # client's own). + for term, pane, word in zip((t, tt), focused, (b'PAIRTYPED', b'ATTACHTYPED')): + os.write(term.master, b'i' + word + b'\x1b') + wait_for('typed into its pane', lambda: word in nine.read(f'/pane/{int(pane)}/body'), timeout=10) + print('pair upgrade views: two clients, each its own view: the pair\'s scroll and the attach\'s focus as they were after an Upgrade') + nine.socket.close() + a.terminate() + a.wait(timeout=20) + os.kill(c.pid, signal.SIGTERM) + c.wait(timeout=20) + wait_for('the session ended', lambda: not alive(session), timeout=30) + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + +def pair_exec_reaps(old, new): + """PARDES_PAIR across builds: a pair started from `root/bin` (old), its + session upgraded to the build installed there since (new): its client, + the session's parent, execs that build (the blink) and is still its + parent; Exit typed then: the client returns once the session is gone, + reaped, its status the session's (0), as before the exec.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch)) + 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'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + (root / 'bin').mkdir() + binary = root / 'bin' / 'pardes' + install(old, binary) + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + t = Term(30, 100) + terms.append(t) + c = t.spawn([str(binary), '--9p=px', str(notes)], env) + sock = root / 'pardes-9p-px.sock' + wait_for('the socket', sock.exists) + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + assert ppid(session) == c.pid + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + install(new, binary) + ino = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + nine.socket.close() + wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) + wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) + nine = reconnect(sock) + assert ppid(session) == c.pid + mark = len(t.text()) + wait_for('drawn again', lambda: b'line 3 of the notes' in t.text()[mark:], timeout=30) + nine.write('/ctl', b'Exit\n') + nine.socket.close() + assert c.wait(timeout=30) == 0, c.returncode + # Its parent's wait returned: the session reaped, not a zombie left + # to whoever takes it in. + assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read() + print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0') + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + +def far_exec(old, new): + """A far client (PARDES_REPLICA_FAR, as through ssh's forward) of a + session started from `root/bin` (old), the session upgraded to the build + installed there since (new): the far client execs the build at its own + start path (its install holds the session's build now), the same + process, far still, and is back in its view: its key steps the session + and its digest agrees. Not through ssh: its forward's own end is not + here (its socket file left behind at the exec, the far install holding + another build: not covered).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rfx-', dir=scratch)) + 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'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + (root / 'bin').mkdir() + binary = root / 'bin' / 'pardes' + install(old, binary) + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + out = subprocess.run([str(binary), 'new', '--detach=fx', str(notes)], env=env, cwd=root, capture_output=True, timeout=30) + assert out.returncode == 0, out + sock = root / 'pardes-9p-fx.sock' + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + t = Term(30, 100) + terms.append(t) + check = root / 'f.check' + c = t.spawn([str(binary), f'--attach={root / "pardes-replica.sock"}:fx'], + dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check))) + wait_for('the far client drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + key = lambda b: os.write(t.master, b) # noqa: E731 + seen = len(checks(check)) + key(b'gg') + wait_for('its key stepped', lambda: agreed(check, seen + 1), timeout=30) + install(new, binary) + mark = len(t.text()) + ino = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + nine.socket.close() + wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) + nine = reconnect(sock) + wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) + assert b'PARDES_REPLICA_FAR=1' in open(f'/proc/{c.pid}/environ', 'rb').read().split(b'\0') if procfs else True + wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + seen = len(checks(check)) + key(b'j') + wait_for('its key stepped after', lambda: agreed(check, seen + 1), timeout=30) + assert c.poll() is None + print('far exec: a far client exec\'d the build at its start path at its session\'s Upgrade, far still, and agrees') + c.terminate() + c.wait(timeout=20) + nine.socket.close() + assert subprocess.run([str(binary), 'kill', 'fx'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the session ended', lambda: not alive(session), timeout=30) + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + +def pair_window_geometry(gui_binary, new_gui): + """PARDES_PAIR, a window with `--geometry=WxH` (offscreen, not test + mode: its grid is its window's): another build at its start path, its + session upgraded: the window client execs it, and its new window is the + size it had (the session's grid as before), not the default's.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rgg-', dir=scratch)) + 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'), + SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1', + SDL_VIDEO_DRIVER='offscreen') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + (root / 'bin').mkdir() + gui = root / 'bin' / 'pardes-gui' + install(Path(gui_binary), gui) + install(Path(gui_binary).with_name('pardes'), gui.with_name('pardes')) + procs = [] + + def grid(nine): + s = json.loads(nine.read('/screen')) + return s['cols'], s['rows'] + + def started(name, *flags): + p = subprocess.Popen([str(gui), f'--9p={name}', *flags, str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=open(root / f'{name}.err', 'w'), start_new_session=True) + procs.append(p) + sock = root / f'pardes-9p-{name}.sock' + wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30) + nine = Client(sock) + wait_for('its window\'s grid', lambda: grid(nine) != (80, 24), timeout=30) + time.sleep(1) + return p, nine, grid(nine) + + try: + p0, n0, plain = started('plain') + n0.write('/ctl', b'Exit\n') + n0.socket.close() + p0.wait(timeout=30) + p, nine, sized = started('sized', '--geometry=900x560') + assert sized != plain, ('--geometry makes its own grid', sized, plain) + install(Path(new_gui), gui) + install(Path(new_gui).with_name('pardes'), gui.with_name('pardes')) + sock = root / 'pardes-9p-sized.sock' + ino = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + nine.socket.close() + wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) + wait_for('the window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30) + nine = reconnect(sock) + time.sleep(3) + assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain) + print(f'pair window geometry: --geometry=900x560 ({sized[0]}x{sized[1]}, the default {plain[0]}x{plain[1]}): the window exec\'d at an Upgrade the size it had') + nine.write('/ctl', b'Exit\n') + nine.socket.close() + p.wait(timeout=30) + finally: + for p in procs: + if p.poll() is None: + p.kill() + for q in processes(root): + try: + os.kill(q, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def manage(binary): """`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions and their shells listed, one session killed outright and its shell @@ -2145,6 +2515,8 @@ def main(binary, cycles): launch(binary) pair(binary) pair_rows(binary) + attach_upgrading(binary) + pair_upgrade_views(binary) manage(binary) relink(binary) answer_late(binary) @@ -3093,10 +3465,16 @@ if __name__ == '__main__': if sys.argv[1:3] == ['--upgrade', '--gui']: gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve()) elif sys.argv[1:2] == ['--upgrade']: - upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()) + old, new = Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve() + upgrades(old, new) + if knows_exec(old): + pair_exec_reaps(old, new) + far_exec(old, new) # With a pardes-gui beside each: the clients carried too. - if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]): - upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()) + if all(a.with_name('pardes-gui').exists() for a in (old, new)): + upgrade_clients(old, new) + if knows_exec(old): + pair_window_geometry(old.with_name('pardes-gui'), new.with_name('pardes-gui')) elif sys.argv[1:2] == ['--upgrade-clients']: upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()) elif sys.argv[1:2] == ['--clients']: @@ -3108,6 +3486,10 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--pair']: pair(sys.argv[2]) pair_rows(sys.argv[2]) + attach_upgrading(sys.argv[2]) + pair_upgrade_views(sys.argv[2]) + elif sys.argv[1:2] == ['--attach-upgrading']: + attach_upgrading(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: relink(sys.argv[2]) answer_late(sys.argv[2]) |
