summaryrefslogtreecommitdiff
path: root/test/process.zig
diff options
context:
space:
mode:
Diffstat (limited to 'test/process.zig')
-rw-r--r--test/process.zig323
1 files changed, 286 insertions, 37 deletions
diff --git a/test/process.zig b/test/process.zig
index ef825ef0..f797c063 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -7,6 +7,7 @@ const std = @import("std");
const libc = std.c;
const eh = @import("e2e_harness.zig");
const Client = @import("9p_io").Client;
+const c9 = @import("cloud9");
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
extern "c" fn unsetenv(name: [*:0]const u8) c_int;
@@ -16,6 +17,173 @@ extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8;
extern "c" fn system(cmd: [*:0]const u8) c_int;
extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8;
+/// One 9P2000 connection to a socket, blocking, as a client program holds
+/// one: fids walked, opened, read, written, clunked and removed by path,
+/// for the tests that need more than a file read or written whole (an open
+/// held while others write, a directory's entries, a stat, a remove).
+/// The last refusal's words are in `said`.
+pub const Conn = struct {
+ fd: c_int,
+ cl: c9.Client,
+ in: [msize]u8 = undefined,
+ out: [msize]u8 = undefined,
+ next_fid: u32 = 1,
+ said_buf: [256]u8 = undefined,
+ said: []const u8 = "",
+
+ const msize = 64 * 1024;
+ pub const Fid = u32;
+
+ /// Connected to the unix socket at `path`, versioned and attached as
+ /// fid 0. Heap-held: its buffers are big and the client points into them.
+ pub fn dial(gpa: std.mem.Allocator, path: []const u8) !*Conn {
+ const c = try gpa.create(Conn);
+ errdefer gpa.destroy(c);
+ c.* = .{ .fd = -1, .cl = undefined };
+ c.cl = c9.Client.init(.{ .in = &c.in, .out = &c.out });
+ c.fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0);
+ if (c.fd < 0) return error.NoSocket;
+ errdefer _ = libc.close(c.fd);
+ var addr: libc.sockaddr.un = .{ .path = undefined };
+ if (path.len >= addr.path.len) return error.NameTooLong;
+ @memset(&addr.path, 0);
+ @memcpy(addr.path[0..path.len], path);
+ if (libc.connect(c.fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) != 0) return error.ConnectFailed;
+ _ = try c.call(.{ .version = .{ .msize = msize } });
+ _ = try c.call(.{ .attach = .{ .fid = 0, .uname = "test" } });
+ return c;
+ }
+
+ pub fn deinit(c: *Conn, gpa: std.mem.Allocator) void {
+ _ = libc.close(c.fd);
+ gpa.destroy(c);
+ }
+
+ fn call(c: *Conn, req: c9.Client.Request) !c9.Client.Result {
+ _ = c.cl.submit(req) catch return error.Protocol;
+ while (c.cl.output().len > 0) {
+ const out = c.cl.output();
+ const n = libc.write(c.fd, out.ptr, out.len);
+ if (n <= 0) return error.Hangup;
+ c.cl.wrote(@intCast(n));
+ }
+ while (true) {
+ if (c.cl.take()) |done| {
+ if (done.result == .fail) {
+ const words = done.result.fail;
+ const n = @min(words.len, c.said_buf.len);
+ @memcpy(c.said_buf[0..n], words[0..n]);
+ c.said = c.said_buf[0..n];
+ return error.Refused;
+ }
+ return done.result;
+ }
+ var buf: [msize]u8 = undefined;
+ const n = libc.read(c.fd, &buf, buf.len);
+ if (n <= 0) return error.Hangup;
+ var at: usize = 0;
+ while (at < n) at += c.cl.push(buf[at..@intCast(n)]);
+ }
+ }
+
+ /// A new fid walked to `path` from the root.
+ pub fn walk(c: *Conn, path: []const u8) !Fid {
+ var names: [c9.max_welem][]const u8 = undefined;
+ var n: usize = 0;
+ var it = std.mem.tokenizeScalar(u8, path, '/');
+ while (it.next()) |name| : (n += 1) {
+ if (n == names.len) return error.PathTooDeep;
+ names[n] = name;
+ }
+ const fid = c.next_fid;
+ c.next_fid += 1;
+ const r = try c.call(.{ .walk = .{ .fid = 0, .newfid = fid, .names = names[0..n] } });
+ if (r.walk.nwqid != n) return error.NotFound;
+ return fid;
+ }
+
+ /// `path` walked and opened (0 read, 1 write, 2 both; 16 truncates).
+ pub fn hold(c: *Conn, path: []const u8, mode: u8) !Fid {
+ const fid = try c.walk(path);
+ errdefer c.clunk(fid);
+ _ = try c.call(.{ .open = .{ .fid = fid, .mode = mode } });
+ return fid;
+ }
+
+ /// One read on an open fid; valid until the next call.
+ pub fn readFid(c: *Conn, fid: Fid, offset: u64, count: u32) ![]const u8 {
+ return (try c.call(.{ .read = .{ .fid = fid, .offset = offset, .count = @min(count, c.cl.maxRead()) } })).read;
+ }
+
+ /// One write on an open fid: the count the server took.
+ pub fn writeFid(c: *Conn, fid: Fid, offset: u64, data: []const u8) !u32 {
+ return (try c.call(.{ .write = .{ .fid = fid, .offset = offset, .data = data } })).write;
+ }
+
+ /// A fid let go; a refusal there (an Edit block left open) is in `said`.
+ pub fn clunk(c: *Conn, fid: Fid) void {
+ _ = c.call(.{ .clunk = .{ .fid = fid } }) catch {};
+ }
+
+ /// The whole file at `path`, read on an open of its own.
+ pub fn read(c: *Conn, gpa: std.mem.Allocator, path: []const u8) ![]u8 {
+ const fid = try c.hold(path, 0);
+ defer c.clunk(fid);
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(gpa);
+ while (true) {
+ const got = try c.readFid(fid, out.items.len, msize);
+ if (got.len == 0) break;
+ try out.appendSlice(gpa, got);
+ }
+ return out.toOwnedSlice(gpa);
+ }
+
+ /// `data` written to `path` in one write, the open clunked after; a
+ /// refusal by the write or by the clunk is `error.Refused`.
+ pub fn write(c: *Conn, path: []const u8, data: []const u8) !void {
+ const fid = try c.hold(path, 1);
+ _ = c.writeFid(fid, 0, data) catch |err| {
+ c.clunk(fid);
+ return err;
+ };
+ _ = c.call(.{ .clunk = .{ .fid = fid } }) catch |err| return err;
+ }
+
+ pub fn remove(c: *Conn, path: []const u8) !void {
+ const fid = try c.walk(path);
+ _ = try c.call(.{ .remove = .{ .fid = fid } });
+ }
+
+ /// What a stat of `path` answers; its strings valid until the next call.
+ pub fn stat(c: *Conn, path: []const u8) !c9.Stat {
+ const fid = try c.walk(path);
+ defer c.clunk(fid);
+ return (try c.call(.{ .stat = .{ .fid = fid } })).stat;
+ }
+
+ /// The names of a directory's entries.
+ pub fn list(c: *Conn, gpa: std.mem.Allocator, path: []const u8) ![]const []const u8 {
+ const fid = try c.hold(path, 0);
+ defer c.clunk(fid);
+ var names: std.ArrayList([]const u8) = .empty;
+ var off: u64 = 0;
+ while (true) {
+ const got = try c.readFid(fid, off, msize);
+ if (got.len == 0) break;
+ off += got.len;
+ var at: usize = 0;
+ while (at + 2 <= got.len) {
+ const len = @as(usize, std.mem.readInt(u16, got[at..][0..2], .little)) + 2;
+ const st = try c9.Stat.decode(got[at..][0..len]);
+ try names.append(gpa, try gpa.dupe(u8, st.name));
+ at += len;
+ }
+ }
+ return names.toOwnedSlice(gpa);
+ }
+};
+
/// A running pardes's file tree, dialled by its pid or socket path.
pub const Files = struct {
arena: std.heap.ArenaAllocator,
@@ -122,24 +290,54 @@ pub fn of(gpa: std.mem.Allocator, h: *const eh.Harness) Files {
/// harness starts one): the process is the session, and nothing outlives it.
pub const Detached = struct {
pid: libc.pid_t,
- root_buf: [64]u8 = undefined,
+ root_buf: [4096]u8 = undefined,
root_len: usize = 0,
+ socket_buf: [4096]u8 = undefined,
+ socket_len: usize = 0,
+ /// Whether deinit removes the root (one passed in is its owner's).
+ owns_root: bool = true,
+ /// The exit status, once it has exited (`exited`).
+ status: ?c_int = null,
files: Files,
- pub fn start(gpa: std.mem.Allocator, exe: [:0]const u8, name: []const u8) !Detached {
+ pub const Options = struct {
+ /// Arguments before the file (`--mount=...`, `--9p=<name>`).
+ args: []const [:0]const u8 = &.{},
+ /// The file it opens; null: `<root>/<name>.txt`, holding "initial\n".
+ file: ?[]const u8 = null,
+ /// More environment, set after the root's.
+ env: []const [2][:0]const u8 = &.{},
+ /// Another session's root to run in, which both then share (its
+ /// store, its runtime directory); it is not removed.
+ root: ?[]const u8 = null,
+ /// The name its socket is linked as, when `--9p=<name>` names one.
+ socket: ?[]const u8 = null,
+ };
+
+ pub fn start(gpa: std.mem.Allocator, exe: [:0]const u8, name: []const u8, opts: Options) !Detached {
var d: Detached = .{ .pid = 0, .files = undefined };
- const template = "/tmp/pardes-process-XXXXXX";
- @memcpy(d.root_buf[0..template.len], template);
- d.root_buf[template.len] = 0;
- _ = mkdtemp(d.root_buf[0..template.len :0]) orelse return error.NoTempDir;
- d.root_len = template.len;
+ if (opts.root) |shared| {
+ @memcpy(d.root_buf[0..shared.len], shared);
+ d.root_len = shared.len;
+ d.owns_root = false;
+ } else {
+ const template = "/tmp/pardes-process-XXXXXX";
+ @memcpy(d.root_buf[0..template.len], template);
+ d.root_buf[template.len] = 0;
+ _ = mkdtemp(d.root_buf[0..template.len :0]) orelse return error.NoTempDir;
+ d.root_len = template.len;
+ }
+ errdefer if (d.owns_root) d.removeRoot();
const dir = d.root();
var buf: [4096]u8 = undefined;
- const fixture = try std.fmt.bufPrintSentinel(&buf, "{s}/{s}.txt", .{ dir, name }, 0);
- try eh.writeFile(fixture, "initial\n");
- var sock: [4096]u8 = undefined;
+ const fixture = if (opts.file) |f| try std.fmt.bufPrintSentinel(&buf, "{s}", .{f}, 0) else blk: {
+ const path = try std.fmt.bufPrintSentinel(&buf, "{s}/{s}.txt", .{ dir, name }, 0);
+ try eh.writeFile(path, "initial\n");
+ break :blk path;
+ };
// The session's socket, as its 9P service links it (src/9p_io.zig).
- const socket = try std.fmt.bufPrint(&sock, "{s}/9p/pardes/{s}", .{ dir, name });
+ const sock_path = try std.fmt.bufPrint(&d.socket_buf, "{s}/9p/pardes/{s}", .{ dir, opts.socket orelse name });
+ d.socket_len = sock_path.len;
var arg_buf: [256]u8 = undefined;
const detach = try std.fmt.bufPrintSentinel(&arg_buf, "--detach={s}", .{name}, 0);
var env_buf: [3][4096]u8 = undefined;
@@ -147,11 +345,17 @@ pub const Detached = struct {
const config = try std.fmt.bufPrintSentinel(&env_buf[1], "{s}/config", .{dir}, 0);
const dump = try std.fmt.bufPrintSentinel(&env_buf[2], "{s}/{s}.dump.zon", .{ dir, name }, 0);
var err_buf: [4096]u8 = undefined;
- const err_log = try std.fmt.bufPrintSentinel(&err_buf, "{s}/stderr", .{dir}, 0);
+ const err_log = try std.fmt.bufPrintSentinel(&err_buf, "{s}/{s}.stderr", .{ dir, name }, 0);
// The build hands the binary over by a relative path, and the child
// runs in the root.
var exe_buf: [4096]u8 = undefined;
const exe_abs = realpath(exe, &exe_buf) orelse return error.NoBinary;
+ var argv: [24:null]?[*:0]const u8 = @splat(null);
+ if (opts.args.len + 3 > argv.len) return error.TooManyArgs;
+ argv[0] = exe_abs;
+ argv[1] = detach;
+ for (opts.args, 0..) |a, k| argv[2 + k] = a;
+ argv[2 + opts.args.len] = fixture;
const pid = libc.fork();
if (pid < 0) return error.ForkFailed;
if (pid == 0) {
@@ -164,25 +368,20 @@ pub const Detached = struct {
.{ "PARDES_LSP_C", "" }, .{ "PARDES_LSP_GO", "" }, .{ "PARDES_LSP_TS", "" },
.{ "PARDES_LSP_PY", "" }, .{ "PARDES_DAEMON", "off" },
}) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126);
+ for (opts.env) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126);
if (libc.chdir(root_z) != 0) _exit(126);
const fd = libc.open(err_log, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd >= 0) _ = libc.dup2(fd, 2);
- const argv = [_:null]?[*:0]const u8{ exe_abs, detach, fixture };
_ = execvp(exe_abs, &argv);
_exit(127);
}
d.pid = pid;
- errdefer {
- d.stop();
- d.removeRoot();
- }
+ errdefer d.stop();
const deadline = eh.nowMs() + 10_000;
var sock_z: [4096]u8 = undefined;
- const socket_z = try std.fmt.bufPrintSentinel(&sock_z, "{s}", .{socket}, 0);
+ const socket_z = try std.fmt.bufPrintSentinel(&sock_z, "{s}", .{sock_path}, 0);
while (libc.access(socket_z, 0) != 0) {
- var status: c_int = 0;
- if (libc.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
- d.pid = 0;
+ if (d.exited(0)) |status| {
var said: [4096]u8 = undefined;
const fd = libc.open(err_log, .{}, @as(libc.mode_t, 0));
const n = if (fd >= 0) libc.read(fd, &said, said.len) else 0;
@@ -191,10 +390,9 @@ pub const Detached = struct {
return error.SessionExited;
}
if (eh.nowMs() > deadline) return error.NoSocket;
- var ts: libc.timespec = .{ .sec = 0, .nsec = 5 * std.time.ns_per_ms };
- _ = libc.nanosleep(&ts, null);
+ sleepMs(5);
}
- d.files = .init(gpa, socket);
+ d.files = .init(gpa, sock_path);
return d;
}
@@ -202,15 +400,68 @@ pub const Detached = struct {
return d.root_buf[0..d.root_len];
}
- /// Ended (SIGTERM, then SIGKILL after 5 s), its root removed.
+ /// The socket's path, which a held connection dials (`Conn.dial`).
+ pub fn socket(d: *const Detached) []const u8 {
+ return d.socket_buf[0..d.socket_len];
+ }
+
+ /// `data` written to `rel` under the root.
+ pub fn put(d: *const Detached, rel: []const u8, data: []const u8) !void {
+ var buf: [4096]u8 = undefined;
+ try eh.writeFile(try std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d.root(), rel }, 0), data);
+ }
+
+ /// The file `rel` under the root, whole.
+ pub fn get(d: *const Detached, gpa: std.mem.Allocator, rel: []const u8) ![]u8 {
+ var buf: [4096]u8 = undefined;
+ const path = try std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ d.root(), rel }, 0);
+ const fd = libc.open(path, .{}, @as(libc.mode_t, 0));
+ if (fd < 0) return error.FileNotFound;
+ defer _ = libc.close(fd);
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(gpa);
+ var chunk: [16 * 1024]u8 = undefined;
+ while (true) {
+ const n = libc.read(fd, &chunk, chunk.len);
+ if (n < 0) return error.ReadFailed;
+ if (n == 0) break;
+ try out.appendSlice(gpa, chunk[0..@intCast(n)]);
+ }
+ return out.toOwnedSlice(gpa);
+ }
+
+ pub fn signal(d: *const Detached, sig: c_int) void {
+ if (d.pid > 0) _ = libc.kill(d.pid, @intCast(sig));
+ }
+
+ /// Its exit status once it has exited, waiting up to `ms`; null while
+ /// it runs. A status is the wait(2) word (WEXITSTATUS is `>> 8`).
+ pub fn exited(d: *Detached, ms: i64) ?c_int {
+ if (d.status) |s| return s;
+ if (d.pid <= 0) return null;
+ const deadline = eh.nowMs() + ms;
+ while (true) {
+ var status: c_int = 0;
+ if (libc.waitpid(d.pid, &status, std.c.W.NOHANG) == d.pid) {
+ d.status = status;
+ d.pid = 0;
+ return status;
+ }
+ if (eh.nowMs() >= deadline) return null;
+ sleepMs(10);
+ }
+ }
+
+ /// Ended (SIGTERM, then SIGKILL after 5 s), its root removed if it is
+ /// its own.
pub fn deinit(d: *Detached) void {
d.files.deinit();
d.stop();
- d.removeRoot();
+ if (d.owns_root) d.removeRoot();
}
fn removeRoot(d: *Detached) void {
- var cmd: [128]u8 = undefined;
+ var cmd: [4200]u8 = undefined;
if (std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{d.root()}, 0)) |c| {
_ = system(c);
} else |_| {}
@@ -219,17 +470,15 @@ pub const Detached = struct {
fn stop(d: *Detached) void {
if (d.pid <= 0) return;
_ = libc.kill(d.pid, libc.SIG.TERM);
- const deadline = eh.nowMs() + 5_000;
- var status: c_int = 0;
- while (libc.waitpid(d.pid, &status, std.c.W.NOHANG) != d.pid) {
- if (eh.nowMs() > deadline) {
- _ = libc.kill(d.pid, libc.SIG.KILL);
- _ = libc.waitpid(d.pid, &status, 0);
- break;
- }
- var ts: libc.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
- _ = libc.nanosleep(&ts, null);
+ if (d.exited(5_000) == null) {
+ _ = libc.kill(d.pid, libc.SIG.KILL);
+ _ = d.exited(5_000);
}
d.pid = 0;
}
};
+
+fn sleepMs(ms: u32) void {
+ var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms };
+ _ = libc.nanosleep(&ts, null);
+}