summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/CHANGELOG.md11
-rw-r--r--core/replica.zig10
-rw-r--r--dev/tui/tui.zig23
-rw-r--r--docs/next-run.md27
-rw-r--r--docs/typ/command-line.txt10
-rw-r--r--docs/typ/running.typ31
-rw-r--r--runtime/client.zig5
-rw-r--r--runtime/daemon.zig54
-rw-r--r--runtime/main.zig33
-rw-r--r--runtime/session.zig5
-rw-r--r--runtime/upgrade.zig23
-rw-r--r--test/daemon.py161
12 files changed, 310 insertions, 83 deletions
diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md
index faa02ade..e5d592bb 100644
--- a/core/CHANGELOG.md
+++ b/core/CHANGELOG.md
@@ -2,6 +2,17 @@
## Unreleased
+- An experiment, behind `PARDES_PAIR=1` until it is the default: `pardes
+ FILE` in a terminal and `pardes-gui FILE` fork a session with no
+ frontend of its own and are its first client. Such a session is kept
+ (started with `new --detach`, or a Detach typed in any client since) or
+ not: closing a client's window or terminal, or a TERM to it, ends a
+ session not kept when that was its last client; a client killed outright
+ leaves it running. `pardes ps` says `(tty, kept)` or `(tty)` of it.
+ Without the variable nothing changes, but a terminal client (`pardes
+ attach`) ended by a TERM now says goodbye and exits 0, its terminal put
+ back, where it died of the signal.
+
- `pardes new --detach[=NAME]` returns once the session runs (registered
and listening), printing its name, exit 0; the session runs on in a
session of its own. `pardes --detach=NAME` without `new` is still the
diff --git a/core/replica.zig b/core/replica.zig
index ff1e138e..1883e836 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -2059,10 +2059,10 @@ pub const Peers = struct {
/// No frontend of its own (the host says): with no client either, the
/// session is unattended.
detached: bool = false,
- /// Its last client left by closing its window, and no Detach was typed
- /// in any (`kept`): a pair's session ends there (runtime/session.zig).
+ /// Its last client left with a close (its window closed, its terminal
+ /// hung up) and the session is a pair's not kept (daemon.sessionState): it
+ /// ends there (runtime/session.zig).
closed: bool = false,
- kept: bool = false,
/// The worst a join cost the session's step, and the last one's dump.
join_ns: u64 = 0,
each_join: std.ArrayListUnmanaged(u64) = .empty,
@@ -2362,7 +2362,7 @@ pub const Peers = struct {
core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view));
ps.closeViewOf(core, peer, peer.again);
if (ps.count() == 0) core.unattended = ps.detached;
- if (ps.count() == 0 and peer.close and !ps.kept) ps.closed = true;
+ if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true;
ps.seq += 1;
ps.unit(0, ps.seq);
ps.letGo(peer);
@@ -2467,7 +2467,7 @@ pub const Peers = struct {
/// (`left`), its last word; the client goes, and its reader says so.
pub fn detach(ps: *Peers, k: u8) bool {
for (ps.list) |slot| if (slot) |peer| if (peer.view == k) {
- ps.kept = true;
+ daemon.keepSession();
var out: [wire.max_name + 8]u8 = undefined;
peer.last(wire.encodeServer(&out, .{ .left = ps.name[0..@min(ps.name.len, wire.max_name)] }) catch unreachable);
return true;
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index 72028b04..67c0e2a0 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -721,19 +721,22 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
std.process.exit(1);
}
};
- var start: client_loop.Start = undefined;
- if (!start.open(init, opts, .{ .path = path, .session = session, .far = far_link })) Said.no(io, "{s}", .{start.said()});
- defer start.close();
-
+ // Blocked before its join makes a thread, so that winchWatch alone
+ // takes them: a hangup (its terminal closed) or a TERM ends it the
+ // normal way (`quit`), its goodbye a close (a pair's session not kept
+ // ends at its last client's), what it made kept on disk (`Have.keep`)
+ // and its ssh forward's socket unlinked (main.zig).
var winch_set = posix.sigemptyset();
posix.sigaddset(&winch_set, posix.SIG.WINCH);
- // A hangup ends it the normal way (`quit`), what it made kept on disk
- // (`Have.keep`) and its ssh forward's socket unlinked (main.zig).
posix.sigaddset(&winch_set, posix.SIG.HUP);
+ posix.sigaddset(&winch_set, posix.SIG.TERM);
hangup_quits = true;
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);
+ var start: client_loop.Start = undefined;
+ if (!start.open(init, opts, .{ .path = path, .session = session, .far = far_link })) Said.no(io, "{s}", .{start.said()});
+ defer start.close();
var tty_buf: [0x10000]u8 = undefined;
var screen: Screen = .{ .io = io, .gpa = gpa, .env = init.environ_map, .buf = &tty_buf, .kitty = .init(gpa) };
defer screen.kitty.deinit();
@@ -1544,7 +1547,10 @@ const Shell = struct {
virtual.* = @max(virtual.*, s.wake_to);
},
.quit => {
+ // A client's terminal went (a hangup, its input's end) or it
+ // took a TERM: a close, as a window's close button.
if (s.client) |c| {
+ c.link.close = true;
c.link.quit = true;
return true;
}
@@ -1939,19 +1945,20 @@ const Shell = struct {
fn keepSignal(_: posix.SIG) callconv(.c) void {}
-/// A replica client's (`runClient`): a hangup is its end, whoever sent it.
+/// A replica client's (`runClient`): a hangup or a TERM is its end.
var hangup_quits = false;
fn winchWatch(loop: *Loop) void {
var set = posix.sigemptyset();
posix.sigaddset(&set, posix.SIG.WINCH);
if (daemon.link >= 0 or hangup_quits) posix.sigaddset(&set, posix.SIG.HUP);
+ if (hangup_quits) posix.sigaddset(&set, posix.SIG.TERM);
while (true) {
var sig: c_int = 0;
if (libc.sigwait(&set, &sig) != 0) continue;
// 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.HUP)) .winched else if (hangup_quits) .quit else .hangup;
+ const ev: Msg = if (sig == @backingInt(posix.SIG.WINCH)) .winched else if (hangup_quits) .quit else .hangup;
loop.postEvent(ev) catch {};
}
}
diff --git a/docs/next-run.md b/docs/next-run.md
index c2d3488b..00890ef1 100644
--- a/docs/next-run.md
+++ b/docs/next-run.md
@@ -178,6 +178,33 @@ it). For the window's build the fork comes before SDL starts. Then
`pardes --detach=work` returns at once, `&` is not needed, and every
session in `ps` is either its stub's child or a process of its own.
+## `PARDES_PAIR`: every frontend a client (an experiment, built)
+
+With `PARDES_PAIR=1` in its environment (`export PARDES_PAIR=1` in a
+shell's rc; unset, nothing below happens), `pardes FILE` in a terminal and
+`pardes-gui FILE` start the way the last step's design has every frontend
+start: the process you started forks a session with no terminal or window
+of its own (`setsid`, `/dev/null`; a window's child execs the `pardes`
+beside it) and is its first client over a socket pair, the job your shell
+waits on (`runtime/main.zig` `pair`). A session is `kept` or not: kept from
+birth when started with `new --detach[=NAME]` or `--detach`, kept once a
+Detach is typed in any of its clients, never unkept, and an Upgrade
+carries it (`runtime/daemon.zig` `State`, the upgrade record's `state`).
+`pardes ps` says `(tty, kept)` of a kept session and `(tty)` of one that
+is not; a session with a frontend of its own still says `(tty, has a
+frontend)` and a detached one `(tty, detached)`. Its lifetime
+(`core/replica.zig` `Peers.leave`, `runtime/session.zig`):
+
+| What happens | Not kept | Kept |
+|---|---|---|
+| Detach typed in a client | it becomes kept; the client says "detached from 'NAME', which is still running" and exits 0 | the same |
+| a window closed, a terminal closed (its hangup), a TERM to a client | the client says goodbye with a close and exits 0, its terminal put back; the session ends if that was its last client | it runs on |
+| a client killed outright (KILL) or crashed | the link ends with no goodbye: it runs on, listed by `pardes ps`, attachable | it runs on |
+| no daemon | it ends when its last client's link ends, goodbye or not | cannot be: Detach refuses |
+
+Tested by `test/daemon.py --pair` (`pair`, `pair_rows`) and `--gui`
+(`gui_pair`).
+
## Rex beside pardes
From Rex's own help (captured under
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt
index 0ced145f..2f7753e4 100644
--- a/docs/typ/command-line.txt
+++ b/docs/typ/command-line.txt
@@ -39,10 +39,12 @@ The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and
== pardes help ps
What the per-user daemon lists: each session with its name, pid, kind
-(tty or gui) and whether it has a frontend of its own or is detached;
-under it its clients and its shells; then the shells no session holds,
-which Adopt takes. /sessions is the same list, read from inside a
-session (where a session with a frontend says attached).
+(tty or gui) and whether it has a frontend of its own or is detached
+(under PARDES_PAIR: kept, or nothing when its last client's close
+ends it); under it its clients and its shells; then the shells no
+session holds, which Adopt takes. /sessions is the same list, read
+from inside a session (where a session with a frontend says
+attached, and a pair's not kept says pair).
Usage:
pardes ps
diff --git a/docs/typ/running.typ b/docs/typ/running.typ
index 74eb8cbd..320b3130 100644
--- a/docs/typ/running.typ
+++ b/docs/typ/running.typ
@@ -205,6 +205,37 @@ daemon died is not: it starts the next one itself (#link(<run-survives>)[below])
`pardes-gui` built for a Mac has no daemon either, but can still be a far
client.
+= An experiment: `PARDES_PAIR` <run-pair>
+
+// runtime/main.zig pair (the fork); runtime/daemon.zig State, keepSession;
+// core/replica.zig Peers.leave, Peers.detach; runtime/session.zig (the
+// end); dev/tui/tui.zig runClient and winchWatch (HUP and TERM a close);
+// dev/gui/gui.zig Input.close; runtime/upgrade.zig Record.state.
+With `PARDES_PAIR=1` in its environment (`export PARDES_PAIR=1`; unset,
+none of this happens), `pardes FILE` in a terminal and `pardes-gui FILE`
+start the way every frontend will: the process you started forks a
+session with no terminal or window of its own and is its first client,
+the job your shell waits on. A session is _kept_ or not: kept from birth
+when started with `pardes new --detach` (or `--detach`), and once a
+#word("Detach") is typed in any of its clients; an #word("Upgrade") keeps
+which. `pardes ps` says `(tty, kept)` of a kept session and `(tty)` of
+one that is not.
+
+#{
+ set text(size: 0.85em)
+ set par(justify: false)
+ table(
+ columns: (1.2fr, 1.6fr, 0.9fr),
+ stroke: (x, y) => if y == 0 { (bottom: 0.8pt) } else { (bottom: 0.3pt) },
+ inset: (x: 4pt, y: 4pt),
+ table.header([*what happens*], [*not kept*], [*kept*]),
+ [#word("Detach") typed in a client], [it becomes kept; the client says so and exits 0], [the same],
+ [a window closed, a terminal closed, a TERM to a client], [the client says goodbye and exits 0, its terminal put back; the session ends if that was its last client], [it runs on],
+ [a client killed outright (KILL) or crashed], [it runs on, listed by `pardes ps`], [it runs on],
+ [no daemon], [it ends with its last client, whatever ended it], [cannot be: #word("Detach") refuses],
+ )
+}
+
= At a glance <run-glance>
// The rows' sources are the sections above; `ps`:
diff --git a/runtime/client.zig b/runtime/client.zig
index 329bdab3..7941889e 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -149,6 +149,11 @@ pub fn execAgain(s: *Start, view: u8) []const u8 {
k += 1;
}
envp[k] = null;
+ // The mask goes across an exec: the signals a terminal client blocks
+ // for its own sigwait (HUP, TERM) would stay blocked under a build that
+ // waits on fewer, a TERM never delivered.
+ const none = std.posix.sigemptyset();
+ std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null);
_ = libc.execve(path, &argv, envp.ptr);
return "Upgrade: the build at this client's start path would not start";
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 9b566e60..1afdd878 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -279,9 +279,9 @@ fn spawn(listener: c_int, lock: c_int) bool {
/// Says who this session is. Its answer is not waited for: a daemon just
/// started is still being exec'd, and no startup waits on it. The reader
/// (`watch`) takes the `ok`, and only then is the session kept (`kept`).
-fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) bool {
+fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, s: State) bool {
var buf: [256]u8 = undefined;
- const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {x} {s}", .{ version, k, pid, if (detached) "detached" else "attached", wire.semantics, named }) catch return false;
+ const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {t} {x} {s}", .{ version, k, pid, s, wire.semantics, named }) catch return false;
return send(fd, words, &.{});
}
@@ -300,9 +300,23 @@ var quitting = std.atomic.Value(bool).init(false);
/// A new daemon took the hello since the last one died: the rest of what
/// the dead one was told is to be told again (`relinked`).
var retell = std.atomic.Value(bool).init(false);
-/// What the hello says besides the name: the kind, and whether detached.
+/// What a session's hello says of it besides its kind and name: a frontend
+/// of its own (`attached`) or none (`detached`); a pair's (PARDES_PAIR),
+/// whether its last client's close ends it (`pair`) or it is `kept`
+/// (started --detach, or a Detach typed in a client since): `ps` says it.
+/// Numbered as the daemon's record said a bool before (`reexec`).
+pub const State = enum(u8) { attached, detached, pair, kept };
var kind: Kind = .tty;
-var detached_now = std.atomic.Value(bool).init(false);
+var state_now = std.atomic.Value(State).init(.detached);
+
+pub fn sessionState() State {
+ return state_now.load(.acquire);
+}
+
+/// A Detach typed in a client: a pair's session is kept from now on.
+pub fn keepSession() void {
+ if (state_now.cmpxchgStrong(.pair, .kept, .acq_rel, .acquire) == null) tell("state kept", &.{});
+}
/// What it is called (its 9P name).
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
@@ -347,14 +361,14 @@ fn setName(named: []const u8) void {
/// Registers this session on `fd` (connected already, as a terminal's
/// stub does before it forks), or on a new connection when `fd` is null.
-pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool {
+pub fn register(fd: ?c_int, k: Kind, named: []const u8, s: State) bool {
if (comptime !supported) return false;
setName(named);
kind = k;
- detached_now.store(detached, .release);
+ state_now.store(s, .release);
const c = fd orelse connect(true) orelse return false;
startPending(true);
- if (!hello(c, k, libc.getpid(), name(), detached)) {
+ if (!hello(c, k, libc.getpid(), name(), s)) {
_ = libc.close(c);
return false;
}
@@ -386,7 +400,7 @@ pub fn closed(pid: libc.pid_t) void {
/// Its own frontend let go (Detach, its terminal's end): detached for
/// good, an attach after it a client.
pub fn setDetached() void {
- detached_now.store(true, .release);
+ state_now.store(.detached, .release);
tell("state detached", &.{});
}
@@ -429,14 +443,14 @@ pub fn upgraded() void {
/// An upgraded session's link and stub as its old process left them: its
/// build's hello said again on the link (the daemon keeps its masters as
/// they were), and the stub's death a HUP again.
-pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detached: bool) void {
+pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, s: State) void {
if (comptime !supported) return;
stub = stub_fd;
if (stub >= 0) hupOnStubDeath(true);
setName(named);
kind = k;
- detached_now.store(detached, .release);
- if (fd >= 0 and hello(fd, k, libc.getpid(), name(), detached)) link = fd else if (fd >= 0) _ = libc.close(fd);
+ state_now.store(s, .release);
+ if (fd >= 0 and hello(fd, k, libc.getpid(), name(), s)) link = fd else if (fd >= 0) _ = libc.close(fd);
}
pub const Note = union(enum) {
@@ -518,7 +532,7 @@ fn redial(fd: c_int) bool {
startPending(true);
defer _ = libc.close(c);
return libc.dup3(c, fd, @bitCast(@as(u32, @bitCast(libc.O{ .CLOEXEC = true })))) >= 0 and
- hello(fd, kind, libc.getpid(), name(), detached_now.load(.acquire));
+ hello(fd, kind, libc.getpid(), name(), sessionState());
}
/// `bytes` sent whole on a socket, never raising SIGPIPE: false when the
@@ -778,7 +792,7 @@ const Conn = struct {
fd: c_int = -1,
kind: ?Kind = null,
pid: libc.pid_t = 0,
- detached: bool = false,
+ state: State = .attached,
/// Its build's wire.semantics: a replica's must be the same.
semantics: u64 = 0,
/// `pardes --kill` asked its end: its shells go with it, not kept.
@@ -871,7 +885,7 @@ const Daemon = struct {
var w: std.Io.Writer = .fixed(&line);
w.print("daemon {d}\n", .{libc.getpid()}) catch unreachable; // a pid fits msg_max
for (&d.conns, 0..) |*s, k| if (s.fd >= 0 and s.kind != null) {
- w.print("session {d} {t} {s} {s}\n", .{ s.pid, s.kind.?, if (s.detached) "detached" else "attached", s.named() }) catch break;
+ w.print("session {d} {t} {t} {s}\n", .{ s.pid, s.kind.?, s.state, s.named() }) catch break;
for (s.clients[0..s.nclients]) |pid| w.print("client {d}\n", .{pid}) catch break;
for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break;
};
@@ -896,7 +910,7 @@ const Daemon = struct {
const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0;
const k = std.meta.stringToEnum(Kind, words.next() orelse "");
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0;
- const state = words.next() orelse "";
+ const said = words.next() orelse "";
const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0;
const rest = std.mem.trim(u8, words.rest(), " ");
if (v != version or k == null or pid <= 0) {
@@ -906,14 +920,14 @@ const Daemon = struct {
}
c.kind = k;
c.pid = pid;
- c.detached = std.mem.eql(u8, state, "detached");
+ c.state = std.meta.stringToEnum(State, said) orelse .attached;
c.semantics = semantics;
c.nclients = 0;
c.name_len = @min(rest.len, c.name.len);
@memcpy(c.name[0..c.name_len], rest[0..c.name_len]);
return d.reply(i, "ok", &.{});
},
- .state => c.detached = std.mem.eql(u8, words.next() orelse "", "detached"),
+ .state => c.state = std.meta.stringToEnum(State, words.next() orelse "") orelse .attached,
.clients => {
c.nclients = 0;
while (words.next()) |w| if (c.nclients < max_clients) {
@@ -1026,7 +1040,7 @@ const Daemon = struct {
w.print("{s}replicas {d}\n", .{ upgrade.flag, replicas }) catch return;
for (&d.conns, 0..) |*c, i| if (c.fd >= 0) {
const k: []const u8 = if (c.kind) |k| @tagName(k) else "-";
- w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromBool(c.detached), c.semantics, c.named() }) catch return;
+ w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromEnum(c.state), c.semantics, c.named() }) catch return;
};
for (&d.held) |*h| if (h.fd >= 0) {
w.print("h {d} {d} {d}\n", .{ h.fd, h.pid, h.owner orelse 255 }) catch return;
@@ -1076,12 +1090,12 @@ const Daemon = struct {
if (i >= max_conns) continue;
const k = std.meta.stringToEnum(Kind, words.next() orelse "");
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0;
- const detached = std.mem.eql(u8, words.next() orelse "", "1");
+ const s = std.enums.fromInt(State, std.fmt.parseInt(u8, words.next() orelse "", 10) catch 0) orelse .attached;
const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0;
const rest = std.mem.trim(u8, words.rest(), " ");
ninep_io.setCloexec(fd);
const c = &d.conns[i];
- c.* = .{ .fd = fd, .kind = k, .pid = pid, .detached = detached, .semantics = semantics };
+ c.* = .{ .fd = fd, .kind = k, .pid = pid, .state = s, .semantics = semantics };
c.nclients = 0;
c.name_len = @min(rest.len, c.name.len);
@memcpy(c.name[0..c.name_len], rest[0..c.name_len]);
diff --git a/runtime/main.zig b/runtime/main.zig
index a21eb83f..dc351c30 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -269,10 +269,12 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{
.line = "the daemon's sessions, their clients and shells",
.doc =
\\What the per-user daemon lists: each session with its name, pid, kind
- \\(tty or gui) and whether it has a frontend of its own or is detached;
- \\under it its clients and its shells; then the shells no session holds,
- \\which Adopt takes. /sessions is the same list, read from inside a
- \\session (where a session with a frontend says attached).
+ \\(tty or gui) and whether it has a frontend of its own or is detached
+ \\(under PARDES_PAIR: kept, or nothing when its last client's close
+ \\ends it); under it its clients and its shells; then the shells no
+ \\session holds, which Adopt takes. /sessions is the same list, read
+ \\from inside a session (where a session with a frontend says
+ \\attached, and a pair's not kept says pair).
,
.examples = &.{.{ "pardes ps", "every session, client and shell" }},
.see = "attach, kill, /sessions",
@@ -1570,14 +1572,14 @@ fn nativeMain(std_init: std.process.Init) !void {
term = .{ .fd = .{ .fd = t.fd, .termios = t.termios } };
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
- daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
+ daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, rec.state orelse if (detached) .detached else .attached);
} else if (paired) |fd| {
// A window's pair's session: its first client on `fd`, the daemon
// its own to dial (and to start, when none runs).
opts.pair = fd;
term = .detached;
detached = true;
- if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true);
+ if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, .pair);
} else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
// this terminal or window a client of a session forked off for it
@@ -1586,7 +1588,9 @@ fn nativeMain(std_init: std.process.Init) !void {
term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
- _ = daemon.register(null, kind, opts.ninep_name, detach != null);
+ // A session started detached is kept from birth: a pair's word.
+ const s: daemon.State = if (detach == null) .attached else if (std.c.getenv("PARDES_PAIR") != null) .kept else .detached;
+ _ = daemon.register(null, kind, opts.ninep_name, s);
} else if (pardes.platform == .tui) fork: {
// A terminal's session is forked off its stub, which stays the
// job the shell waits on: Detach (or the terminal's end) ends
@@ -1610,7 +1614,7 @@ fn nativeMain(std_init: std.process.Init) !void {
_ = std.c.close(conn);
break :fork;
};
- _ = daemon.register(conn, .tty, opts.ninep_name, false);
+ _ = daemon.register(conn, .tty, opts.ninep_name, .attached);
term = .{ .fd = .{ .fd = fd } };
}
}
@@ -1662,7 +1666,12 @@ fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) nore
.session => {
const kind = it.next() orelse "";
const state = it.next() orelse "";
- w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break;
+ const named = std.mem.trim(u8, it.rest(), " ");
+ // A pair's not kept: its clients are all there is to it.
+ if (std.mem.eql(u8, state, "pair"))
+ w.print(" session {s} {s} ({s})\n", .{ named, pid, kind }) catch break
+ else
+ w.print(" session {s} {s} ({s}, {s})\n", .{ named, pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break;
},
.client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break,
.shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break,
@@ -1784,7 +1793,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u
opts.pair = fds[0];
// The daemon is the client's to start; the hello is this one's.
daemon.startPending(false);
- if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true);
+ if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, .pair);
return;
}
_ = std.c.close(fds[0]);
@@ -1941,7 +1950,7 @@ fn bareAttach(list: []const u8, names: *std.Io.Writer) ?[]const u8 {
one = std.mem.trim(u8, words.rest(), " ");
n += 1;
names.print(" {s}", .{one.?}) catch {}; // cut short
- if (!std.mem.eql(u8, state, "detached")) continue;
+ if (std.mem.eql(u8, state, "attached")) continue;
detached = one;
n_detached += 1;
}
@@ -1954,6 +1963,8 @@ test "a bare attach takes the one detached session, else the one there is, else
var names: std.Io.Writer = .fixed(&buf);
try std.testing.expectEqualStrings("b", bareAttach("daemon 1\nsession 2 tty attached a\nshell 9\nsession 3 gui detached b\n", &names).?);
try std.testing.expectEqualStrings("a", bareAttach("daemon 1\nsession 2 tty attached a\n", &names).?);
+ // A pair's, kept or not, has no frontend of its own either.
+ try std.testing.expectEqualStrings("c", bareAttach("session 2 tty attached a\nsession 3 tty pair c\n", &names).?);
names = .fixed(&buf);
try std.testing.expect(bareAttach("daemon 1\norphan 4\n", &names) == null);
try std.testing.expectEqual(@as(usize, 0), names.end);
diff --git a/runtime/session.zig b/runtime/session.zig
index 9c8446e3..8630495c 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -129,9 +129,8 @@ pub fn Loop(comptime Frontend: type) type {
l.peers.boundary(l.core);
// A pair's session with no daemon ends with its last link:
// nothing could attach to it again; with one, when its last
- // client closed its window (a close, not a loss), no Detach
- // typed in any.
- if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break;
+ // client left with a close (not a loss) and it is not kept.
+ if (l.peers.count() == 0 and (l.peers.closed or (o.pair != null and daemon.link < 0))) break;
fe.sent();
upgrade.locate();
// Asked in the step (the word), done between steps: the
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 37d4890b..f59117ee 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -19,6 +19,7 @@ const builtin = @import("builtin");
const libc = std.c;
const posix = std.posix;
const pardes = @import("core");
+const daemon = @import("daemon.zig");
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
pub const flag = "--upgraded=";
@@ -140,6 +141,9 @@ pub const Record = struct {
/// This process's own: its dump would not load, so it started afresh
/// and adopts the shells.
fresh: bool = false,
+ /// A pair's session's state (daemon.State): whether it is kept, which
+ /// the dump does not say. None: as its frontend says (attached or not).
+ state: ?daemon.State = null,
pub fn addPty(rec: *Record, pane: usize, pid: libc.pid_t, fd: c_int) void {
if (rec.nptys == rec.ptys.len or fd < 0) return;
@@ -177,6 +181,7 @@ pub const Record = struct {
for (rec.ttys[0..rec.nttys]) |t| try w.print("tty {d} {d} {d} {d} {x}\n", .{ t.view, t.fd, t.stub, @intFromBool(t.primary), std.mem.asBytes(&t.termios) });
if (rec.refused.len > 0) try w.print("refused {s}\n", .{rec.refused});
if (rec.label.len > 0) try w.print("label {s}\n", .{rec.label});
+ if (rec.state) |s| try w.print("state {t}\n", .{s});
try w.print("exe {s}\ndump {s}\n", .{ rec.exe, rec.dump });
}
@@ -191,7 +196,7 @@ pub const Record = struct {
const rest = line[sp + 1 ..];
var it = std.mem.tokenizeScalar(u8, rest, ' ');
// A word of a later build's record is passed over.
- switch (std.meta.stringToEnum(enum { link, stub, old, window, pty, tty, refused, label, exe, dump }, word) orelse continue) {
+ switch (std.meta.stringToEnum(enum { link, stub, old, window, pty, tty, refused, label, state, exe, dump }, word) orelse continue) {
.link => rec.link = try std.fmt.parseInt(c_int, rest, 10),
.stub => rec.stub = try std.fmt.parseInt(c_int, rest, 10),
.old => rec.old = try std.fmt.parseInt(c_int, rest, 10),
@@ -225,6 +230,7 @@ pub const Record = struct {
},
.refused => rec.refused = rest,
.label => rec.label = rest,
+ .state => rec.state = std.meta.stringToEnum(daemon.State, rest),
.exe => rec.exe = rest,
.dump => rec.dump = rest,
}
@@ -383,9 +389,14 @@ pub fn dumpInto(core: *pardes.Pardes, rec: *Record, at: *[1024:0]u8, why: []u8)
/// dump stays, a dump among the state file's): why, in words (`why`'s).
pub fn execAs(gpa: std.mem.Allocator, path: [:0]const u8, rec: *const Record, at: [*:0]const u8, fs: ?*@import("9p_io.zig").Listener, why: []u8) []const u8 {
_ = at;
- @import("daemon.zig").upgraded();
+ daemon.upgraded();
if (fs) |f| f.flushOut();
- const err_words = exec(gpa, path, -1, rec);
+ var with = rec.*;
+ with.state = switch (daemon.sessionState()) {
+ .pair, .kept => |s| s,
+ .attached, .detached => null,
+ };
+ const err_words = exec(gpa, path, -1, &with);
// Still here: the exec failed.
if (rec.old >= 0) _ = libc.close(rec.old);
return std.fmt.bufPrint(why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start";
@@ -453,7 +464,7 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op
}
test "an upgrade's record reads back as it was written, and refuses one cut short" {
- var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1" };
+ var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1", .state = .kept };
rec.addPty(3, 1234, 11);
rec.addPty(0, 99, 12);
var tio: posix.termios = std.mem.zeroes(posix.termios);
@@ -474,10 +485,12 @@ test "an upgrade's record reads back as it was written, and refuses one cut shor
try std.testing.expectEqualStrings("/a b/pardes", back.exe);
try std.testing.expectEqualStrings("/home/u/.local/share/pardes/pardes.xitdb", back.dump);
try std.testing.expectEqualStrings("upgrade-1", back.label);
- // An older build's: its dump a file, no label.
+ try std.testing.expectEqual(daemon.State.kept, back.state.?);
+ // An older build's: its dump a file, no label, no state.
const older = try Record.decode("link 5\nexe /a\ndump /run/u/pardes-upgrade-1.dump\n");
try std.testing.expectEqualStrings("/run/u/pardes-upgrade-1.dump", older.dump);
try std.testing.expectEqualStrings("", older.label);
+ try std.testing.expect(older.state == null);
try std.testing.expectError(error.BadRecord, Record.decode("link 5\n"));
try std.testing.expectError(error.BadRecord, Record.decode("tty 0 1 2 1 abc\ndump x\n"));
}
diff --git a/test/daemon.py b/test/daemon.py
index 2325f721..c1e0d54a 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -635,7 +635,7 @@ def pair(binary):
assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
- wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed()
+ wait_for('the client listed', lambda: f'session pair {session} (tty)' in listed()
and f'client {c.pid} ' in listed())
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
os.write(t.master, b'Ofrom-the-pair\x1b')
@@ -676,12 +676,13 @@ def pair(binary):
def pair_rows(binary):
"""PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
- session's lifetime (2.2 B), one row a step. With a daemon: a Detach in
- the pair's client says so and exits 0, the session runs on (listed); an
- attach is a client again; TERM to the client puts its terminal back and
- the session runs on; so does a KILL, and a closed terminal (HUP): each a
- loss, not a close. With none: a Detach refused (nothing could attach),
- the client on; its terminal closed, the session ends with its last link."""
+ session's lifetime (2.2 B), one row a step. `ps` says a pair's session
+ `kept` (started --detach, or a Detach typed in any client since), or
+ nothing after its kind; an Upgrade carries which. Kept: a client ended
+ by TERM, KILL or a closed terminal (HUP) leaves it running, as does a
+ Detach typed in one (said, exit 0). With no daemon: a Detach refused
+ (nothing could attach), the client on; its terminal closed, the session
+ ends with its last link."""
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))
@@ -697,6 +698,12 @@ def pair_rows(binary):
def listed():
return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+ def state_of(name):
+ """What `ps` says of session `name` after its pid: `(tty)`, `(tty, kept)`."""
+ for line in listed().splitlines():
+ if line.split()[:2] == ['session', name]:
+ return line[line.index('('):]
+
def drawn(t):
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
@@ -717,30 +724,112 @@ def pair_rows(binary):
drawn(t)
return t, c, nine, session, pane
+ def attached(name):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', name], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ return tt, a
+
+ def ended_by(how, tt, a):
+ """Client `a` on terminal `tt` ended: TERM, KILL, or HUP (its terminal
+ closed); its exit status, once it is unlisted."""
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ code = a.wait(timeout=20)
+ if how == 'TERM':
+ wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
+ wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
+ return code
+
+ def upgraded(name, nine, session):
+ """An Upgrade to the same build: the session exec'd under its pid, its
+ 9P again."""
+ nine.write('/ctl', b'Upgrade\n')
+ wait_for('the session exec\'d', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(session)), timeout=60)
+ nine.socket.close()
+ again = reconnect(root / f'pardes-9p-{name}.sock')
+ assert alive(session)
+ return again
+
try:
+ # Kept from birth: `new --detach`. Its clients end and it runs on.
+ out = subprocess.run([binary, 'new', '--detach=kd', str(notes)], env=env, cwd=root, capture_output=True,
+ timeout=30, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out
+ with Client(root / 'pardes-9p-kd.sock') as kn:
+ kd = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
+ assert state_of('kd') == '(tty, kept)', listed()
+ for how in ('HUP', 'TERM'):
+ ended_by(how, *attached('kd'))
+ assert alive(kd) and state_of('kd') == '(tty, kept)', (how, listed())
+ assert subprocess.run([binary, 'kill', 'kd'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('kd ended', lambda: not alive(kd), timeout=30)
+ print('pair rows: `new --detach` kept from birth (ps: (tty, kept)); its client ended by HUP, by TERM: it runs on')
+ # 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
+ 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
+ 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()
+ print('pair rows: not kept: a client\'s terminal closed (not the last): it runs on; its own killed -9: it runs on, '
+ 'listed; the last client TERMed (exit 0, its terminal put back): the session ended')
+ # The pair's own terminal closed after an Upgrade: its last client's
+ # close, which the Upgrade did not make kept.
+ t, c, nine, session, pane = started('nk2', env)
+ nine = upgraded('nk2', nine, session)
+ wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ assert c.wait(timeout=20) == 0, 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
+ # leaves the session running, and its own terminal closed detaches it.
+ 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 alive(session) and state_of('own') == '(tty, has a frontend)', listed()
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ wait_for('the own session detached', lambda: state_of('own') == '(tty, detached)')
+ assert alive(session)
+ assert subprocess.run([binary, 'kill', 'own'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the own session ended', lambda: not alive(session), timeout=30)
+ print('pair rows: without the variable: an attach client TERMed, the session on; its terminal closed, it detached (ps: (tty, detached))')
+ # A pair: not kept, and not across an Upgrade either; a Detach typed
+ # in its client keeps it, across an Upgrade too.
t, c, nine, session, pane = started('rows', env)
+ assert state_of('rows') == '(tty)', listed()
+ nine = upgraded('rows', nine, session)
+ wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty)')
+ wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
typed_detach(t, nine, pane)
assert c.wait(timeout=20) == 0, c.returncode
wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
- assert alive(session) and f'session rows {session} (tty, detached)' in listed()
- print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ assert alive(session) and state_of('rows') == '(tty, kept)', listed()
+ nine = upgraded('rows', nine, session)
+ wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty, kept)')
+ print('pair rows: a pair (ps: (tty)), so after an Upgrade; Detach in its client: said, exit 0, it runs on, kept, so after an Upgrade')
for how in ('TERM', 'KILL', 'HUP'):
- tt = Term(30, 100)
- terms.append(tt)
- a = tt.spawn([binary, 'attach', 'rows'], env)
- drawn(tt)
- wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
- if how == 'HUP':
- tt.close()
- terms.remove(tt)
- else:
- os.kill(a.pid, getattr(signal, 'SIG' + how))
- a.wait(timeout=20)
- if how == 'TERM':
- wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
- wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
- assert alive(session), how
- print(f'pair rows: a client ended by {how}: the session runs on')
+ ended_by(how, *attached('rows'))
+ assert alive(session) and state_of('rows') == '(tty, kept)', (how, listed())
+ print(f'pair rows: kept: a client ended by {how}: the session runs on')
nine.socket.close()
assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
@@ -2298,7 +2387,7 @@ def gui_pair(gui_binary):
try:
w, nine, session, pane = started('gp', env)
- wait_for('the window listed its client', lambda: f'session gp {session} (tty, detached)' in listed()
+ wait_for('the window listed its client', lambda: f'session gp {session} (tty)' 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'))
@@ -2316,11 +2405,29 @@ def gui_pair(gui_binary):
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()
+ assert alive(session) and f'session gl {session} (tty)' 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')
+ # Kept from birth (`new --detach`): its window client's close leaves it.
+ out = subprocess.run([binary, 'new', '--detach=gk', str(notes)], env=env, cwd=root, capture_output=True,
+ timeout=30, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out
+ with Client(root / 'pardes-9p-gk.sock') as kn:
+ gk = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
+ assert f'session gk {gk} (tty, kept)' in listed(), listed()
+ w = Window(root, 'gkw', [gui_binary, 'attach', 'gk'], env)
+ windows.append(w)
+ wait_for('the window client listed', lambda: f'client {w.pid} ' in listed(), timeout=30)
+ 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 client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(gk) and f'session gk {gk} (tty, kept)' in listed(), listed()
+ assert subprocess.run([binary, 'kill', 'gk'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(gk), timeout=30)
+ print('pair window: a `new --detach` session (kept): its window client closed, it runs on')
w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
nine.socket.close()
os.kill(w.pid, signal.SIGKILL)