summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
Diffstat (limited to 'runtime')
-rw-r--r--runtime/9p_io.zig8
-rw-r--r--runtime/client.zig59
-rw-r--r--runtime/daemon.zig171
-rw-r--r--runtime/macos.zig51
-rw-r--r--runtime/main.zig146
-rw-r--r--runtime/session.zig45
-rw-r--r--runtime/upgrade.zig35
7 files changed, 385 insertions, 130 deletions
diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig
index bcb0f81b..1079b102 100644
--- a/runtime/9p_io.zig
+++ b/runtime/9p_io.zig
@@ -203,7 +203,7 @@ pub const Listener = struct {
// Asked first: a release that runs a held line has none after.
const changes = pardes.ctlfs.changesPane(core, req);
const fills = pardes.ctlfs.handsOff(core, req);
- const reply = core.serveFs(req);
+ const reply = pardes.filesystem.EditHold.retried(&core.fs, req) orelse core.serveFs(req);
const edit_started = core.fs.edit_started;
core.fs.edit_started = false;
// The held Edit write asked again by a retry, its Edit still
@@ -1896,7 +1896,9 @@ pub const Client = struct {
/// same open, as /pane/new answers its own open: a session's last
/// answer, from another client, can never be what comes back. `exec
/// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in
- /// Twrites at rising offsets, each answer giving the next its budget.
+ /// Twrites at rising offsets. Untimed once connected: the answer comes
+ /// when the session's step has run, however long a loaded machine
+ /// takes over 256 MiB, and a session that died ends the connection.
pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 {
if (comptime !supported) return error.Unsupported;
var names: [max_depth][]const u8 = undefined;
@@ -1905,6 +1907,7 @@ pub const Client = struct {
errdefer said = remote;
const s = try startSession(dial, path);
defer endSession(s, false);
+ s.deadline = std.math.maxInt(i64);
const fid = try walkTo(s, names[0..n], &remote);
_ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote);
var written: usize = 0;
@@ -1914,7 +1917,6 @@ pub const Client = struct {
const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write;
if (count == 0 or count > chunk.len) return Error.Botch;
written += count;
- s.deadline = nowMs() +| write_budget_ms;
}
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
diff --git a/runtime/client.zig b/runtime/client.zig
index 7c0bcb7f..55171af2 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -37,6 +37,7 @@ const std = @import("std");
const libc = std.c;
const pardes = @import("core");
const replica = pardes.replica;
+const upgrade = @import("upgrade.zig");
/// A wait with no wake of its own: until an input or a message.
pub const forever: u32 = std.math.maxInt(u32);
@@ -92,6 +93,8 @@ pub const Start = struct {
s.o.distrusted = &s.distrusted;
// Its frame timings, this process's (Pardes.frames).
s.o.frames = &s.frames;
+ // Exec'd at an Upgrade (`execAgain`): for the view it had.
+ if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null;
s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false;
return true;
}
@@ -111,8 +114,49 @@ pub const Start = struct {
/// How a client's joins ended: it quit, the session let it go, it could
/// not join again (`Start.said`), it left the session running (a Detach in
-/// it), or the session ended, with its code.
-pub const Ended = union(enum) { done, gone, failed, left, ended: u8 };
+/// it), the session ended, with its code, or it runs another build now and
+/// one is installed at this client's start path since it started: the
+/// frontend lets its screen go and execs that, for this view (`execAgain`).
+pub const Ended = union(enum) { done, gone, failed, left, ended: u8, upgrade: u8 };
+
+/// An Upgrade's client again (`Ended.upgrade`), its frontend's screen let
+/// go: this process exec'd as the file at its start path, an attach of the
+/// same session through the same socket (a far one's forward, its ssh this
+/// process's child still), joining for `view` (PARDES_JOIN_VIEW; far,
+/// PARDES_REPLICA_FAR). The terminal's blink: no record crosses the exec.
+/// Returns only when the exec failed: why.
+pub fn execAgain(s: *Start, view: u8) []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";
+ const argv = [_:null]?[*:0]const u8{ path, at };
+ 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";
+ 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;
+ envp[k] = e;
+ k += 1;
+ }
+ envp[k] = joining.ptr;
+ k += 1;
+ if (s.have != null) {
+ envp[k] = "PARDES_REPLICA_FAR=1";
+ 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";
+}
pub fn Loop(comptime Frontend: type) type {
return struct {
@@ -143,6 +187,8 @@ pub fn Loop(comptime Frontend: type) type {
/// (to upgrade, or cut off); the frontend stays as it is.
pub fn run(l: *L, s: *Start) !Ended {
const link = &l.link;
+ // Its start path's file, for an Upgrade's question (`upgrade`).
+ upgrade.locate();
while (true) {
link.reset(s.r, &s.joined);
l.fe.start(l);
@@ -153,7 +199,7 @@ pub fn Loop(comptime Frontend: type) type {
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
- if (!link.gone) replica.bye(s.joined.fd, s.r.diverged != null or link.lagged != 0);
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close });
// The link's reader ends with the link, posting as it goes:
// what it posted is let go until it has (a terminal's queue
// is bounded: a reader blocked on it would never end).
@@ -178,8 +224,11 @@ pub fn Loop(comptime Frontend: type) type {
}
// The session again, the core it leaves held meanwhile: its
// blobs are not sent again.
- s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse
- return if (replica.ended(&s.why)) .gone else .failed;
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse {
+ if (replica.ended(&s.why)) return .gone;
+ if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
+ return .failed;
+ };
}
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index a2e890f9..7ae0d8b5 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, &.{});
}
@@ -290,22 +290,42 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
-/// The daemon said `ok` to the hello, and the link has not ended since;
-/// `gone` once it has ended for good (`readNotes`).
-var up = std.atomic.Value(bool).init(false);
-var gone = std.atomic.Value(bool).init(false);
+/// The hello's answer, as the reader took it (`readNotes`): `up`, the
+/// daemon said `ok` and the link has not ended since; `gone`, it has ended
+/// for good; `asked` until either (and while a new daemon is dialled).
+const Answer = enum(u32) { asked, up, gone };
+var answer = std.atomic.Value(Answer).init(.asked);
/// The session is ending (`quit`): its link's end is no daemon's death.
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;
var reader: ?std.Thread = null;
+/// Where the reader hands each note (`notesTo`), the lock a hand-over and
+/// a change of it take.
+var notes: ?Notes = null;
+var notes_lock: std.Io.Mutex = .init;
+pub const Notes = struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void };
pub fn name() []const u8 {
return name_buf[0..name_len];
@@ -314,12 +334,22 @@ pub fn name() []const u8 {
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
-/// that answer (up to 2 s): never on a startup's path, only on those two.
+/// that answer, or the link's end, whenever they come: never on a startup's
+/// path, only on those two. The reader takes it: started here if the first
+/// frame has not started it yet.
pub fn kept() bool {
if (link < 0) return false;
- var waited: u32 = 0;
- while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
- return up.load(.acquire);
+ watch();
+ if (reader == null) return false;
+ const io = std.Io.Threaded.global_single_threaded.io();
+ while (answer.load(.acquire) == .asked) io.futexWaitUncancelable(Answer, &answer.raw, .asked);
+ return answer.load(.acquire) == .up;
+}
+
+/// The reader's word on the hello's answer, to `kept` waiting on it.
+fn settle(a: Answer) void {
+ answer.store(a, .release);
+ std.Io.Threaded.global_single_threaded.io().futexWake(Answer, &answer.raw, 1);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
@@ -334,14 +364,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;
}
@@ -373,7 +403,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", &.{});
}
@@ -416,14 +446,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) {
@@ -438,24 +468,50 @@ pub const Note = union(enum) {
pub const Joining = struct { fd: c_int, view: ?u8 = null };
-/// Hands every note the daemon sends on to `deliver`, on a thread of its
+/// Where every note the daemon sends goes, once `watch` has started the
+/// reader: the session loop's, before its first step, until its state
+/// goes (null): once this returns, no note reaches the one before.
+pub fn notesTo(to: ?Notes) void {
+ const io = std.Io.Threaded.global_single_threaded.io();
+ notes_lock.lockUncancelable(io);
+ defer notes_lock.unlock(io);
+ notes = to;
+}
+
+/// A note handed on (`notesTo`); with nowhere to go (the loop ended, the
+/// link not yet), let go: its connections closed.
+fn give(note: Note) void {
+ const io = std.Io.Threaded.global_single_threaded.io();
+ notes_lock.lockUncancelable(io);
+ defer notes_lock.unlock(io);
+ if (notes) |n| return n.deliver(n.ctx, note);
+ switch (note) {
+ .relinked => {},
+ .adopted => |a| for (a.fds[0..a.n]) |f| {
+ _ = libc.close(f);
+ },
+ .replica => |j| _ = libc.close(j.fd),
+ }
+}
+
+/// Hands every note the daemon sends on (`notesTo`), on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
-pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
- if (link < 0 or reader != null) return;
- reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
+pub fn watch() void {
+ if (notes == null or link < 0 or reader != null) return;
+ reader = std.Thread.spawn(.{}, readNotes, .{link}) catch null;
}
-fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
+fn readNotes(fd: c_int) void {
var buf: [msg_max]u8 = undefined;
while (true) {
while (recv(fd, &buf)) |got| {
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.meta.stringToEnum(enum { ok, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
+ .ok => settle(.up),
.replica => {
const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null;
- if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } });
+ if (got.nfds >= 1) give(.{ .replica = .{ .fd = got.fds[0], .view = view } });
for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f);
},
.adopted => {
@@ -470,7 +526,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
a.fds[a.n] = f;
a.n += 1;
}
- deliver(ctx, note);
+ give(note);
},
} else for (got.fds[0..got.nfds]) |f| {
_ = libc.close(f);
@@ -482,12 +538,12 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no
// link's end is what wakes this, never a timer. One that never took
// it (another build's daemon), or the session's own end, is not:
// an end begun while it dialled finds the new link (`quit`).
- if (!up.swap(false, .acq_rel) or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
+ if (answer.swap(.asked, .acq_rel) != .up or quitting.load(.acquire) or !redial(fd) or quitting.load(.acquire)) break;
retell.store(true, .release);
- deliver(ctx, .relinked);
+ give(.relinked);
}
// Not kept, until the session's end.
- gone.store(true, .release);
+ settle(.gone);
}
/// A new connection in the place of `fd`, the link (its number kept, so
@@ -498,7 +554,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
@@ -758,7 +814,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.
@@ -851,7 +907,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;
};
@@ -876,7 +932,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) {
@@ -886,14 +942,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) {
@@ -1006,7 +1062,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;
@@ -1056,12 +1112,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]);
@@ -1184,6 +1240,43 @@ pub fn serve(state: ?[]const u8) noreturn {
libc._exit(0);
}
+test "a client's connection the daemon hands on after the session's loop ended reaches no loop: it is closed" {
+ if (comptime !supported) return error.SkipZigTest;
+ var pair: [2]c_int = undefined;
+ try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0, &pair));
+ defer _ = libc.close(pair[1]);
+ // The session's link, its daemon this test's end.
+ link = pair[0];
+ defer {
+ quit();
+ quitting.store(false, .release);
+ answer.store(.asked, .release);
+ }
+ const Loop = struct {
+ var notes_taken: u32 = 0;
+ fn note(_: *anyopaque, n: Note) void {
+ notes_taken += 1;
+ if (n == .replica) _ = libc.close(n.replica.fd);
+ }
+ };
+ var loop: u8 = 0;
+ notesTo(.{ .ctx = &loop, .deliver = Loop.note });
+ watch();
+ try std.testing.expect(send(pair[1], "ok", &.{}));
+ // The loop ends (runtime/session.zig `run`); the link outlives it
+ // until main's `quit`.
+ notesTo(null);
+ var conn: [2]c_int = undefined;
+ try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &conn));
+ defer _ = libc.close(conn[0]);
+ try std.testing.expect(send(pair[1], "replica 0", &.{conn[1]}));
+ _ = libc.close(conn[1]);
+ // Closed by the reader: the client sees its link end.
+ var fds = [_]posix.pollfd{.{ .fd = conn[0], .events = posix.POLL.IN, .revents = 0 }};
+ try std.testing.expectEqual(@as(usize, 1), try posix.poll(&fds, 5000));
+ try std.testing.expectEqual(@as(u32, 0), Loop.notes_taken);
+}
+
test "a message carries its words and its fds, and the peer's end is null" {
if (comptime !supported) return error.SkipZigTest;
var pair: [2]c_int = undefined;
diff --git a/runtime/macos.zig b/runtime/macos.zig
index cfe93b13..23d70b27 100644
--- a/runtime/macos.zig
+++ b/runtime/macos.zig
@@ -250,7 +250,7 @@ const State = struct {
io: std.Io,
core: *pardes.Pardes,
started: bool = false,
- runtime: Callbacks,
+ callbacks: Callbacks,
tag_cells: [pardes.MAX_TAG_LAYERS][]Cell = @splat(&.{}),
layer_cells: [pardes.MAX_PANES][]Cell = @splat(&.{}),
cells: []Cell = &.{},
@@ -290,9 +290,9 @@ const State = struct {
var state: ?State = null;
-export fn pardes_init(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) c_int {
+export fn pardes_init(callbacks: ?*const Callbacks, cols_arg: u16, rows_arg: u16) c_int {
if (state != null) return 1; // already up; deinit first
- initCore(runtime, cols_arg, rows_arg) catch |err| {
+ initCore(callbacks, cols_arg, rows_arg) catch |err| {
log.err("init failed: {t}", .{err});
return 2;
};
@@ -302,7 +302,7 @@ export fn pardes_init(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16)
/// The shell's gpa in a Debug build, as std.start's is for the others.
var debug_gpa: std.heap.DebugAllocator(.{}) = .init;
-fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
+fn initCore(callbacks: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
// The allocator every other shell gets from std.start: a DebugAllocator
// in Debug, libc's malloc otherwise. libc's measured at least as fast as
// std.heap.smp_allocator everywhere and faster on MuPDF's page-sized
@@ -348,6 +348,7 @@ fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
+ opts.tape = pardes.tape.fromEnv();
const core = try pardes.Pardes.init(allocs.pardes, opts);
errdefer core.deinit();
// The workspace tag row is the macOS menu bar's business here (see
@@ -372,7 +373,7 @@ fn initCore(runtime: ?*const Callbacks, cols_arg: u16, rows_arg: u16) !void {
.core = core,
.config_arena = config_arena,
.prompt_rcs = prompt_rcs,
- .runtime = if (runtime) |r| r.* else .{},
+ .callbacks = if (callbacks) |c| c.* else .{},
};
const st = &state.?;
st.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io, .wake_fn = wakeHost, .wake_ctx = st };
@@ -682,7 +683,7 @@ fn reloadWatchedTheme(st: *State, announce: bool) bool {
live.retries_left = 0;
if (announce) {
var mbuf: [256]u8 = undefined;
- st.core.setMessage(.at(request.pane), message.stamp(&mbuf, "reloaded theme", request.path));
+ st.core.setMessage(request.pane, message.stamp(&mbuf, "reloaded theme", request.path));
}
return true;
}
@@ -1757,14 +1758,14 @@ fn dumpThemes(ctx: ?*anyopaque, id: pardes.Pane.Id) void {
fn setClipboard(ctx: ?*anyopaque, text: []const u8) void {
const st = hostState(ctx);
- const cb = st.runtime.set_clipboard orelse return;
- cb(st.runtime.userdata, text.ptr, text.len);
+ const cb = st.callbacks.set_clipboard orelse return;
+ cb(st.callbacks.userdata, text.ptr, text.len);
}
fn readClipboard(ctx: ?*anyopaque) void {
const st = hostState(ctx);
- const cb = st.runtime.read_clipboard orelse return;
- cb(st.runtime.userdata);
+ const cb = st.callbacks.read_clipboard orelse return;
+ cb(st.callbacks.userdata);
}
fn openLink(_: ?*anyopaque, url: []const u8) void {
@@ -1802,9 +1803,9 @@ fn wakeHost(ctx: ?*anyopaque) void {
}
fn wake(st: *State) void {
- const cb = st.runtime.wakeup orelse return;
+ const cb = st.callbacks.wakeup orelse return;
if (st.wake_pending.swap(true, .acq_rel)) return;
- cb(st.runtime.userdata);
+ cb(st.callbacks.userdata);
}
fn captureEnv(arena: std.mem.Allocator) ?std.process.Environ.Map {
@@ -2057,7 +2058,7 @@ test "mac queued results never cancel a newer LSP request" {
.threaded = undefined,
.io = std.testing.io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io },
@@ -2100,7 +2101,7 @@ test "mac worker setup failures finish matching LSP and pipe requests" {
.threaded = undefined,
.io = failing_io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io },
@@ -2111,7 +2112,7 @@ test "mac worker setup failures finish matching LSP and pipe requests" {
const req: host_io.Lsp.Request = .{
.id = core.lsp_ask.wait.?.id,
.kind = .status,
- .pane = @intCast(core.view().active),
+ .pane = .at(core.view().active),
.offset = 0,
.arg = "",
};
@@ -2223,7 +2224,7 @@ test "mac Restore keeps host state and rejects callbacks from the old core" {
.threaded = undefined,
.io = std.testing.io,
.core = core,
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io },
@@ -2265,8 +2266,8 @@ test "mac Restore keeps host state and rejects callbacks from the old core" {
.failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") },
} });
}
- st.inbox.acceptReader(0, 23);
- _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output"));
+ st.inbox.acceptReader(.at(0), 23);
+ _ = st.inbox.pushOutput(.at(0), 23, try gpa.dupe(u8, "old PTY output"));
core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) });
try std.testing.expect(restoreCore(&st));
try std.testing.expect(st.core != core);
@@ -2324,7 +2325,7 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
.threaded = undefined,
.io = io,
.core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }),
- .runtime = .{},
+ .callbacks = .{},
.config_arena = .init(gpa),
.prompt_rcs = .{},
.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io },
@@ -2336,8 +2337,8 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
try dump.dumpState(st.core);
try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? });
while (st.core.nextEffect()) |_| {}
- st.inbox.acceptReader(1, 1);
- for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output"));
+ st.inbox.acceptReader(.at(1), 1);
+ for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(.at(1), 1, try gpa.dupe(u8, "retained output"));
const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40);
st.gens[0] = 1;
st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } };
@@ -2361,8 +2362,8 @@ test "mac Restore cancels a PTY reader waiting for output capacity" {
try std.testing.expect(st.ptys[0] == null);
try std.testing.expectEqual(@as(usize, 0), st.inbox.len);
try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters);
- st.inbox.acceptReader(0, st.gens[0]);
- _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output"));
+ st.inbox.acceptReader(.at(0), st.gens[0]);
+ _ = st.inbox.pushOutput(.at(0), st.gens[0], try gpa.dupe(u8, "fresh output"));
var batch = st.inbox.take();
defer for (batch.slice()) |msg| msg.deinit(gpa, gpa);
try std.testing.expectEqual(@as(usize, 1), batch.len);
@@ -2626,7 +2627,7 @@ test "mac row metrics ABI preserves PDF cell dimensions and the unrendered grid"
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
defer core.deinit();
- state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
+ state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .callbacks = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
defer {
state.?.config_arena.deinit();
state = null;
@@ -2645,7 +2646,7 @@ test "mac tag layer ABI preserves logical capacity and physical grip" {
const gpa = std.testing.allocator;
const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 8, .rows = 3 });
defer core.deinit();
- state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
+ state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .callbacks = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} };
defer {
for (state.?.tag_cells) |cells| gpa.free(cells);
state.?.config_arena.deinit();
diff --git a/runtime/main.zig b/runtime/main.zig
index 29c19bc0..0751f6b0 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",
@@ -1157,6 +1159,13 @@ fn nativeMain(std_init: std.process.Init) !void {
upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{});
};
const resuming = upgrade.resumed != null;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
// `pardes new`: with --detach it returns once the session runs.
@@ -1166,21 +1175,29 @@ fn nativeMain(std_init: std.process.Init) !void {
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
+ // An upgraded session's arguments are the ones it was started with: its
+ // `new` is the verb still, not a file's name (taken for one, the file
+ // after it was "the second" and the session ended at its Upgrade).
+ if (resuming and args.len > i and std.meta.stringToEnum(Cmd, args[i]) == .new) {
+ new_session = true;
+ new_verb = true;
+ i += 1;
+ }
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
new_verb = true;
- i = 2;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1521,11 +1538,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1566,15 +1580,25 @@ 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);
- } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ 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, .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 a client of a session forked off for it (`pair`).
- pair(init, &opts);
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
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
@@ -1598,7 +1622,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 } };
}
}
@@ -1650,7 +1674,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,
@@ -1708,23 +1737,48 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
-/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
-/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
-/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
-/// (the shell's job, the terminal its own; signals reach what draws), its
-/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
-/// and 2 on /dev/null, detached), its end of the pair its first client,
-/// taken before its first effects (runtime/session.zig). Returns in the
-/// session; the client exits. No fork to be had: returns, and this process
-/// is the session, with no terminal: said by the caller's run.
-fn pair(init: std.process.Init, opts: *pardes.Options) void {
- const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// 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.
+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;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ 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)
die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
// The session laid out at the terminal's size: no reflow at the join.
var ws: std.posix.winsize = undefined;
- if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
opts.cols = ws.col;
opts.rows = ws.row;
}
@@ -1738,10 +1792,16 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
_ = std.c.dup2(null_fd, @intCast(i));
};
if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
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]);
@@ -1752,7 +1812,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
- @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
@@ -1842,8 +1902,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1852,7 +1915,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
@@ -1894,7 +1958,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;
}
@@ -1907,6 +1971,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 5d7eff78..60644aa6 100644
--- a/runtime/session.zig
+++ b/runtime/session.zig
@@ -6,10 +6,10 @@
//! posts, `Inbox`), its ptys (`Ptys`) and the files it watches
//! (`file_watch.Watches`): a step, its unit to the clients and theirs
//! taken in, an Upgrade or a Restore between steps; and the order its
-//! parts end in. Its other devices (the LSP's and the pipes' and addons'
-//! jobs, the session's own input) are still its frontend's (each `Shell`);
-//! the language servers' answers come through its queue (`Inbox.startLsp`).
-//! What a frontend does is:
+//! parts end in. Its workers (a language server's query, the pipes, the
+//! addons' jobs and draws, a search) answer through its queue, which holds
+//! their tasks and ends them (`Inbox.land`, `Inbox.deinit`); the session's
+//! own input is its frontend's (each `Shell`). What a frontend does is:
//!
//! - `options(o)`: before the core: what it gives the core it starts (a
//! window's size, for a dump's layout).
@@ -25,8 +25,6 @@
//! session's first wait (`l.watch`).
//! - `sent()`: after each step's unit went to the clients.
//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs).
-//! - `note(n)`: what the daemon says (an adopted shell, a client's
-//! connection, a new daemon's hello taken), onto its queue.
//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it
//! replaces the old one (its devices let go, what it is told of the
//! frontend) and after (its own view of it again).
@@ -75,6 +73,7 @@ pub fn Loop(comptime Frontend: type) type {
o.tree_sitter_allocator = l.allocs.tree_sitter;
o.frame_allocator = l.allocs.frame;
fe.options(&o);
+ o.tape = pardes.tape.fromEnv();
l.core = if (upgrade.resumed) |*rec|
try upgrade.load(l.gpa, l.allocs.pardes, o, rec)
else if (o.load_path) |lp| blk: {
@@ -90,6 +89,8 @@ pub fn Loop(comptime Frontend: type) type {
l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() };
l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp };
defer l.inbox.deinit();
+ // A search's worker may be waiting on the queue for room.
+ defer l.core.stream.cancelTask();
// The language servers' status lines, from the first effects on.
pardes.lsp.setStatusSink(&l.inbox, host_io.Inbox.lspStatus);
defer pardes.lsp.setStatusSink(null, null);
@@ -103,6 +104,10 @@ pub fn Loop(comptime Frontend: type) type {
defer l.peers.deinit();
// Before the core goes: each client sees its link end.
defer l.peers.dropAll(l.core);
+ // The daemon's notes, to the loop until its state goes (the
+ // reader runs on until main's `daemon.quit`).
+ daemon.notesTo(.{ .ctx = &l, .deliver = note });
+ defer daemon.notesTo(null);
// A first client on the socket it was started with, before its
// first effects: it has every terminal from its first byte, and
// no reload (Core.openView).
@@ -126,8 +131,9 @@ pub fn Loop(comptime Frontend: type) type {
// Its unit to each replica client, and theirs taken in.
l.peers.boundary(l.core);
// A pair's session with no daemon ends with its last link:
- // nothing could attach to it again.
- if (o.pair != null and daemon.link < 0 and l.peers.count() == 0) break;
+ // nothing could attach to it again; with one, when its last
+ // 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
@@ -154,17 +160,28 @@ pub fn Loop(comptime Frontend: type) type {
while (l.core.nextEffect()) |e| l.core.perform(e);
}
- /// What the daemon says, onto the frontend's queue (once: its
+ /// What the daemon says, onto the session's queue (once: its
/// reader is started by the first call); and a daemon started
/// since the last one died told the shells' masters it held.
pub fn watch(l: *L) void {
if (daemon.relinked()) l.ptys.tellDaemon();
- daemon.watch(l.fe, note);
+ daemon.watch();
}
+ /// The daemon's thread: an adopted shell onto the queue (taken
+ /// in the frontend's wait), a client's connection to `Peers`
+ /// (joined at the next step boundary), a new daemon's hello taken
+ /// a wake (`watch` tells it the rest).
fn note(ctx: *anyopaque, n: daemon.Note) void {
- const fe: *Frontend = @ptrCast(@alignCast(ctx));
- fe.note(n);
+ const l: *L = @ptrCast(@alignCast(ctx));
+ switch (n) {
+ .relinked => l.inbox.wake(),
+ .adopted => |a| {
+ for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| l.inbox.push(.{ .adopted = .{ .pid = pid, .fd = fd } });
+ l.inbox.push(.{ .adopted = .{ .pid = 0, .fd = -1 } });
+ },
+ .replica => |j| l.peers.handed(j.fd, j.view),
+ }
}
/// A Restore: the core its dump makes replaces this one, its clients
@@ -173,7 +190,9 @@ pub fn Loop(comptime Frontend: type) type {
fn restore(l: *L, path: []const u8) void {
const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return;
l.fe.restoring(nc);
- // An answer to the old core's query is turned away.
+ // The old core's pipes end, and an answer to its query is
+ // turned away.
+ l.inbox.pipe_tasks.cancelAll(l.io);
l.inbox.discardCompletions();
l.ptys.stop();
nc.host = l.host;
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index 2a8d6edf..f59117ee 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -19,9 +19,13 @@ 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=";
+/// A window's pair's session's first word (main.zig `pair`): its first
+/// client's fd, which an Upgrade does not name again (that client joined).
+pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
@@ -46,6 +50,7 @@ var located = false;
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
+ if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
@@ -91,6 +96,14 @@ pub fn newer() bool {
return true;
}
+/// Another file at its start path than the one it started from: a build
+/// installed there since (`locate` first). A client's question at an
+/// Upgrade (client.zig).
+pub fn replaced() bool {
+ const was = started_inode orelse return false;
+ return (inodeOf(exe() orelse return false) orelse return false) != was;
+}
+
pub fn exe() ?[:0]const u8 {
return if (exe_len == 0) null else exe_buf[0..exe_len :0];
}
@@ -128,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;
@@ -165,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 });
}
@@ -179,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),
@@ -213,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,
}
@@ -371,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";
@@ -441,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);
@@ -462,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"));
}