Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/+atomic-write-at.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
`atomic.atomicWriteAt` writes through an open directory descriptor with
the exact mode the caller names, umask aside, for the metrics writers
that hold their directory pinned.
2 changes: 2 additions & 0 deletions changelog.d/+json-dumps-compact.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
`json.dumpsCompact` writes the one-line form Python's default json.dumps
call gives, with the same separators and ensure_ascii, byte for byte.
3 changes: 3 additions & 0 deletions changelog.d/+lock-exclusive-u64-timeout.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
`state.lockExclusive` and `lockExclusiveCancel` take the timeout as u64
milliseconds, wide enough for the 999_999_999 seconds a flock -w style
caller passes, where a u32 held only about 49 days.
3 changes: 3 additions & 0 deletions changelog.d/+self-exe.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
`fsx.selfExe` reads this program's own path from /proc/self/exe, answering a
failed, empty or truncated read with null so each caller can choose what
that means.
3 changes: 3 additions & 0 deletions changelog.d/+state-create-private-at.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
`state.createPrivateAt` creates a private file through an open directory
descriptor at an exact mode without ever replacing an existing name, the
never-clobber shape the tools' new-file writers need.
92 changes: 92 additions & 0 deletions src/atomic.zig
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,41 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write
try fsyncDir(parent);
}

/// atomic_write pinned to an open directory: replace `dir/name` with
/// `bytes` at exactly `mode`, whatever the process umask leaves, as
/// the tools' metrics writer does with the descriptor it holds. The
/// bytes go to a temporary file in the same directory, made durable,
/// and only then renamed over the destination; a failure leaves the
/// destination as it was and removes the temporary file. Shares
/// atomicWrite's write, sync and rename steps, through the same ops a
/// replaceable build may fail. Everything it allocates from `a` is
/// freed before it returns.
pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []const u8, mode: u32) (Allocator.Error || sys.Error)!void {
sys.last_errno = .SUCCESS;
var rnd: [4]u8 = undefined;
_ = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 });
const tmp = try a.print(".{s}.{d}.{x:0>8}.tmp", .{ name, linux.getpid(), std.mem.readInt(u32, &rnd, .little) });
defer a.free(tmp);
var zb: [sys.path_max:0]u8 = undefined;
const ztmp = try sys.z(&zb, tmp);
const flags: sys.O = .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .CLOEXEC = true };
const fd: sys.fd_t = @intCast(try op(ops.openat, .{ dir, ztmp.ptr, flags, @as(linux.mode_t, 0o600) }));
var done = false;
defer {
sys.close(fd);
if (!done) sys.unlinkat(dir, tmp, 0) catch {};
}
// openat applies the umask to the create, so the exact mode the
// caller names is set on the descriptor before anything is written
_ = try op(ops.fchmod, .{ fd, mode });
try writeTemp(fd, data);
_ = try op(ops.fsync, .{fd});
var zn: [sys.path_max:0]u8 = undefined;
_ = try op(ops.renameat, .{ dir, ztmp.ptr, dir, (try sys.z(&zn, name)).ptr });
done = true;
try sys.fsync(dir);
}

