diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-21 09:10:24 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-21 09:10:24 -0300 |
| commit | c4f7bb9477c7aa4c8864f14edb9e85b6c8c08437 (patch) | |
| tree | 9b60bce9e53f96855b40f2ba53e23945a7798ddf | |
| parent | f7de6f49ee3d9ac241575f5244743193c9943841 (diff) | |
| parent | 5ad6067936f306271b875aaf182d4866055da10d (diff) | |
| download | pardes-c4f7bb9477c7aa4c8864f14edb9e85b6c8c08437.tar.gz pardes-c4f7bb9477c7aa4c8864f14edb9e85b6c8c08437.zip | |
integration: the pair's round 5 and the layers' round 2 on the gathered line: pardes-pair-5 (`ssrtxkzx`, on pardes-merge48: a link an Upgrade cuts with no last word asks the daemon whether its session is listed still and joins again (`replica.cutListed`): an upgrade from the installed build carries its clients; a no-daemon pair refuses Restore in words (P42); /dev/tty opened before the pair forks; a TERMed or hung-up client dies of the signal; the process suite as pairs 13 to 8 of 145) and pardes-layers-2 (`myxnnquu`, on pardes-merge49: the click on path@rev tested, a revision read-only from 9P, Syntax off in a patch keeps the patch's colours); no conflict; core-test 893/1053 (160 skipped), shell-test 1095/1098; its gate: .scratch/sketch/reorg/merge50, the numbers in PARDES.md (2026-11-21)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | core/replica.zig | 28 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 4 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 22 | ||||
| -rw-r--r-- | runtime/client.zig | 19 | ||||
| -rw-r--r-- | runtime/main.zig | 17 | ||||
| -rw-r--r-- | runtime/session.zig | 4 | ||||
| -rw-r--r-- | test/daemon.py | 58 | ||||
| -rw-r--r-- | test/e2e_harness.zig | 4 | ||||
| -rw-r--r-- | test/process.zig | 35 | ||||
| -rw-r--r-- | test/process/flags.zig | 4 | ||||
| -rw-r--r-- | test/process/root_ctl.zig | 3 | ||||
| -rw-r--r-- | test/process/tty_boot.zig | 2 | ||||
| -rw-r--r-- | test/tty.zig | 22 |
13 files changed, 199 insertions, 23 deletions
diff --git a/core/replica.zig b/core/replica.zig index 56fc4a59..97da9c74 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -3112,6 +3112,26 @@ pub fn ended(why: []const u8) bool { /// What an Upgrade tells its clients (`Peers.refuseAll`): each dials again. pub const upgrading = "the session is upgrading to another build of pardes"; +/// A link cut with no last word (`why` its hang-up) whose session its +/// daemon lists still: an Upgrade's exec cut it, a dump on the way past the +/// clients' flush (`Peers.refuseAll`), whichever build the session is, not +/// the session's end, which the daemon sees as its link's: so the client +/// joins again as one told `upgrading` does, whatever the flush's bound let +/// through. Near, this machine's daemon is asked; far, the dial again is +/// the asking (the far daemon's "no session called" ends it: `redial`). +pub fn cutListed(why: []const u8, session: []const u8, far: bool) bool { + if (!std.mem.startsWith(u8, std.mem.sliceTo(why, 0), "the session hung up")) return false; + if (far) return true; + var buf: [8192]u8 = undefined; + const list = daemon.ask("list", &buf) orelse return false; + var lines = std.mem.tokenizeScalar(u8, list, '\n'); + while (lines.next()) |line| { + if (!std.mem.startsWith(u8, line, "session ")) continue; + if (std.mem.eql(u8, line[(std.mem.lastIndexOfScalar(u8, line, ' ') orelse continue) + 1 ..], session)) return true; + } + return false; +} + /// The words a client goes with when its session runs another build now. const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; @@ -3151,8 +3171,9 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o redial(gpa, path, session, why, have, true, v) else sameBuild(gpa, (dial(gpa, path, session, why, have, null) orelse - // Handed to the session as it upgraded: it is there again soon. - if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why)) orelse return null; + // Handed to the session as it upgraded, or cut by its exec with + // its dump on the way: it is there again soon. + if (std.mem.eql(u8, std.mem.sliceTo(why, 0), upgrading) or cutListed(why, session, have != null)) redial(gpa, path, session, why, have, true, null) else null) orelse return null, why)) orelse return null; defer { if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; @@ -3280,6 +3301,9 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, _ = std.fmt.bufPrint(why, "{s}\x00", .{upgrade_words}) catch {}; return null; } + // Its daemon lists no such session: it is gone, not away a moment + // (an Upgrade keeps it listed throughout). + if (std.mem.startsWith(u8, words, "no session called ")) return null; if (!patient or tries > 200) return null; const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; _ = libc.nanosleep(&ts, null); diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index d779cf47..aa28a3f0 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -808,7 +808,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, di var want_w: c_int = 1120; var want_h: c_int = 720; var want_at: ?[2]c_int = null; - if (opts_in.geometry) |spec| geometry: { + // ...or the size an Upgrade's exec says its window had (client.zig + // `execAgain`). + if (opts_in.geometry orelse if (std.c.getenv("PARDES_JOIN_SIZE")) |e| std.mem.span(e) else null) |spec| geometry: { const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 09704424..7e5a75fb 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -731,6 +731,10 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, posix.sigaddset(&winch_set, posix.SIG.HUP); posix.sigaddset(&winch_set, posix.SIG.TERM); hangup_quits = true; + // Last of all, after its goodbye and its terminal put back: dead of the + // TERM or HUP that ended it, as the own path's stub dies (the shell's + // $? is 128+N), not exit 0. + defer dieOfQuitSignal(); if (comptime builtin.os.tag == .freebsd) posix.sigaction(.WINCH, &.{ .handler = .{ .handler = keepSignal }, .mask = posix.sigemptyset(), .flags = 0 }, null); posix.sigprocmask(posix.SIG.BLOCK, &winch_set, null); @@ -808,6 +812,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var status: c_int = 0; while (libc.waitpid(@intCast(start.joined.pid), &status, 0) < 0 and libc.errno(-1) == .INTR) {} } + dieOfQuitSignal(); std.process.exit(code); }, .failed => { @@ -1954,6 +1959,22 @@ fn keepSignal(_: posix.SIG) callconv(.c) void {} /// A replica client's (`runClient`): a hangup or a TERM is its end. var hangup_quits = false; +/// The signal a client's `.quit` came of (`winchWatch`), 0 for none. +var quit_signal: std.atomic.Value(c_int) = .init(0); + +/// A client ended by TERM or HUP dies of it, its goodbye said and its +/// terminal put back first; no other way out. +fn dieOfQuitSignal() void { + const sig: posix.SIG = @enumFromInt(quit_signal.load(.acquire)); + if (@backingInt(sig) == 0) return; + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + var set = posix.sigemptyset(); + posix.sigaddset(&set, sig); + posix.sigprocmask(posix.SIG.UNBLOCK, &set, null); + _ = std.c.raise(sig); +} + fn winchWatch(loop: *Loop) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); @@ -1965,6 +1986,7 @@ fn winchWatch(loop: *Loop) void { // The terminals are the loop's: it asks each its size, and takes a // hangup as the end of the one that hung up. const ev: Msg = if (sig == @backingInt(posix.SIG.WINCH)) .winched else if (hangup_quits) .quit else .hangup; + if (ev == .quit) quit_signal.store(sig, .release); loop.postEvent(ev) catch {}; } } diff --git a/runtime/client.zig b/runtime/client.zig index d4b76a1b..49ebbc6e 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -129,24 +129,29 @@ pub fn execAgain(s: *Start, view: u8, size: ?[2]c_int) []const u8 { const path = upgrade.exe() orelse return "Upgrade: this client does not know the path it was started from"; var at_buf: [4200]u8 = undefined; const at = std.fmt.bufPrintSentinel(&at_buf, "--attach={s}:{s}", .{ s.dial.path, s.dial.session }, 0) catch return "Upgrade: the session's socket's path is too long to attach again by"; - // A window's new window the size it had (`--geometry`), not the default. + const argv = [_:null]?[*:0]const u8{ path, at }; + // A window's new window the size it had (gui.zig reads it as a + // `--geometry`), not the default. var size_buf: [48]u8 = undefined; - const geometry: ?[*:0]const u8 = if (size) |wh| (std.fmt.bufPrintSentinel(&size_buf, "--geometry={d}x{d}", .{ wh[0], wh[1] }, 0) catch unreachable).ptr else null; // two c_ints fit 48 - const argv = [_:null]?[*:0]const u8{ path, at, geometry }; + const sized: ?[*:0]const u8 = if (size) |wh| (std.fmt.bufPrintSentinel(&size_buf, "PARDES_JOIN_SIZE={d}x{d}", .{ wh[0], wh[1] }, 0) catch unreachable).ptr else null; // two c_ints fit 48 var view_buf: [32]u8 = undefined; const joining = std.fmt.bufPrintSentinel(&view_buf, "PARDES_JOIN_VIEW={d}", .{view}, 0) catch unreachable; // a u8 fits 32 var n: usize = 0; while (libc.environ[n] != null) n += 1; - const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 2, null) catch return "Upgrade: no memory for this client's environment"; + const envp = s.gpa.allocSentinel(?[*:0]const u8, n + 3, null) catch return "Upgrade: no memory for this client's environment"; var k: usize = 0; for (libc.environ[0..n]) |e| { const entry = std.mem.span(e.?); - if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue; + if (std.mem.startsWith(u8, entry, "PARDES_JOIN_VIEW=") or std.mem.startsWith(u8, entry, "PARDES_JOIN_SIZE=") or std.mem.startsWith(u8, entry, "PARDES_REPLICA_FAR=")) continue; envp[k] = e; k += 1; } envp[k] = joining.ptr; k += 1; + if (sized) |e| { + envp[k] = e; + k += 1; + } if (s.have != null) { envp[k] = "PARDES_REPLICA_FAR=1"; k += 1; @@ -218,6 +223,10 @@ pub fn Loop(comptime Frontend: type) type { reader.join(); _ = libc.close(s.joined.fd); s.joined.rest.deinit(s.gpa); + // Its link cut with no word by a session that is there still + // (an Upgrade's exec): joined again, as when told so. + if (link.gone and link.refused == null and link.ended == null and !link.left and replica.cutListed("the session hung up", s.dial.session, s.have != null)) + link.refused = std.heap.c_allocator.dupe(u8, replica.upgrading) catch null; // Why it joins again is in its notice until a key. if (!link.rejoins()) { // What it made since it joined, kept for its next start. diff --git a/runtime/main.zig b/runtime/main.zig index b0338831..aa35e687 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -1632,8 +1632,7 @@ fn nativeMain(std_init: std.process.Init) !void { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { - std.Io.File.stderr().writeStreamingAll(init.io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {}; - std.process.exit(1); + noTerminal(init.io); }, else => return err, }, @@ -1761,6 +1760,13 @@ fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 { /// the client exits. No fork to be had: returns, and this process is the /// session, with no terminal: said by the caller's run. A window with no /// `pardes` beside it returns at once, its own session as before. +/// A terminal's launch with no terminal to draw on (a detached pty, a +/// daemon): said, not an error trace, and exit 1. +fn noTerminal(io: std.Io) noreturn { + std.Io.File.stderr().writeStreamingAll(io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {}; + std.process.exit(1); +} + fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void { var path_buf: [4104]u8 = undefined; var fd_buf: [32]u8 = undefined; @@ -1771,6 +1777,13 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u argv[0] = path.ptr; for (args[1..], 2..) |a, k| argv[k] = a.ptr; } + // Its client draws on /dev/tty: none to be had, said as the own path + // says it, before a session is forked for nobody. + if (pardes.platform == .tui) { + const tty = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0)); + if (tty < 0) noTerminal(init.io); + _ = std.c.close(tty); + } const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null; var fds: [2]c_int = undefined; if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) diff --git a/runtime/session.zig b/runtime/session.zig index 60644aa6..5e99384e 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -188,6 +188,10 @@ pub fn Loop(comptime Frontend: type) type { /// let go (host_io.restoreCore); its shells and the frontend's /// devices with it. fn restore(l: *L, path: []const u8) void { + // A pair's session no daemon keeps: a Restore lets every client + // go, and its one could not join it again (no socket finds it): + // refused, as its Upgrade is (tui.zig `upgradeNow`). + if (l.peers.count() > 0 and daemon.link < 0) return l.core.reportFailure(l.core.view().active, "Restore: no daemon keeps this session, so its client could not join it again; this session stays as it is"); const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return; l.fe.restoring(nc); // The old core's pipes end, and an answer to its query is diff --git a/test/daemon.py b/test/daemon.py index 041bc75b..5c075520 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -806,13 +806,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() @@ -826,7 +827,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 @@ -834,7 +835,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() @@ -888,7 +889,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 @@ -932,8 +933,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: @@ -3259,6 +3292,12 @@ 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 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).""" @@ -3489,7 +3528,10 @@ if __name__ == '__main__': 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']: @@ -3501,7 +3543,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]) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index 9481166e..40209af3 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -108,7 +108,9 @@ pub const Harness = struct { if (unsetenv(name) != 0) _exit(126); // The app is the process this kills and the terminal it hangs // up (deinit): no daemon to fork it off and keep it (daemon.zig). - if (setenv("PARDES_DAEMON", "off", 1) != 0) _exit(126); + // PARDES_HARNESS_DAEMON (tty.zig `privateDaemon`): a daemon of + // the case's own runtime directory, for a pair that is Restored. + if (setenv("PARDES_DAEMON", if (std.mem.span(std.c.getenv("PARDES_HARNESS_DAEMON") orelse "").len > 0) "on" else "off", 1) != 0) _exit(126); _ = execvp(exe, argv.ptr); _exit(127); } diff --git a/test/process.zig b/test/process.zig index e2a4f592..791a5b8e 100644 --- a/test/process.zig +++ b/test/process.zig @@ -496,10 +496,25 @@ pub const Files = struct { } }; -/// The files of the app a pty harness started. +/// The files of the app a pty harness started: its session's, named by +/// its pid, which is the app's own, or under PARDES_PAIR the app's child's +/// (the app the client, its session forked off: main.zig `pair`). pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files { var digits: [24]u8 = undefined; - return .init(gpa, std.fmt.bufPrint(&digits, "{d}", .{h.pid}) catch unreachable); + return .init(gpa, std.fmt.bufPrint(&digits, "{d}", .{if (std.c.getenv("PARDES_PAIR") != null) childOf(h.pid) else h.pid}) catch unreachable); +} + +/// A process's one child (Linux's /proc), or itself when it has none. +fn childOf(pid: libc.pid_t) libc.pid_t { + var path: [64]u8 = undefined; + var buf: [64]u8 = undefined; + const fd = libc.open(std.fmt.bufPrintSentinel(&path, "/proc/{d}/task/{d}/children", .{ pid, pid }, 0) catch unreachable, .{}); // two pids fit 64 + if (fd < 0) return pid; + defer _ = libc.close(fd); + const n = libc.read(fd, &buf, buf.len); + if (n <= 0) return pid; + var words = std.mem.tokenizeScalar(u8, buf[0..@intCast(n)], ' '); + return std.fmt.parseInt(libc.pid_t, words.next() orelse return pid, 10) catch pid; } /// `pardes --detach=<name>` in a throwaway root that is its HOME, runtime @@ -537,6 +552,9 @@ pub const Detached = struct { cap_len: usize = 0, /// Whether deinit removes the root (one passed in is its owner's). owns_root: bool = true, + /// Its tty pair has a daemon of the root's own (`startTty`, a Restored + /// pair's): this build, to end them both (`--kill-all`) at deinit. + tty_daemon: ?[:0]const u8 = null, files: Files, pub const Options = struct { @@ -697,6 +715,11 @@ pub const Detached = struct { pub fn deinit(d: *Detached) void { d.files.deinit(); d.child.deinit(); + if (d.tty_daemon) |exe| if (Child.spawn(&.{ exe, "--kill-all" }, .{ .root = d.root() })) |k| { + var killer = k; + _ = killer.wait(10_000); + killer.deinit(); + } else |_| {}; if (d.cap_len > 0) removeDir(d.captures()); if (d.owns_root) d.removeRoot(); } @@ -800,7 +823,13 @@ pub const Detached = struct { try argv.appendSlice(a, &.{ exe, "--tty", try std.fmt.allocPrintSentinel(a, "--9p={s}", .{name}, 0) }); try argv.appendSlice(a, args); try argv.append(a, d.abs(try std.fmt.allocPrint(a, "{s}.txt", .{name}))); - const env = try a.dupe([2][:0]const u8, &.{.{ "PARDES_DUMP", d.abs(try std.fmt.allocPrint(a, "{s}.dump.zon", .{name})) }}); + // A pair's (PARDES_PAIR) with a daemon of the root's own: a Restore + // lets its client go, and it joins again through it. + const dump = d.abs(try std.fmt.allocPrint(a, "{s}.dump.zon", .{name})); + const env = if (d.tty_daemon != null and std.c.getenv("PARDES_PAIR") != null) + try a.dupe([2][:0]const u8, &.{ .{ "PARDES_DUMP", dump }, .{ "PARDES_DAEMON", "on" } }) + else + try a.dupe([2][:0]const u8, &.{.{ "PARDES_DUMP", dump }}); var c = try Child.spawn(argv.items, .{ .root = d.root(), .env = env, .pty = .{ .log = d.abs(try std.fmt.allocPrint(a, "{s}.pty", .{name})) } }); errdefer c.deinit(); try c.waitPath(d.abs(try std.fmt.allocPrint(a, "pardes-9p-{s}.sock", .{name})), 10_000); diff --git a/test/process/flags.zig b/test/process/flags.zig index c9aa12fb..cfdb1faf 100644 --- a/test/process/flags.zig +++ b/test/process/flags.zig @@ -730,7 +730,9 @@ fn killedTty(gpa: std.mem.Allocator, exe: [:0]const u8) !void { killed.kill(sig); try exitsWith(&killed, -@as(c_int, @intCast(@intFromEnum(sig))), 5_000); const own_z = z(a, "{s}", .{own}); - if (sig == .HUP) { + // As a pair (PARDES_PAIR) a hangup is a close (P36): the session, + // its last client gone and not kept, ends with it. + if (sig == .HUP and std.c.getenv("PARDES_PAIR") == null) { // A hangup is the terminal's end: the session carries on // detached (the daemon keeps it) until told to end. try check(libc.access(own_z, 0) == 0, "a hangup ended the session", .{}); diff --git a/test/process/root_ctl.zig b/test/process/root_ctl.zig index e3420ac5..979cfc48 100644 --- a/test/process/root_ctl.zig +++ b/test/process/root_ctl.zig @@ -127,6 +127,9 @@ fn restore(gpa: std.mem.Allocator, exe: [:0]const u8) !void { defer d.deinit(); var term: ?process.Child = null; defer if (term) |*t| t.deinit(); + // As a pair, with a daemon of the root's own: the Restore lets its + // client go, and it joins again through it (P42). + if (tty) d.tty_daemon = exe; if (tty) term = try d.startTty(exe, name, &.{}); const address = d.abs(try std.fmt.allocPrint(a, "pardes-9p-{s}.sock", .{name})); const old = try Conn.dial(gpa, address); diff --git a/test/process/tty_boot.zig b/test/process/tty_boot.zig index 741f6260..51aea53b 100644 --- a/test/process/tty_boot.zig +++ b/test/process/tty_boot.zig @@ -271,6 +271,7 @@ fn load(gpa: std.mem.Allocator, exe: [:0]const u8) !void { fn restore(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "restore"); defer t.deinit(); + t.privateDaemon(); try t.start(31, 100, &.{ "-n", "1" }); try t.wait(8000, "Newcol Joincol"); try t.stable(700, 20000); @@ -380,6 +381,7 @@ fn headersweep(gpa: std.mem.Allocator, exe: [:0]const u8) !void { fn headersweep_restored(gpa: std.mem.Allocator, exe: [:0]const u8) !void { var t = try Tty.init(gpa, exe, "headersweep-restored"); defer t.deinit(); + t.privateDaemon(); try t.start(21, 120, &.{ "-n", "3" }); try t.wait(8000, "Newcol"); try t.stable(700, 20000); diff --git a/test/tty.zig b/test/tty.zig index f26328ca..5cd92887 100644 --- a/test/tty.zig +++ b/test/tty.zig @@ -58,6 +58,10 @@ pub var replay_with: ?[]const u8 = null; const base_dir = "/tmp/pardes-snap"; const gpa = std.heap.page_allocator; +/// The runner's own runtime directory while a case has one of its own +/// (`Tty.privateDaemon`). +var runtime_dir: ?[*:0]const u8 = null; + pub const Tty = struct { arena: std.mem.Allocator, exe: [:0]const u8, @@ -139,6 +143,24 @@ pub const Tty = struct { pub fn deinit(t: *Tty) void { if (t.h) |*h| h.deinit(); + // Set back, not unset: an unsetenv compacts the environment block + // the runner's std.Io holds (host_io.testUnsetenv's reason). + if (runtime_dir) |was| { + _ = setenv("PARDES_HARNESS_DAEMON", "", 1); + _ = setenv("XDG_RUNTIME_DIR", was, 1); + runtime_dir = null; + } + } + + /// Under PARDES_PAIR, the pair started next has a daemon of its own, in + /// the case's directory as its runtime directory (never the user's): a + /// Restore lets its client go, and it joins again through it, as with a + /// user's daemon. `deinit` puts the runtime directory back. + pub fn privateDaemon(t: *Tty) void { + if (std.c.getenv("PARDES_PAIR") == null) return; + runtime_dir = std.c.getenv("XDG_RUNTIME_DIR") orelse return; + _ = setenv("XDG_RUNTIME_DIR", t.arena.dupeSentinel(u8, t.base, 0) catch return, 1); + _ = setenv("PARDES_HARNESS_DAEMON", "1", 1); } /// The captures against the golden, or written to it under `--update`. |
