diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-29 22:56:07 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-29 23:37:00 -0300 |
| commit | 370913ae34c69b7958911c6146612c77275f6ebf (patch) | |
| tree | 61e4fd328e104afbb381d2fd161029d1be637aa7 | |
| parent | ddcfd860ef05c37f5536038d8828cc81c0c4125c (diff) | |
| download | pardes-370913ae34c69b7958911c6146612c77275f6ebf.tar.gz pardes-370913ae34c69b7958911c6146612c77275f6ebf.zip | |
upgrade: a newer build at the path a session started from is said at a focus-in, once a build, the path read just after the first frame (off a startup's way); an upgraded process lets the binary it replaced go (held, its deleted file kept its blocks) and sweeps its old image's prompt files (kept for an exec that failed); test/daemon.py --upgrade asks through /ctl, checks the fds and prompt files level, and runs on FreeBSD (procstat, the daemon's registry, no kept old binary there)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| -rw-r--r-- | src/daemon.zig | 2 | ||||
| -rw-r--r-- | src/gui/gui.zig | 7 | ||||
| -rw-r--r-- | src/host_io.zig | 6 | ||||
| -rw-r--r-- | src/tty/tty.zig | 7 | ||||
| -rw-r--r-- | src/upgrade.zig | 50 | ||||
| -rw-r--r-- | test/daemon.py | 94 |
6 files changed, 123 insertions, 43 deletions
diff --git a/src/daemon.zig b/src/daemon.zig index 43f15c6c..785f4afd 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -1087,7 +1087,7 @@ pub fn serve(state: ?[]const u8) noreturn { ninep_io.setCloexec(4); const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; for ([_]posix.SIG{ .PIPE, .HUP, .INT }) |sig| posix.sigaction(sig, &ignore, null); - upgrade.remember(&.{}); + upgrade.locate(); var d: Daemon = .{}; const given = if (state) |text| d.restore(text) else -1; const replicas = if (given >= 0) given else listenReplicas(); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 24061251..e4d69281 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2502,6 +2502,7 @@ fn localSession( while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + upgrade.locate(); // Asked in the step (the word), done between steps: the session whole. if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); // A window asked for again, or an adopted shell, from the daemon's @@ -3138,7 +3139,10 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { in.close(); }, c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), - c.SDL_EVENT_WINDOW_FOCUS_GAINED => in.post(.{ .focus = true }), + c.SDL_EVENT_WINDOW_FOCUS_GAINED => { + in.post(.{ .focus = true }); + if (in.core) |core| upgrade.noticeNewer(core); + }, c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { g.pointer_present = false; @@ -4060,7 +4064,6 @@ const Shell = struct { 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(); - host_io.Shell.unlinkOwnedRcs(); daemon.upgraded(); if (s.fs) |f| f.flushOut(); const err_words = upgrade.exec(s.gpa, path, -1, &rec); diff --git a/src/host_io.zig b/src/host_io.zig index 46ee9afc..c627d4ab 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -977,8 +977,10 @@ pub const Shell = struct { while (std.c.readdir(dir)) |ent| { const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); const pid = rcPid(name) orelse continue; - if (pid == std.c.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; + // This pid's are this process's, but in an upgraded one: those + // were its old image's (upgrade.zig), and its own come after. + if (pid == std.c.getpid() and @import("upgrade.zig").resumed == null) continue; + if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; if (name.len >= 64 or n == dead.len) continue; @memcpy(dead[n][0..name.len], name); dead_len[n] = name.len; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index ef7688bc..14dc8042 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1564,6 +1564,7 @@ fn localSession( while (!core.quit) { pardes.turn.bump(&pardes.turn.restores); try core.pump(host); + upgrade.locate(); // 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 @@ -1973,7 +1974,6 @@ const Shell = struct { }; popped = true; unlinkKittyShm(); - host_io.Shell.unlinkOwnedRcs(); daemon.upgraded(); if (s.fs) |f| f.flushOut(); const err_words = upgrade.exec(s.gpa, path, -1, &rec); @@ -2261,7 +2261,10 @@ const Shell = struct { }, .attach => |a| s.attachTerminal(a.tty, a.stub, null), .adopted => |a| s.adoptShell(a.pid, a.fd), - .focus_in => core.update(.{ .focus = true }), + .focus_in => { + core.update(.{ .focus = true }); + upgrade.noticeNewer(core); + }, .focus_out => { core.update(.pointer_leave); core.update(.{ .focus = false }); diff --git a/src/upgrade.zig b/src/upgrade.zig index c49d2370..49e8aff5 100644 --- a/src/upgrade.zig +++ b/src/upgrade.zig @@ -32,21 +32,53 @@ var exe_buf: [4096:0]u8 = undefined; var exe_len: usize = 0; /// The arguments it was started with (an upgrade's record left out). var given: []const [:0]const u8 = &.{}; +/// The file at that path when it started, and the newer one last said. +var started_inode: ?u64 = null; +var told_inode: ?u64 = null; -/// Its path asked of the system now, at its start (one readlink), and its -/// arguments kept; an upgraded process takes the path its record names -/// (the system would name a fallback's old binary, deleted). +var located = false; + +/// Its arguments kept, at its start; an upgraded process's path is the one +/// its record names (the system would name a fallback's old binary, +/// 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 (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; exe_len = rec.exe.len; - return; }; - const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0; - exe_buf[n] = 0; - exe_len = n; +} + +/// Its path asked of the system (a readlink) and the file there now (a +/// stat), once: after the first frame, off a startup's way (the hosts' +/// loops; nothing is reinstalled within a frame of a start). +pub fn locate() void { + if (located) return; + located = true; + if (exe_len == 0) { + const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0; + exe_buf[n] = 0; + exe_len = n; + } + if (exe()) |path| started_inode = inodeOf(path); +} + +fn inodeOf(path: [:0]const u8) ?u64 { + const st = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{}) catch return null; + return @intCast(st.inode); +} + +/// A newer build installed at that path since this process started, said +/// in a line, once a build: asked at a focus-in, where one comes back from +/// rebuilding (a stat). ponytail: explicit only, no watch and no automatic +/// upgrade. +pub fn noticeNewer(core: *pardes.Pardes) void { + const was = started_inode orelse return; + const now = inodeOf(exe() orelse return) orelse return; + if (now == was or told_inode == now) return; + told_inode = now; + core.setMessage(core.active, "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"); } pub fn exe() ?[:0]const u8 { @@ -336,6 +368,10 @@ pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Op var buf: [700]u8 = undefined; if (loaded) |p| { _ = libc.unlink(path); + // The binary it replaced, let go: held, its file (deleted) would + // keep its blocks for as long as this session runs. + if (rec.old >= 0) _ = libc.close(rec.old); + rec.old = -1; p.setMessage(p.active, if (rec.refused.len > 0) std.fmt.bufPrint(&buf, "Upgrade: the new build could not load this session ({s}); it goes on as {s}", .{ rec.refused[0..@min(rec.refused.len, 200)], version_line }) catch "Upgrade: the new build could not load this session; it goes on as before" else diff --git a/test/daemon.py b/test/daemon.py index 7d35e427..ce19b502 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -549,10 +549,11 @@ def saying(sock, words, timeout=30): def exe_of(pid): """What /proc says the process runs: (its path, whether that file is the - one at the path now).""" - link = os.readlink(f'/proc/{pid}/exe') if procfs else ps('-o', 'comm=', '-p', str(pid)).decode().strip() + one at the path now). FreeBSD's procstat names the path alone.""" if not procfs: - return link, True + rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines() + return (rows[-1].split()[-1] if len(rows) > 1 else ''), None + link = os.readlink(f'/proc/{pid}/exe') try: same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino except OSError: @@ -570,7 +571,10 @@ def install(binary, at): """As `zig build` and install(1) put a build in place: a new file renamed over the old, which a process running it keeps, deleted.""" tmp = at.with_name(at.name + '.new') - subprocess.run(['cp', '--reflink=auto', os.fspath(binary), os.fspath(tmp)], check=True) + if procfs: + subprocess.run(['cp', '--reflink=auto', os.fspath(binary), os.fspath(tmp)], check=True) + else: + shutil.copyfile(binary, tmp) os.chmod(tmp, 0o755) os.replace(tmp, at) @@ -627,18 +631,45 @@ def upgrades(old, new): before = len(term.text()), len(term2.text()) install(new, binary) - assert exe_of(session)[1] is False, 'the session runs the old build, deleted' - client.write(f'/pane/{shell}/exec', b'Upgrade\n') + assert not procfs or exe_of(session)[1] is False, 'the session runs the old build, deleted' + # Come back to the terminal: the newer build is said. + os.write(term.master, b'\x1b[I') + wait_for('the newer build said', lambda: 'a newer pardes is installed' in screen_text(client)) + fds_before = fds(session), fds(daemon) + rcs = sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) + t = time.monotonic() + client.write('/ctl', b'Upgrade\n') client.socket.close() - wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30) + new_build = semantics(new) + assert new_build != old_build + if procfs: + wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30) + else: + wait_for('the session registered as the new build', + lambda: Replica(root / 'pardes-replica.sock').hello('work', new_build)[0] == 'welcome', timeout=30) client = reconnect(sock) + took = time.monotonic() - t assert int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid']) == session - wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True)) + if procfs: + wait_for('the daemon on the new build', lambda: exe_of(daemon) == (str(binary), True)) + else: + wait_for('the daemon exec\'d again', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(daemon))) assert alive(daemon) and stub.poll() is None and stub2.poll() is None # A replica of the old build is told why it is let go. tag, body = replica.read() assert tag == 0x02 and b'upgrading to another build' in body, (tag, body) replica.close() + # The old image's prompt files swept, the new one's made. + wait_for('the prompt files level', lambda: len(list(Path('/tmp').glob(f'pardes-osc133-*-{session}-*'))) == len(rcs)) + assert sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) != rcs or not rcs + # Nothing kept that was not: the old binary let go, every fd back. + # (The replica's connection is the one fewer.) + level = fds_before[0] - 1, fds_before[1] + try: + wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level, timeout=5) + except TimeoutError: + raise AssertionError(('fds', level, (fds(session), fds(daemon)), + os.listdir(f'/proc/{session}/fd') if procfs else None)) # The edit and its undo. assert client.read(f'/pane/{text}/body') == b'one\ntwo\nunsaved\n' assert any(row.split()[0] == str(text).encode() and row.split()[2] == b'1' for row in client.read('/index').splitlines()), client.read('/index') @@ -651,37 +682,39 @@ def upgrades(old, new): wait_for('the second terminal redrawn', lambda: b'\x1b[?1049h' in term2.text()[before[1]:]) wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client)) # The daemon lists the session under its new build. - new_build = semantics(new) - assert new_build != old_build said = Replica(root / 'pardes-replica.sock').hello('work', new_build) assert said == ('welcome', session, 'work'), said said = Replica(root / 'pardes-replica.sock').hello('work', old_build) assert said[0] == 'refused' and 'another build' in said[1], said os.kill(sleeper, signal.SIGTERM) wait_for('the shell carrying on', lambda: b'done-after-upgrade\n' in client.read(f'/pane/{shell}/body')) - print(f'upgrade: session {session}, its daemon {daemon}, shell {shell_pid} and two terminals on the new build; ' - 'the edit, its undo and the job kept') + print(f'upgrade: session {session}, its daemon {daemon}, shell {shell_pid} and two terminals on the new build ' + f'(the word to its 9P again: {took * 1000:.0f} ms); the edit, its undo and the job kept') - # A build that cannot load the dump: back to the one running. + # A build that cannot load the dump: back to the one running (a copy + # of it kept open from /proc/self/exe; FreeBSD keeps none). refuser = root / 'refuser' - refuser.write_text('#!/bin/sh\n# A pardes whose load refuses the dump (upgrade.zig).\n' - f'case "$1" in --upgraded=*) PARDES_TEST_UPGRADE_REFUSE=1 exec {new} "$@";; esac\n' - f'exec {new} "$@"\n') - refuser.chmod(0o755) - running = os.stat(f'/proc/{session}/exe').st_ino - install(refuser, binary) - client.write(f'/pane/{shell}/exec', b'Upgrade\n') - client.socket.close() - client = saying(sock, 'it goes on as') - assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran' - assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None - assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' - assert run(client, shell, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() - print('upgrade: a build that refused the dump fell back to the one running; the shell ran on') + + def refusing(how): + refuser.write_text('#!/bin/sh\n# A pardes whose load refuses the dump (upgrade.zig).\n' + f'case "$1" in --upgraded=*) PARDES_TEST_UPGRADE_REFUSE={how} exec {new} "$@";; esac\n' + f'exec {new} "$@"\n') + refuser.chmod(0o755) + install(refuser, binary) + if procfs: + running = os.stat(f'/proc/{session}/exe').st_ino + refusing('1') + client.write(f'/pane/{shell}/exec', b'Upgrade\n') + client.socket.close() + client = saying(sock, 'it goes on as') + assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran' + assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None + assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' + assert run(client, shell, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + print('upgrade: a build that refused the dump fell back to the one running; the shell ran on') # One that refuses it everywhere: a fresh session, the shells adopted. - refuser.write_text(refuser.read_text().replace('=1 exec', '=all exec')) - install(refuser, binary) + refusing('all') client.write(f'/pane/{shell}/exec', b'Upgrade\n') client.socket.close() client = saying(sock, 'brings the rest back') @@ -712,6 +745,9 @@ def upgrades(old, new): wait_for('the next session', sock.exists) client = Client(sock) started.append(int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])) + # Its reader of the daemon starts after its first frame: an Adopt + # before that waits for an `ok` nobody reads, and is refused. + wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text()) before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop() |
