summaryrefslogtreecommitdiff
path: root/runtime/daemon.zig
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/daemon.zig')
-rw-r--r--runtime/daemon.zig326
1 files changed, 113 insertions, 213 deletions
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 0d860918..80e1cc09 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -10,9 +10,10 @@
//! - a dup of every pty master it forks (`pty`), so a session killed
//! outright never hangs its shells up, and which ones it closed;
//! - whether a terminal or a window shows it (`state`).
-//! It hands a terminal (`pardes --attach`) or a window request
-//! (`pardes-gui --attach`) to a detached session, and a crashed session's
-//! masters to the one that asks for them (Adopt).
+//! It lists the sessions (`pardes ps`), hands a crashed session's masters
+//! to the one that asks for them (Adopt), and a client's connection to the
+//! session it names (below). A session whose daemon died dials the next
+//! one and registers again (`readNotes`).
//!
//! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it
//! carries (SCM_RIGHTS).
@@ -290,9 +291,17 @@ fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool)
/// 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.
+/// `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 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.
+var kind: Kind = .tty;
+var detached_now = std.atomic.Value(bool).init(false);
/// What it is called (its 9P name).
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
@@ -328,6 +337,8 @@ fn setName(named: []const u8) void {
pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool {
if (comptime !supported) return false;
setName(named);
+ kind = k;
+ detached_now.store(detached, .release);
const c = fd orelse connect(true) orelse return false;
startPending(true);
if (!hello(c, k, libc.getpid(), name(), detached)) {
@@ -359,20 +370,36 @@ pub fn closed(pid: libc.pid_t) void {
tell(std.fmt.bufPrint(&buf, "close {d}", .{pid}) catch unreachable, &.{}); // a pid fits 32
}
-pub fn setState(detached: bool) void {
- tell(if (detached) "state detached" else "state attached", &.{});
+/// 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);
+ tell("state detached", &.{});
}
+/// The last `clients` line, kept to be told to a new daemon (`relinked`).
+var clients_line: ["clients".len + max_clients * " -2147483648".len]u8 = undefined;
+var clients_len: usize = 0;
+
/// This session's replica clients now, each its process's pid (0 when its
/// socket's peer is not known), for `--ps`.
pub fn clients(pids: []const libc.pid_t) void {
- var buf: ["clients".len + max_clients * " -2147483648".len]u8 = undefined;
- var w: std.Io.Writer = .fixed(&buf);
- w.writeAll("clients") catch unreachable; // a literal, its .len in buf's
- for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in buf's type
+ var w: std.Io.Writer = .fixed(&clients_line);
+ w.writeAll("clients") catch unreachable; // a literal, its .len in clients_line's
+ for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in clients_line's type
+ clients_len = w.end;
tell(w.buffered(), &.{});
}
+/// Whether a new daemon took this session's hello since the last call
+/// (the session loop's, each pass): its clients told it again here, its
+/// ptys the caller's to tell (`pty`).
+pub fn relinked() bool {
+ if (!retell.swap(false, .acq_rel)) return false;
+ if (clients_len > 0) tell(clients_line[0..clients_len], &.{});
+ return true;
+}
+
/// Asks for the masters of sessions that died holding them; they come back
/// as an `adopted` note.
pub fn adopt() void {
@@ -394,13 +421,15 @@ pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detache
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);
}
pub const Note = union(enum) {
- /// A terminal for a detached tui session (`pardes --attach`), and the
- /// stub's pipe; for a window session, both -1: open a window.
- attach: struct { tty: c_int, stub: c_int },
+ /// A new daemon took the hello (`readNotes`): the session loop is woken
+ /// to tell it the rest (`relinked`).
+ relinked,
adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize },
/// A replica's connection, its hello taken (core/replica.zig `Peers`),
/// and the view it joins again for, if it does.
@@ -418,46 +447,58 @@ pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) v
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
var buf: [msg_max]u8 = undefined;
- // The end of the link (a daemon gone, a hello refused): not kept.
- defer {
- up.store(false, .release);
- gone.store(true, .release);
- }
- while (recv(fd, &buf)) |got| {
- var words = std.mem.tokenizeScalar(u8, got.words, ' ');
- const verb = words.next() orelse "";
- if (std.meta.stringToEnum(enum { ok, attach, replica, adopted }, verb)) |v| switch (v) {
- .ok => up.store(true, .release),
- .attach => {
- deliver(ctx, .{ .attach = .{
- .tty = if (got.nfds >= 2) got.fds[0] else -1,
- .stub = if (got.nfds >= 2) got.fds[1] else -1,
- } });
- for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f);
- },
- .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 } });
- for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f);
- },
- .adopted => {
- var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } };
- const a = &note.adopted;
- for (got.fds[0..got.nfds]) |f| {
- const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch {
- _ = libc.close(f);
- continue;
- };
- a.pids[a.n] = pid;
- a.fds[a.n] = f;
- a.n += 1;
- }
- deliver(ctx, note);
- },
- } else for (got.fds[0..got.nfds]) |f| {
- _ = libc.close(f);
+ 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),
+ .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 } });
+ for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f);
+ },
+ .adopted => {
+ var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } };
+ const a = &note.adopted;
+ for (got.fds[0..got.nfds]) |f| {
+ const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch {
+ _ = libc.close(f);
+ continue;
+ };
+ a.pids[a.n] = pid;
+ a.fds[a.n] = f;
+ a.n += 1;
+ }
+ deliver(ctx, note);
+ },
+ } else for (got.fds[0..got.nfds]) |f| {
+ _ = libc.close(f);
+ }
}
+ // The end of the link. One whose daemon took the hello (it died, or
+ // let the session go) is dialled again, a daemon started if none
+ // answers, and the hello said, here, off the session's way: the
+ // 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;
+ retell.store(true, .release);
+ deliver(ctx, .relinked);
}
+ // Not kept, until the session's end.
+ gone.store(true, .release);
+}
+
+/// A new connection in the place of `fd`, the link (its number kept, so
+/// the session's own sends never race a new fd), and the hello said on it.
+fn redial(fd: c_int) bool {
+ if (comptime !supported) return false;
+ const c = connect(true) orelse return false;
+ 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));
}
/// `bytes` sent whole on a socket, never raising SIGPIPE: false when the
@@ -493,6 +534,7 @@ pub fn hangUp() void {
/// link closed, the reader joined.
pub fn quit() void {
if (link < 0) return;
+ quitting.store(true, .release);
tell("quit", &.{});
_ = libc.shutdown(link, 2);
if (reader) |r| r.join();
@@ -501,37 +543,13 @@ pub fn quit() void {
link = -1;
}
-// ---- `pardes --attach`: a terminal, or a window, for a detached session ----
-
-/// `other`: the session is the other kind (a window's for a terminal, or a
-/// terminal's for a window), named so: joined as a replica client instead
-/// (`replicaSocket`).
-pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8, other: []const u8 };
+// ---- `pardes attach`: a client, by the replica socket ----
/// This machine's replica socket, which joins a session of either kind.
pub fn replicaSocket(buf: *[sun_path_len:0]u8) ?[:0]const u8 {
return place(buf, "pardes-replica.sock");
}
-/// Asks the daemon to hand `fds` (a terminal and a stub's pipe, or none for
-/// a window) to the detached session `named` (any one, when empty), and
-/// answers how it went; the words are `buf`'s.
-pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer {
- const fd = connect(false) orelse return .{ .no = "no detached session is running" };
- defer _ = libc.close(fd);
- var line: [256]u8 = undefined;
- const words = std.fmt.bufPrint(&line, "attach {t} {s}", .{ k, named }) catch return .{ .no = "that name is too long" };
- if (!send(fd, words, fds) or !readable(fd, 2000)) return .{ .no = "the daemon does not answer" };
- const got = recv(fd, buf) orelse return .{ .no = "the daemon hung up" };
- for (got.fds[0..got.nfds]) |f| _ = libc.close(f);
- if (std.mem.startsWith(u8, got.words, "ok ")) {
- const pid = std.fmt.parseInt(libc.pid_t, got.words[3..], 10) catch return .{ .no = "the daemon answered nonsense" };
- return .{ .ok = pid };
- }
- if (std.mem.startsWith(u8, got.words, "other ")) return .{ .other = got.words["other ".len..] };
- return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else got.words };
-}
-
/// The daemon's answer to `words` (`list`, `kill <name>`, `killall`), in
/// `buf`; null with no daemon running, or none answering.
pub fn ask(words: []const u8, buf: []u8) ?[]const u8 {
@@ -558,13 +576,11 @@ fn forward(sig: posix.SIG) callconv(.c) void {
}
}
-/// The job the shell waits on, for a session that is not its child any
-/// more (`pardes --attach`) or that it forked (`child`, reaped here): what
-/// a terminal sends the job goes on to the session (its size, an end
+/// The job the shell waits on, for the session it forked (reaped here):
+/// what a terminal sends the job goes on to the session (its size, an end
/// asked for), and it ends when the session is gone from the terminal --
-/// detached (`d<name>`), exited (`x<code>`, or the pipe's end and the
-/// child's status), or refused (`r<why>`).
-pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn {
+/// detached (`d<name>`), or exited (the pipe's end and the child's status).
+fn stubWait(session: libc.pid_t, pipe: c_int) noreturn {
stub_child = session;
const on: posix.Sigaction = .{ .handler = .{ .handler = forward }, .mask = posix.sigemptyset(), .flags = posix.SA.RESTART };
for ([_]posix.SIG{ .WINCH, .TERM, .INT, .QUIT, .HUP }) |sig| posix.sigaction(sig, &on, null);
@@ -587,31 +603,21 @@ pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn {
if (said.len > 0 and said[0] == 'd') {
var text: [700]u8 = undefined;
const who = said[1..];
- out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes --attach={s}`\n", .{ who, who }) catch "pardes: detached\n") catch {};
+ out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes attach {s}`\n", .{ who, who }) catch "pardes: detached\n") catch {};
libc._exit(0);
}
- if (said.len > 0 and said[0] == 'r') {
- var text: [700]u8 = undefined;
- out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: --attach: {s}\n", .{said[1..]}) catch "pardes: --attach refused\n") catch {};
- libc._exit(1);
+ var status: c_int = 0;
+ while (libc.waitpid(session, &status, 0) < 0) {
+ if (libc.errno(-1) != .INTR) libc._exit(1);
}
- if (child) {
- var status: c_int = 0;
- while (libc.waitpid(session, &status, 0) < 0) {
- if (libc.errno(-1) != .INTR) libc._exit(1);
- }
- const s: u32 = @bitCast(status);
- if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s)));
- if (libc.W.IFSIGNALED(s)) {
- const sig = libc.W.TERMSIG(s);
- const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
- posix.sigaction(sig, &default, null);
- _ = libc.raise(sig);
- }
- libc._exit(1);
+ const s: u32 = @bitCast(status);
+ if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s)));
+ if (libc.W.IFSIGNALED(s)) {
+ const sig = libc.W.TERMSIG(s);
+ const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
+ posix.sigaction(sig, &default, null);
+ _ = libc.raise(sig);
}
- if (said.len > 0 and said[0] == 'x') libc._exit(std.fmt.parseInt(u8, said[1..], 10) catch 1);
- out.writeStreamingAll(io, "pardes: the session ended without a word\n") catch {};
libc._exit(1);
}
@@ -642,16 +648,8 @@ pub fn tellStubDetached() void {
stub = -1;
}
-/// The session's end, `code` its exit status: the stub is told (and goes).
-pub fn tellStubExit(code: u8) void {
- tellStub(stub, "x{d}", .{code});
- stub = -1;
-}
-
-/// The stub on `fd` told how its terminal's session went, what stubWait
-/// reads, and its pipe let go: `d<name>` detached (one of a session's
-/// several terminals, views.zig), `x<code>` exited, `r<why>` refused (an
-/// attach that came too late).
+/// The stub on `fd` told that its terminal's session detached
+/// (`d<name>`), what stubWait reads, and its pipe let go.
pub fn tellStub(fd: c_int, comptime fmt: []const u8, args: anytype) void {
if (fd < 0) return;
var buf: [256]u8 = undefined;
@@ -694,7 +692,7 @@ pub fn forkSession(conn: c_int) ?void {
_ = libc.close(conn);
// Off the session's way: it is drawing already, its hello queued.
startPending(true);
- stubWait(pid, true, pipe[0]);
+ stubWait(pid, pipe[0]);
}
// ---- the daemon ----
@@ -815,7 +813,7 @@ const Daemon = struct {
};
const c = &d.conns[i];
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
- const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt, attach };
+ const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt };
switch (std.meta.stringToEnum(Verb, words.next() orelse return) orelse return) {
.hello => {
const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0;
@@ -880,95 +878,7 @@ const Daemon = struct {
if (!send(c.fd, w.buffered(), fds[0..n])) return d.hangUp(i);
for (given[0..n]) |h| h.owner = i;
},
- .attach => {
- const k = std.meta.stringToEnum(Kind, words.next() orelse "") orelse return d.reply(i, "no bad attach", &.{});
- const wanted_name = std.mem.trim(u8, words.rest(), " ");
- var why: [512]u8 = undefined;
- // "other <name>": the client joins it through the replica socket.
- const target = d.find(k, wanted_name, &why) orelse return d.reply(i, std.mem.sliceTo(&why, 0), &.{});
- const t = &d.conns[target];
- if (!send(t.fd, "attach", got.fds[0..got.nfds])) {
- d.hangUp(target);
- return d.reply(i, "no that session does not answer", &.{});
- }
- t.detached = false;
- var line: [32]u8 = undefined;
- return d.reply(i, std.fmt.bufPrint(&line, "ok {d}", .{t.pid}) catch unreachable, &.{}); // a pid fits 32
- },
- }
- }
-
- /// The detached session of kind `k` called `wanted_name`, or the one
- /// there is when it is empty; else null, and why not in `why`
- /// (0-terminated): "other <its name>" for one to join as a replica
- /// client (of the other kind, or attached already: a session shows one
- /// frontend of its own).
- fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 {
- @memset(why, 0);
- const other: []const u8 = switch (k) {
- .tty => "a window: attach it with `pardes-gui --attach",
- .gui => "a terminal session: attach it with `pardes --attach",
- };
- if (wanted_name.len != 0) {
- for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) {
- if (s.kind.? != k or !s.detached) {
- _ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {};
- return null;
- }
- return @as(u8, @intCast(i));
- };
- _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {};
- return null;
- }
- var found: ?u8 = null;
- var count: usize = 0;
- var others: usize = 0;
- var w: std.Io.Writer = .fixed(why[0 .. why.len - 1]);
- for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.detached and s.kind != null) {
- if (s.kind.? != k) {
- others += 1;
- continue;
- }
- count += 1;
- found = @intCast(i);
- };
- if (count == 1) return found.?;
- // None detached: the one session there is, joined as a client.
- if (count == 0) {
- for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) {
- count += 1;
- found = @intCast(i);
- };
- if (count == 1) {
- _ = std.fmt.bufPrint(why, "other {s}", .{d.conns[found.?].named()}) catch unreachable; // a [128]u8 field's name fits 512
- return null;
- }
- count = 0;
- // None of this kind at all: the one session there is, the other kind's.
- var only: ?*Conn = null;
- var sessions: usize = 0;
- for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) {
- sessions += 1;
- only = s;
- };
- if (found == null and sessions == 1) {
- _ = std.fmt.bufPrint(why, "other {s}", .{only.?.named()}) catch unreachable; // a [128]u8 field's name fits 512
- return null;
- }
}
- if (count == 0 and others == 0) {
- w.writeAll("no no detached session is running") catch unreachable; // a literal fits 511
- return null;
- }
- if (count == 0) {
- w.print("no the detached session{s} running {s} {s}=<name>`", .{ if (others == 1) " is" else "s are", if (others == 1) "is" else "are each", other }) catch {}; // cut short, still 0-terminated
- return null;
- }
- w.print("no {d} detached sessions are running; say which with --attach=<name>:", .{count}) catch unreachable; // a usize fits 511
- for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) {
- w.print(" {s}", .{s.named()}) catch {};
- };
- return null;
}
/// More of a replica's hello; once it is whole, the connection refused
@@ -1239,13 +1149,3 @@ test "a message carries its words and its fds, and the peer's end is null" {
_ = libc.close(pair[1]);
try std.testing.expect(recv(pair[0], &buf) == null);
}
-
-test "an attach by a name longer than any session's is refused in words, never an empty reason" {
- var d: Daemon = .{};
- var why: [512]u8 = undefined;
- const long: []const u8 = &@as([600]u8, @splat('n'));
- try std.testing.expect(d.find(.tty, long, &why) == null);
- const said = std.mem.sliceTo(&why, 0);
- try std.testing.expect(std.mem.startsWith(u8, said, "no "));
- try std.testing.expect(said.len > "no ".len);
-}