From ddcfd860ef05c37f5536038d8828cc81c0c4125c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 29 Oct 2026 22:18:34 -0300 Subject: upgrade: the Upgrade word (SPC s U, a tag, 9P) moves a running session onto the pardes installed where it started, in place, by exec at a step boundary: its dump in the DumpDir, its pty masters, terminals, stubs and daemon link kept open and named on the new command line, every view and running shell its own again; the daemon re-execs too, its registry on its command line; a build that cannot load the dump falls back to the old binary, or starts afresh with the shells adopted and the dump kept (test/daemon.py --upgrade, --upgrade --gui) Co-Authored-By: Claude Opus 5.5 --- src/tty/tty.zig | 220 ++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 198 insertions(+), 22 deletions(-) (limited to 'src/tty') diff --git a/src/tty/tty.zig b/src/tty/tty.zig index a7048645..ef7688bc 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -16,6 +16,7 @@ const ninep_io = @import("../9p_io.zig"); const panel_compositor = @import("panel_compositor.zig"); const daemon = @import("../daemon.zig"); const host_io = @import("../host_io.zig"); +const upgrade = @import("../upgrade.zig"); extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; @@ -69,6 +70,16 @@ fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); } +/// A terminal unlinks what it reads; whatever it never read (the probe +/// unanswered, a transmission lost with the terminal) is ours to remove. +fn unlinkKittyShm() void { + var name_buf: [64]u8 = undefined; + var n: u32 = 0; + while (n <= kitty_shm_serial) : (n += 1) { + if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} + } +} + /// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); @@ -1208,7 +1219,9 @@ fn nativePdfWheelTarget(core: *const pardes.Pardes, mouse: vaxis.Mouse) ?PdfWhee /// Where a session's terminal comes from: /dev/tty, as a plain `pardes` /// opens it; one open already (a session forked off its stub, /// daemon.forkSession); or none, until one is attached (`--detach`). -pub const Term = union(enum) { open, fd: posix.fd_t, none }; +/// The terminal a session starts on: /dev/tty, one its stub opened (an +/// upgraded session's is raw already, `termios` the cooked one), or none. +pub const Term = union(enum) { open, fd: struct { fd: posix.fd_t, termios: ?posix.termios = null }, none }; pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { const io = init.io; @@ -1230,7 +1243,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { defer screen.kitty.deinit(); switch (term) { .open => try screen.enter(try vaxis.Tty.init(io, &tty_buf)), - .fd => |fd| try screen.enter(try Screen.ttyOn(io, &tty_buf, fd)), + .fd => |t| try screen.enter(try Screen.ttyOn(io, &tty_buf, t.fd, t.termios)), .none => {}, } defer screen.leave(); @@ -1277,9 +1290,10 @@ const Screen = struct { /// `fd` made raw, as vaxis.Tty.init makes /dev/tty: the terminal of a /// forked session is no controlling terminal of its, which /dev/tty is. - fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t) !vaxis.Tty { + /// An upgraded session's is raw already, `cooked` what it goes back to. + fn ttyOn(io: std.Io, buf: []u8, fd: posix.fd_t, cooked: ?posix.termios) !vaxis.Tty { if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty - const termios = try vaxis.Tty.makeRaw(fd); + const termios = cooked orelse try vaxis.Tty.makeRaw(fd); const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; return .{ .io = io, .fd = file, .termios = termios, .tty_writer = file.writerStreaming(io, buf) }; } @@ -1416,7 +1430,9 @@ fn localSession( pardes.syntax.stop(); } - var core = if (options.load_path) |lp| blk: { + var core = if (upgrade.resumed) |*rec| + try upgrade.load(gpa, allocs.pardes, options, rec) + else if (options.load_path) |lp| blk: { const bytes = try filesystem.readFile(gpa, lp); defer gpa.free(bytes); break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); @@ -1505,9 +1521,17 @@ fn localSession( const host = sh.host(); core.host = host; + // An upgraded session's terminals, its own again. + if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec, screen); // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - core.unattended = !screen.on; + core.unattended = !sh.attached(); while (core.nextEffect()) |effect| core.perform(effect); + // ...and its shells, once a fresh session's own has a directory to + // adopt them in. + if (upgrade.resumed) |*rec| { + sh.resumePtys(rec); + while (core.nextEffect()) |effect| core.perform(effect); + } if (screen.on) try startInput(loop, screen); defer stopInput(io, &screen.thread); @@ -1520,15 +1544,15 @@ fn localSession( // PARDES_TEST_VIEWS: the terminals at these paths are views of the // session too, from its start, as `pardes --attach`ed ones are (the // snapshot harness's `start ... views=N`). - if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { + if (upgrade.resumed == null) if (init.environ_map.get("PARDES_TEST_VIEWS")) |paths| { var it = std.mem.tokenizeScalar(u8, paths, ' '); while (it.next()) |path| { var path_buf: [256]u8 = undefined; const z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch continue; const fd = libc.open(z, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(libc.mode_t, 0)); - if (fd >= 0) sh.attachTerminal(fd, -1); + if (fd >= 0) sh.attachTerminal(fd, -1, null); } - } + }; sh.threads_ok = true; for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { @@ -1536,18 +1560,12 @@ fn localSession( }; if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; - // A terminal unlinks what it reads; whatever it never read (the probe - // unanswered, a transmission lost with the terminal) is ours to remove. - defer { - var name_buf: [64]u8 = undefined; - var n: u32 = 0; - while (n <= kitty_shm_serial) : (n += 1) { - if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} - } - } + defer unlinkKittyShm(); while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + // Asked in the step (the word), done between steps: the session whole. + if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); // A terminal (`pardes --attach`) or an adopted shell, handed on by // the daemon's thread to this loop; started after the first frame, // off a startup's way. @@ -1695,6 +1713,10 @@ const Shell = struct { drawn_ns: u64 = 0, input_ns: u64 = 0, focused_ns: u64 = 0, + /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). + upgrade_asked: ?u8 = null, + /// Its pty readers stopped for it: their end of file is not a shell's. + upgrading: bool = false, const Leaving = enum { detach, exit }; @@ -1723,6 +1745,7 @@ const Shell = struct { .watched = watched, .detach = detach, .adopt = adopt, + .upgrade = upgradeAsked, .spawn = spawn, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -1825,7 +1848,7 @@ const Shell = struct { /// `pardes --attach`'s terminal: for a detached session its own again, /// entered as the first one was; for one attached already, a view of /// its own (views.zig). Sized, asked what it can do, and drawn whole. - fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t) void { + fn attachTerminal(s: *Shell, fd: posix.fd_t, stub: posix.fd_t, cooked: ?posix.termios) void { const live = s.term() orelse return; const screen = if (!live.on) live else extra: { const sc = s.gpa.create(Screen) catch break :extra null; @@ -1840,7 +1863,7 @@ const Shell = struct { return refuse(stub, "that session has no room for another terminal"); }; const extra = screen != live; - const tty = Screen.ttyOn(s.io, screen.buf, fd) catch { + const tty = Screen.ttyOn(s.io, screen.buf, fd, cooked) catch { _ = libc.close(fd); if (extra) s.freeScreen(screen) else daemon.setState(true); return refuse(stub, "that terminal would not go raw"); @@ -1886,6 +1909,159 @@ const Shell = struct { daemon.adopt(); } + fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { + const s = of(ctx); + if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); + s.upgrade_asked = pane; + } + + /// Upgrade, between steps: this process exec'd as the pardes now at the + /// path it was started from, the session in its dump, and its ptys, + /// terminals, stubs and daemon link kept open across (upgrade.zig). + /// Returns only when it could not be, the session going on as it was. + fn upgradeNow(s: *Shell, pane: u8) void { + if (comptime builtin.is_test) unreachable; // vaxis.Tty is its TestTty + s.upgrade_asked = null; + const core = s.core; + var why: [800]u8 = undefined; + const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from"); + // 9P is served while the new binary is asked (its clients' clunks + // and reads after the word are answered), and not after. + pardes.turn.rest(); + const checked = upgrade.check(path, &why); + pardes.turn.wake(); + switch (checked) { + .no => |w| return core.reportFailure(pane, w), + .ok => {}, + } + // Nothing more read from a pty or a terminal, and what was read + // goes in; a reader's cancel posts an end of file, passed over. + s.upgrading = true; + defer s.upgrading = false; + for (&s.ptys) |*slot| if (slot.*) |*pt| pt.reader.cancel(s.io) catch {}; + for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); + while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); + core.settle(); + var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; + for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); + for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ + .view = @intCast(k), + .fd = sc.tty.fd.handle, + .stub = if (sc.primary) daemon.stub else sc.stub, + .primary = sc.primary, + .termios = sc.tty.termios, + }); + var popped = false; + var at_buf: [1024:0]u8 = undefined; + const failed: []const u8 = failed: { + const at = pardes.dump.upgradePath(&at_buf, core.settings.dump_dir.get()) orelse break :failed "Upgrade: no directory for the session's dump; this session stays as it is"; + const bytes = pardes.dump.dumpBytes(core) catch |err| { + var words: [128]u8 = undefined; + break :failed std.fmt.bufPrint(&why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump"; + }; + defer s.gpa.free(bytes); + if (!upgrade.writeDump(at, bytes)) break :failed std.fmt.bufPrint(&why, "Upgrade: the session's dump could not be written to {s}; it stays as it is", .{at[0..@min(at.len, 600)]}) catch "Upgrade: its dump could not be written"; + rec.dump = at; + rec.old = upgrade.openSelf(); + // What this process put in its terminals that the next puts in + // again: its images, and its keyboard mode, a stack. + for (s.terms) |slot| if (slot) |sc| if (sc.on) { + clearNativeImages(&sc.kitty, &sc.vx, &sc.tty); + if (sc.vx.state.kitty_keyboard) sc.tty.writer().writeAll("\x1b[= 0) _ = libc.close(rec.old); + break :failed 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"; + }; + // As it was: its ptys read on, its terminals' keys as they were. + for (&s.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = s.io.concurrent(readPty, .{ s.io, s.gpa, pt.file, id, s.gens[id], s.loop }) catch pt.reader; + }; + for (s.terms) |slot| if (slot) |sc| if (sc.on) { + if (popped) sc.vx.enableDetectedFeatures(sc.tty.writer()) catch {}; + startInput(s.loop, sc) catch {}; + }; + core.reportFailure(pane, failed); + } + + /// An upgraded session's shells, running on: each its pane's pty again, + /// or, when its dump would not load (`fresh`), adopted as new panes. + fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { + for (rec.ptys[0..rec.nptys]) |k| { + const pane = if (rec.fresh) null else s.core.panes[k.pane]; + if (pane == null or !pane.?.isTerminal()) { + s.adoptShell(k.pid, k.fd); + continue; + } + const file: std.Io.File = .{ .handle = k.fd, .flags = .{ .nonblocking = false } }; + s.ptys[k.pane] = .{ .file = file, .pid = k.pid, .reader = .{ .any_future = null, .result = {} }, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; + } + } + + /// An upgraded session's terminals, each its view's again (`primary`, + /// run's, entered already); in a fresh session each but the primary a + /// view of its own, as `--attach` makes one. A view left with none + /// closes. + fn resumeTerminals(s: *Shell, rec: *const upgrade.Record, primary: *Screen) void { + if (comptime builtin.is_test) unreachable; + const core = s.core; + if (rec.fresh) { + for (rec.ttys[0..rec.nttys]) |t| if (!t.primary) s.attachTerminal(t.fd, t.stub, t.termios); + return; + } + s.terms = @splat(null); + if (rec.nttys == 0) { + pardes.views.only(core); + s.terms[core.view] = primary; + return; + } + for (rec.ttys[0..rec.nttys]) |t| { + if (!pardes.views.isOpen(core, t.view) or s.terms[t.view] != null) { + if (t.primary) continue; + _ = libc.close(t.fd); + if (t.stub >= 0) daemon.tellDetached(t.stub); + continue; + } + const sc = if (t.primary) primary else extra: { + const sc = s.gpa.create(Screen) catch break :extra null; + const buf = s.gpa.alloc(u8, 0x10000) catch { + s.gpa.destroy(sc); + break :extra null; + }; + sc.* = .{ .io = s.io, .gpa = s.gpa, .env = primary.env, .buf = buf, .kitty = .init(s.gpa) }; + const tty = Screen.ttyOn(s.io, sc.buf, t.fd, t.termios) catch { + s.freeScreen(sc); + break :extra null; + }; + sc.enter(tty) catch { + s.freeScreen(sc); + break :extra null; + }; + sc.setStub(t.stub); + startInput(s.loop, sc) catch {}; + sc.vx.queryTerminalSend(sc.tty.writer()) catch {}; + break :extra sc; + } orelse { + _ = libc.close(t.fd); + if (t.stub >= 0) daemon.tellDetached(t.stub); + continue; + }; + sc.feed.view = t.view; + s.terms[t.view] = sc; + } + for (0..pardes.views.max) |k| if (pardes.views.isOpen(core, @intCast(k)) and s.terms[k] == null) core.closeView(@intCast(k)); + if (s.terms[core.view] == null) s.terms[core.view] = primary; + } + /// One shell of a dead session (`pid` 0: the last of them was told). fn adoptShell(s: *Shell, pid: posix.pid_t, fd: posix.fd_t) void { const core = s.core; @@ -2083,7 +2259,7 @@ const Shell = struct { core.quit = true; return true; }, - .attach => |a| s.attachTerminal(a.tty, a.stub), + .attach => |a| s.attachTerminal(a.tty, a.stub, null), .adopted => |a| s.adoptShell(a.pid, a.fd), .focus_in => core.update(.{ .focus = true }), .focus_out => { @@ -2102,7 +2278,7 @@ const Shell = struct { s.takeExits(); return true; }, - .pty_eof => |e| if (s.gens[e.id] == e.gen) { + .pty_eof => |e| if (s.gens[e.id] == e.gen and !s.upgrading) { if (s.ptys[e.id]) |*pt| { pt.reader.await(s.io) catch {}; // reader just finished; join it or its future leaks // A command's pty stays open until its child has exited: -- cgit v1.3