Files and syncing¶
A file on a disk is only as safe as the bytes the operating system has put there. A recorder must know what a power failure can take, and that no second program writes the same file. How does a writer make a file durable, and how much may a crash cost? The examples use the drive's recording, whose host loses power at minute 37 (When the power fails).
Opening a file¶
Everything that names a path lives in the crate ww_tape_fs, so ww_tape itself builds without a file system. Its
module writer opens a TapeWriter on a path in one of four ways:
| Call | What it opens |
|---|---|
writer::create |
a new file, under its final name from the start |
writer::append |
an existing file, with a new piece after the last one, or a new file |
writer::resume |
the unclosed piece of a file, after a crash (Resuming the file) |
writer::cut |
the next piece of a chain in a new file (Pieces and chains) |
A recorder starts with writer::create and its sync policy. A host program usually also gives the writer its
clock, which decides when a time interval is up:
let mut writer =
ww_tape_fs::writer::create(&path, SyncPolicy::Interval(Duration::from_secs(1)))?;
writer.set_clock(ClockRef::new(clock.clone())); // the system's clock unless set
writer::create never empties a file. It refuses a NAME that exists, closed, unclosed or empty
(FsError::Exists). Reopen such a piece with writer::resume, or remove it. The sink syncs the new
file and its directory at once, so the name cannot vanish in a crash.
An error states the step, the file and the kind of failure in its first line. For example: opening a writer to append:
/data/x.wwt: locked by another writer. A log line of that text alone says what went wrong. An error of the operating
system, such as a full disk, is the source of that first error and is not repeated in its text.
One writer per file¶
Two writers appending to one file would interleave their blocks into a file that reads as damaged. A file sink
therefore holds a lock on the open file itself. A second writer of the same file is refused with
FsError::Locked, whether it runs in the same process or another:
let options = writer.options();
let second = ww_tape_fs::writer::resume(&path, options);
assert!(matches!(
second,
Err(WriteError::Sink {
error: FsError::Locked(_),
..
})
));
The kernel keeps the lock: flock on unix, and on Windows an open that lets no second writer in. A reader opens
and closes the file as it likes and never releases the lock by doing so. Nothing sits beside the file, so a piece
copied or moved loses nothing.
The kernel releases the lock when the writer's process ends, so a crash leaves no stale lock behind. A child process forked by the writer's process holds no lock either. Locks gives the rules for links, devices and each system.
A network or user-space file system, such as NFS, SMB or sshfs, may not keep the lock. The sink still writes there,
but FileSink::warning returns a FsWarning that names the file system. The application shows it to its user.
A file on a read-only mount takes no writer: each step that meets the refusal fails with FsError::ReadOnly and the
path. Read such a file with FileSource, which opens it for reading only and takes no lock.
How often to sync¶
An operating system keeps written bytes in memory for a while before it puts them on the disk. A power failure loses whatever it has not put there yet. The writer asks for the bytes to go to the disk, a sync, by its sync policy:
SyncPolicy |
The writer syncs |
|---|---|
SyncPolicy::Interval, 1 s by default |
when blocks wait and the last sync is that long ago |
SyncPolicy::EveryBlocks |
after every n blocks |
SyncPolicy::None |
only at the close |
The drive's crash shows what each policy costs. The example writes the hour four times, once per policy, and counts what was not synced when the power failed at minute 37:
| Policy | Syncs | Bytes not synced | Whole blocks not synced | Of the run |
|---|---|---|---|---|
Interval(1 s) |
2223 | 30866 | 3 | 1.000 s |
EveryBlocks(1) |
8526 | 1263 | 0 | 0.333 s |
EveryBlocks(256) |
36 | 622577 | 75 | 20.000 s |
None |
4 | 13423184 | 1611 | 420.000 s |
ww_tape_figures from the drive's first two
minutes at full rate.A sync after every block loses only the torn block, the 1263 bytes a resume cuts off. It pays with about 8530 waits for the disk. The default loses the last second, three whole blocks, with 2223 syncs. Without syncs, the crash may lose all of piece 2: 420 s of the run. A recorder of a slow, precious stream syncs after every block; one of a fast stream keeps the default.
A quiet input¶
SyncPolicy::Interval acts only when a block arrives. A log line written just before the input goes quiet would wait
unsynced until the next block. A producer whose input may stop for a while therefore calls TapeWriter::tick now and
then:
clock.0.fetch_add(2_000, Ordering::SeqCst); // the input is quiet
writer.tick()?; // the interval is up: the waiting blocks are synced
tick syncs the waiting blocks once the interval is up, even when no block comes. With IndexPolicy::interval set,
it also places a checkpoint when that interval is up. In an aligned file, that
checkpoint waits for the gap before the next chunk's payload. TapeWriter::sync syncs at once.
The writer's clock¶
The writer reads time only through its clock, set by WriterOptions::clock or TapeWriter::set_clock. With the
standard library, the default is the system's monotonic clock, ClockRef::SYSTEM. Without it, the default is
ClockRef::NONE: no interval is ever due, and only the block and byte limits apply. Firmware passes its own
clock::Clock, and a test passes one it moves by hand.
Time decides only when the writer syncs, places a checkpoint or cuts. No reading of the clock goes into a block. The
drive's recorder sets ClockRef::NONE, so its bytes follow from its calls alone.
A failed write ends the file¶
A failed write or sync ends the file. The writer reports the failure and refuses every later write
(WriteError::Failed). It never retries: after a failed fsync, Linux may drop the pages it could not write, and a
second fsync then succeeds without them.
Writing so a crash costs little¶
A file sink writes the way databases write their logs. The bytes before the last sync are whole, because the writer only appends and never rewrites a byte. The bytes tell whether the file was closed: a closed piece ends in a close and a tail. And the close is written so that a whole close never names bytes that missed the disk.
The close¶
TapeWriter::close ends the piece in four steps:
- It places the deferred blocks still waiting.
- It writes the final index and syncs the file.
- It writes the close, padded so that the piece ends on a 4 KiB boundary, then the tail.
- It syncs the file again.
The two syncs hold whatever the sync policy. A disk may write pages out of order, so a crash could leave a whole close behind blocks that never reached the disk. The sync in step 2 rules that out: a close found whole names only bytes that were on the disk before it. A file without a whole close and tail at its end was never closed.
Appending to a closed file¶
writer::append opens a closed file again and adds a new piece after the last one, in a new session. The pieces
before stay as they were, to the byte:
let mut writer = ww_tape_fs::writer::append(&path, SyncPolicy::default())?;
writer.write_block(defs, &records(writer.next_id(), 2))?;
let again = writer.close()?; // a second piece in the same file
The file then holds two pieces, each read alone. A resume differs: it writes on in the last piece, after its close, and the next close names the one before (Closing more than once).
TapeWriter.pub struct TapeWriter<S: TapeSink>
Appends blocks to a TapeSink, a file by default, see the module docs.
pub fn create(
path: &Path,
policy: SyncPolicy,
) -> Result<TapeWriter<FileSink>, WriteError<FsError>> {
let sink = FileSink::create(path).map_err(sink_err("creating a writer"))?;
Ok(TapeWriter::create_on(sink, policy))
}
A new file at path, created exclusively under its final name; fails if path is there (FileSink::create).
Exists(PathBuf),
A new file that is already there, closed, unclosed or empty.
pub fn resume(
path: &Path,
options: WriterOptions,
) -> Result<(TapeWriter<FileSink>, Resumed), WriteError<FsError>>
Reopen the piece path to write on, see TapeWriter::resume_on.
Locked(PathBuf),
Another writer holds the file: one writer per file (ww_tape::sink).
TapeReader.pub fn warning(&self) -> Option<&FsWarning> {
self.warning.as_ref()
}
Set when the file is on a network or user-space file system, where the lock may not keep a second writer out: the application shows it. Writing goes on.
pub struct FsWarning {
path: PathBuf,
fs: SharedFs,
}
A file sink's file is on a SharedFs, where its lock and syncs may not hold.
ReadOnly(PathBuf),
The file system of path takes no writes (io::ErrorKind::ReadOnlyFilesystem): a read-only mount or medium.
Read the file with crate::FileSource instead.
pub struct FileSource {
file: File,
path: PathBuf,
}
A file read by positional reads, a closed piece or any tape: the ByteSource of a file for a TapeReader.
Interval(Duration),
When blocks are waiting and the last sync is this long ago, at a block or at TapeWriter::tick.
pub fn tick(&mut self) -> Result<(), WriteError<S::Error>>
Sync now if blocks wait and the interval of SyncPolicy::Interval is up; call it when no blocks come.
pub interval: Option<core::time::Duration>,
Also when blocks wait unlisted and the previous checkpoint is this long ago, at a block or a writer's tick; None by default, since a checkpoint placed by time makes the bytes depend on it.
pub fn sync(&mut self) -> Result<(), WriteError<S::Error>>
Sync the data written so far to the disk.
pub clock: ClockRef,
[TapeWriter::set_clock]: when intervals are up (the system clock with std).
pub fn set_clock(&mut self, clock: ClockRef) {
self.last_sync = clock.now_ms();
self.last_checkpoint = self.last_sync;
self.clock = clock;
}
Read time from clock from now on (ClockRef); the intervals start again at its reading now.
pub const SYSTEM: Self = Self(Source::System);
The system clock (SystemClock), the default with std.
pub const NONE: Self = Self(Source::None);
No clock: interval rules are off.
pub trait Clock: Send + Sync {
/// Milliseconds since the clock's origin.
fn now_ms(&self) -> u64;
}
A source of milliseconds, from an origin the clock picks, that never decrease.
Failed,
An earlier write or sync failed (said then); the file takes no more blocks.
pub fn close(self) -> Result<Closed, WriteError<S::Error>> {
self.close_as(CloseReason::Closed)
}
Close the piece (CloseReason::Closed) and sync it.
pub fn append(
path: &Path,
policy: SyncPolicy,
) -> Result<TapeWriter<FileSink>, WriteError<FsError>> {
let sink = FileSink::append(path).map_err(sink_err("opening a writer to append"))?;
TapeWriter::append_on(sink, policy)
}
Append to the file at path in place, created if it isn't there, see TapeWriter::append_on.
pub fn cut(
writer: TapeWriter<FileSink>,
defs: &Definitions,
next_path: &Path,
) -> Result<(Closed, TapeWriter<FileSink>), CutError<FileSink>> {
writer.cut_with(defs, &mut FilePieces::file(next_path), &0)
}
End the piece writer writes by a cut and start the next piece of the chain in a new file at next_path.
pub enum SyncPolicy {
/// Only at the end: a crash may lose everything the OS hadn't written yet.
None,
/// After every N blocks.
EveryBlocks(u32),
/// When blocks are waiting and the last sync is this long ago, at a block or at [TapeWriter::tick].
Interval(Duration),
}
When a TapeWriter syncs the data to the disk, besides at TapeWriter::close.
EveryBlocks(u32),
After every N blocks.
None,
Only at the end: a crash may lose everything the OS hadn't written yet.