diff options
Diffstat (limited to 'test/daemon.py')
| -rw-r--r-- | test/daemon.py | 368 |
1 files changed, 363 insertions, 5 deletions
diff --git a/test/daemon.py b/test/daemon.py index f8402af2..b28d16ea 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -241,7 +241,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 = 23 + WIRE = 24 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout @@ -653,12 +653,16 @@ def pair(binary): c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off')) nine2, session2 = session_of('lone') wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30) + # An Upgrade refused, with why: its client could not find it again. + nine2.write('/ctl', b'Upgrade\n') + wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20) + assert alive(session2) and c2.poll() is None nine2.socket.close() os.kill(c2.pid, signal.SIGKILL) c2.wait(timeout=10) wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) - print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind') + print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind') finally: for p in processes(root): try: @@ -1737,6 +1741,138 @@ def games(binary, libs, secs=10): shutil.rmtree(root, ignore_errors=True) +def far_find(binary): + """A far client types a query into a Find over 40,000 names: each key + scores the names again a slice at a time (core/Names.zig `rescore`), + the client's guess of the key first. The slice is a count, the same on + both sides, so no guess is wrong (a slice the clock ended was the + client's clock's verdict, which the session's own contradicted).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rq-', 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'), XDG_DATA_HOME=str(root / 'data'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + tree = root / 'tree' + for d in range(200): + (tree / f'module_{d}').mkdir(parents=True) + for f in range(200): + (tree / f'module_{d}' / f'replica_{f}.zig').touch() + notes = tree / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + started, terms = [], [] + try: + sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + wait_for('the replica socket', (root / 'pardes-replica.sock').exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists) + nine = Client(root / 'pardes-9p-find.sock') + text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'], + dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats'))) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) + time.sleep(.3) + # SPC f f: the Find, typed into, its names walked on the session's worker. + os.write(t.master, b' ff') + time.sleep(3) + wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60) + query = b'module_19/replica_3' + for ch in query: + os.write(t.master, bytes([ch])) + time.sleep(.15) + seen = len(checks(root / 'q.check')) + wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60) + c.send_signal(signal.SIGHUP) + c.wait(timeout=20) + line = (root / 'q.stats').read_text().split() + got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)} + print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs ' + f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once') + assert got['mispredicted'] == '0', got + exit_session(nine, text) + sess.wait(timeout=60) + nine.socket.close() + finally: + for term in terms: + term.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + +def restore_client(binary): + """A Restore while a client is attached: the client is let go (its link + ends), the replacement core is the session's (its tape adopts it, its + options keep none), and a client attached after agrees with it, its + keys reaching it.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rr-', 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'), XDG_DATA_HOME=str(root / 'data'), + 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(300))) + started, terms = [], [] + try: + sess = subprocess.Popen([binary, '--detach=back', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + wait_for('the replica socket', (root / 'pardes-replica.sock').exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-back.sock').exists) + nine = Client(root / 'pardes-9p-back.sock') + text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + def client(name): + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'], + dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check'))) + started.append(c.pid) + wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) + time.sleep(.3) + return t, c + t, c = client('a') + nine.write(f'/pane/{text}/exec', b'Dump\n') + nine.write(f'/pane/{text}/exec', b'Restore\n') + wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30) + # The 9P link was the old core's. + nine.socket.close() + nine = reconnect(root / 'pardes-9p-back.sock') + text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + t, c = client('r') + os.write(t.master, b'Oafter the restore\x1b') + texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines() + if row.split()[1] == b'text') + wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30) + seen = len(checks(root / 'r.check')) + wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60) + assert c.poll() is None, 'the client ended' + print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session') + exit_session(nine, text) + sess.wait(timeout=60) + nine.socket.close() + finally: + for term in terms: + term.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def far_joins(sock, session, binary, n): """`n` far joins of one session in a row, each read whole (its blobs asked for by none, its zstd frames unpacked) and answering a ping, then @@ -2120,6 +2256,90 @@ def gui(binary, cycles): shutil.rmtree(root, ignore_errors=True) +def gui_pair(gui_binary): + """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui + FILE` is a window client and a session with no SDL, the `pardes` beside + it exec'd in a child (a window's session needs SDL for its wake, a + terminal's binary none): the session the window's child, in a session + of its own, listed detached with the window its client; the file in + the window's first frame, keys in. The window's close ends the session, + its last client (a CLOSE); the window killed leaves it running (a LOSS), + and with no daemon the session ends with its last link. Test mode: + hidden windows, offscreen.""" + binary = gui_binary.replace('pardes-gui', 'pardes') + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rgp-', 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') + (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))) + windows = [] + + def listed(): + return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode() + + def started(name, e): + w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e) + windows.append(w) + sock = root / f'pardes-9p-{name}.sock' + wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30) + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid) + assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session)) + wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30) + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s' + return w, nine, session, pane + + try: + w, nine, session, pane = started('gp', env) + wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed() + and f'client {w.pid} ' in listed()) + w.keys(b'Ofrom-the-window\x1b') + wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body')) + # The close button (the test feed's word for it): its last client + # closed, the session ends. + w.p.stdin.write(b'\x1b]777;close\x07') + w.p.stdin.flush() + assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:]) + wait_for('the session ended with its window', lambda: not alive(session), timeout=20) + nine.socket.close() + print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, ' + 'setsid, listed detached with the window); drawn, typed; the window closed ended both') + w, nine, session, pane = started('gl', env) + wait_for('the client listed', lambda: f'client {w.pid} ' in listed()) + os.kill(w.pid, signal.SIGKILL) + w.p.wait(timeout=10) + wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed()) + assert alive(session) and f'session gl {session} (tty, detached)' in listed(), listed() + nine.socket.close() + assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the session ended', lambda: not alive(session), timeout=30) + print('pair window: the window killed: the session runs on, listed (a loss); killed by name') + w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off')) + nine.socket.close() + os.kill(w.pid, signal.SIGKILL) + w.p.wait(timeout=10) + wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20) + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + print('pair window: with no daemon, the window killed, its session ended; nothing left behind') + finally: + for w in windows: + if w.p.poll() is None: + w.p.kill() + for p in processes(root): + try: + os.kill(p, 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']) @@ -2300,7 +2520,9 @@ def upgrades(old, new): # its terminal and its stub's pipe let go once its stub is told # (two fewer). def level(): - gone = 2 if b'detached from' in term2.text() else 1 + # (A client of a build that execs at an Upgrade comes back: its + # connection is the session's again.) + gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1 return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1] try: wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5) @@ -2320,7 +2542,9 @@ def upgrades(old, new): # build's own, let go (a session shows one frontend of its own now), # its stub told. wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or - (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()))) + (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text() + or b'run the same pardes at both ends' in term2.text())), + timeout=30) 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) @@ -2409,7 +2633,10 @@ def upgrades(old, new): install(new, binary) os.kill(session, signal.SIGKILL) stub.wait(timeout=10) - stub2.wait(timeout=10) + try: + stub2.wait(timeout=30) + except subprocess.TimeoutExpired: + raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:])) client.socket.close() term.close() term2.close() @@ -2454,6 +2681,124 @@ def upgrades(old, new): shutil.rmtree(root, ignore_errors=True) +def knows_exec(binary): + """Whether a build's client execs the build at its start path at an + Upgrade, for the view it is handed (PARDES_JOIN_VIEW).""" + return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes() + + +def upgrade_clients(old, new): + """Upgrade with near clients (the last step's design, 1.4): a session + (`new --detach`) with a terminal client and a window client attached, + each in its own view with a pane of its own there, onto another build installed at the path all three were + started from. A client of a build that execs (its start path holding + another file than the one it runs, the session another build than its + own) comes back on the build at its start path, the same process, for + its view: the terminal's leaves its screen and enters it again (the + blink), the window is a new one; in ITS view when that build joins for + a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One + of a build before it is let go and told to upgrade too. The session's + shell alive throughout; nothing left behind.""" + old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui') + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='ruc-', 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, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui' + install(old, binary) + install(old_gui, gui_binary) + terms = [] + procs = [] + + def still(check, key): + """Its view the live one (made_live's, for either client).""" + seen = len(checks(check)) + key(b'gg') + wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30) + + try: + out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30) + assert out.returncode == 0, out + sock = root / 'pardes-9p-up.sock' + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + shell = terminals(nine)[0] + shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1]) + t = Term(30, 100) + terms.append(t) + tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check'))) + procs.append(tc) + wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30) + w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check'))) + procs.append(w.p) + wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30) + tkey = lambda b: os.write(t.master, b) # noqa: E731 + # Each client's view live in turn, a pane of its own made there (New). + owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check')) + mine = [] + for key, check in owners: + still(check, key) + shown = view_panes(nine) + nine.write('/exec', b'New\n') + mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop()) + for (key, check), pane, theirs in zip(owners, mine, reversed(mine)): + still(check, key) + assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout')) + install(new, binary) + install(new_gui, gui_binary) + mark = len(t.text()) + nine.write('/ctl', b'Upgrade\n') + nine.socket.close() + wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30) + nine = reconnect(sock) + if not knows_exec(old): + # A build before the exec: let go, dialled again for 20 s, told. + assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode) + said = t.text()[mark:] + w.said().encode() + assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:] + print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too') + else: + wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30) + wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30) + # The blink: its screen left, and entered again. + wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + assert tc.poll() is None and w.p.poll() is None + for (key, check), pane, theirs in zip(owners, mine, reversed(mine)): + still(check, key) + if knows_exec(new): + shown = view_panes(nine) + assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout')) + print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, ' + + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)')) + assert alive(shell_pid) and ppid(shell_pid) == session + for p in procs: + if p.poll() is None: + p.terminate() + p.wait(timeout=20) + nine.socket.close() + assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the session ended', lambda: not alive(session), timeout=30) + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + print('upgrade with clients: the shell ran on throughout; nothing left behind') + finally: + for p in procs: + if p.poll() is None: + p.kill() + 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 gui_upgrades(old, new): """Upgrade in a window session (test mode: hidden windows, captured): its window, a client window, an unsaved edit and a shell's job, onto @@ -2548,6 +2893,11 @@ if __name__ == '__main__': 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()) + # 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()) + 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']: clients(sys.argv[2]) elif sys.argv[1:2] == ['--manage']: @@ -2565,13 +2915,21 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) by_hash(sys.argv[2]) + far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-find']: + far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--restore']: + restore_client(sys.argv[2]) elif sys.argv[1:2] == ['--window-clients']: window_clients(sys.argv[2], sys.argv[3]) pdf_window(sys.argv[2], sys.argv[3]) 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 sys.argv[1:2] == ['--pair-gui']: + gui_pair(sys.argv[2]) 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) + gui_pair(args[0]) else: main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50) |
