summaryrefslogtreecommitdiff
path: root/test/daemon.py
diff options
context:
space:
mode:
Diffstat (limited to 'test/daemon.py')
-rw-r--r--test/daemon.py162
1 files changed, 120 insertions, 42 deletions
diff --git a/test/daemon.py b/test/daemon.py
index caa1272b..f456837b 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -188,14 +188,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')
+def pid_in(client, pane):
+ """The pid of terminal `pane`'s shell, its `echo $$` by pty/run, asked
+ at once: a run written before its first prompt (or before the prompt
+ after its greeting) waits for it, and one under a prompt drawn again
+ (a window's first size, an adoption's two) is still the line run
+ (core/ninep/pty.zig). Any other answer is said whole."""
said = run(client, pane, b'echo $$\n')
- return said.split(b'\n')[1], said
+ pid = re.fullmatch(rb'exit 0\n([0-9]+)\n', said)
+ assert pid, f'pane {pane}: `echo $$` answered {said!r}'
+ return int(pid[1])
# FreeBSD has no /proc: ps and procstat answer instead.
@@ -611,7 +613,8 @@ def clients(binary):
c = tc.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check')))
started.append(c.pid)
wait_for('client C\'s first frame', lambda: b'$' in tc.text(), timeout=20)
- run(nine, shell, b'echo from-the-session\n')
+ said = run(nine, shell, b'echo from-the-session\n')
+ assert said == b'exit 0\nfrom-the-session\n', said
os.write(tc.master, b'echo from-C\r')
wait_for('client C\'s keys in the shell', lambda: b'from-C' in nine.read(f'/pane/{shell}/body'))
wait_for('client C agrees with a shell\'s output', lambda: agreed(root / 'c.check', 0))
@@ -1332,12 +1335,18 @@ def pair_upgrade_views(binary):
shutil.rmtree(root, ignore_errors=True)
-def pair_exec_reaps(old, new):
+def pair_exec_reaps(old, new, early=False):
"""PARDES_PAIR across builds: a pair started from `root/bin` (old), its
session upgraded to the build installed there since (new): its client,
the session's parent, execs that build (the blink) and is still its
parent; Exit typed then: the client returns once the session is gone,
- reaped, its status the session's (0), as before the exec."""
+ reaped, its status the session's (0), as before the exec. `early`: old
+ and new the same build, installed again at once, before the session's
+ first pass round its loop, where it first looks its start path up
+ (upgrade.zig `locate`), and as the client starts the daemon from its
+ own (daemon.zig `spawn`): the path is the path, not Linux's "PATH
+ (deleted)", so the daemon starts and the session execs it; the client,
+ its build the session's still, joins again in place (no exec)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch))
@@ -1352,36 +1361,48 @@ def pair_exec_reaps(old, new):
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
+ sock = root / 'pardes-9p-px.sock'
+ c = session = None
try:
t = Term(30, 100)
terms.append(t)
c = t.spawn([str(binary), '--9p=px', str(notes)], env)
- sock = root / 'pardes-9p-px.sock'
+ if early:
+ install(new, binary)
wait_for('the socket', sock.exists)
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
assert ppid(session) == c.pid
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
- install(new, binary)
+ if not early:
+ 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)
+ if early:
+ wait_for('joined again in place', lambda: b'joined again' in t.text()[mark:], timeout=30)
+ else:
+ wait_for('the client on the new build', lambda: on_build(c, binary), timeout=30)
nine = reconnect(sock)
assert ppid(session) == c.pid
# 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)
+ if not early:
+ wait_for('drawn again', lambda: b'line 3 of the notes' in (entered_again(t.text(), mark) or b''), timeout=30)
nine.write('/ctl', b'Exit\n')
nine.socket.close()
assert c.wait(timeout=30) == 0, c.returncode
# Its parent's wait returned: the session reaped, not a zombie left
# to whoever takes it in.
assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read()
- print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0')
+ print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0'
+ + (' (the same build installed again before the session looked its path up: joined again in place)' if early else ''))
+ except (TimeoutError, AssertionError, OSError, EOFError, subprocess.TimeoutExpired) as err:
+ kept = keep_evidence('pair-exec', root, env, binary, sock, [('session', session)] if session else [],
+ [('client', t, c, root / 'client.check', root / 'client.stats')] if c else [])
+ raise AssertionError(f'{type(err).__name__}: {err} (kept: {kept})') from None
finally:
for p in processes(root):
try:
@@ -1439,8 +1460,8 @@ def far_exec(old, new):
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
nine = reconnect(sock)
- wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
- wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ wait_for('the far client on the new build', lambda: on_build(c, binary), timeout=30)
+ wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30)
# Its environment read once the new image runs (it entered the
# screen): an exec names the new file in /proc/PID/exe before it has
# written where the environment is, and a read between gets nothing
@@ -1518,7 +1539,7 @@ def pair_window_geometry(gui_binary, new_gui):
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 window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30)
+ wait_for('the window on the new build', lambda: on_build(p, gui), timeout=30)
nine = reconnect(sock)
time.sleep(3)
assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain)
@@ -1573,8 +1594,7 @@ def manage(binary):
c.write('/pane/1/exec', b'Term\n')
wait_for(f'session {name}\'s shell', lambda: terminals(c))
shell = terminals(c)[0]
- wait_for(f'session {name}\'s shell answers', lambda: run(c, shell, b'true\n') == b'exit 0\n')
- shells[name] = int(run(c, shell, b'echo $$\n').split(b'\n')[1])
+ shells[name] = pid_in(c, shell)
started.append(shells[name])
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
@@ -1678,8 +1698,7 @@ def relink(binary):
work.write('/pane/1/exec', b'Term\n')
wait_for('its shell', lambda: terminals(work))
shell = terminals(work)[0]
- wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n')
- shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(work, shell)
started.append(shell_pid)
term = Term()
terms.append(term)
@@ -1691,7 +1710,7 @@ def relink(binary):
started.append(own_pid)
wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text())
own_shell = terminals(own)[0]
- own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1])
+ own_shell_pid = pid_in(own, own_shell)
started.append(own_shell_pid)
expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("has a frontend")}',
f'shell {shell_pid}', f'shell {own_shell_pid}']
@@ -1723,8 +1742,7 @@ 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()
- pid, said = adopted_pid(own, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(own, pane)) == shell_pid, (pid, 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)
@@ -1774,7 +1792,7 @@ def answer_late(binary):
one = Client(root / 'pardes-9p-one.sock')
session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
started.append(session)
- shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(one, terminals(one)[0])
started.append(shell_pid)
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
@@ -1798,8 +1816,7 @@ 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()
- pid, said = adopted_pid(two, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(two, pane)) == shell_pid, (pid, 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)
@@ -2852,6 +2869,46 @@ def cpu_ticks(pid):
return int(stat[11]) + int(stat[12])
+def killed_session(binary):
+ """A terminal's session killed outright (KILL, as the OOM killer does):
+ the job its terminal waits on ends with it, and says nothing of its own
+ (no trace): the own path's stub dead of the same signal, as a job is
+ (daemon.zig `stubWait`, which aborted re-raising a KILL); a pair's
+ client let go of its session, 1."""
+ 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 = base_env()
+ 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')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ t = Term(30, 100)
+ try:
+ c = t.spawn([binary, '--9p=k', str(notes)], env)
+ sock = root / 'pardes-9p-k.sock'
+ wait_for('the socket', sock.exists)
+ with Client(sock) as nine:
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ os.kill(session, signal.SIGKILL)
+ code = c.wait(timeout=30)
+ said = t.last()
+ assert b'panic' not in said and b'unreachable' not in said, said[-1500:]
+ assert code == (1 if WITH_PAIR else -signal.SIGKILL), (code, said[-600:])
+ print(f'killed session: its terminal\'s job ended {code} with it, no trace')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def kitty_image(binary, secs=5):
"""A plain attach watching a terminal in which a program
shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it
@@ -2960,7 +3017,7 @@ def main(binary, cycles):
answer_late(binary)
kitty_image(binary)
shell = terminals(client)[0]
- shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
# Detach in the terminal it was born with: the stub ends (exit 0,
# its words), the terminal put back; the session runs on detached,
@@ -3101,8 +3158,7 @@ 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()
- pid, said = adopted_pid(client, pane)
- assert pid == str(shell_pid).encode(), said
+ assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
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
@@ -3392,7 +3448,10 @@ def exe_of(pid):
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:
+ link = os.readlink(f'/proc/{pid}/exe')
+ except OSError: # gone, or a zombie: it runs nothing
+ return '', False
try:
same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino
except OSError:
@@ -3400,6 +3459,22 @@ def exe_of(pid):
return link, same
+def entered_again(text, mark):
+ """The blink of a client exec'd at an Upgrade: its terminal's screen
+ left at or after `mark` (the text's length before the Upgrade: when the
+ reader had read all the old client wrote, the leave is its very next
+ byte) and entered again. What was drawn since that enter, or None."""
+ enter, leave = text.rfind(b'\x1b[?1049h'), text.rfind(b'\x1b[?1049l')
+ return text[enter:] if enter > leave >= mark else None
+
+
+def on_build(proc, binary):
+ """Whether the test's child `proc` runs `binary` now (exe_of); one that
+ ended says so with its status at once, not as a wait run out."""
+ assert proc.poll() is None, f'pid {proc.pid} ended ({proc.returncode}) before it ran {binary}'
+ return exe_of(proc.pid) == (str(binary), True)
+
+
def ppid(pid):
if not procfs:
return int(ps('-o', 'ppid=', '-p', str(pid)))
@@ -3509,7 +3584,7 @@ def upgrades(old, new):
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])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
@@ -3699,7 +3774,7 @@ def upgrades(old, new):
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()
+ assert (pid := pid_in(client, shell)) == shell_pid, (pid, shell_pid)
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.
@@ -3712,8 +3787,8 @@ def upgrades(old, new):
kept = client.read('/dumps').decode()
assert any(line.split()[0].startswith(f'upgrade-{session}') for line in kept.splitlines()), kept
assert alive(shell_pid) and ppid(shell_pid) == session, ('the shell under the fresh session', shell_pid, 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()]]
+ pids = {p: pid_in(client, p) for p in terminals(client)}
+ adopted = [p for p, pid in pids.items() if pid == shell_pid]
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')
@@ -3750,8 +3825,7 @@ 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()
- pid, said = adopted_pid(client, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted')
exit_session(client, pane)
stub.wait(timeout=10)
@@ -3850,7 +3924,7 @@ def upgrade_clients(old, new):
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])
+ shell_pid = pid_in(nine, shell)
t = Term(30, 100)
terms.append(t)
tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
@@ -3888,7 +3962,7 @@ def upgrade_clients(old, new):
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)
+ wait_for('the terminal entered again', lambda: entered_again(t.text(), 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)):
if knows_exec(new):
@@ -3955,7 +4029,7 @@ def gui_upgrades(old, new):
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])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
@@ -4035,6 +4109,9 @@ if __name__ == '__main__':
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)')
+ # A reinstall of the new build before the pair's first look: the
+ # new build's own, whatever the old one does.
+ pair_exec_reaps(new, new, early=True)
# 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)
@@ -4092,3 +4169,4 @@ if __name__ == '__main__':
gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
+ killed_session(sys.argv[1])