#!/usr/bin/env python3 """The per-user daemon end to end (docs/next-daemon.md, phase 3), under a private HOME and runtime directory: - a terminal's session detached (the stub ends, exit 0) and attached again from another terminal, N times; - a session killed outright: its shells live on, held by the daemon, and another session adopts them as terminal panes; - a replica's hello on the daemon's stream socket (phase 5): one of this build handed to its session, which answers it and its pings; another build's refused, and a session nobody has; - nothing left behind: no session, shell, daemon or socket. python3 -B test/daemon.py [cycles] python3 -B test/daemon.py --gui [cycles] (a hidden window; needs a Wayland display, and a pardes beside it for the refusal) python3 -B test/daemon.py --ping [n] a hello of 's build and n pings on a replica socket (one `ssh -L` forwards, say), timed """ import fcntl import os import shutil import signal import socket import statistics import struct import subprocess import sys import tempfile import termios import threading import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from ninep import Client # noqa: E402 def wait_for(what, check, timeout=10): deadline = time.monotonic() + timeout while True: got = check() if got: return got if time.monotonic() > deadline: raise TimeoutError(what) time.sleep(.01) class Term: """A terminal: a pty whose other end is read and kept, its frame requests answered (CSI 5 n), as a terminal emulator does.""" def __init__(self, rows=24, cols=80): self.master, self.slave = os.openpty() fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0)) self.out = bytearray() self.lock = threading.Lock() self.reader = threading.Thread(target=self.drain, daemon=True) self.reader.start() def drain(self): while True: try: got = os.read(self.master, 65536) except OSError: return if not got: return with self.lock: self.out += got if b'\x1b[5n' in got: try: os.write(self.master, b'\x1b[0n') except OSError: return def spawn(self, argv, env): slave = self.slave return subprocess.Popen(argv, env=env, stdin=slave, stdout=slave, stderr=slave, start_new_session=True, preexec_fn=lambda: fcntl.ioctl(0, termios.TIOCSCTTY, 0)) def text(self): with self.lock: return bytes(self.out) def close(self): os.close(self.slave) os.close(self.master) self.reader.join(timeout=2) def run(client, serial, line): """pty/run: a line in, `exit N` and its output out.""" fid = client.open(f'/pane/{serial}/pty/run', 2) try: client.rpc(118, struct.pack(' "$0"; wait; exec sleep 600', str(stub_pid), binary, '--tty', '--9p=fresh'], env) started.append(shell.pid) sock = root / 'pardes-9p-fresh.sock' wait_for('the second session', sock.exists) stub = int(stub_pid.read_text()) started.append(stub) client = Client(sock) status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines()) session = int(status['pid']) started.append(session) # Its stub killed outright, the terminal left open: the session # (the stub's child) takes that as the terminal's end and detaches. wait_for('the second session\'s first frame', lambda: b'\x1b[?1049h' in term.text()) drawn = len(term.text()) os.kill(stub, signal.SIGKILL) wait_for('the stub gone', lambda: not alive(stub)) wait_for('the session detached from its killed stub', lambda: sized(client)) assert b'\x1b[?1049l' in term.text()[drawn:], 'the terminal is put back' assert alive(session) shell.kill() shell.wait(timeout=10) term.close() term = Term() stub = term.spawn([binary, '--attach=fresh'], env) wait_for('the attached terminal\'s first frame', lambda: b'\x1b[?1049h' in term.text()) wait_for('the session sized to its new terminal', lambda: not sized(client)) print('daemon: a session whose stub was killed outright detached, and was attached again') before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() said = run(client, pane, b'echo $$\n') assert said.split(b'\n')[1] == str(shell_pid).encode(), said print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') # The end: the session quits, its shells hang up, the daemon goes. client.write(f'/pane/{pane}/exec', b'Exit\n') stub.wait(timeout=10) client.socket.close() term.close() wait_for('the adopted 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] sockets = [p.name for p in root.iterdir() if p.is_socket()] assert not sockets, sockets print('daemon: 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 sized(client): """Whether the session takes a `size`: only with no window or terminal.""" try: client.write('/ctl', b'size 100 30\n') return True except OSError: return False def gui(binary, cycles): """A window's Detach closes it and keeps the process; `pardes-gui --attach` opens it again. Test mode: a hidden window, its stdin the test feed.""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' root = Path(tempfile.mkdtemp(prefix='rtg-', 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 (root / '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(root / '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') feed_r, feed_w = os.pipe() proc = subprocess.Popen([binary, '--9p=win'], env=env, cwd=root, stdin=feed_r, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) os.close(feed_r) try: sock = root / 'pardes-9p-win.sock' wait_for('the window session', sock.exists, timeout=20) client = Client(sock) shell = terminals(client)[0] assert not sized(client), 'a window owns the size' baseline = None for cycle in range(cycles): client.write(f'/pane/{shell}/exec', b'Detach\n') wait_for('the window closed', lambda: sized(client)) assert proc.poll() is None, 'the process carries on with no window' attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, stdout=subprocess.PIPE, stderr=subprocess.PIPE) assert attach.returncode == 0, attach.stderr wait_for('the window open again', lambda: not sized(client)) now = (fds(proc.pid), len(processes(root))) baseline = baseline or now assert now == baseline, (cycle, now, baseline) print(f'daemon: {cycles} window detach/attach cycles, fds/processes level: {baseline}') # Attached already: another window, a view of its own (its test # captures under view-1); Detach in it closes only it. attach = subprocess.run([binary, '--attach=win'], env=env, cwd=root, timeout=10, stdout=subprocess.PIPE, stderr=subprocess.PIPE) assert attach.returncode == 0, attach.stderr wait_for('the second window drawn', lambda: (root / 'caps' / 'view-1' / 'latest.ppm').exists()) client.write(f'/pane/{shell}/exec', b'Detach\n') time.sleep(.5) assert not sized(client), 'the first window stays' assert proc.poll() is None print('daemon: a second window on an attached window session, detached alone') # Another kind is refused in words, and so is a name nobody has. client.write(f'/pane/{shell}/exec', b'Detach\n') wait_for('the window closed', lambda: sized(client)) term = Term() tty_attach = term.spawn([binary.replace('pardes-gui', 'pardes'), '--attach=win'], env) assert tty_attach.wait(timeout=10) == 1 said = term.text() term.close() assert b'is a window' in said, said nobody = subprocess.run([binary, '--attach=nobody'], env=env, cwd=root, timeout=10, stdout=subprocess.PIPE, stderr=subprocess.PIPE) assert nobody.returncode == 1 and b"no session called 'nobody'" in nobody.stderr, nobody.stderr # Detached and told to end: it ends. client.write(f'/pane/{shell}/exec', b'Exit\n') proc.wait(timeout=10) client.socket.close() wait_for('the daemon gone once idle', lambda: not [p for p in processes(root) if alive(p)], timeout=5) print('daemon: window session ended, nothing left behind') finally: os.close(feed_w) for pid in [proc.pid] + processes(root): try: os.kill(pid, signal.SIGKILL) except OSError: pass 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). FreeBSD's procstat names the path alone.""" if not procfs: rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines() return (rows[-1].split()[-1] if len(rows) > 1 else ''), None link = os.readlink(f'/proc/{pid}/exe') 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') if procfs: subprocess.run(['cp', '--reflink=auto', os.fspath(binary), os.fspath(tmp)], check=True) else: shutil.copyfile(binary, tmp) 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 not procfs or exe_of(session)[1] is False, 'the session runs the old build, deleted' # Come back to the terminal: the newer build is said. os.write(term.master, b'\x1b[I') wait_for('the newer build said', lambda: 'a newer pardes is installed' in screen_text(client)) fds_before = fds(session), fds(daemon) rcs = sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) t = time.monotonic() client.write('/ctl', b'Upgrade\n') client.socket.close() new_build = semantics(new) assert new_build != old_build if procfs: wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30) else: wait_for('the session registered as the new build', lambda: Replica(root / 'pardes-replica.sock').hello('work', new_build)[0] == 'welcome', timeout=30) client = reconnect(sock) took = time.monotonic() - t assert int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) == session if procfs: wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True)) else: wait_for('the daemon exec\'d again', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(daemon))) 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 old image's prompt files swept, the new one's made. wait_for('the prompt files level', lambda: len(list(Path('/tmp').glob(f'pardes-osc133-*-{session}-*'))) == len(rcs)) assert sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) != rcs or not rcs # Nothing kept that was not: the old binary let go, every fd back. # (The replica's connection is the one fewer.) level = fds_before[0] - 1, fds_before[1] try: wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level, timeout=5) except TimeoutError: raise AssertionError(('fds', level, (fds(session), fds(daemon)), os.listdir(f'/proc/{session}/fd') if procfs else None)) # 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. 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 ' f'(the word to its 9P again: {took * 1000:.0f} ms); the edit, its undo and the job kept') # A build that cannot load the dump: back to the one running (a copy # of it kept open from /proc/self/exe; FreeBSD keeps none). refuser = root / 'refuser' def refusing(how): 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={how} exec {new} "$@";; esac\n' f'exec {new} "$@"\n') refuser.chmod(0o755) install(refuser, binary) if procfs: running = os.stat(f'/proc/{session}/exe').st_ino refusing('1') 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. refusing('all') 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'])) # Its reader of the daemon starts after its first frame: an Adopt # before that waits for an `ok` nobody reads, and is refused. wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text()) 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: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'] gui(args[0], int(args[1]) if len(args) > 1 else 50) else: main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)