diff options
Diffstat (limited to 'test/daemon.py')
| -rw-r--r-- | test/daemon.py | 212 |
1 files changed, 186 insertions, 26 deletions
diff --git a/test/daemon.py b/test/daemon.py index 2c86c04f..c6ff6256 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -143,6 +143,16 @@ def run(client, serial, line): client.close(fid) +def adopted_pid(client, pane): + """An adopted shell's `echo $$`, once it answers: sized twice at its + adoption (dev/Ptys.zig `take`), it draws its prompt again, and a run + sent into a prompt redrawn under it reads as not run (core/ninep/pty.zig + `noteMarks`).""" + wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') + said = run(client, pane, b'echo $$\n') + return said.split(b'\n')[1], said + + # FreeBSD has no /proc: ps and procstat answer instead. procfs = os.path.isdir('/proc/self') @@ -399,6 +409,23 @@ def view_panes(client): if line.split()[:1] != ['active'] for x in line.split()[6:]} +def in_own_view(what, live, client, pane, theirs): + """`live()` makes a client's view the live one (made_live, still), and + /layout read after it lays out its pane and not the other client's: + asked again until it does, for a view is the live one only until the + next input (the session's own terminal answering a query late, the + other client's rejoin sizing it). A view lost lays out neither pane, + another's lays out theirs: neither ever passes.""" + def own(): + live() + shown = view_panes(client) + return pane in shown and theirs not in shown + try: + wait_for(what, own, timeout=30) + except TimeoutError: + raise AssertionError((what, pane, theirs, client.read('/layout'))) from None + + def clients(binary): """Replica clients of a detached session: one on the replica socket, one through the delay relay; each one's keys in the session's text and @@ -789,13 +816,14 @@ def pair_rows(binary): # Not kept: a client's close (its terminal closed, a TERM) ends the # session when it was the last; a KILL is a loss, it runs on. t, c, nine, session, pane = started('nk', env) - assert ended_by('HUP', *attached('nk')) == 0 + # Dead of the signal, its goodbye said, as the own path's stub dies. + assert ended_by('HUP', *attached('nk')) == -signal.SIGHUP assert alive(session) and state_of('nk') == '(tty)', ('not its last client', listed()) os.kill(c.pid, signal.SIGKILL) c.wait(timeout=10) wait_for('the client unlisted', lambda: f'client {c.pid} ' not in listed()) assert alive(session) and state_of('nk') == '(tty)', ('a loss', listed()) - assert ended_by('TERM', *attached('nk')) == 0 + assert ended_by('TERM', *attached('nk')) == -signal.SIGTERM wait_for('the session ended at its last client\'s close', lambda: not alive(session), timeout=20) assert state_of('nk') is None, listed() nine.socket.close() @@ -809,7 +837,7 @@ def pair_rows(binary): nine.socket.close() t.close() terms.remove(t) - assert c.wait(timeout=20) == 0, c.returncode + assert c.wait(timeout=20) == -signal.SIGHUP, c.returncode wait_for('the session ended with its terminal', lambda: not alive(session), timeout=20) print('pair rows: not kept, upgraded: its terminal closed (exit 0): the session ended') # Without the variable nothing changes: an attach client's TERM @@ -817,7 +845,7 @@ def pair_rows(binary): own_env = {k: v for k, v in env.items() if k != 'PARDES_PAIR'} t, c, nine, session, pane = started('own', own_env) assert state_of('own') == '(tty, has a frontend)', listed() - assert ended_by('TERM', *attached('own')) == 0 + assert ended_by('TERM', *attached('own')) == -signal.SIGTERM assert alive(session) and state_of('own') == '(tty, has a frontend)', listed() nine.socket.close() t.close() @@ -871,7 +899,7 @@ def pair_rows(binary): shutil.rmtree(root, ignore_errors=True) -def attach_upgrading(binary, rounds=6): +def attach_upgrading(binary, rounds=6, dump=True): """`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 @@ -915,8 +943,40 @@ def attach_upgrading(binary, rounds=6): 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) + # A join whose dump is still on its way when the Upgrade comes (a + # 100 MB file: the flush before the exec lets it go cut): it joins + # again, as one told so does; never "let this client go". + # Once a run (plain mode, --attach-upgrading): a slow round. + if dump: + big = root / 'big.txt' + with open(big, 'w') as f: + f.write('a line of a big file, long enough to be a fair line of text in a log: 0123456789\n' * 1_250_000) + out = subprocess.run([binary, 'new', '--detach=big', str(big)], env=env, cwd=root, capture_output=True, + timeout=60, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + sock = root / 'pardes-9p-big.sock' + nine = Client(sock) + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + for k in range(2): + t = Term(30, 100) + terms.append(t) + a = t.spawn([binary, 'attach', 'big'], env) + listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode() # noqa: E731 + wait_for('the attach joined', lambda: f'client {a.pid} ' in listed() or a.poll() is not None, timeout=60) + before = sock.stat().st_ino + nine.write('/ctl', b'Upgrade\n') + wait_for('joined again, or gone', lambda: b'joined again' in t.text() or a.poll() is not None, timeout=180) + assert a.poll() is None, ('a join cut mid-dump', k, a.returncode, t.text()[-120:]) + a.terminate() + a.wait(timeout=20) + wait_for('the session exec\'d', lambda: sock.stat().st_ino != before, timeout=60) + nine.socket.close() + nine = reconnect(sock) + nine.socket.close() + assert subprocess.run([binary, 'kill', 'big'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('the big 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)') + 'without the variable and with it)' + ('; a join whose 100 MB dump the exec cut joined again, 2 of 2' if dump else '')) finally: for p in processes(root): try: @@ -928,6 +988,65 @@ def attach_upgrading(binary, rounds=6): shutil.rmtree(root, ignore_errors=True) +def kept_views(binary): + """A view kept for its client's rejoin (views.away: a bye that says it + joins again, a client cut off behind, every client at an Upgrade) is + that client's for 30 s, then a join with no room takes it, in a session + nobody types in: a `new --detach` session at its four views (a client + attached, idle; raw replicas), two of them leaving to join again and + never coming back; a join at once is refused and told for how long, one + 31 s later, nothing typed in between, is welcomed.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rk-', 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') + t = Term(30, 100) + rs = [] + try: + out = subprocess.run([binary, 'new', '--detach=kv'], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + a = t.spawn([binary, 'attach', 'kv'], env) + wait_for('the client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30) + sock, build = root / 'pardes-replica.sock', semantics(binary) + while True: + r = Replica(sock) + said = r.hello('kv', build) + if said[0] != 'welcome': + break + rs.append(r) + assert said[0] == 'refused' and 'as many views' in said[1] and len(rs) >= 2, (said, len(rs)) + for r in rs[:2]: + r.send(0x02, b'\x01') + r.close() + left = time.monotonic() + said = Replica(sock).hello('kv', build) + assert said[0] == 'refused' and re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]), said + print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}"') + time.sleep(max(0, left + 31 - time.monotonic())) + said = Replica(sock).hello('kv', build) + assert said[0] == 'welcome', ('a view kept 31 s in an idle session, still kept', said) + assert a.poll() is None + print('kept views: a join 31 s after, nothing typed in between, took a kept view') + a.terminate() + a.wait(timeout=20) + assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + finally: + for r in rs: + r.close() + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + 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 @@ -1067,14 +1186,17 @@ def pair_exec_reaps(old, new): wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) install(new, binary) ino = sock.stat().st_ino + # Before the Upgrade: the exec'd client can draw before its exec is seen. + mark = len(t.text()) 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) + # The blink: its screen left and entered again, the notes drawn there. + wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark + and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), timeout=30) nine.write('/ctl', b'Exit\n') nine.socket.close() assert c.wait(timeout=30) == 0, c.returncode @@ -1419,7 +1541,8 @@ def relink(binary): before = set(terminals(own)) own.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() - assert run(own, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + pid, said = adopted_pid(own, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') exit_session(own, pane) stub.wait(timeout=10) @@ -1493,7 +1616,8 @@ def answer_late(binary): two.write(f'/pane/{min(before)}/exec', b'Adopt\n') took = time.monotonic() - asked pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop() - assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + pid, said = adopted_pid(two, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, ' f'and shell {shell_pid} was adopted') exit_session(two, pane) @@ -1985,7 +2109,10 @@ def far(binary): time.sleep(.3) os.write(ts.master, b' sD') wait_for(f'the client through ssh ends ({name})', lambda: sc.poll() is not None, timeout=30) - assert name == 'files' or b"no session called 'nobody'" in ts.text(), ts.text()[-300:] + # Its words are read off its terminal by a thread of the Term's: + # the process can be gone before they are in `text()`. + if name == 'nobody': + wait_for('the refusal said through ssh', lambda: b"no session called 'nobody'" in ts.text(), timeout=5) wait_for(f'its ssh and socket gone ({name})', lambda: not forwarded(), timeout=10) body = texts() for words in (b'from-A', b'from-B', b'again-A', b'from-C', b'from-D', b'from-E', b'from-F'): @@ -2516,6 +2643,7 @@ def main(binary, cycles): pair(binary) pair_rows(binary) attach_upgrading(binary) + kept_views(binary) pair_upgrade_views(binary) manage(binary) relink(binary) @@ -2662,11 +2790,8 @@ def main(binary, cycles): client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() - # Sized twice (Ptys.take): a run into a prompt redrawn under it - # reads as not run (core/ninep/pty.zig). - wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') - said = run(client, pane, b'echo $$\n') - assert said.split(b'\n')[1] == str(shell_pid).encode(), said + pid, said = adopted_pid(client, pane) + assert pid == str(shell_pid).encode(), said print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') # Attached again: a client. (After the runs: a pty/run under a # client puts it off the session's state, and it joins again; one @@ -3109,6 +3234,16 @@ def upgrades(old, new): 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)) + # Two clients' views kept at the Upgrade, with the time (views.away), + # whose clients never come back (the raw replica, the old build's): + # each its client's for 30 s, and the session's views all taken. + # The first join waits as long as its refusal says. + if keeps_views(old): + said = Replica(root / 'pardes-replica.sock').hello('work', new_build) + kept = re.search(r'one is kept (\d+) s more', said[1]) if said[0] == 'refused' else None + if kept: + time.sleep(int(kept.group(1)) + .5) + print(f'upgrade: two views kept for clients that never came back; the join waited {kept.group(1)} s for one, as its refusal said') # 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 @@ -3161,9 +3296,7 @@ def upgrades(old, new): wait_for('the client joined again', lambda: b'joined again: the session is upgrading' in t.text(), timeout=30) assert again.poll() is None and again5.poll() is None for (t, check), pane, theirs in zip(owners, mine, reversed(mine)): - made_live(t, check) - shown = view_panes(client) - assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, client.read('/layout')) + in_own_view('its own view again', lambda: made_live(t, check), client, pane, theirs) for c, t in ((again, term4), (again5, term5)): c.send_signal(signal.SIGHUP) c.wait(timeout=10) @@ -3224,7 +3357,8 @@ def upgrades(old, new): 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() + pid, said = adopted_pid(client, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) 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) @@ -3244,6 +3378,26 @@ def upgrades(old, new): shutil.rmtree(root, ignore_errors=True) +def knows_size(gui_binary): + """Whether a build's window exec'd at an Upgrade comes back the size + it had (PARDES_JOIN_SIZE: client.zig `execAgain`).""" + return b'PARDES_JOIN_SIZE' in Path(gui_binary).read_bytes() + + +def keeps_views(binary): + """Whether a build keeps its clients' views at an Upgrade with the time + each was kept (View.away_ns), so that the build after holds them.""" + return b'away_ns' in Path(binary).read_bytes() + + +def redials_far(binary): + """Whether a build's far client whose link an Upgrade cuts with no last + word dials again (core/replica.zig `cutListed`'s `far`) rather than take + it for its session's end: the change that made it gave the window its + size at its exec too (PARDES_JOIN_SIZE), the string that says so.""" + return b'PARDES_JOIN_SIZE' in Path(binary).read_bytes() + + 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).""" @@ -3332,10 +3486,10 @@ def upgrade_clients(old, new): 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')) + in_own_view('its own view again', lambda: still(check, key), nine, pane, theirs) + else: + still(check, key) 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 @@ -3469,12 +3623,18 @@ if __name__ == '__main__': upgrades(old, new) if knows_exec(old): pair_exec_reaps(old, new) - far_exec(old, new) + if redials_far(old): + far_exec(old, new) + else: + print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)') # With a pardes-gui beside each: the clients carried too. 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')) + if knows_size(old.with_name('pardes-gui')): + pair_window_geometry(old.with_name('pardes-gui'), new.with_name('pardes-gui')) + else: + print('pair window geometry: skipped: the old build\'s window passes no size at its exec (no PARDES_JOIN_SIZE)') 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']: @@ -3486,7 +3646,7 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--pair']: pair(sys.argv[2]) pair_rows(sys.argv[2]) - attach_upgrading(sys.argv[2]) + attach_upgrading(sys.argv[2], dump=False) pair_upgrade_views(sys.argv[2]) elif sys.argv[1:2] == ['--attach-upgrading']: attach_upgrading(sys.argv[2]) |