fn discard(tmp: []const u8, created: fsx.Stat) void {
const cur = fsx.statAt(fsx.cwd, tmp, false) catch return;
if (cur.dev == created.dev and cur.ino == created.ino) sys.unlinkat(fsx.cwd, tmp, 0) catch {};
Expand Down Expand Up @@ -698,6 +733,63 @@ test "an interrupted ACL read is retried" {
defer acls.deinit(gpa);
}

test "atomicWriteAt publishes the exact mode under any umask" {
const gpa = std.testing.allocator;
var pb: [sys.path_max]u8 = undefined;
var cwd_buf: [sys.path_max]u8 = undefined;
const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf);
const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-atomic-at-{d}", .{ cwd, linux.getpid() });
var zb: [sys.path_max:0]u8 = undefined;
_ = linux.mkdirat(fsx.cwd, (try sys.z(&zb, base)).ptr, 0o700);
const dir = try fsx.openDir(fsx.cwd, base, false);
defer {
fsx.deleteTree(gpa, fsx.cwd, base) catch {};
sys.close(dir);
}

// the umask bites the create but not the published mode, which is
// exactly what the caller names, as the metrics writer's chmod does
const old: u32 = @intCast(linux.syscall1(.umask, 0o077));
defer _ = linux.syscall1(.umask, old);
try atomicWriteAt(gpa, dir, "metrics", "first\n", 0o644);
const first = try fsx.statAt(dir, "metrics", false);
try std.testing.expectEqual(@as(u32, 0o644), first.perm());

// an existing destination is replaced with the mode it is given and
// keeps its bytes when a step fails, with no temporary left behind
try atomicWriteAt(gpa, dir, "metrics", "second\n", 0o640);
const second = try fsx.statAt(dir, "metrics", false);
try std.testing.expectEqual(@as(u32, 0o640), second.perm());
const f = try fsx.openRegular(dir, "metrics", false);
defer sys.close(f.fd);
const second_text = try fsx.readAll(gpa, f.fd, 100);
defer gpa.free(second_text);
try std.testing.expectEqualStrings("second\n", second_text);

const S = struct {
var fail_fsync = false;
fn fsync(fd_: sys.fd_t) usize {
if (fail_fsync) return @bitCast(-@as(isize, @backingInt(linux.E.IO)));
return linux.fsync(fd_);
}
};
defer ops.* = .{};
S.fail_fsync = true;
ops.fsync = S.fsync;
try std.testing.expectError(error.Unexpected, atomicWriteAt(gpa, dir, "metrics", "broken\n", 0o644));
S.fail_fsync = false;
const after = try fsx.openRegular(dir, "metrics", false);
defer sys.close(after.fd);
const after_text = try fsx.readAll(gpa, after.fd, 100);
defer gpa.free(after_text);
try std.testing.expectEqualStrings("second\n", after_text);
var it = try fsx.DirIter.init(gpa, dir);
defer it.deinit(gpa);
while (try it.next()) |e| {
try std.testing.expect(std.mem.indexOf(u8, e.name, ".tmp") == null);
}
}

