#!/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; - 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) """ import fcntl import os import shutil import signal 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}') # 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) if __name__ == '__main__': if '--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)