diff options
| -rw-r--r-- | docs/typ/guide.typ | 2 | ||||
| -rw-r--r-- | docs/typ/reference.typ | 8 | ||||
| -rw-r--r-- | src/daemon.zig | 61 | ||||
| -rw-r--r-- | src/main.zig | 113 | ||||
| -rw-r--r-- | test/daemon.py | 79 |
5 files changed, 259 insertions, 4 deletions
diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 4430276f..56fe3ebd 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -344,6 +344,8 @@ cheatsheet (#doc("cheatsheet")) say so. pardes --detach=work & a session with no screen of its own pardes --attach=work show it here pardes-gui --attach=work a window session's window again +pardes --ps every session the daemon keeps, and its shells +pardes --kill=work end it and its shells (--kill-all: every one) ``` #word("Detach") (#key("SPC s D")) lets the terminal or the window go and diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 2d8658c6..4de57d64 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -1012,7 +1012,13 @@ to its end before the write is answered, and one that finds nothing fails, another; a removed line's `-` goes to the line now standing where it was. git's `a/` `b/` (and `c/ i/ w/ o/`) prefixes are dropped; a `--no-prefix` diff's paths are kept. -- *Sessions.* Bare `--detach` names the session after its pid; bare +- *Sessions.* `pardes --ps` prints what the daemon keeps: each session + (its pid, terminal or window, attached or detached, name) with the pids + and commands of the shells it holds, then the shells no session holds, + which #word("Adopt") takes. `--kill=NAME` ends that session and its + shells (a TERM, then a KILL 2 s later; unsaved changes are lost), + `--kill-all` every session and every kept shell; with no daemon running + each says so and exits 1. Bare `--detach` names the session after its pid; bare `--attach` needs exactly one detached session of its kind (a terminal's for `pardes`, a window's for `pardes-gui`), or with none detached the only session of that kind; a second `--detach=NAME` diff --git a/src/daemon.zig b/src/daemon.zig index d2ae012c..c6cd7f85 100644 --- a/src/daemon.zig +++ b/src/daemon.zig @@ -489,6 +489,17 @@ pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer 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 { + const fd = connect(false) orelse return null; + defer _ = libc.close(fd); + if (!send(fd, words, &.{}) or !readable(fd, 2000)) return null; + const got = recv(fd, buf) orelse return null; + for (got.fds[0..got.nfds]) |f| _ = libc.close(f); + return got.words; +} + // ---- a terminal's stub ---- var stub_child: libc.pid_t = 0; @@ -665,6 +676,8 @@ const Conn = struct { detached: bool = false, /// 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. + killed: bool = false, name: [128]u8 = undefined, name_len: usize = 0, @@ -709,12 +722,53 @@ const Daemon = struct { fn hangUp(d: *Daemon, i: u8) void { const c = &d.conns[i]; + const killed = c.killed; _ = libc.close(c.fd); c.* = .{}; - // Whatever it still held, it died holding: kept for an Adopt. + // Whatever it still held, it died holding: kept for an Adopt, unless + // it was killed on purpose, when its shells hang up with it. for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) { - h.owner = null; + if (killed) d.drop(h) else h.owner = null; + }; + } + + /// `pardes --kill`: each session named (every one, for null) sent a + /// TERM and marked, its pids answered; the shells of none kept, for + /// all of them. + fn kill(d: *Daemon, i: u8, named: ?[]const u8) void { + var line: [msg_max]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.writeAll("ok") catch {}; + var n: usize = 0; + for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) { + if (named) |want| if (!std.mem.eql(u8, s.named(), want)) continue; + s.killed = true; + _ = libc.kill(s.pid, .TERM); + w.print(" {d}", .{s.pid}) catch {}; + n += 1; + }; + if (named == null) { + for (&d.held) |*h| if (h.fd >= 0 and h.owner == null) d.drop(h); + } else if (n == 0) { + var why: [256]u8 = undefined; + return d.reply(i, std.fmt.bufPrint(&why, "no no session called '{s}'", .{named.?}) catch "no no such session", &.{}); + } + d.reply(i, w.buffered(), &.{}); + } + + /// `pardes --ps`: a line a session (pid, kind, state, name), a line + /// for each shell it holds after it, then the shells nobody holds. + /// ponytail: one message, so a registry past msg_max is cut short. + fn list(d: *Daemon, i: u8) void { + var line: [msg_max]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.print("daemon {d}\n", .{libc.getpid()}) catch {}; + 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; + for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break; }; + for (d.held) |h| if (h.fd >= 0 and h.owner == null) w.print("orphan {d}\n", .{h.pid}) catch break; + d.reply(i, w.buffered(), &.{}); } fn reply(d: *Daemon, i: u8, words: []const u8, fds: []const c_int) void { @@ -776,6 +830,9 @@ const Daemon = struct { d.upgrade_asked = true; return; } + if (std.mem.eql(u8, verb, "list")) return d.list(i); + if (std.mem.eql(u8, verb, "kill")) return d.kill(i, std.mem.trim(u8, words.rest(), " ")); + if (std.mem.eql(u8, verb, "killall")) return d.kill(i, null); if (std.mem.eql(u8, verb, "adopt")) { var line: [msg_max]u8 = undefined; var w: std.Io.Writer = .fixed(&line); diff --git a/src/main.zig b/src/main.zig index fafafc08..d4edc74d 100644 --- a/src/main.zig +++ b/src/main.zig @@ -111,11 +111,17 @@ const help_text = \\ --attach=<host>:<name> a client of session <name> on another machine, \\ over `ssh -L` to its pardes-replica.sock \\ ($PARDES_SSH: the ssh command, words, default - \\ `ssh -C`; and + \\ `ssh`; and \\ $PARDES_REMOTE_RUNTIME: its runtime directory, \\ if not this one's path). Its keys show at once \\ --attach=<sock>:<name> ...through that socket (a path, with a '/'), \\ one forwarded already, or this machine's + \\ --ps what the pardes daemon keeps: each session (its + \\ pid, kind, whether attached) and its shells, then + \\ the shells no session holds + \\ --kill=<name> end session <name> and its shells (TERM, then + \\ KILL 2 s later); unsaved changes are lost + \\ --kill-all end every session and every shell the daemon keeps \\ --geometry=WxH[+X+Y] the window's size in points, and where it goes \\ where the display lets a window say (X11) \\ -h, --help show this help and exit @@ -507,6 +513,14 @@ fn nativeMain(std_init: std.process.Init) !void { attach = ""; } else if (std.mem.startsWith(u8, a, "--attach=")) { attach = a["--attach=".len..]; + } else if (std.mem.eql(u8, a, "--ps")) { + manage(init.io, "list", ""); + } else if (std.mem.startsWith(u8, a, "--kill=")) { + const name = a["--kill=".len..]; + if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{}); + manage(init.io, "kill", name); + } else if (std.mem.eql(u8, a, "--kill-all")) { + manage(init.io, "killall", ""); } else if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) { try std.Io.File.stdout().writeStreamingAll(init.io, help_text); return; @@ -870,6 +884,103 @@ fn nativeMain(std_init: std.process.Init) !void { extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +/// `pardes --ps`: what the per-user daemon keeps, as a tree; `--kill=<name>` +/// and `--kill-all`: those sessions ended with their shells, a TERM and, +/// for one still there 2 s later, a KILL. +fn manage(io: std.Io, verb: []const u8, name: []const u8) noreturn { + const Say = struct { + fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + var buf: [700]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\n", args) catch "pardes: failed\n") catch {}; + std.process.exit(1); + } + }; + if (comptime !daemon.supported) Say.no(io, "this system has no pardes daemon", .{}); + var words_buf: [300]u8 = undefined; + const words = if (std.mem.eql(u8, verb, "kill")) + std.fmt.bufPrint(&words_buf, "kill {s}", .{name}) catch Say.no(io, "that name is too long", .{}) + else + verb; + var buf: [4096]u8 = undefined; + const said = daemon.ask(words, &buf) orelse Say.no(io, "no pardes daemon is running", .{}); + if (std.mem.startsWith(u8, said, "no ")) Say.no(io, "{s}", .{said[3..]}); + if (std.mem.eql(u8, verb, "list")) { + var out: [8192]u8 = undefined; + var w: std.Io.Writer = .fixed(&out); + var lines = std.mem.tokenizeScalar(u8, said, '\n'); + var orphans = false; + while (lines.next()) |line| { + var it = std.mem.tokenizeScalar(u8, line, ' '); + const what = it.next() orelse continue; + const pid = it.next() orelse continue; + var comm_buf: [64]u8 = undefined; + const comm = commOf(pid, &comm_buf); + if (std.mem.eql(u8, what, "daemon")) { + w.print("pardes daemon {s}\n", .{pid}) catch break; + } else if (std.mem.eql(u8, what, "session")) { + const kind = it.next() orelse ""; + const state = it.next() orelse ""; + w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, state }) catch break; + } else if (std.mem.eql(u8, what, "shell")) { + w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; + } else if (std.mem.eql(u8, what, "orphan")) { + if (!orphans) w.writeAll(" shells no session holds (Adopt takes them, --kill-all ends them)\n") catch break; + orphans = true; + w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; + } + } + std.Io.File.stdout().writeStreamingAll(io, w.buffered()) catch {}; + std.process.exit(0); + } + var pids: [64]std.c.pid_t = undefined; + var n: usize = 0; + var it = std.mem.tokenizeScalar(u8, said, ' '); + _ = it.next(); // ok + while (it.next()) |p| if (n < pids.len) { + pids[n] = std.fmt.parseInt(std.c.pid_t, p, 10) catch continue; + n += 1; + }; + // Gone once the daemon no longer lists them: a session's link ends with + // its process, a zombie's too, which kill(pid, 0) would call alive. + const Gone = struct { + fn all(list: []const std.c.pid_t, ms: u32) bool { + var waited: u32 = 0; + while (true) : (waited += 20) { + var reply: [4096]u8 = undefined; + const now = daemon.ask("list", &reply) orelse return true; + var lines = std.mem.tokenizeScalar(u8, now, '\n'); + const left = while (lines.next()) |line| { + var fields = std.mem.tokenizeScalar(u8, line, ' '); + if (!std.mem.eql(u8, fields.next() orelse "", "session")) continue; + const pid = std.fmt.parseInt(std.c.pid_t, fields.next() orelse "", 10) catch continue; + if (std.mem.indexOfScalar(std.c.pid_t, list, pid) != null) break true; + } else false; + if (!left) return true; + if (waited >= ms) return false; + const ts: std.c.timespec = .{ .sec = 0, .nsec = 20 * std.time.ns_per_ms }; + _ = std.c.nanosleep(&ts, null); + } + } + }; + if (!Gone.all(pids[0..n], 2000)) { + for (pids[0..n]) |p| _ = std.c.kill(p, .KILL); + if (!Gone.all(pids[0..n], 1000)) Say.no(io, "a session would not end, even killed", .{}); + } + std.process.exit(0); +} + +/// The command `pid` runs, as /proc says it (Linux); empty where it does not. +fn commOf(pid: []const u8, buf: *[64]u8) []const u8 { + var path_buf: [64]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{s}/comm", .{pid}, 0) catch return ""; + const fd = std.c.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(std.c.mode_t, 0)); + if (fd < 0) return ""; + defer _ = std.c.close(fd); + const got = std.c.read(fd, buf, buf.len); + if (got <= 0) return ""; + return std.mem.trimEnd(u8, buf[0..@intCast(got)], "\n"); +} + /// `pardes --attach=<where>:<name>`: a replica client (tty.zig `remote`), /// through the socket `where` names, or through `ssh -L` of host `where`'s /// replica socket to one of this process's. diff --git a/test/daemon.py b/test/daemon.py index fb4f3013..d9ca7153 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -452,6 +452,82 @@ def clients(binary): shutil.rmtree(root, ignore_errors=True) +def manage(binary): + """`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions + and their shells listed, one session killed outright and its shell + listed as no one's, the other ended by name with its shell, a name no + session has refused, the kept shell ended by --kill-all, and the daemon + gone after it.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rm-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + + def cli(*args): + return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=30) + + started = [] + try: + sessions, shells = {}, {} + for name in ('one', 'two'): + (root / f'{name}.txt').write_text(f'{name}\n') + started.append(subprocess.Popen([binary, f'--detach={name}', str(root / f'{name}.txt')], env=env, cwd=root, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True).pid) + sock = root / f'pardes-9p-{name}.sock' + wait_for(f'session {name}\'s 9P socket', sock.exists) + with Client(sock) as c: + status = dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines()) + sessions[name] = int(status['pid']) + started.append(sessions[name]) + c.write('/pane/1/exec', b'Tty\n') + wait_for(f'session {name}\'s shell', lambda: terminals(c)) + shell = terminals(c)[0] + wait_for(f'session {name}\'s shell answers', lambda: run(c, shell, b'true\n') == b'exit 0\n') + shells[name] = int(run(c, shell, b'echo $$\n').split(b'\n')[1]) + started.append(shells[name]) + daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0] + started.append(daemon) + out = cli('--ps') + assert out.returncode == 0, out + listed = out.stdout.decode() + assert f'pardes daemon {daemon}' in listed, listed + for name in ('one', 'two'): + assert f'session {name} {sessions[name]} (tty, detached)' in listed, listed + assert f'shell {shells[name]}' in listed, listed + os.kill(sessions['two'], signal.SIGKILL) + wait_for('session two gone', lambda: not alive(sessions['two'])) + wait_for('its shell no session\'s', lambda: 'no session holds' in cli('--ps').stdout.decode()) + listed = cli('--ps').stdout.decode() + assert 'session two' not in listed and listed.index(f'shell {shells["two"]}') > listed.index('no session holds'), listed + assert alive(shells['two']) + print('manage: --ps listed two sessions and their shells, then a killed one\'s shell as no one\'s') + refused = cli('--kill=nobody') + assert refused.returncode == 1 and b"no session called 'nobody'" in refused.stderr, refused + killed = cli('--kill=one') + assert killed.returncode == 0, killed + assert not alive(sessions['one']) + wait_for('session one\'s shell hung up with it', lambda: not alive(shells['one'])) + assert alive(shells['two']) and 'session one' not in cli('--ps').stdout.decode() + assert cli('--kill-all').returncode == 0 + wait_for('the kept shell ended', lambda: not alive(shells['two'])) + wait_for('the daemon gone once it keeps nothing', lambda: not alive(daemon)) + none = cli('--ps') + assert none.returncode == 1 and b'no pardes daemon is running' in none.stderr, none + print('manage: --kill=one ended it and its shell, --kill-all the kept shell, a name nobody has refused; the daemon left') + finally: + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + shutil.rmtree(root, ignore_errors=True) + + def joins(path): """A replica client's joins (PARDES_REPLICA_STATS, a line a link): how many blobs each listed, how many it held already from the core it left @@ -660,6 +736,7 @@ def main(binary, cycles): replicas(root, binary, session, daemon) clients(binary) far(binary) + manage(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) @@ -1260,6 +1337,8 @@ if __name__ == '__main__': upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve()) elif sys.argv[1:2] == ['--clients']: clients(sys.argv[2]) + elif sys.argv[1:2] == ['--manage']: + manage(sys.argv[2]) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) elif sys.argv[1:2] == ['--ping']: |
