diff options
Diffstat (limited to 'runtime/daemon.zig')
| -rw-r--r-- | runtime/daemon.zig | 171 |
1 files changed, 132 insertions, 39 deletions
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; |
