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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ the entry and its hash.
| `state` | private files in a shared directory: trusted only when the open file is a regular file of this user with one link and no group or other bits, a lock trusted the same way, atomic 0600 writes; `RootLock`, a flock gate plus a POSIX record lock on a sidecar, with a deadline read from the clock. The gate and the sidecar must each be a regular file of this user with one link |
| `json` | a JSON reader with Python's two string encodings (surrogateescape text, one byte per code point), Python values, and `json.dumps(indent=N, sort_keys=True)` byte for byte, float repr included |
| `pytext` | byte strings as Python text: the surrogateescape character, the 'replace' decoder, str.isspace, strip and split, shlex.quote |
| `atomic` | `atomic_write`: replace a file only after its bytes, owner, mode and every ACL form (GPFS NFSv4, NFSv4, POSIX access) are durable and read back; fault points before write, fsync and rename |
| `atomic` | `atomic_write`: replace a file only after its bytes, owner, mode and every ACL form (GPFS NFSv4, NFSv4, POSIX access) are durable and read back, and the temporary file has been closed; fault points before write, fsync and rename |
| `syslog` | events to a collector: a `unix:`, `journal:`, `udp:` or `tcp:` target, RFC 5424 and native journald framing for the `Identity` the caller names, and `send`, the transport alone, with a timeout; nothing here fails the caller |
| `cli` | messages to stdout and stderr that ignore a closed stream, exit code 2 for a refused invocation, the version line |

Expand Down
1 change: 1 addition & 0 deletions changelog.d/+atomic-write-close.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`atomic.atomicWrite` and `atomic.atomicWriteAt` sync and close the temporary file before renaming it over the destination. A failed close is returned as `sys.Error`, the destination is left as it was, and the temporary file is removed. `atomicWrite` puts that errno in `why` with no path, as it does for a failed write or fsync. Before this change, `atomicWrite` ignored the close, and `atomicWriteAt` closed only after the rename and ignored the result. A write that the Network File System (NFS) reported lost at the close then replaced the destination and was returned as success. A close that `EINTR` interrupts is not retried and is not an error, as `sys.result` treats `EINTR`. The call is replaceable through `atomic.ops.close` in the same builds as the other `atomic.ops` calls.
6 changes: 4 additions & 2 deletions docs/orgmode/howto/replace-a-file-keeping-its-acls.org
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
* Replace a file and keep its access control lists

Use this when a tool rewrites a file whose owner, group, mode or access control lists (ACLs) decide who may read it, such as a module file under =/project/climate= that the project's members read through an ACL.
[[zig:zig_common.atomic.atomicWrite]] writes the new bytes to a temporary file beside the old one, gives it the old file's owner, group, mode and ACLs, reads them back, and only then renames it over the old file.
[[zig:zig_common.atomic.atomicWrite]] writes the new bytes to a temporary file beside the old one, gives it the old file's owner, group, mode and ACLs, reads them back, syncs and closes the temporary file, and renames it over the old file only when that close succeeds.
A close that =EINTR= interrupts is not an error and is not retried: Linux has already freed the descriptor, and the sync before the close has flushed the bytes.
[[zig:zig_common.atomic.atomicWriteAt]] closes the same way before its rename.
A reader sees the old file or the new one, never a part of either, and never the new bytes with other permissions.
[[file:../explanation/descriptor-checks.org][Checks on the descriptor, not the path]] says why each check is made on an open file.

Expand Down Expand Up @@ -38,7 +40,7 @@ A reader sees the old file or the new one, never a part of either, and never the
};
#+end_src

=why.msg= includes the filename or filenames of an operating-system error. If a failure happened before it could be filled, [[zig:zig_common.atomic.describe]] supplies text such as =[Errno 12] Cannot allocate memory=.
=why.msg= carries the text of an operating-system error. When the failing call names a path, the text includes that filename, or both filenames of a rename. A failed write, sync or close of the open temporary file names no path. If a failure happened before the text could be filled, [[zig:zig_common.atomic.describe]] supplies text such as =[Errno 12] Cannot allocate memory=.

3. To give the new file the access of another file, such as a file prepared beside the live one it is to replace, name that file in [[zig:zig_common.atomic.WriteOptions]]:

Expand Down
98 changes: 70 additions & 28 deletions src/atomic.zig
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! Same-directory replacement of a file whose access metadata must survive:
//! the bytes, owner, mode and every listed ACL form are written to a
//! temporary file, read back, made durable, and only then renamed over the
//! destination. The ACL forms are the GPFS native NFSv4 ACL, the generic
//! NFSv4 ACL and the POSIX access ACL, most native first; a filesystem may
//! expose one ACL through several of them.
//! temporary file, read back, made durable, closed, and only then renamed
//! over the destination. The ACL forms are the GPFS native NFSv4 ACL, the
//! generic NFSv4 ACL and the POSIX access ACL, most native first; a
//! filesystem may expose one ACL through several of them.
const std = @import("std");
const builtin = @import("builtin");
const linux = std.os.linux;
Expand All @@ -22,7 +22,8 @@ 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.
/// applies an inherited ACL. `close` is that temporary file's close, before
/// the rename; the caller does not retry it.
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,
Expand All @@ -31,6 +32,7 @@ pub const Ops = struct {
fchmod: *const fn (fd: sys.fd_t, mode: u32) usize = realChmod,
fchown: *const fn (fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize = realChown,
fsync: *const fn (fd: sys.fd_t) usize = realFsync,
close: *const fn (fd: sys.fd_t) usize = realClose,
openat: *const fn (dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize = realOpenat,
write: *const fn (fd: sys.fd_t, bytes: []const u8) usize = realWrite,
renameat: *const fn (old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize = realRenameat,
Expand Down Expand Up @@ -70,6 +72,9 @@ fn realChown(fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize {
fn realFsync(fd: sys.fd_t) usize {
return linux.fsync(fd);
}
fn realClose(fd: sys.fd_t) usize {
return linux.close(fd);
}
fn realOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize {
return linux.openat(dir, path, flags, mode);
}
Expand Down Expand Up @@ -108,6 +113,22 @@ fn writeTemp(fd: sys.fd_t, bytes: []const u8) sys.Error!void {
}
}

/// Close the temporary file once. EINTR is not retried, as Linux has
/// freed the descriptor, and is not an error, as `sys.result` treats
/// EINTR. Any other errno is returned with `sys.last_errno` set.
fn closeTemp(fd: sys.fd_t) sys.Error!void {
_ = try sys.result(ops.close(fd));
}

/// Close a temporary file whose result is not the one being returned.
/// Linux frees the descriptor whatever close reports, so the result is
/// ignored, and `sys.last_errno` stays the errno of the failure in hand.
fn closeDiscarded(fd: sys.fd_t) void {
const saved = sys.last_errno;
defer sys.last_errno = saved;
_ = ops.close(fd);
}

fn renameTemp(old_path: []const u8, new_path: []const u8) sys.Error!void {
var za: [sys.path_max:0]u8 = undefined;
var zb: [sys.path_max:0]u8 = undefined;
Expand Down Expand Up @@ -562,13 +583,21 @@ pub const WriteOptions = struct {
};

/// atomic_write: replace `path` only after its bytes and access metadata
/// are durable. An existing file keeps its owner, mode and ACL forms,
/// including the absence of one; `metadata_from` names another file whose
/// metadata to apply. Fault 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. Everything it
/// allocates from `a` is freed before it returns, except the failure message
/// in `why`. Call `why.deinit(a)` after any error.
/// are durable. The temporary file is synced and closed before the rename.
/// A failed close is reported the way a failed write or fsync is, with
/// no path in the message; the temporary file is removed and the
/// destination is left as it was. The descriptor is closed once on every
/// path. A close that EINTR interrupts is not retried, as Linux has freed
/// the descriptor, and is not an error, as `sys.result` treats EINTR; the
/// fsync before it has already flushed the bytes. An existing file keeps
/// its owner, mode and ACL forms, including the absence of one;
/// `metadata_from` names another file whose metadata to apply. Fault
/// 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.
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 ".";
Expand Down Expand Up @@ -608,30 +637,34 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write
const created = fsx.fstat(fd) catch |err| {
// os.fstat names no path. Record that before the cleanup calls.
const failed = failOs(a, why, err, null, null);
sys.close(fd);
// Created above with O_EXCL, so it is this call's file. A failed
// cleanup must not replace the errno the message was built from.
closeDiscarded(fd);
const saved = sys.last_errno;
defer sys.last_errno = saved;
sys.unlinkat(fsx.cwd, tmp, 0) catch {};
return failed;
};
ops.created(fd);
var open = true;
var renamed = false;
errdefer if (!renamed) discard(tmp, created);
defer if (open) closeDiscarded(fd);
writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null);
{
defer sys.close(fd);
writeTemp(fd, data) catch |err| return failOs(a, why, err, null, null);
var inner: Why = .{};
defer inner.deinit(a);
restoreMetadata(a, fd, metadata, mode, &inner) catch |err| return refuse(a, why, "cannot preserve access metadata for {s}: {s}", .{ path, if (err == error.Refused) inner.msg else describe(err) });
{
const step = try a.print("{s}.fsync", .{opts.step});
defer a.free(step);
if (opts.faults.fails(step)) return injected(a, why, step);
}
_ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null);
}
{
const step = try a.print("{s}.fsync", .{opts.step});
defer a.free(step);
if (opts.faults.fails(step)) return injected(a, why, step);
}
_ = op(ops.fsync, .{fd}) catch |err| return failOs(a, why, err, null, null);
// Once, before the rename. A later failure must not close again.
open = false;
closeTemp(fd) catch |err| return failOs(a, why, err, null, null);
if (metadata) |m| {
var inner: Why = .{};
defer inner.deinit(a);
Expand All @@ -655,12 +688,17 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write
/// 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.
/// bytes go to a temporary file in the same directory, synced and
/// closed, and only then renamed over the destination. A failed write,
/// fchmod, fsync or close is returned with `sys.last_errno` set to its
/// errno; the destination is left as it was and the temporary file is
/// removed. A write lost on NFS may be reported only by the close. The
/// descriptor is closed once on every path. A close that EINTR
/// interrupts is not retried, as Linux has freed the descriptor, and is
/// not an error, as `sys.result` treats EINTR; the fsync before it has
/// already flushed the bytes. Shares atomicWrite's write, sync, close
/// 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;
Expand All @@ -671,9 +709,10 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons
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 open = true;
var done = false;
defer {
sys.close(fd);
if (open) closeDiscarded(fd);
if (!done) {
// The temporary name may already be gone. That failure is not
// the call the caller is reporting.
Expand All @@ -687,6 +726,9 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons
_ = try op(ops.fchmod, .{ fd, mode });
try writeTemp(fd, data);
_ = try op(ops.fsync, .{fd});
// Once, before the rename. A later failure must not close again.
open = false;
try closeTemp(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;
Expand Down
Loading
Loading