From 2a0f5e6fd6506dbf4d6e5af5a5878ace4df5ec00 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Thu, 26 Nov 2026 01:02:30 +0000 Subject: [PATCH] fix: check directory closes after sync Some directory closes are now checked. The checked closes are the ones that follow a sync the caller relies on. They go through the same replaceable calls as a file close. A failed close is returned. A close that a signal interrupts counts as success and is not retried. Cleanup closes after an earlier error ignore their result and keep the earlier errno. What is left at the target name is unchanged. --- changelog.d/+dir-close-after-sync.bugfix.md | 1 + src/atomic.zig | 31 ++- src/atomic_test.zig | 95 ++++++- src/fsx.zig | 269 ++++++++++++++++++-- src/logs.zig | 92 ++++++- 5 files changed, 446 insertions(+), 42 deletions(-) create mode 100644 changelog.d/+dir-close-after-sync.bugfix.md diff --git a/changelog.d/+dir-close-after-sync.bugfix.md b/changelog.d/+dir-close-after-sync.bugfix.md new file mode 100644 index 0000000..d50f0b7 --- /dev/null +++ b/changelog.d/+dir-close-after-sync.bugfix.md @@ -0,0 +1 @@ +`fsx.moveAcross` closes a copied directory after syncing it and before the rename that publishes the copy, including each directory of a copied tree. `fsx.copyTo` and `moveAcross` close the parent directory after the sync that makes the new name durable. `atomic.fsyncDir` and the parent directory sync in `atomic.atomicWrite` check that close as well, as does the directory sync at the end of `logs.gzipInPlace`. A failed close is returned as `sys.Error`. A close on the way out of an earlier error is ignored and that errno is kept. Before this change those closes were ignored, so a directory sync that a network file system (NFS) reported lost only at the close was returned as success. Before the rename, a failure leaves the destination name as it was and removes the temporary path. After the rename, the published name keeps what the rename put there. A close that `EINTR` interrupts is not retried and is not an error, as `sys.result` treats `EINTR`. The closes go through `fsx.publish_ops`, `atomic.ops.close` and `logs.gzip_ops` in the same builds as the other replaceable calls. diff --git a/src/atomic.zig b/src/atomic.zig index 7c714ed..6ef4756 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -22,8 +22,9 @@ const posix_access = "system.posix_acl_access"; /// filesystem's ACL model or a failing call, in a `replaceable` build only /// (this library's tests, a tool's -Dtest-ops artifact). `created` runs on /// the temporary file right after its O_EXCL creation, where a filesystem -/// applies an inherited ACL. `close` is that temporary file's close, before -/// the rename; the caller does not retry it. +/// applies an inherited ACL. `close` is the temporary file's close before +/// the rename, and the parent directory's close after its sync; the caller +/// does not retry either. pub const Ops = struct { flistxattr: *const fn (fd: sys.fd_t, buf: []u8) usize = realList, fgetxattr: *const fn (fd: sys.fd_t, name: [:0]const u8, buf: []u8) usize = realGet, @@ -453,12 +454,19 @@ pub fn fileMode(path: []const u8) u32 { return 0o644 & ~currentUmask(); } -/// Open `path` read-only and fsync it. For a directory, that makes a -/// rename or a new name in it durable. +/// Open `path` read-only, fsync it and close it. For a directory, that +/// makes a rename or a new name in it durable. A failed close is returned +/// with `sys.last_errno` set. A close that EINTR interrupts is not retried +/// and is not an error, as `sys.result` treats EINTR. The close goes +/// through `ops.close`. On an earlier error the cleanup close is ignored +/// and that errno is kept. pub fn fsyncDir(path: []const u8) sys.Error!void { const fd = try sys.openat(fsx.cwd, path, .{}, 0); - defer sys.close(fd); + var open = true; + errdefer if (open) closeDiscarded(fd); try sys.fsync(fd); + open = false; + try closeTemp(fd); } /// os.makedirs(path, exist_ok=True): a name that exists as something @@ -595,9 +603,11 @@ pub const WriteOptions = struct { /// points STEP.write, STEP.fsync and STEP.rename precede those /// operations, and in a replaceable build can fail them (Faults.fails); /// the destination is never unlinked first. The close goes through -/// `ops.close`. Everything it allocates from `a` is freed before it -/// returns, except the failure message in `why`. Call `why.deinit(a)` -/// after any error. +/// `ops.close`. After the rename the parent directory is synced and closed +/// through that same call. A failed close of the directory is reported +/// with no path, and the destination keeps the bytes the rename published. +/// Everything it allocates from `a` is freed before it returns, except the +/// failure message in `why`. Call `why.deinit(a)` after any error. pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: WriteOptions, why: *Why) Error!void { sys.last_errno = .SUCCESS; const parent = if (std.fs.path.dirname(path)) |d| (if (d.len > 0) d else ".") else "."; @@ -681,8 +691,11 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write renamed = true; // Opening the directory names it. Flushing the descriptor names no file. const directory = sys.openat(fsx.cwd, parent, .{}, 0) catch |err| return failOs(a, why, err, parent, null); - defer sys.close(directory); + var dir_open = true; + defer if (dir_open) closeDiscarded(directory); sys.fsync(directory) catch |err| return failOs(a, why, err, null, null); + dir_open = false; + closeTemp(directory) catch |err| return failOs(a, why, err, null, null); } /// atomic_write pinned to an open directory: replace `dir/name` with diff --git a/src/atomic_test.zig b/src/atomic_test.zig index 4e914ec..c3e6c5b 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -2044,7 +2044,9 @@ fn expectPublishClose(dir_path: []const u8, dfd: fsx.fd_t, close_errno: linux.E, try testing.expectEqualStrings("old\n", readFile(path)); } else try testing.expect(!exists(path)); } else try testing.expectEqualStrings("new\n", readFile(path)); - try testing.expectEqual(@as(usize, 1), ncloses); + // atomicWrite also closes the parent directory after the rename. + const want_closes: usize = if (!fails and !c.at) 2 else 1; + try testing.expectEqual(want_closes, ncloses); try testing.expectEqual(before, try test_support.fdCount(gpa)); try expectNoPublishTemp(gpa, dfd); } @@ -2081,3 +2083,94 @@ test "a failed fsync of an atomic write closes the temporary file once" { defer sys.close(dfd); try expectPublishClose(dir_path, dfd, .SUCCESS, true, .IO, error.Unexpected, true); } + +const DirCloseHook = struct { + var closes: usize = 0; + var errno: linux.E = .SUCCESS; + /// When set, only a directory descriptor is injected. A file close stays + /// the real call, so the parent close can fail on its own. + var dirs_only: bool = false; + + fn arm(e: linux.E, directories_only: bool) void { + closes = 0; + errno = e; + dirs_only = directories_only; + atomic.ops.close = close; + } + + fn close(fd: sys.fd_t) usize { + const is_dir = if (fsx.fstat(fd)) |st| st.isDir() else |_| false; + const rc = linux.close(fd); + if (dirs_only and !is_dir) return rc; + closes += 1; + if (errno == .SUCCESS or closes > 1) return rc; + return err(errno); + } +}; + +test "dir close: fsyncDir returns EIO and leaves the directory" { + begin(); + defer end(); + const dir_path = tmpdir(); + defer cleanup(dir_path); + DirCloseHook.arm(.IO, false); + sys.last_errno = .SUCCESS; + try testing.expectError(error.Unexpected, atomic.fsyncDir(dir_path)); + try testing.expectEqual(linux.E.IO, sys.last_errno); + try testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try testing.expect(exists(dir_path)); +} + +test "dir close: fsyncDir publishes on EINTR" { + begin(); + defer end(); + const dir_path = tmpdir(); + defer cleanup(dir_path); + DirCloseHook.arm(.INTR, false); + try atomic.fsyncDir(dir_path); + try testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try testing.expect(exists(dir_path)); +} + +test "dir close: atomicWrite parent returns EIO and keeps the published bytes" { + begin(); + defer end(); + const gpa = testing.allocator; + const dir_path = tmpdir(); + defer cleanup(dir_path); + const path = join(dir_path, "kept"); + seed(path, true); + DirCloseHook.arm(.IO, true); + var why: atomic.Why = .{}; + defer why.deinit(gpa); + sys.last_errno = .SUCCESS; + const before = try test_support.fdCount(gpa); + try testing.expectError(error.Unexpected, atomic.atomicWrite(gpa, path, "new\n", .{}, &why)); + try testing.expectEqual(linux.E.IO, sys.last_errno); + try testing.expectEqualStrings(sys.describeErrno(.IO), why.msg); + try testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try testing.expectEqualStrings("new\n", readFile(path)); + const dfd = try fsx.openDir(fsx.cwd, dir_path, false); + defer sys.close(dfd); + try expectNoPublishTemp(gpa, dfd); +} + +test "dir close: atomicWrite parent publishes on EINTR" { + begin(); + defer end(); + const gpa = testing.allocator; + const dir_path = tmpdir(); + defer cleanup(dir_path); + const path = join(dir_path, "kept"); + seed(path, true); + DirCloseHook.arm(.INTR, true); + var why: atomic.Why = .{}; + defer why.deinit(gpa); + const before = try test_support.fdCount(gpa); + try atomic.atomicWrite(gpa, path, "new\n", .{}, &why); + try testing.expectEqualStrings("", why.msg); + try testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try testing.expectEqual(before, try test_support.fdCount(gpa)); + try testing.expectEqualStrings("new\n", readFile(path)); +} diff --git a/src/fsx.zig b/src/fsx.zig index b360c5a..3b59788 100644 --- a/src/fsx.zig +++ b/src/fsx.zig @@ -258,8 +258,12 @@ fn copyFd(src: fd_t, dst: fd_t) Error!void { /// and its mode; a new file gets the source's permission bits less the /// umask. A destination that is a symbolic link or not a regular file is /// refused. A destination with other hard links keeps those links on the -/// previous inode; `name` is the new inode. Returns the open destination, -/// which the caller closes. +/// previous inode; `name` is the new inode. The directory that receives +/// `name` is synced and closed after the rename. A failed close is returned +/// with `sys.last_errno` set and `name` is left as the rename made it. A +/// close that EINTR interrupts is not retried and is not an error, as +/// `sys.result` treats EINTR. That close is replaceable through +/// `publish_ops`. Returns the open destination, which the caller closes. pub fn copyTo(src: fd_t, src_stat: Stat, dir: fd_t, name: []const u8) Error!fd_t { const existing: ?Stat = statAt(dir, name, false) catch |err| switch (err) { error.NotFound => null, @@ -463,8 +467,16 @@ fn moveFsync(faults: MoveFaults, dir: fd_t) Error!void { /// `fsyncNameParent` for moveAcross, reported to its trace. fn moveFsyncNameParent(faults: MoveFaults, dir: fd_t, name: []const u8) Error!void { const parent_dir = try openDir(dir, std.fs.path.dirname(name) orelse ".", true); - defer sys.close(parent_dir); + var open = true; + errdefer if (open) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = publish_ops.close(parent_dir); + }; try moveFsync(faults, parent_dir); + open = false; + try closeBeforePublish(parent_dir); } /// Whether `a_dir/a_name` and `b_dir/b_name` name entries of the same @@ -492,8 +504,16 @@ fn tmpName(base: []const u8, out: *[sys.path_max]u8) Error![]const u8 { fn fsyncNameParent(dir: fd_t, name: []const u8) Error!void { const parent = std.fs.path.dirname(name) orelse "."; const parent_dir = try openDir(dir, parent, true); - defer sys.close(parent_dir); + var open = true; + errdefer if (open) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = publish_ops.close(parent_dir); + }; try sys.fsync(parent_dir); + open = false; + try closeBeforePublish(parent_dir); } fn setModeOwnerAndAcl(src_fd: fd_t, src: Stat, dst_fd: fd_t, policy: MoveAcrossPolicy) Error!void { @@ -508,10 +528,11 @@ fn setModeOwnerAndAcl(src_fd: fd_t, src: Stat, dst_fd: fd_t, policy: MoveAcrossP } /// The close of a file about to be published by `replaceContents` or by the -/// cross-device copy inside `moveAcross`, and the close after `appendLine` -/// writes, as a raw system-call result. Replaceable in the same builds as -/// `atomic.ops`; constant real calls in any other build. A close that EINTR -/// interrupts is not retried. +/// cross-device copy inside `moveAcross`, the close after `appendLine` +/// writes, and the close of a directory after the sync that makes that +/// directory durable, as a raw system-call result. Replaceable in the same +/// builds as `atomic.ops`; constant real calls in any other build. A close +/// that EINTR interrupts is not retried. pub const PublishOps = struct { close: *const fn (fd: fd_t) usize = realPublishClose, }; @@ -528,10 +549,11 @@ fn realPublishClose(fd: fd_t) usize { /// Close `fd` once. `replaceContents` and the cross-device copy inside /// `moveAcross` do this before the file is published; `appendLine` does this -/// after the write. EINTR is success and is not retried, as Linux has freed -/// the descriptor and `sys.result` does not treat EINTR as an error. Any -/// other errno is returned with `sys.last_errno` set. The caller does not -/// close `fd` again. +/// after the write; a directory is closed after the sync that makes it +/// durable. EINTR is success and is not retried, as Linux has freed the +/// descriptor and `sys.result` does not treat EINTR as an error. Any other +/// errno is returned with `sys.last_errno` set. The caller does not close +/// `fd` again. fn closeBeforePublish(fd: fd_t) Error!void { _ = try sys.result(publish_ops.close(fd)); } @@ -583,11 +605,19 @@ fn copyTreeContents(gpa: Allocator, src_fd: fd_t, dst_fd: fd_t, policy: MoveAcro const sdir = try openDir(src_fd, e.name, false); defer sys.close(sdir); const ddir = try openDir(dst_fd, e.name, false); - defer sys.close(ddir); + var dopen = true; + errdefer if (dopen) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = publish_ops.close(ddir); + }; try copyTreeContents(gpa, sdir, ddir, policy); const st = try fstat(sdir); try setModeOwnerAndAcl(sdir, st, ddir, policy); try sys.fsync(ddir); + dopen = false; + try closeBeforePublish(ddir); }, DT.LNK => try copyLinkAt(src_fd, e.name, dst_fd, e.name), else => return error.NotRegularFile, @@ -622,10 +652,18 @@ fn moveAcrossCopy(gpa: Allocator, src_dir: fd_t, src_name: []const u8, dst_dir: const sdir = try openDir(src_dir, src_name, false); defer sys.close(sdir); const ddir = try openDir(dst_dir, tmp, false); - defer sys.close(ddir); + var dopen = true; + errdefer if (dopen) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = publish_ops.close(ddir); + }; try copyTreeContents(gpa, sdir, ddir, opts.policy); try setModeOwnerAndAcl(sdir, src, ddir, opts.policy); try sys.fsync(ddir); + dopen = false; + try closeBeforePublish(ddir); } else if (src.isLink()) { try copyLinkAt(src_dir, src_name, dst_dir, tmp); } else { @@ -662,11 +700,14 @@ fn moveAcrossInternal(gpa: Allocator, src_dir: fd_t, src_name: []const u8, dst_d /// Move `src_dir/src_name` to `dst_dir/dst_name`. On one file system this is /// a rename; on `error.CrossDevice` it copies to a destination-side temporary -/// path, syncs and closes each copied regular file, then atomically publishes -/// with rename and removes the source. A failed close is returned with -/// `sys.last_errno` set, the destination name is left as it was, and the -/// temporary path is removed. Each copied descriptor is closed once. A close -/// that EINTR interrupts is not retried and is not an error, as `sys.result` +/// path, syncs and closes each copied regular file and each copied +/// directory, then atomically publishes with rename and removes the source. +/// A failed close before that rename is returned with `sys.last_errno` set, +/// the destination name is left as it was, and the temporary path is +/// removed. The parent directory is synced and closed after the rename. A +/// failed close there is returned and the published name is left as the +/// rename made it. Each of these descriptors is closed once. A close that +/// EINTR interrupts is not retried and is not an error, as `sys.result` /// treats EINTR. The close is replaceable through `publish_ops`. pub fn moveAcross(gpa: Allocator, src_dir: fd_t, src_name: []const u8, dst_dir: fd_t, dst_name: []const u8, opts: MoveAcrossOptions) (Error || Allocator.Error)!void { return moveAcrossInternal(gpa, src_dir, src_name, dst_dir, dst_name, opts, .{}); @@ -2175,7 +2216,8 @@ test "fsx publish close: moveAcross file publishes on EINTR" { const before = try test_support.fdCount(gpa); PublishHook.arm(.INTR); try crossMove(gpa, scratch.fd, "src", "dst"); - try std.testing.expectEqual(@as(usize, 1), PublishHook.closes); + // The file, then the destination parent and the source parent. + try std.testing.expectEqual(@as(usize, 3), PublishHook.closes); try std.testing.expectEqual(before, try test_support.fdCount(gpa)); try std.testing.expectError(error.NotFound, statAt(scratch.fd, "src", false)); try expectText(gpa, scratch.fd, "dst", "new\n"); @@ -2197,7 +2239,8 @@ test "fsx publish close: moveAcross tree returns EIO and leaves the destination" sys.last_errno = .SUCCESS; try std.testing.expectError(error.Unexpected, crossMove(gpa, scratch.fd, "src", "dst")); try std.testing.expectEqual(linux.E.IO, sys.last_errno); - try std.testing.expectEqual(@as(usize, 1), PublishHook.closes); + // The file close fails, then the temporary directory is closed on the way out. + try std.testing.expectEqual(@as(usize, 2), PublishHook.closes); try std.testing.expectEqual(before, try test_support.fdCount(gpa)); try expectText(gpa, sub, "a", "tree\n"); try std.testing.expectError(error.NotFound, statAt(scratch.fd, "dst", false)); @@ -2217,7 +2260,8 @@ test "fsx publish close: moveAcross tree publishes on EINTR" { const before = try test_support.fdCount(gpa); PublishHook.arm(.INTR); try crossMove(gpa, scratch.fd, "src", "dst"); - try std.testing.expectEqual(@as(usize, 1), PublishHook.closes); + // The file, the temporary directory, then both parent directories. + try std.testing.expectEqual(@as(usize, 4), PublishHook.closes); try std.testing.expectEqual(before, try test_support.fdCount(gpa)); try std.testing.expectError(error.NotFound, statAt(scratch.fd, "src", false)); try expectText(gpa, scratch.fd, "dst/a", "tree\n"); @@ -2255,3 +2299,184 @@ test "fsx publish close: appendLine keeps the line on EINTR" { try std.testing.expectEqual(before, try test_support.fdCount(gpa)); try expectText(gpa, scratch.fd, "list", "old\nnew\n"); } + +const DirCloseHook = struct { + var closes: usize = 0; + var errno: linux.E = .SUCCESS; + /// 1-based index of the directory close that reports `errno`. + var fail_at: usize = 1; + + fn arm(e: linux.E, at: usize) void { + closes = 0; + errno = e; + fail_at = at; + publish_ops.* = .{ .close = close }; + } + + /// Closes `fd` for real. A file is returned unchanged. `errno` is + /// reported for one directory close, and later directory closes are the + /// real result, so that call is not retried. + fn close(fd: fd_t) usize { + const is_dir = if (fstat(fd)) |st| st.isDir() else |_| false; + const rc = linux.close(fd); + if (!is_dir) return rc; + closes += 1; + if (errno == .SUCCESS or closes != fail_at) return rc; + return @bitCast(-@as(isize, @backingInt(errno))); + } +}; + +fn mkdirAt(dir: fd_t, name: []const u8) !void { + var zb: [sys.path_max:0]u8 = undefined; + _ = try sys.call(linux.mkdirat, .{ dir, (try sys.z(&zb, name)).ptr, @as(linux.mode_t, 0o700) }); +} + +test "dir close: moveAcross empty directory returns EIO and leaves the destination" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-empty-eio"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.IO, 1); + sys.last_errno = .SUCCESS; + try std.testing.expectError(error.Unexpected, crossMove(gpa, scratch.fd, "src", "dst")); + try std.testing.expectEqual(linux.E.IO, sys.last_errno); + try std.testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expect((try statAt(scratch.fd, "src", false)).isDir()); + try std.testing.expectError(error.NotFound, statAt(scratch.fd, "dst", false)); + try expectNoTmp(gpa, scratch.fd); +} + +test "dir close: moveAcross empty directory publishes on EINTR" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-empty-eintr"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.INTR, 1); + try crossMove(gpa, scratch.fd, "src", "dst"); + // Temporary directory, then the destination parent and the source parent. + try std.testing.expectEqual(@as(usize, 3), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expectError(error.NotFound, statAt(scratch.fd, "src", false)); + try std.testing.expect((try statAt(scratch.fd, "dst", false)).isDir()); + try expectNoTmp(gpa, scratch.fd); +} + +test "dir close: copied subdirectory returns EIO and leaves the destination" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-sub-eio"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const sub = try openDir(scratch.fd, "src", false); + defer sys.close(sub); + try mkdirAt(sub, "child"); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.IO, 1); + sys.last_errno = .SUCCESS; + try std.testing.expectError(error.Unexpected, crossMove(gpa, scratch.fd, "src", "dst")); + try std.testing.expectEqual(linux.E.IO, sys.last_errno); + // The child close fails, then the temporary directory is closed on the way out. + try std.testing.expectEqual(@as(usize, 2), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expect((try statAt(sub, "child", false)).isDir()); + try std.testing.expectError(error.NotFound, statAt(scratch.fd, "dst", false)); + try expectNoTmp(gpa, scratch.fd); +} + +test "dir close: copied subdirectory publishes on EINTR" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-sub-eintr"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const sub = try openDir(scratch.fd, "src", false); + try mkdirAt(sub, "child"); + sys.close(sub); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.INTR, 1); + try crossMove(gpa, scratch.fd, "src", "dst"); + // Child directory, temporary root, then both parents. + try std.testing.expectEqual(@as(usize, 4), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expectError(error.NotFound, statAt(scratch.fd, "src", false)); + try std.testing.expect((try statAt(scratch.fd, "dst/child", false)).isDir()); + try expectNoTmp(gpa, scratch.fd); +} + +test "dir close: copyTo parent returns EIO and leaves the published file" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-copy-eio"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try putBytes(scratch.fd, "src", "new\n"); + try putBytes(scratch.fd, "dst", "old\n"); + const opened = try openRegular(scratch.fd, "src", false); + defer sys.close(opened.fd); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.IO, 1); + sys.last_errno = .SUCCESS; + try std.testing.expectError(error.Unexpected, copyTo(opened.fd, opened.stat, scratch.fd, "dst")); + try std.testing.expectEqual(linux.E.IO, sys.last_errno); + try std.testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectText(gpa, scratch.fd, "dst", "new\n"); +} + +test "dir close: copyTo parent publishes on EINTR" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-copy-eintr"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try putBytes(scratch.fd, "src", "new\n"); + try putBytes(scratch.fd, "dst", "old\n"); + const opened = try openRegular(scratch.fd, "src", false); + defer sys.close(opened.fd); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.INTR, 1); + const fd = try copyTo(opened.fd, opened.stat, scratch.fd, "dst"); + sys.close(fd); + try std.testing.expectEqual(@as(usize, 1), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try expectText(gpa, scratch.fd, "dst", "new\n"); +} + +test "dir close: moveAcross parent sync returns EIO and leaves the published tree" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-parent-eio"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const before = try test_support.fdCount(gpa); + // The second directory close is the destination parent, after the rename. + DirCloseHook.arm(.IO, 2); + sys.last_errno = .SUCCESS; + try std.testing.expectError(error.Unexpected, crossMove(gpa, scratch.fd, "src", "dst")); + try std.testing.expectEqual(linux.E.IO, sys.last_errno); + try std.testing.expectEqual(@as(usize, 2), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expect((try statAt(scratch.fd, "src", false)).isDir()); + try std.testing.expect((try statAt(scratch.fd, "dst", false)).isDir()); + try expectNoTmp(gpa, scratch.fd); +} + +test "dir close: moveAcross parent sync publishes on EINTR" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "fsx-dir-close-parent-eintr"); + defer scratch.deinit(); + defer publish_ops.* = .{}; + try mkdirAt(scratch.fd, "src"); + const before = try test_support.fdCount(gpa); + DirCloseHook.arm(.INTR, 2); + try crossMove(gpa, scratch.fd, "src", "dst"); + // Temporary directory, destination parent, then the source parent. + try std.testing.expectEqual(@as(usize, 3), DirCloseHook.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expectError(error.NotFound, statAt(scratch.fd, "src", false)); + try std.testing.expect((try statAt(scratch.fd, "dst", false)).isDir()); + try expectNoTmp(gpa, scratch.fd); +} diff --git a/src/logs.zig b/src/logs.zig index 42c40d7..63d96bf 100644 --- a/src/logs.zig +++ b/src/logs.zig @@ -54,10 +54,10 @@ pub const GzipStep = enum { /// and so did the removal of the archive that follows; then both are /// present. archive, - /// Opening the archive's directory and syncing it, after the rename of - /// the archive and the removal of the original. `name.gz` is in place - /// and the original is gone; only whether that survives a crash is in - /// doubt. + /// Opening the archive's directory, syncing it and closing it, after the + /// rename of the archive and the removal of the original. `name.gz` is + /// in place and the original is gone; only whether that survives a crash + /// is in doubt. A failed close of that directory is this same step. directory_sync, }; @@ -182,13 +182,22 @@ pub fn gzipInPlaceAtStep(gpa: Allocator, io: Io, dir: fsx.fd_t, name: []const u8 done = true; failed_at.* = .directory_sync; const parent_fd = try fsx.openDir(dir, gz_parent, true); - defer sys.close(parent_fd); + var parent_open = true; + errdefer if (parent_open) { + // The error being returned keeps its errno. + const saved = sys.last_errno; + defer sys.last_errno = saved; + _ = gzip_ops.close(parent_fd); + }; try sys.fsync(parent_fd); + parent_open = false; + _ = try sys.result(gzip_ops.close(parent_fd)); } -/// The close of the temporary archive `gzipInPlaceAtStep` publishes, as a -/// raw system-call result. Replaceable in the same builds as `atomic.ops`; -/// a constant real close in any other build. The caller does not retry it. +/// The close of the temporary archive `gzipInPlaceAtStep` publishes, and of +/// the directory synced once that archive is in place, as a raw system-call +/// result. Replaceable in the same builds as `atomic.ops`; a constant real +/// close in any other build. The caller does not retry it. pub const GzipOps = struct { close: *const fn (fd: fsx.fd_t) usize = realClose, }; @@ -614,7 +623,7 @@ test "gzip close EIO leaves the log and publishes nothing" { try std.testing.expectEqualStrings("a log\n", body); } -test "gzip close EINTR publishes the archive and closes once" { +test "gzip close EINTR publishes the archive and does not retry" { const gpa = std.testing.allocator; const scratch = try test_support.ScratchDir.init(gpa, "logs-close-eintr"); defer scratch.deinit(); @@ -627,7 +636,8 @@ test "gzip close EINTR publishes the archive and closes once" { var failed_at: GzipStep = .archive; try gzipInPlaceAtStep(gpa, io, dir, "a.log", &failed_at); gzip_ops.* = .{}; - try std.testing.expectEqual(@as(usize, 1), GzipClose.closes); + // The archive close, then the directory close. EINTR is not retried. + try std.testing.expectEqual(@as(usize, 2), GzipClose.closes); try std.testing.expectEqual(before, try test_support.fdCount(gpa)); try expectNoGzTemp(gpa, dir); try std.testing.expectError(error.NotFound, fsx.statAt(dir, "a.log", false)); @@ -639,3 +649,65 @@ test "gzip close EINTR publishes the archive and closes once" { defer gpa.free(plain); try std.testing.expectEqualStrings("a log\n", plain); } + +const GzipDirClose = struct { + var closes: usize = 0; + var errno: linux.E = .SUCCESS; + + fn arm(e: linux.E) void { + closes = 0; + errno = e; + gzip_ops.* = .{ .close = close }; + } + + /// The archive close stays the real call. Only the directory close is + /// counted and, on the first one, replaced, so this hook can share + /// `gzip_ops.close` with the archive-close tests. + fn close(fd: fsx.fd_t) usize { + const is_dir = if (fsx.fstat(fd)) |st| st.isDir() else |_| false; + const rc = linux.close(fd); + if (!is_dir) return rc; + closes += 1; + if (errno == .SUCCESS or closes > 1) return rc; + return @bitCast(-@as(isize, @backingInt(errno))); + } +}; + +test "dir close: gzip directory close returns EIO and leaves the archive" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "logs-dir-close-eio"); + defer scratch.deinit(); + defer gzip_ops.* = .{}; + const dir = scratch.fd; + const io = std.Io.Threaded.global_single_threaded.io(); + try writeLog(dir, "a.log"); + GzipDirClose.arm(.IO); + var failed_at: GzipStep = .archive; + sys.last_errno = .SUCCESS; + const before = try test_support.fdCount(gpa); + try std.testing.expectError(error.Unexpected, gzipInPlaceAtStep(gpa, io, dir, "a.log", &failed_at)); + try std.testing.expectEqual(GzipStep.directory_sync, failed_at); + try std.testing.expectEqual(linux.E.IO, sys.last_errno); + try std.testing.expectEqual(@as(usize, 1), GzipDirClose.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expectError(error.NotFound, fsx.statAt(dir, "a.log", false)); + try std.testing.expect((try fsx.statAt(dir, "a.log.gz", false)).isReg()); +} + +test "dir close: gzip directory close publishes on EINTR" { + const gpa = std.testing.allocator; + const scratch = try test_support.ScratchDir.init(gpa, "logs-dir-close-eintr"); + defer scratch.deinit(); + defer gzip_ops.* = .{}; + const dir = scratch.fd; + const io = std.Io.Threaded.global_single_threaded.io(); + try writeLog(dir, "a.log"); + GzipDirClose.arm(.INTR); + var failed_at: GzipStep = .archive; + const before = try test_support.fdCount(gpa); + try gzipInPlaceAtStep(gpa, io, dir, "a.log", &failed_at); + try std.testing.expectEqual(@as(usize, 1), GzipDirClose.closes); + try std.testing.expectEqual(before, try test_support.fdCount(gpa)); + try std.testing.expectError(error.NotFound, fsx.statAt(dir, "a.log", false)); + try std.testing.expect((try fsx.statAt(dir, "a.log.gz", false)).isReg()); +}