test "the umask is read without changing it" {
const old: u32 = @intCast(linux.syscall1(.umask, 0o027));
defer _ = linux.syscall1(.umask, old);
Expand Down
16 changes: 16 additions & 0 deletions src/fsx.zig
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,15 @@ pub fn realpathFd(fd: fd_t, out: *[sys.path_max]u8) Error![]const u8 {
return out[0..n];
}

/// The path of this program, as /proc/self/exe reports it, or null when
/// the kernel does not report it whole: a failed read, an empty one, or
/// one that filled the buffer.
pub fn selfExe(out: *[sys.path_max]u8) ?[]const u8 {
const n = sys.call(linux.readlinkat, .{ linux.AT.FDCWD, "/proc/self/exe", out, out.len }) catch return null;
if (n == 0 or n >= out.len) return null;
return out[0..n];
}

/// realpath(1) with -e: every component must exist; symbolic links are
/// followed.
pub fn realpath(dir: fd_t, path: []const u8, out: *[sys.path_max]u8) Error![]const u8 {
Expand Down Expand Up @@ -631,6 +640,13 @@ pub fn mkdtemp(gpa: Allocator, dir: []const u8, prefix: []const u8) (Error || Al
return error.Exists;
}

test "selfExe names this program as a readable regular file" {
var out: [sys.path_max]u8 = undefined;
const got = selfExe(&out) orelse return error.TestUnexpectedResult;
const st = try statAt(cwd, got, true);
try std.testing.expect(st.isReg());
}

test "mkdtemp creates private 0700 directories with distinct names" {
const gpa = std.testing.allocator;
var cwd_buf: [sys.path_max]u8 = undefined;
Expand Down
68 changes: 68 additions & 0 deletions src/json.zig
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,74 @@ pub fn dumps(gpa: Allocator, v: Py, indent: usize, sort: bool) Allocator.Error![
return out.toOwnedSlice(gpa);
}

fn dumpsCompactInner(out: *std.ArrayList(u8), gpa: Allocator, v: Py, sort: bool) Allocator.Error!void {
switch (v) {
.null => try out.appendSlice(gpa, "null"),
.bool => |b| try out.appendSlice(gpa, if (b) "true" else "false"),
.int => |i| {
var buf: [24]u8 = undefined;
try out.appendSlice(gpa, std.mem.print(&buf, "{d}", .{i}) catch unreachable);
},
.float => |f| try writeFloat(out, gpa, f),
.str => |s| try writeCacheString(out, gpa, s),
.list => |items| {
try out.append(gpa, '[');
for (items, 0..) |it, i| {
if (i > 0) try out.appendSlice(gpa, ", ");
try dumpsCompactInner(out, gpa, it, sort);
}
try out.append(gpa, ']');
},
.dict => |entries| {
if (entries.len == 0) return out.appendSlice(gpa, "{}");
const sorted = try gpa.dupe(Py.Entry, entries);
defer gpa.free(sorted);
if (sort) std.mem.sort(Py.Entry, sorted, {}, lessKey);
try out.append(gpa, '{');
for (sorted, 0..) |e, i| {
if (i > 0) try out.appendSlice(gpa, ", ");
try writeCacheString(out, gpa, e.key);
try out.appendSlice(gpa, ": ");
try dumpsCompactInner(out, gpa, e.value, sort);
}
try out.append(gpa, '}');
},
}
}

/// json.dumps(v, sort_keys=sort) with the separators of the default call,
/// one line and no indent, ensure_ascii as Python's default. The compact
/// form the tools print for the --json lines.
pub fn dumpsCompact(gpa: Allocator, v: Py, sort: bool) Allocator.Error![]u8 {
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
try dumpsCompactInner(&out, gpa, v, sort);
return out.toOwnedSlice(gpa);
}

test "dumpsCompact matches json.dumps with the default separators" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
const v: Py = .{ .dict = &.{
.{ .key = "b", .value = .{ .list = &.{ .{ .int = 1 }, .null, .{ .bool = true } } } },
.{ .key = "a", .value = .{ .str = "\u{e9}\xff" } },
.{ .key = "c", .value = .{ .dict = &.{} } },
.{ .key = "d", .value = .{ .list = &.{} } },
.{ .key = "e", .value = .{ .float = 2.0 } },
.{ .key = "f", .value = .{ .str = "" } },
} };
const s = try dumpsCompact(a, v, true);
try std.testing.expectEqualStrings(
"{\"a\": \"\\u00e9\\udcff\", \"b\": [1, null, true], \"c\": {}, \"d\": [], \"e\": 2.0, \"f\": \"\"}",
s,
);
const bare = try dumpsCompact(a, .{ .list = &.{} }, false);
try std.testing.expectEqualStrings("[]", bare);
const wrapped = try dumpsCompact(a, .{ .list = &.{.{ .dict = &.{.{ .key = "k", .value = .{ .str = "v" } }} }} }, false);
try std.testing.expectEqualStrings("[{\"k\": \"v\"}]", wrapped);
}

test "dumps matches json.dumps(indent=2, sort_keys=True)" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
Expand Down
113 changes: 104 additions & 9 deletions src/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,14 @@ pub const LockError = Error || error{TimedOut};
pub const LockCancelError = LockError || error{Canceled};

/// flock(LOCK_EX) on `fd`, giving up after `timeout_ms` when one is given.
/// The deadline is read from the monotonic clock. A signal that cuts a
/// sleep short does not consume the whole wait: the next check looks at
/// the clock again. A failure other than contention is the flock error,
/// with its errno in `sys.last_errno`.
pub fn lockExclusive(fd: fsx.fd_t, timeout_ms: ?u32) LockError!void {
/// The timeout is u64 milliseconds, wide enough for the seconds callers
/// like flock -w take: the largest a tool passes is 999_999_999 seconds,
/// whose milliseconds a u32 could not hold. The deadline is read from
/// the monotonic clock. A signal that cuts a sleep short does not
/// consume the whole wait: the next check looks at the clock again. A
/// failure other than contention is the flock error, with its errno in
/// `sys.last_errno`.
pub fn lockExclusive(fd: fsx.fd_t, timeout_ms: ?u64) LockError!void {
return lockExclusiveCancel(fd, timeout_ms, null) catch |err| switch (err) {
error.Canceled => unreachable,
else => |e| return e,
Expand All @@ -81,8 +84,8 @@ pub fn lockExclusive(fd: fsx.fd_t, timeout_ms: ?u32) LockError!void {

/// Like `lockExclusive`, also stopping with `error.Canceled` if `cancel`
/// becomes true while waiting.
pub fn lockExclusiveCancel(fd: fsx.fd_t, timeout_ms: ?u32, cancel: ?*const std.atomic.Value(bool)) LockCancelError!void {
const deadline: ?i64 = if (timeout_ms) |ms| nowMs() + ms else null;
pub fn lockExclusiveCancel(fd: fsx.fd_t, timeout_ms: ?u64, cancel: ?*const std.atomic.Value(bool)) LockCancelError!void {
const deadline: ?i64 = if (timeout_ms) |ms| nowMs() + @as(i64, @intCast(ms)) else null;
if (deadline == null and cancel == null) {
_ = try lockCall(lock_ops.flock, .{ fd, @as(i32, std.posix.LOCK.EX) });
return;
Expand Down Expand Up @@ -117,6 +120,20 @@ pub fn readPrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, limit: usize
};
}

/// Create `dir/name` with `bytes` at exactly `mode`, never replacing an
/// existing name: the create is O_EXCL with O_NOFOLLOW, an existing
/// name is `error.Exists`, and the mode is set on the descriptor so the
/// umask cannot bite it. The name is created and closed in one step;
/// nothing is renamed, so another name's file is never touched. A
/// symbolic link at the name is refused without being followed, as
/// `openPrivate` refuses one.
pub fn createPrivateAt(dir: fsx.fd_t, name: []const u8, bytes: []const u8, mode: u32) Error!void {
const fd = try sys.openat(dir, name, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .NONBLOCK = true }, 0o600);
defer sys.close(fd);
try sys.fchmod(fd, mode);
try sys.writeAll(fd, bytes);
}

/// Replace `dir/name` with `bytes`: written to `.NAME.PID.RANDOM.tmp` with
/// mode 0600, then renamed over the name.
pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []const u8) (Error || Allocator.Error)!void {
Expand All @@ -138,6 +155,45 @@ pub fn writePrivate(gpa: Allocator, dir: fsx.fd_t, name: []const u8, bytes: []co
done = true;
}

test "createPrivateAt creates without clobbering" {
const gpa = std.testing.allocator;
var pb: [sys.path_max]u8 = undefined;
var cwd_buf: [sys.path_max]u8 = undefined;
const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf);
const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-create-at-{d}", .{ cwd, linux.getpid() });
defer fsx.deleteTree(gpa, fsx.cwd, base) catch {};
var zb: [sys.path_max:0]u8 = undefined;
_ = linux.mkdirat(fsx.cwd, (try sys.z(&zb, base)).ptr, 0o700);
const d = try fsx.openDir(fsx.cwd, base, false);
defer sys.close(d);

// a fresh name at an exact mode under a restrictive umask
const old: u32 = @intCast(linux.syscall1(.umask, 0o077));
defer _ = linux.syscall1(.umask, old);
try createPrivateAt(d, "new", "bytes\n", 0o644);
try std.testing.expectEqual(@as(u32, 0o644), (try fsx.statAt(d, "new", false)).perm());

// an existing name is refused with its bytes untouched
try std.testing.expectError(error.Exists, createPrivateAt(d, "new", "second\n", 0o600));
const f = try fsx.openRegular(d, "new", false);
defer sys.close(f.fd);
const got = try fsx.readAll(gpa, f.fd, 100);
defer gpa.free(got);
try std.testing.expectEqualStrings("bytes\n", got);

// a symbolic link at the name is refused, not followed
_ = linux.symlinkat("new", d, (try sys.z(&zb, "link")).ptr);
try std.testing.expectError(error.Exists, createPrivateAt(d, "link", "x\n", 0o600));

// a name under a directory the caller already holds is created there
var nb: [sys.path_max]u8 = undefined;
const nested_name = try std.mem.print(&nb, "{s}/nested", .{base});
try createPrivateAt(fsx.cwd, nested_name, "n\n", 0o600);
const nested = try fsx.openRegular(fsx.cwd, nested_name, false);
defer sys.close(nested.fd);
try std.testing.expectEqual(@as(u32, 0o600), nested.stat.perm());
}

test "a file that is not private is not read" {
const gpa = std.testing.allocator;
var pb: [sys.path_max]u8 = undefined;
Expand Down Expand Up @@ -244,13 +300,52 @@ test "lockExclusive waits out the timeout while signals arrive" {
}

test "a lock that fails reports its errno, with or without a timeout" {
for ([_]?u32{ null, 0, 50 }) |timeout| {
for ([_]?u64{ null, 0, 50 }) |timeout| {
sys.last_errno = .SUCCESS;
try std.testing.expectError(error.InvalidArgument, lockExclusive(-1, timeout));
try std.testing.expectEqualStrings("[Errno 9] Bad file descriptor", sys.describe(error.InvalidArgument));
}
}

test "lockExclusive takes the timeout flock -w seconds give" {
const gpa = std.testing.allocator;
var pb: [sys.path_max]u8 = undefined;
var cwd_buf: [sys.path_max]u8 = undefined;
const cwd = try fsx.realpath(fsx.cwd, ".", &cwd_buf);
const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-locku64-{d}", .{ cwd, linux.getpid() });
var zb: [sys.path_max:0]u8 = undefined;
_ = linux.mkdirat(fsx.cwd, (try sys.z(&zb, base)).ptr, 0o700);
const d = try fsx.openDir(fsx.cwd, base, false);
defer {
fsx.deleteTree(gpa, fsx.cwd, base) catch {};
sys.close(d);
}

// the 999_999_999 seconds a tool may pass, as milliseconds: wider
// than a u32 holds, and with the lock free it returns at once
const fd1 = try sys.openat(d, "L", .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
defer sys.close(fd1);
try lockExclusive(fd1, 999_999_999 * std.time.ms_per_s);

// with the lock held, a timeout past u32 range still waits for the
// release instead of wrapping to a deadline already past
const fd2 = try sys.openat(d, "L", .{ .ACCMODE = .RDWR }, 0);
defer sys.close(fd2);
const Holder = struct {
var fd: fsx.fd_t = -1;
fn letGo() void {
var ts: linux.timespec = .{ .sec = 0, .nsec = 150 * std.time.ns_per_ms };
_ = linux.nanosleep(&ts, null);
_ = linux.flock(fd, std.posix.LOCK.UN);
}
};
Holder.fd = fd1;
const thread = try std.Thread.spawn(.{}, Holder.letGo, .{});
thread.join();
try lockExclusive(fd2, 500_000_000 * std.time.ms_per_s);
_ = linux.flock(fd2, std.posix.LOCK.UN);
}

// ---- the state-root lock: a flock gate and a POSIX record lock -------------

/// A state root's lock. The flock gate excludes processes on one kernel; the
Expand Down Expand Up @@ -637,7 +732,7 @@ test "lockExclusive covers timeout 0, bounded timeout, and unsupported flock" {
lock_ops.flock = Hooks.fail;
for ([_]linux.E{ .OPNOTSUPP, .NOSYS }) |e| {
Hooks.err_code = e;
for ([_]?u32{ null, 0, 25 }) |timeout| {
for ([_]?u64{ null, 0, 25 }) |timeout| {
sys.last_errno = .SUCCESS;
try std.testing.expectError(error.Unsupported, lockExclusive(fd2, timeout));
try std.testing.expectEqual(e, sys.last_errno);
Expand Down
Loading
Loading