diff options
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/9p_io.zig | 6 | ||||
| -rw-r--r-- | runtime/client.zig | 59 | ||||
| -rw-r--r-- | runtime/daemon.zig | 105 | ||||
| -rw-r--r-- | runtime/macos.zig | 1 | ||||
| -rw-r--r-- | runtime/main.zig | 140 | ||||
| -rw-r--r-- | runtime/session.zig | 50 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 12 |
7 files changed, 324 insertions, 49 deletions
diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig index bcb0f81b..aaca377d 100644 --- a/runtime/9p_io.zig +++ b/runtime/9p_io.zig @@ -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 75518552..329bdab3 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; } @@ -109,9 +112,46 @@ pub const Start = struct { } }; -/// How a client's joins ended: it quit, the session let it go, or it could -/// not join again (`Start.said`). -pub const Ended = enum { done, gone, failed }; +/// 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), 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; + _ = 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 { @@ -141,6 +181,8 @@ pub fn Loop(comptime Frontend: type) type { /// the session let it go to upgrade; 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); @@ -151,7 +193,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); + if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null, .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). @@ -170,12 +212,17 @@ pub fn Loop(comptime Frontend: type) type { // What it made since it joined, kept for its next start. if (s.have) |h| h.keep(s.r.core()); s.r.deinit(); + if (link.left) return .left; + if (link.ended) |code| return .{ .ended = code }; return if (link.gone) .gone else .done; } // 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 80e1cc09..9b566e60 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -290,10 +290,11 @@ 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 @@ -306,6 +307,8 @@ var detached_now = std.atomic.Value(bool).init(false); var name_buf: [128]u8 = undefined; var name_len: usize = 0; var reader: ?std.Thread = null; +/// Where the reader hands each note (`notesTo`). +var notes: ?struct { ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void } = null; pub fn name() []const u8 { return name_buf[0..name_len]; @@ -314,12 +317,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 @@ -438,11 +451,18 @@ 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's, before its first step. +pub fn notesTo(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { + notes = .{ .ctx = ctx, .deliver = deliver }; +} + +/// 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 { +pub fn watch() void { + const n = notes orelse return; if (link < 0 or reader != null) return; - reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null; + reader = std.Thread.spawn(.{}, readNotes, .{ link, n.ctx, n.deliver }) catch null; } fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { @@ -452,7 +472,7 @@ fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, no 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 } }); @@ -482,12 +502,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); } // 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 @@ -600,6 +620,12 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { const said = buf[0..len]; const out = std.Io.File.stderr(); const io = std.Io.Threaded.global_single_threaded.io(); + // `new --detach`'s session runs (`launched`): its name, for a script. + if (said.len > 0 and said[0] == 'r') { + var text: [520]u8 = undefined; + std.Io.File.stdout().writeStreamingAll(io, std.fmt.bufPrint(&text, "{s}\n", .{said[1..]}) catch said[1..]) catch {}; + libc._exit(0); + } if (said.len > 0 and said[0] == 'd') { var text: [700]u8 = undefined; const who = said[1..]; @@ -695,6 +721,57 @@ pub fn forkSession(conn: c_int) ?void { stubWait(pid, pipe[0]); } +/// `pardes new --detach`: the session forked off in a session of its own, +/// its stdin /dev/null, and this process its stub until the session runs +/// (`launched`): it then prints the name and exits 0, or with the +/// session's status if it ended first. Returns in the session, called +/// `named` (else by its pid); when no fork can be made, here, which is +/// then the session. +pub fn launch(named: []const u8) void { + var pipe: [2]c_int = undefined; + if (libc.pipe(&pipe) != 0) return; + ninep_io.setCloexec(pipe[0]); + ninep_io.setCloexec(pipe[1]); + const pid = libc.fork(); + if (pid < 0) { + _ = libc.close(pipe[0]); + _ = libc.close(pipe[1]); + return; + } + if (pid == 0) { + _ = libc.close(pipe[0]); + _ = libc.setsid(); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd >= 0) _ = libc.dup2(null_fd, 0); + if (null_fd > 0) _ = libc.close(null_fd); + stub = pipe[1]; + launching = true; + setName(named); + return; + } + _ = libc.close(pipe[1]); + stubWait(pid, pipe[0]); +} + +/// Forked by `launch`, and its stub not told yet. +var launching = false; + +/// The session of a `new --detach` runs: registered (the daemon took its +/// hello, when there is one) and listening. Its stub told, with its name; +/// its stdout and stderr, still the launch's until now, let go. +pub fn launched() void { + if (!launching) return; + launching = false; + _ = kept(); + tellStub(stub, "r{s}", .{name()}); + stub = -1; + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd < 0) return; + _ = libc.dup2(null_fd, 1); + _ = libc.dup2(null_fd, 2); + if (null_fd > 2) _ = libc.close(null_fd); +} + // ---- the daemon ---- const Conn = struct { diff --git a/runtime/macos.zig b/runtime/macos.zig index cfe93b13..4f9a9c33 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -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 diff --git a/runtime/main.zig b/runtime/main.zig index 36c25f2b..a21eb83f 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -323,8 +323,10 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{ .doc = \\Start a session here, even in a pane of another: in this terminal for \\pardes, a window for pardes-gui, or with --detach none until one - \\attaches. Bare `pardes` takes the same flags, and starts one unless - \\it is in a pane (where it hands its FILE to that session). + \\attaches, which returns once the session runs and prints its name. + \\Bare `pardes` takes the same flags, and starts one unless it is in a + \\pane (where it hands its FILE to that session); its --detach is the + \\session itself, until it ends (a supervisor's way). , .examples = &.{ .{ "pardes new", "a session here, its shell pane in tty mode" }, @@ -1155,27 +1157,37 @@ 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. + var new_verb = false; var explicit_tty = false; var detach: ?[]const u8 = null; 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; // 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; - i = 2; + new_verb = true; + 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]; @@ -1516,11 +1528,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; @@ -1531,6 +1540,9 @@ fn nativeMain(std_init: std.process.Init) !void { // socket holds already (a plain session is named by its pid too). if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name}); if (opts.ninep_name.len == 0) opts.ninep_name = name; + // `new --detach` forks the session and returns once it runs; the + // flag alone is the session itself (a supervisor's, a harness's). + if (new_verb and !resuming) daemon.launch(opts.ninep_name); // Said where it was started (stderr, as the log says it): no pane // anyone sees would show it. The session runs on, with no 9P. var pid_buf: [16]u8 = undefined; @@ -1559,6 +1571,19 @@ fn nativeMain(std_init: std.process.Init) !void { }; detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0; daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached); + } else if (paired) |fd| { + // A window's pair's session: its first client on `fd`, the daemon + // its own to dial (and to start, when none runs). + opts.pair = fd; + term = .detached; + detached = true; + if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, true); + } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) { + // The last step's way, behind its variable until it is the default: + // this terminal or window a client of a session forked off for it + // (`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); @@ -1695,6 +1720,85 @@ 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"); } +/// 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 (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; + } + const pid = std.c.fork(); + if (pid < 0) die(init.io, "no fork for a session and its terminal", .{}); + if (pid == 0) { + _ = std.c.close(fds[1]); + _ = std.c.setsid(); + const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(std.c.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = 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); + return; + } + _ = std.c.close(fds[0]); + if (conn) |c| _ = std.c.close(c); + daemon.startPending(true); + var name_buf: [16]u8 = undefined; + const name = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&name_buf, "{d}", .{pid}) catch unreachable; // a pid fits 16 + var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; + var o = opts.*; + o.pair = fds[1]; + clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err}); + std.process.exit(0); +} + /// The replica client of this build's frontend: a terminal's (tui.zig) or a /// window's (gui.zig). fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void { @@ -1781,8 +1885,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; @@ -1791,7 +1898,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); } diff --git a/runtime/session.zig b/runtime/session.zig index fdd72c2b..9c8446e3 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); @@ -100,9 +101,14 @@ pub fn Loop(comptime Frontend: type) type { l.host = try fe.open(&l); defer fe.close(&l); + daemon.notesTo(&l, note); defer l.peers.deinit(); // Before the core goes: each client sees its link end. defer l.peers.dropAll(l.core); + // 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). + if (o.pair) |fd| l.peers.join(l.core, .{ .fd = fd }); l.effects(); // ...and its shells, once a fresh session's own has a directory // to adopt them in. @@ -113,12 +119,19 @@ pub fn Loop(comptime Frontend: type) type { l.ptys.start(l.core); l.watches.start(); try fe.start(&l); + // A `new --detach`'s launch returns now. + daemon.launched(); while (!l.core.quit) { pardes.turn.bump(&pardes.turn.restores); try l.core.pump(l.host); // 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; with one, when its last + // client closed its window (a close, not a loss), no Detach + // typed in any. + if (o.pair != null and l.peers.count() == 0 and (daemon.link < 0 or l.peers.closed)) break; fe.sent(); upgrade.locate(); // Asked in the step (the word), done between steps: the @@ -132,6 +145,8 @@ pub fn Loop(comptime Frontend: type) type { if (l.core.quit) break; if (l.core.takeRestore()) |rp| l.restore(rp); } + // The clients' last word: the session ended (Exit). + l.peers.ended(0); // Its serve threads read the core: they end first. if (l.fs) |f| { f.deinit(l.gpa); @@ -143,17 +158,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 @@ -162,7 +188,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..37d4890b 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -22,6 +22,9 @@ const pardes = @import("core"); 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 +49,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 +95,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]; } |
