1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
|
#!/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 <pardes> [cycles]
python3 -B test/daemon.py --gui <pardes-gui> [cycles] (a hidden window;
needs a Wayland display, and a pardes beside it for the refusal)
python3 -B test/daemon.py --ping <socket> <session> <pardes> [n]
a hello of <pardes>'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('<IQI', fid, 0, len(line)) + line)
return client.read_fid(fid)
finally:
client.close(fid)
# FreeBSD has no /proc: ps and procstat answer instead.
procfs = os.path.isdir('/proc/self')
def ps(*args):
return subprocess.run(['ps', *args], capture_output=True).stdout
def processes(root):
"""The pids whose environment is this run's (its runtime directory)."""
found = []
mark = f'XDG_RUNTIME_DIR={root}'.encode()
if not procfs: # ps -e prints each environment before its command
return [int(row.split()[0]) for row in ps('-axeww', '-o', 'pid=', '-o', 'command=').splitlines()
if mark in row.split()]
for entry in os.listdir('/proc'):
if not entry.isdigit():
continue
try:
environ = open(f'/proc/{entry}/environ', 'rb').read().split(b'\0')
except OSError:
continue
if mark in environ:
found.append(int(entry))
return found
def cmdline(pid):
if not procfs:
return ps('-ww', '-o', 'args=', '-p', str(pid)).split()
try:
return open(f'/proc/{pid}/cmdline', 'rb').read().split(b'\0')
except OSError:
return []
def alive(pid):
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
if not procfs:
return not ps('-o', 'state=', '-p', str(pid)).startswith(b'Z')
try:
state = open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[0]
except OSError:
return False
return state != 'Z'
def fds(pid):
if not procfs:
return len(subprocess.run(['procstat', '-f', str(pid)], capture_output=True).stdout.splitlines()) - 1
try:
return len(os.listdir(f'/proc/{pid}/fd'))
except OSError:
return -1
def semantics(binary):
"""What a replica's build must share with its session's (--version)."""
out = subprocess.run([binary, '--version'], capture_output=True, check=True).stdout.decode()
return int(next(line.split()[1] for line in out.splitlines() if line.startswith('semantics ')), 16)
class Replica:
"""A replica's connection (src/detached/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length."""
WIRE = 14
def __init__(self, path, timeout=10):
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.s.settimeout(timeout)
self.s.connect(os.fspath(path))
def send(self, tag, payload):
self.s.sendall(struct.pack('<BI', tag, len(payload)) + payload)
def take(self, n):
got = b''
while len(got) < n:
more = self.s.recv(n - len(got))
if not more:
raise EOFError('the connection ended')
got += more
return got
def read(self):
tag, n = struct.unpack('<BI', self.take(5))
return tag, self.take(n)
def hello(self, session, build):
"""('welcome', pid, name) or ('refused', why)."""
name = session.encode()
self.send(0x01, struct.pack('<HQH', self.WIRE, build, len(name)) + name)
tag, body = self.read()
if tag == 0x01:
pid, n = struct.unpack_from('<IH', body)
return 'welcome', pid, body[6:6 + n].decode()
assert tag == 0x02, (tag, body)
n, = struct.unpack_from('<H', body)
return 'refused', body[2:2 + n].decode()
def ping(self, value):
"""One round trip, in ms."""
t = time.monotonic()
self.send(0x03, struct.pack('<Q', value))
tag, body = self.read()
assert (tag, body) == (0x03, struct.pack('<Q', value)), (tag, body)
return (time.monotonic() - t) * 1000
def close(self):
self.s.close()
def replicas(root, binary, session, daemon):
sock = root / 'pardes-replica.sock'
wait_for('the replicas\' socket', sock.exists)
assert len(os.fspath(sock)) < 104, 'FreeBSD\'s sun_path'
ours = semantics(binary)
before = fds(session), fds(daemon)
t = time.monotonic()
r = Replica(sock)
said = r.hello('work', ours)
hello_ms = (time.monotonic() - t) * 1000
# The session answers, so the connection is its own now: the daemon
# keeps no copy of it.
assert said == ('welcome', session, 'work'), said
rtt = [r.ping(i) for i in range(50)]
assert fds(session) == before[0] + 1 and fds(daemon) == before[1], (before, fds(session), fds(daemon))
r.close()
wait_for('the replica\'s end, in the session', lambda: fds(session) == before[0])
said = Replica(sock).hello('work', ours ^ 1)
assert said[0] == 'refused' and 'another build' in said[1] and f'{ours ^ 1:016x}' in said[1], said
said = Replica(sock).hello('nobody', ours)
assert said == ('refused', "no session called 'nobody'"), said
wait_for('the daemon\'s refused connections closed', lambda: fds(daemon) == before[1])
print(f'daemon: a replica handed to its session (hello {hello_ms:.2f} ms, ping median '
f'{statistics.median(rtt):.3f} ms); another build, and a session nobody has, refused')
def ping(path, session, binary, n):
build = semantics(binary)
t = time.monotonic()
r = Replica(path, timeout=30)
said = r.hello(session, build)
hello_ms = (time.monotonic() - t) * 1000
if said[0] != 'welcome':
sys.exit(f'refused: {said[1]}')
rtt = sorted(r.ping(i) for i in range(n))
r.send(0x02, b'')
r.close()
print(f'connect and hello {hello_ms:.2f} ms; {n} pings min/median/p90/max '
f'{rtt[0]:.2f}/{statistics.median(rtt):.2f}/{rtt[int(n * .9) - 1]:.2f}/{rtt[-1]:.2f} ms')
def terminals(client):
return [int(row.split()[0]) for row in client.read('/index').splitlines() if row.split()[1] == b'term']
def main(binary, cycles):
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rt-', 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')
daemon_sock = root / 'pardes-daemon.sock'
started = []
try:
term = Term()
stub = term.spawn([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)
status = dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())
session = int(status['pid'])
started.append(session)
assert session != stub.pid, 'the session is forked off its stub'
assert daemon_sock.exists(), list(root.iterdir())
daemons = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']]
assert len(daemons) == 1, [cmdline(p) for p in processes(root)]
daemon = daemons[0]
started.append(daemon)
replicas(root, binary, session, daemon)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
baseline = None
for cycle in range(cycles):
client.write(f'/pane/{shell}/exec', b'Detach\n')
assert stub.wait(timeout=10) == 0, stub.returncode
said = term.text()
assert b'detached from \'work\'' in said, said[-400:]
assert b'\x1b[?1049l' in said, 'the terminal is put back'
term.close()
assert alive(session) and alive(shell_pid)
assert run(client, shell, b'echo still\n').startswith(b'exit 0\nstill'), 'the shell runs on, detached'
term = Term(30, 100)
stub = term.spawn([binary, '--attach=work'], 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: client.screen()['cols'] == 100 and client.screen()['rows'] == 30)
now = (fds(session), fds(daemon), len(list(root.iterdir())), len(processes(root)))
if baseline is None:
baseline = now
assert now == baseline, (cycle, now, baseline)
print(f'daemon: {cycles} detach/attach cycles, fds/sockets/processes level: {baseline}')
# Another terminal while one is attached: a view of its own
# (src/views.zig), drawn beside the first. Detached from inside, its
# stub ends and the first draws on; closed outright, the same.
for how in ('detach', 'close'):
# Bigger than the first: the shell, sized for the first (its
# last typist), shows whole in it.
term2 = Term(40, 120)
stub2 = term2.spawn([binary, '--attach=work'], env)
started.append(stub2.pid)
wait_for('the second terminal\'s first frame', lambda: b'\x1b[?1049h' in term2.text())
wait_for('the second terminal\'s view live', lambda: client.screen()['cols'] == 120)
seen = len(term.text())
run(client, shell, f'echo both-drawn-{how}\n'.encode())
wait_for('the first terminal drawn', lambda: f'both-drawn-{how}'.encode() in term.text()[seen:])
wait_for('the second terminal drawn', lambda: f'both-drawn-{how}'.encode() in term2.text())
assert stub.poll() is None and stub2.poll() is None
if how == 'detach':
# Its view is the live one (its terminal spoke last).
client.write(f'/pane/{shell}/exec', b'Detach\n')
assert stub2.wait(timeout=10) == 0, stub2.returncode
assert b'detached from \'work\'' in term2.text(), term2.text()[-400:]
term2.close()
else:
term2.close()
stub2.wait(timeout=10)
wait_for('the first terminal\'s view live again', lambda: client.screen()['cols'] == 100)
seen = len(term.text())
run(client, shell, f'echo first-on-{how}\n'.encode())
wait_for('the first terminal drawn on', lambda: f'first-on-{how}'.encode() in term.text()[seen:])
assert stub.poll() is None, 'the first terminal stays attached'
now = (fds(session), fds(daemon), len(list(root.iterdir())), len([p for p in processes(root) if alive(p)]))
assert now[:3] == baseline[:3], (how, now, baseline)
print('daemon: a second terminal on an attached session drawn beside the first, then detached and closed; the first drew on')
# Killed outright: its shells live on, their masters the daemon's.
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
client.socket.close()
term.close()
wait_for('the killed session gone', lambda: not alive(session))
time.sleep(.3)
assert alive(shell_pid), 'a killed session\'s shell is not hung up'
assert alive(daemon)
# Started from a shell, which leads the terminal's session and
# outlives the stub, as a terminal's shell does (on FreeBSD the
# leader's exit revokes the terminal for every process).
term = Term()
stub_pid = root / 'stub.pid'
shell = term.spawn(['sh', '-c', '"$@" & echo $! > "$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)
if __name__ == '__main__':
if 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)
|