diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-29 22:18:34 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-29 23:37:00 -0300 |
| commit | ddcfd860ef05c37f5536038d8828cc81c0c4125c (patch) | |
| tree | 447d95dc0769273f2919747e30f5a24faec3fc21 /test/daemon.py | |
| parent | 2d86687b98f389232b213dfa67cfa731b0280fbb (diff) | |
| download | pardes-ddcfd860ef05c37f5536038d8828cc81c0c4125c.tar.gz pardes-ddcfd860ef05c37f5536038d8828cc81c0c4125c.zip | |
upgrade: the Upgrade word (SPC s U, a tag, 9P) moves a running session onto the pardes installed where it started, in place, by exec at a step boundary: its dump in the DumpDir, its pty masters, terminals, stubs and daemon link kept open and named on the new command line, every view and running shell its own again; the daemon re-execs too, its registry on its command line; a build that cannot load the dump falls back to the old binary, or starts afresh with the shells adopted and the dump kept (test/daemon.py --upgrade, --upgrade --gui)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'test/daemon.py')
| -rw-r--r-- | test/daemon.py | 315 |
1 files changed, 314 insertions, 1 deletions
diff --git a/test/daemon.py b/test/daemon.py index 2be3f355..7d35e427 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -506,8 +506,321 @@ def gui(binary, cycles): shutil.rmtree(root, ignore_errors=True) +def screen_text(client): + shown = client.screen() + cells = ''.join(cell[0] for cell in shown['cells']) + return '\n'.join(cells[i:i + shown['cols']] for i in range(0, len(cells), shown['cols'])) + + +def reconnect(sock, timeout=20): + """The session's 9P again, once its upgraded process listens.""" + return wait_for('the upgraded session\'s 9P', lambda: dial(sock), timeout=timeout) + + +def dial(sock): + try: + return Client(sock) + except (OSError, EOFError): # mid-exec: refused, or cut after the accept + return None + + +def saying(sock, words, timeout=30): + """A connection to the session once its screen shows `words`: dialled + afresh each look, since the process it talks to may exec meanwhile.""" + last = [''] + + def look(): + c = dial(sock) + if c is None: + return None + try: + last[0] = screen_text(c) + if words in last[0]: + return c + except (OSError, EOFError): + pass + c.socket.close() + return None + try: + return wait_for(f'the session saying {words!r}', look, timeout=timeout) + except TimeoutError: + raise TimeoutError(f'the session saying {words!r}; it shows:\n{last[0]}') + + +def exe_of(pid): + """What /proc says the process runs: (its path, whether that file is the + one at the path now).""" + link = os.readlink(f'/proc/{pid}/exe') if procfs else ps('-o', 'comm=', '-p', str(pid)).decode().strip() + if not procfs: + return link, True + try: + same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino + except OSError: + same = False + return link, same + + +def ppid(pid): + if not procfs: + return int(ps('-o', 'ppid=', '-p', str(pid))) + return int(open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[1]) + + +def install(binary, at): + """As `zig build` and install(1) put a build in place: a new file + renamed over the old, which a process running it keeps, deleted.""" + tmp = at.with_name(at.name + '.new') + subprocess.run(['cp', '--reflink=auto', os.fspath(binary), os.fspath(tmp)], check=True) + os.chmod(tmp, 0o755) + os.replace(tmp, at) + + +def upgrades(old, new): + """Upgrade (docs/next-daemon.md, phase 6): a tty session with an unsaved + edit, a shell running `sleep 1000; echo done` and two terminals (two + views) moved onto another build installed at the path it started from, + the daemon with it; then a build that refuses the dump, which falls back + to the running one, and one that refuses it everywhere, which starts + afresh with the shells adopted and the dump kept.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rtu-', 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('one\ntwo\n') + started = [] + try: + term = Term() + stub = term.spawn([str(binary), '--tty', '--9p=work'], env) + started.append(stub.pid) + sock = root / 'pardes-9p-work.sock' + wait_for('the session\'s 9P socket', sock.exists) + client = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) + started.append(session) + daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0] + started.append(daemon) + shell = terminals(client)[0] + shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + client.write(f'/pane/{shell}/look', f'{notes}\n'.encode()) + text = int(client.read('/look')) + client.write(f'/pane/{text}/body', b'unsaved\n') + assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n' + client.write(f'/pane/{shell}/pty/data', b'sleep 1000; echo done-after-upgrade\r') + sleeper = wait_for('the sleep', lambda: [p for p in processes(root) if cmdline(p)[:2] == [b'sleep', b'1000']])[0] + # A second terminal: a view of its own. + term2 = Term(30, 100) + stub2 = term2.spawn([str(binary), '--attach=work'], env) + started.append(stub2.pid) + wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text()) + old_build = semantics(old) + replica = Replica(root / 'pardes-replica.sock') + assert replica.hello('work', old_build)[0] == 'welcome' + before = len(term.text()), len(term2.text()) + + install(new, binary) + assert exe_of(session)[1] is False, 'the session runs the old build, deleted' + client.write(f'/pane/{shell}/exec', b'Upgrade\n') + client.socket.close() + wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30) + client = reconnect(sock) + assert int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) == session + wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True)) + assert alive(daemon) and stub.poll() is None and stub2.poll() is None + # A replica of the old build is told why it is let go. + tag, body = replica.read() + assert tag == 0x02 and b'upgrading to another build' in body, (tag, body) + replica.close() + # The edit and its undo. + assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n' + assert any(row.split()[0] == str(text).encode() and row.split()[2] == b'1' for row in client.read('/index').splitlines()), client.read('/index') + client.write(f'/pane/{text}/exec', b'Undo\n') + assert client.read(f'/pane/{text}/body') == b'one\ntwo\n', client.read(f'/pane/{text}/body') + # The shell, its job and its pty: the same, the session's still. + assert alive(shell_pid) and ppid(shell_pid) == session and alive(sleeper) + # Both terminals drawn again, each its own view. + wait_for('the first terminal redrawn', lambda: b'\x1b[?1049h' in term.text()[before[0]:]) + wait_for('the second terminal redrawn', lambda: b'\x1b[?1049h' in term2.text()[before[1]:]) + wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client)) + # The daemon lists the session under its new build. + new_build = semantics(new) + assert new_build != old_build + said = Replica(root / 'pardes-replica.sock').hello('work', new_build) + assert said == ('welcome', session, 'work'), said + said = Replica(root / 'pardes-replica.sock').hello('work', old_build) + assert said[0] == 'refused' and 'another build' in said[1], said + os.kill(sleeper, signal.SIGTERM) + wait_for('the shell carrying on', lambda: b'done-after-upgrade\n' in client.read(f'/pane/{shell}/body')) + print(f'upgrade: session {session}, its daemon {daemon}, shell {shell_pid} and two terminals on the new build; ' + 'the edit, its undo and the job kept') + + # A build that cannot load the dump: back to the one running. + refuser = root / 'refuser' + refuser.write_text('#!/bin/sh\n# A pardes whose load refuses the dump (upgrade.zig).\n' + f'case "$1" in --upgraded=*) PARDES_TEST_UPGRADE_REFUSE=1 exec {new} "$@";; esac\n' + f'exec {new} "$@"\n') + refuser.chmod(0o755) + running = os.stat(f'/proc/{session}/exe').st_ino + install(refuser, binary) + client.write(f'/pane/{shell}/exec', b'Upgrade\n') + client.socket.close() + client = saying(sock, 'it goes on as') + assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran' + assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None + assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' + assert run(client, shell, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print('upgrade: a build that refused the dump fell back to the one running; the shell ran on') + + # One that refuses it everywhere: a fresh session, the shells adopted. + refuser.write_text(refuser.read_text().replace('=1 exec', '=all exec')) + install(refuser, binary) + client.write(f'/pane/{shell}/exec', b'Upgrade\n') + client.socket.close() + client = saying(sock, 'brings the rest back') + kept = root / '.local' / 'share' / 'pardes' / f'pardes-upgrade-{session}.dump' + assert kept.exists(), list((root / '.local' / 'share' / 'pardes').iterdir()) + assert alive(shell_pid) and ppid(shell_pid) == session + pids = {p: run(client, p, b'echo $$\n') for p in terminals(client)} + adopted = [p for p, out in pids.items() if out.split(b'\n')[1:2] == [str(shell_pid).encode()]] + assert adopted, ('the shell is a pane of the fresh session', shell_pid, pids, client.read('/index')) + print(f'upgrade: a build that refused it everywhere started afresh, shell {shell_pid} adopted, the dump kept') + + # The daemon, three times upgraded, still holds the shell's master: + # the session killed outright, another adopts it. + install(new, binary) + os.kill(session, signal.SIGKILL) + stub.wait(timeout=10) + stub2.wait(timeout=10) + client.socket.close() + term.close() + term2.close() + wait_for('the killed session gone', lambda: not alive(session)) + time.sleep(.3) + assert alive(shell_pid) and alive(daemon) + term = Term() + stub = term.spawn([str(binary), '--tty', '--9p=again'], env) + started.append(stub.pid) + sock = root / 'pardes-9p-again.sock' + wait_for('the next session', sock.exists) + client = Client(sock) + started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])) + before = set(terminals(client)) + client.write(f'/pane/{min(before)}/exec', b'Adopt\n') + pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop() + assert run(client, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted') + client.write(f'/pane/{pane}/exec', b'Exit\n') + stub.wait(timeout=10) + client.socket.close() + term.close() + wait_for('the shell hung up', lambda: not alive(shell_pid)) + wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5) + left = [p for p in processes(root) if alive(p)] + assert not left, [cmdline(p) for p in left] + print('upgrade: nothing left behind') + finally: + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + +def gui_upgrades(old, new): + """Upgrade in a window session (test mode: hidden windows, captured): + two windows, an unsaved edit and a shell's job, onto another build.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + root = Path(tempfile.mkdtemp(prefix='rtgu-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) + if not display.is_absolute(): + display = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')) / display + caps = root / 'caps' + caps.mkdir() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(caps), + SDL_VIDEODRIVER='wayland', WAYLAND_DISPLAY=str(display), PARDES_DAEMON='on') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + (root / 'bin').mkdir() + binary = root / 'bin' / 'pardes-gui' + install(old, binary) + notes = root / 'notes.txt' + notes.write_text('one\ntwo\n') + feed_r, feed_w = os.pipe() + proc = subprocess.Popen([str(binary), '--9p=win'], env=env, cwd=root, stdin=feed_r, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + os.close(feed_r) + started = [proc.pid] + try: + sock = root / 'pardes-9p-win.sock' + wait_for('the window session', sock.exists, timeout=20) + client = Client(sock) + daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0] + started.append(daemon) + shell = terminals(client)[0] + shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shell_pid) + client.write(f'/pane/{shell}/look', f'{notes}\n'.encode()) + text = int(client.read('/look')) + client.write(f'/pane/{text}/body', b'unsaved\n') + client.write(f'/pane/{shell}/pty/data', b'sleep 1000; echo done-after-upgrade\r') + sleeper = wait_for('the sleep', lambda: [p for p in processes(root) if cmdline(p)[:2] == [b'sleep', b'1000']])[0] + attach = subprocess.run([str(binary), '--attach=win'], env=env, cwd=root, timeout=10, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + assert attach.returncode == 0, attach.stderr + frames = [caps / 'latest.ppm', caps / 'view-1' / 'latest.ppm'] + wait_for('both windows drawn', lambda: all(f.exists() for f in frames)) + install(new, binary) + time.sleep(.05) + mark = time.time() + client.write(f'/pane/{shell}/exec', b'Upgrade\n') + client.socket.close() + wait_for('the session on the new build', lambda: exe_of(proc.pid) == (str(binary), True), timeout=30) + client = reconnect(sock) + assert proc.poll() is None + wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True)) + assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n' + client.write(f'/pane/{text}/exec', b'Undo\n') + assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' + assert alive(shell_pid) and ppid(shell_pid) == proc.pid and alive(sleeper) + wait_for('both windows drawn again', lambda: all(f.stat().st_mtime > mark for f in frames)) + said = Replica(root / 'pardes-replica.sock').hello('win', semantics(new)) + assert said == ('welcome', proc.pid, 'win'), said + os.kill(sleeper, signal.SIGTERM) + wait_for('the shell carrying on', lambda: b'done-after-upgrade\n' in client.read(f'/pane/{shell}/body')) + print(f'upgrade: window session {proc.pid}, its daemon, shell {shell_pid} and two windows on the new build; ' + 'the edit, its undo and the job kept') + client.write(f'/pane/{shell}/exec', b'Exit\n') + proc.wait(timeout=10) + client.socket.close() + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=5) + print('upgrade: window session ended, nothing left behind') + finally: + os.close(feed_w) + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + if __name__ == '__main__': - if sys.argv[1:2] == ['--ping']: + 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()) + elif sys.argv[1:2] == ['--ping']: ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50) elif '--gui' in sys.argv: args = [a for a in sys.argv[1:] if a != '--gui'] |
