diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a36ae2c8..7561ebfd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,3 +21,19 @@ jobs: - uses: Swatinem/rust-cache@v2 - run: cargo clippy --workspace --all-targets --release -- -D warnings - run: cargo test --release --workspace --no-fail-fast + + windows: + runs-on: windows-latest + timeout-minutes: 90 + env: + RUST_BACKTRACE: 1 + steps: + - run: git config --global core.autocrlf false + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.92.0 + components: clippy + - uses: Swatinem/rust-cache@v2 + - run: cargo clippy --workspace --all-targets --release -- -D warnings + - run: cargo test --release -p ferro --no-fail-fast diff --git a/Cargo.lock b/Cargo.lock index 9bc0926c..e655a2a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -414,6 +414,7 @@ dependencies = [ "quick_cache", "tempfile", "thiserror", + "windows-sys", "xxhash-rust", ] diff --git a/DESIGN.md b/DESIGN.md index 7348d68c..eb64f5c5 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -17,6 +17,7 @@ of `T`, and all earlier versions stay readable. and `history_of_range`. - `watch.rs`: `Watcher`, `Closer` and the per-branch feed behind them. - `reclaim.rs`: the copy into a new generation, which `Db::compact` and `admin::compact` share. +- `platform.rs`: the file calls that differ between Unix and Windows, described under Windows. - `sync.rs`: `Have`, `Bundle`, and `Db::pull`, `push` and `receive`, which copy a branch between files. ## Objects and links @@ -642,7 +643,8 @@ itself that it reached the disk whole. A commit does this: In `Durability::Fsync` the superblock is written only after its frame is durable, so it anchors itself and never names anything a crash can lose, and the next fdatasync carries it to disk. A crash -leaves it at most one sync behind. +leaves it at most one sync behind. On Windows every fdatasync here is a `FlushFileBuffers`, as +described under Windows. Open picks the valid slot with the highest sequence and scans forward from its anchor. A frame counts only if its magic, sequence (the previous one plus 1), end offset and check are all right, @@ -857,9 +859,9 @@ voluntary switch with no watchers and one with 8 or 32. A `Snapshot` keeps its version readable for as long as it is held, even past pruning, and so does any `Map` or `Table` cloned from it, and a `Log` or `History` handle. All of them hold the `Store`, and so the open file, but not the writer lock. The lock is a `flock` on the writer's file -descriptor, and closing a writer's store, when the last `Db` handle drops or a cycle retires a -generation, truncates the reservation and then unlocks, in that order, so a new writer can open while -they live. They read what they read before. The new writer's open truncates only past the last +descriptor, or on Windows a one-byte `LockFileEx` range on its handle, and closing a writer's +store, when the last `Db` handle drops or a cycle retires a generation, truncates the reservation +and then unlocks, in that order, so a new writer can open while they live. They read what they read before. The new writer's open truncates only past the last valid frame, and every published object lies before it. It appends after that, and a cycle writes a new file and renames it over the path, so the old inode stays whole for whoever holds it. A closed store writes nothing more, and a second close does nothing, so it never truncates under the new @@ -2166,8 +2168,8 @@ is larger, so the copying stays proportional to what was written. 3. Sync, with no lock, so the pause does not pay for it. 4. Swap, under the `tip` mutex. This is the only pause. Wait for queued commits, copy what is left, write both superblock slots and sync. Open the new file, which takes its writer lock, and read - every branch's tip and root from it. Rename it over the old one, sync the directory, and rebind - every branch. + every branch's tip and root from it. Rename it over the old one, sync the directory (on Windows, + flush the renamed file), and rebind every branch. 5. Retire, with no lock. Clear the old generation's cache. Its file goes when the last handle does. The new file continues the frame sequence, so group commit tickets stay in order. It has no frames @@ -2211,8 +2213,8 @@ with `Error::StalePointer` if it is not there. A pointer read back from the curr fine, because the copy rewrote it. One held in memory across a cycle is refused. A read-only handle keeps its view, in the old file if need be, and `refresh` notices that the path -names a new inode, opens it, and rebinds. Its watchers fire only if the version moved. A process that -never refreshes never fails, and holds the old file open instead. +names a new inode, or a new file index on Windows, opens it, and rebinds. Its watchers fire only if +the version moved. A process that never refreshes never fails, and holds the old file open instead. ### Crashes @@ -2227,8 +2229,9 @@ commits yet. A failed copy, a full disk or a failed rename removes the temp file and reports the error from `Db::compact` or in `Space::last_error`, and commits never notice. A store poisoned while a cycle -copied stays poisoned, because the swap checks first. The new file takes the old one's mode and owner, -and a path through a symlink stays a symlink. +copied stays poisoned, because the swap checks first. On Unix the new file takes the old one's mode +and owner, and a path through a symlink stays a symlink. Windows changes how the rename and its sync +work, but not this order, as described under Windows. ### Measurements @@ -2312,6 +2315,129 @@ in a private copy of the refs and needs no user types. The copy is iterative, be deep as the number of commits. A read-only handle follows it on `refresh` the same way it follows a cycle. +## Windows + +`platform.rs` holds everything the store asks of the OS that differs between Unix and Windows: +positioned reads and writes, the writer lock, the identity of a file, a reader's sync, the directory +sync and the owner of a new generation. The rest of the store is shared. + +### Reads, writes and the lock + +Positioned I/O loops over `seek_read` and `seek_write`, which can return short counts as `pread` +and `pwrite` can. They also move the handle's file pointer, which nothing reads. Windows serialises +requests on a handle opened without `FILE_FLAG_OVERLAPPED`, which `std` never sets, so readers in one +process queue behind each other and behind frame writes, where `pread` lets them run side by side. +That costs throughput, not correctness. + +`File::lock` would shut readers out. On Windows it is `LockFileEx` over the whole file, and Windows +byte-range locks are mandatory: any other handle, in this process or another, fails to read a locked +range with `ERROR_LOCK_VIOLATION`, so no read-only open could read beside a writer. The writer lock is +`LockFileEx` on the single byte at offset 2^62 instead, past the end of any real file, exclusive for +a writer and shared for a reader's scan, and always with `LOCKFILE_FAIL_IMMEDIATELY`, so it behaves +as `try_lock` does. A lock belongs to its handle, so a second writer in the same process conflicts, +as with `flock`, and closing the handle releases it. `Store::close` unlocks explicitly, because +Windows documents that it releases the locks of a process that dies after a delay that "depends upon +available system resources", so a writer that opens right after another was killed can get +`Error::Locked`. + +The identity that `open_locked` checks after locking, and that `refresh` compares to notice a cycle, +is the 64-bit file index from `GetFileInformationByHandle`, read through a handle opened with no +access rights, as `std::fs::metadata` does. `std` keeps the index behind the unstable +`windows_by_handle` feature. On NTFS it is unique on the volume and survives a rename, which is all +both checks need. ReFS ids are 128 bits, and this 64-bit index is not guaranteed to tell two files +apart there. + +### Durability + +`sync_data` and `sync_all` both call `FlushFileBuffers`, which writes the file's cached data and +metadata and then flushes the device's write cache. Every commit therefore pays for an fsync, not an +fdatasync, and the durability point does not move: once the flush returns, the frame survives a +power cut, unless the disk ignores flushes or Windows was told not to send them ("Turn off Windows +write-cache buffer flushing on the device"), the same caveat as a Linux disk mounted without +barriers. + +The flush needs a handle with write access. A read-only open that has to sync the frames a dead +writer left, as described under File format and durability, first checks that the path still names +its file. If it does, the reader opens the path for writing and flushes that. A process that may not +write the file gets `PermissionDenied` there, rather than reading frames that a power cut could +still take back, and opens normally once a writer has recovered the file. If the path names another +file, a cycle replaced this one and there is nothing to sync. A writer lets go of a generation only +after the rename that replaced it is durable, so no crash names it again, unless the writer died or +poisoned between the rename and its flush. Even then, `Durability::Fsync` synced every frame before +the swap, and `Buffered` may lose commits by contract. The reader keeps the old view, and its next +`refresh` moves to the new file. + +The reader used to reopen its own file with `ReOpenFile` instead. That failed with access denied +whenever it had opened the path just before a swap and taken the lock just after the writer retired +the old file, because Windows refuses every new handle to a file that has lost its name. Checking +the path also means the reader never needs write access to a file that is not the database any more. + +Windows has no directory sync. A directory opens only with `FILE_FLAG_BACKUP_SEMANTICS`, and nothing +documents what `FlushFileBuffers` does to one. Where Unix syncs the parent directory, after creating +a file and after a cycle's rename, Windows opens the path for writing and flushes the file it names. +NTFS logs a create or a rename as one transaction in its metadata journal, so after a crash the name +points at the old file or the new one, never at neither. The rename also changed the renamed file's +own record, and ferro relies on a flush of that file committing the journal through the rename. +PostgreSQL's `durable_rename` relies on the same thing, since it too skips the directory on Windows +and flushes the file under its new name, but no Win32 document promises it. With the directory sync +read as this flush, the argument under Reclamation holds unchanged: writers stay paused until it +returns, and a failed flush poisons the store. FAT32 and exFAT keep no journal and are not +supported. + +### Renaming over an open file + +A cycle renames a new file over one that is still open, since the old generation stays open for +every snapshot, `Log` and follower that holds it, and Windows normally refuses that. It works when +two things hold. Every handle on the file must share delete: `std` opens files with +`FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE` unless told otherwise, and ferro never +tells it otherwise. And the rename must use POSIX semantics. `platform::rename` opens the new file +with `DELETE` access and calls `SetFileInformationByHandle(FileRenameInfoEx)` with +`FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS`, which Windows 10 1607 and +later accept where the file system supports it, as NTFS does. Only when that call is refused as +unsupported does it fall back to `std::fs::rename`. That tries `MoveFileExW` first, which an open +target refuses, and today retries with the same POSIX rename, but `std` documents that its choice of +calls may change, so ferro makes the call itself. The name then moves to the new file at once, and +the old file loses its name but stays whole for every handle until the last one closes, as an +unlinked inode does on Unix. Snapshots keep reading the old generation, its space comes back when +the last of them drops, and `refresh` finds a new file index at the path. `admin::compact` renames +the same way. + +An open of the path that races the rename can still fail, which on Unix it cannot. If the lookup +found the old file just as it lost its name, Windows refuses the open with access denied, because +that file is now waiting to be deleted. `canonicalize` opens the path and then asks the handle for +its name, so if the handle reached the old file it fails with not found. Both last only for the +instant of a swap, after which the path names the new file. So on Windows every open of the path, +and the `canonicalize` in `Db::open`, retries those two errors up to 20 times a millisecond apart, +and a real permission error is reported about 20 ms late. CI found this: a reader opening in a loop +beside 60 cycles failed in about one run in two, and a probe saw about one `canonicalize` in 80 +fail and one read-only open in 150. + +If either does not hold, because another program holds the file open without `FILE_SHARE_DELETE` or +the file system has no POSIX rename, the rename fails before anything has changed. The cycle then +fails like any failed rename: the temp file goes, the error lands in `Db::compact` or +`Space::last_error`, commits carry on in the old file, and the next trigger tries again. Nothing is +lost, but the file does not shrink. The cycle is the retry, so the rename does not loop on its own, +which would hold the `tip` mutex and stall commits. + +Two other designs were weighed. Generation-numbered files, with a small file naming the current +one, never rename over an open file and work on any file system, but the path would stop being the +database, so copying or backing up one file would no longer work, and the small file needs its own +atomic, durable update, which is a rename again. Deleting the old file and then renaming the new one +into place needs no POSIX semantics, but a crash between the two leaves no database at the path. + +A new generation keeps the old file's read-only attribute, which is all `set_permissions` carries on +Windows, and takes its ACL from the directory rather than from the old file. The owner is not +copied. + +### Tests + +CI runs the library's tests on `windows-latest`. Tests that interpose libc symbols through `dlsym` +(`fdatasync`, `fsync`, `pread64`, `pwrite64`, `rename`, `clock_gettime`), run a child under `sh` +with `ulimit -f`, kill or abort a child process, or make symlinks or check mode bits are +`#[cfg(unix)]`. The traced crash simulations replay ferro's own writes and run on both. So on Windows +failed syncs, failed renames and process death go unexercised, and as on Unix, power loss was never +tested on hardware. + ## Schema evolution The derive macro writes structs as `(tag, length, payload)` fields, where the tag is a 16-bit diff --git a/README.md b/README.md index 1b3899d6..d58c6dc5 100644 --- a/README.md +++ b/README.md @@ -742,7 +742,13 @@ including caveats about sled, are in `benchmarks/compare/RESULTS.md`. This is an experiment, not a production database. - The file format is not stable and may change without migration. -- It runs on Unix only. +- It runs on Unix and Windows. On Windows the file must be on NTFS: a reclamation cycle renames the + new file over one that snapshots still hold open, which needs POSIX rename semantics, and Windows + cannot sync a directory, so the rename is made durable by flushing the renamed file, which relies + on the NTFS journal. Every sync is a `FlushFileBuffers`, which flushes metadata too, like fsync + rather than fdatasync. Performance on Windows was never measured, and CI skips the tests that + intercept libc calls or kill processes there, so failed syncs and process death are tested on Unix + only. - A single-key commit writes about 3.5 KB at this size, so batch related changes into one commit. Secondary indexes add to that. Without retention the file only grows. - A reclamation cycle copies everything retained, so it needs that much free disk, and reads that diff --git a/ferro-bench/src/bin/delta.rs b/ferro-bench/src/bin/delta.rs index dcad48be..5f16c9f7 100644 --- a/ferro-bench/src/bin/delta.rs +++ b/ferro-bench/src/bin/delta.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; use std::fs::File; -use std::os::unix::fs::FileExt; +use std::io::{Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Instant; @@ -14,8 +14,24 @@ use ferro::{Db, Durability, Map, Options, Ptr, hash_of}; const FRAME_BYTES: usize = 68; +#[cfg(target_os = "linux")] struct Counter(Option); +#[cfg(not(target_os = "linux"))] +struct Counter; + +#[cfg(not(target_os = "linux"))] +impl Counter { + fn instructions() -> Counter { + Counter + } + + fn read(&self) -> u64 { + 0 + } +} + +#[cfg(target_os = "linux")] impl Counter { fn instructions() -> Counter { let mut attr = [0u64; 16]; @@ -40,6 +56,12 @@ impl Counter { } } +#[cfg(not(unix))] +fn cpu_ns() -> u64 { + 0 +} + +#[cfg(unix)] fn cpu_ns() -> u64 { let mut now = libc::timespec { tv_sec: 0, @@ -231,9 +253,10 @@ struct Framed { parts: Parts, } -fn frame_of(file: &File, start: u64, end: u64) -> Framed { +fn frame_of(mut file: &File, start: u64, end: u64) -> Framed { let mut frame = vec![0u8; (end - start) as usize]; - file.read_exact_at(&mut frame, start).unwrap(); + file.seek(SeekFrom::Start(start)).unwrap(); + file.read_exact(&mut frame).unwrap(); let recs = records(&frame, start); let n = recs.len(); assert!(n >= 4, "a commit frame holds at least four records"); diff --git a/ferro-bench/src/bin/tables.rs b/ferro-bench/src/bin/tables.rs index 74cb5a92..d7f452b6 100644 --- a/ferro-bench/src/bin/tables.rs +++ b/ferro-bench/src/bin/tables.rs @@ -7,8 +7,24 @@ use booking::seed::{Plan, seed}; use booking::{BookingError, Hotels, HoldRequest, Reservations, Why}; use ferro::{Db, Durability, Options}; +#[cfg(target_os = "linux")] struct Counter(Option); +#[cfg(not(target_os = "linux"))] +struct Counter; + +#[cfg(not(target_os = "linux"))] +impl Counter { + fn instructions() -> Counter { + Counter + } + + fn read(&self) -> u64 { + 0 + } +} + +#[cfg(target_os = "linux")] impl Counter { fn instructions() -> Counter { let mut attr = [0u64; 16]; @@ -33,6 +49,12 @@ impl Counter { } } +#[cfg(not(unix))] +fn cpu_ns() -> u64 { + 0 +} + +#[cfg(unix)] fn cpu_ns() -> u64 { let mut now = libc::timespec { tv_sec: 0, diff --git a/ferro/Cargo.toml b/ferro/Cargo.toml index 258b0e44..f31542e2 100644 --- a/ferro/Cargo.toml +++ b/ferro/Cargo.toml @@ -13,6 +13,9 @@ quick_cache = "0.6" thiserror = "2" xxhash-rust = { version = "0.8", features = ["xxh3"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_WindowsProgramming"] } + [dev-dependencies] parking_lot = "0.12" proptest = "1" diff --git a/ferro/src/admin.rs b/ferro/src/admin.rs index f76fe47d..f147156b 100644 --- a/ferro/src/admin.rs +++ b/ferro/src/admin.rs @@ -9,7 +9,7 @@ use crate::db::{Commit, Refs}; use crate::error::{Error, Result}; use crate::log::Closures; use crate::map::Map; -use crate::reclaim::{Copier, Roots, sibling, sync_parent}; +use crate::reclaim::{Copier, Roots, rename, sibling, sync_parent}; pub use crate::reclaim::{Compacted, Reclaim, Space}; use crate::store::{Store, StoreOptions}; @@ -258,7 +258,7 @@ pub fn compact(path: impl AsRef, keep: Keep) -> Result { let refs = load_refs(&store, Some(head))?; let temp = sibling(path); let result = write_copy(&store, &refs, keep, &temp, before_bytes).and_then(|mut report| { - fs::rename(&temp, path)?; + rename(&temp, path)?; sync_parent(path)?; report.before_bytes = before_bytes; Ok(report) diff --git a/ferro/src/db.rs b/ferro/src/db.rs index 9f06c29d..f36baac8 100644 --- a/ferro/src/db.rs +++ b/ferro/src/db.rs @@ -1,7 +1,6 @@ use std::cell::OnceCell; use std::collections::{HashMap, VecDeque}; use std::fmt; -use std::fs; use std::future::Future; use std::mem; use std::ops::{Deref, DerefMut, RangeBounds}; @@ -24,7 +23,8 @@ use crate::graph::{self, Start}; use crate::history::History; use crate::log::{Chain, Entry, Log, Merged, Node}; use crate::map::Map; -use crate::reclaim::{Compacted, Copier, Reclaim, Space, sibling, sync_parent}; +use crate::platform::canonicalize; +use crate::reclaim::{Compacted, Copier, Reclaim, Space, rename, sibling, sync_parent}; use crate::store::{Durability, Frame, Op, Retired, Store, StoreOptions, Trace, Txn}; use crate::watch::{Feed, Filter, Notice, Watcher}; @@ -983,7 +983,7 @@ impl Options { base: AtomicU64::new(store.basis().bytes), ..Signal::default() }); - let file = fs::canonicalize(path.as_ref())?; + let file = canonicalize(path.as_ref())?; let mut options = options; let shared = Arc::new(Shared { store: ArcSwap::from_pointee(store), @@ -1835,7 +1835,7 @@ impl Shared { let found = refs.try_get(&branch.name)?; states.push((branch, Arc::new(self.state_of(fresh, found.as_deref())?))); } - fs::rename(temp, &self.file)?; + rename(temp, &self.file)?; fresh.trace_rename(); if let Err(error) = sync_parent(&self.file) { old.poison(); diff --git a/ferro/src/lib.rs b/ferro/src/lib.rs index a10fa977..ee026f89 100644 --- a/ferro/src/lib.rs +++ b/ferro/src/lib.rs @@ -9,6 +9,7 @@ pub mod history; pub mod list; pub mod log; pub mod map; +mod platform; mod reclaim; pub mod set; pub mod store; diff --git a/ferro/src/platform.rs b/ferro/src/platform.rs new file mode 100644 index 00000000..ba8cd977 --- /dev/null +++ b/ferro/src/platform.rs @@ -0,0 +1,294 @@ +#[cfg(unix)] +mod imp { + use std::fs::{File, Metadata, OpenOptions, TryLockError}; + use std::io; + use std::os::unix::fs::{MetadataExt, fchown}; + use std::path::{Path, PathBuf}; + + pub(crate) use std::os::unix::fs::FileExt; + + pub(crate) fn file_id(file: &File) -> io::Result { + Ok(file.metadata()?.ino()) + } + + pub(crate) fn path_id(path: &Path) -> io::Result { + Ok(std::fs::metadata(path)?.ino()) + } + + pub(crate) fn open(options: &OpenOptions, path: &Path) -> io::Result { + options.open(path) + } + + pub(crate) fn canonicalize(path: &Path) -> io::Result { + std::fs::canonicalize(path) + } + + pub(crate) fn try_lock(file: &File) -> Result<(), TryLockError> { + file.try_lock() + } + + pub(crate) fn try_lock_shared(file: &File) -> Result<(), TryLockError> { + file.try_lock_shared() + } + + pub(crate) fn unlock(file: &File) -> io::Result<()> { + file.unlock() + } + + pub(crate) fn sync_reader(file: &File, _path: &Path) -> io::Result<()> { + file.sync_data() + } + + pub(crate) fn rename(from: &Path, to: &Path) -> io::Result<()> { + std::fs::rename(from, to) + } + + pub(crate) fn sync_parent(path: &Path) -> io::Result<()> { + match path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + Some(parent) => File::open(parent)?.sync_all(), + None => Ok(()), + } + } + + pub(crate) fn copy_owner(file: &File, source: &Metadata) { + let _ = fchown(file, Some(source.uid()), Some(source.gid())); + } +} + +#[cfg(windows)] +mod imp { + use std::fs::{File, Metadata, OpenOptions, TryLockError}; + use std::io::{self, ErrorKind}; + use std::os::windows::ffi::OsStrExt; + use std::os::windows::fs::{FileExt as _, OpenOptionsExt}; + use std::os::windows::io::AsRawHandle; + use std::path::{Path, PathBuf}; + use std::thread; + use std::time::Duration; + use std::{mem, ptr}; + + use windows_sys::Win32::Foundation::{ + ERROR_ACCESS_DENIED, ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_LOCK_VIOLATION, + ERROR_NOT_LOCKED, ERROR_NOT_SUPPORTED, + }; + use windows_sys::Win32::Storage::FileSystem::{ + BY_HANDLE_FILE_INFORMATION, DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_RENAME_INFO, + FileRenameInfoEx, GetFileInformationByHandle, LOCK_FILE_FLAGS, LOCKFILE_EXCLUSIVE_LOCK, + LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, SYNCHRONIZE, SetFileInformationByHandle, + UnlockFileEx, + }; + use windows_sys::Win32::System::IO::{OVERLAPPED, OVERLAPPED_0, OVERLAPPED_0_0}; + use windows_sys::Win32::System::WindowsProgramming::{ + FILE_RENAME_FLAG_POSIX_SEMANTICS, FILE_RENAME_FLAG_REPLACE_IF_EXISTS, + }; + + const LOCK_AT: u64 = 1 << 62; + const RACE_RETRIES: u32 = 20; + + pub(crate) trait FileExt { + fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()>; + fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()>; + } + + impl FileExt for File { + fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> { + while !buf.is_empty() { + match self.seek_read(buf, offset) { + Ok(0) => { + return Err(io::Error::new( + ErrorKind::UnexpectedEof, + "failed to fill whole buffer", + )); + } + Ok(read) => { + buf = &mut buf[read..]; + offset += read as u64; + } + Err(error) if error.kind() == ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(()) + } + + fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { + while !buf.is_empty() { + match self.seek_write(buf, offset) { + Ok(0) => { + return Err(io::Error::new( + ErrorKind::WriteZero, + "failed to write whole buffer", + )); + } + Ok(written) => { + buf = &buf[written..]; + offset += written as u64; + } + Err(error) if error.kind() == ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(()) + } + } + + pub(crate) fn file_id(file: &File) -> io::Result { + let mut info = BY_HANDLE_FILE_INFORMATION::default(); + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(u64::from(info.nFileIndexHigh) << 32 | u64::from(info.nFileIndexLow)) + } + + pub(crate) fn path_id(path: &Path) -> io::Result { + file_id(&open(OpenOptions::new().access_mode(0), path)?) + } + + fn racing( + lost: impl Fn(&io::Error) -> bool, + mut attempt: impl FnMut() -> io::Result, + ) -> io::Result { + let mut retries = 0; + loop { + match attempt() { + Err(error) if retries < RACE_RETRIES && lost(&error) => { + retries += 1; + thread::sleep(Duration::from_millis(1)); + } + done => return done, + } + } + } + + fn delete_pending(error: &io::Error) -> bool { + error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) + } + + pub(crate) fn open(options: &OpenOptions, path: &Path) -> io::Result { + racing(delete_pending, || options.open(path)) + } + + pub(crate) fn canonicalize(path: &Path) -> io::Result { + racing( + |error| delete_pending(error) || error.kind() == ErrorKind::NotFound, + || std::fs::canonicalize(path), + ) + } + + fn lock_range() -> OVERLAPPED { + OVERLAPPED { + Anonymous: OVERLAPPED_0 { + Anonymous: OVERLAPPED_0_0 { + Offset: LOCK_AT as u32, + OffsetHigh: (LOCK_AT >> 32) as u32, + }, + }, + ..OVERLAPPED::default() + } + } + + fn lock(file: &File, flags: LOCK_FILE_FLAGS) -> Result<(), TryLockError> { + let mut range = lock_range(); + let flags = flags | LOCKFILE_FAIL_IMMEDIATELY; + if unsafe { LockFileEx(file.as_raw_handle(), flags, 0, 1, 0, &mut range) } != 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) { + Err(TryLockError::WouldBlock) + } else { + Err(TryLockError::Error(error)) + } + } + + pub(crate) fn try_lock(file: &File) -> Result<(), TryLockError> { + lock(file, LOCKFILE_EXCLUSIVE_LOCK) + } + + pub(crate) fn try_lock_shared(file: &File) -> Result<(), TryLockError> { + lock(file, 0) + } + + pub(crate) fn unlock(file: &File) -> io::Result<()> { + let mut range = lock_range(); + if unsafe { UnlockFileEx(file.as_raw_handle(), 0, 1, 0, &mut range) } != 0 { + return Ok(()); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_NOT_LOCKED as i32) { + Ok(()) + } else { + Err(error) + } + } + + pub(crate) fn sync_reader(file: &File, path: &Path) -> io::Result<()> { + match file.sync_data() { + Err(error) if error.kind() == ErrorKind::PermissionDenied => {} + synced => return synced, + } + let id = file_id(file)?; + match path_id(path) { + Ok(named) if named == id => open(OpenOptions::new().write(true), path)?.sync_data(), + Err(error) if error.kind() != ErrorKind::NotFound => Err(error), + _ => Ok(()), + } + } + + pub(crate) fn rename(from: &Path, to: &Path) -> io::Result<()> { + match posix_rename(from, to) { + Err(error) + if matches!( + error.raw_os_error().map(|code| code as u32), + Some(ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED | ERROR_INVALID_PARAMETER) + ) => + { + std::fs::rename(from, to) + } + renamed => renamed, + } + } + + fn posix_rename(from: &Path, to: &Path) -> io::Result<()> { + let source = OpenOptions::new() + .access_mode(DELETE | SYNCHRONIZE) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(from)?; + let name: Vec = std::path::absolute(to)? + .as_os_str() + .encode_wide() + .chain([0]) + .collect(); + let at = mem::offset_of!(FILE_RENAME_INFO, FileName); + let size = u32::try_from(at + name.len() * 2) + .map_err(|_| io::Error::from(ErrorKind::InvalidFilename))?; + let mut buffer = vec![0u64; (size as usize).div_ceil(8)]; + let info = buffer.as_mut_ptr().cast::(); + unsafe { + (*info).Anonymous.Flags = + FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS; + (*info).FileNameLength = size - at as u32 - 2; + ptr::copy_nonoverlapping( + name.as_ptr(), + (&raw mut (*info).FileName).cast(), + name.len(), + ); + } + let handle = source.as_raw_handle(); + if unsafe { SetFileInformationByHandle(handle, FileRenameInfoEx, info.cast(), size) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + + pub(crate) fn sync_parent(path: &Path) -> io::Result<()> { + open(OpenOptions::new().write(true), path)?.sync_all() + } + + pub(crate) fn copy_owner(_file: &File, _source: &Metadata) {} +} + +pub(crate) use imp::*; diff --git a/ferro/src/reclaim.rs b/ferro/src/reclaim.rs index 4f34525e..60b549d4 100644 --- a/ferro/src/reclaim.rs +++ b/ferro/src/reclaim.rs @@ -1,6 +1,5 @@ use std::collections::{HashMap, HashSet}; -use std::fs::{self, File, OpenOptions}; -use std::os::unix::fs::{MetadataExt, fchown}; +use std::fs::{self, OpenOptions}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; @@ -9,6 +8,8 @@ use crate::codec::{Data, Encoder, Hash, Object, Ptr, Sink}; use crate::db::Refs; use crate::error::{Error, Result}; use crate::log::{Chain, Closures, Entry}; +use crate::platform::copy_owner; +pub(crate) use crate::platform::{rename, sync_parent}; use crate::store::{Basis, LOG_START, Store, StoreOptions, Traced, append_record, seal}; const FLUSH_BYTES: usize = 1 << 20; @@ -57,13 +58,6 @@ pub(crate) fn sibling(path: &Path) -> PathBuf { PathBuf::from(name) } -pub(crate) fn sync_parent(path: &Path) -> std::io::Result<()> { - match path.parent().filter(|parent| !parent.as_os_str().is_empty()) { - Some(parent) => File::open(parent)?.sync_all(), - None => Ok(()), - } -} - #[derive(Default)] pub(crate) struct Roots { pub(crate) trees: Vec, @@ -259,7 +253,7 @@ impl<'a> Copier<'a> { .open(temp)?; let source = store.metadata()?; file.set_permissions(source.permissions())?; - let _ = fchown(&file, Some(source.uid()), Some(source.gid())); + copy_owner(&file, &source); let file = Traced::new(file, options.trace.clone())?; file.created(); file.set_len(LOG_START)?; diff --git a/ferro/src/store.rs b/ferro/src/store.rs index 42e8e34a..affe8c1a 100644 --- a/ferro/src/store.rs +++ b/ferro/src/store.rs @@ -6,7 +6,6 @@ use std::hash::{BuildHasherDefault, Hasher}; use std::io::ErrorKind; use std::mem; use std::ops::Deref; -use std::os::unix::fs::{FileExt, MetadataExt}; use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock, Weak}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -21,6 +20,7 @@ use xxhash_rust::xxh3::Xxh3; use crate::codec::{ARC_HEADER, Decoder, HASH_BYTES, Hash, Object, Ptr, Sink, Staged, push_varint}; use crate::error::{Error, Result}; use crate::map::SPILL_BYTES; +use crate::platform::{self, FileExt}; use crate::reclaim::sibling; const MAGIC: &[u8; 8] = b"FERRODB3"; @@ -336,9 +336,9 @@ fn recover(file: &File, sb: Super, slot: u64, len: u64) -> Result<(Super, u64)> Ok((tip, slot)) } -fn observe(file: &File, sb: Super, len: u64) -> Result { +fn observe(file: &File, path: &Path, sb: Super, len: u64) -> Result { let settled = sb.settled() && read_frame(file, &sb, len)?.is_none(); - if settled || file.try_lock_shared().is_err() { + if settled || platform::try_lock_shared(file).is_err() { return Ok(sb); } let before = sb.anchor.seq; @@ -348,11 +348,11 @@ fn observe(file: &File, sb: Super, len: u64) -> Result { .and_then(|meta| scan(file, sb.at_anchor(), meta.len())) .and_then(|tip| { if tip.seq != before { - file.sync_data()?; + platform::sync_reader(file, path)?; } Ok(tip) }); - file.unlock()?; + platform::unlock(file)?; scanned } @@ -499,22 +499,16 @@ pub(crate) fn seal(file: &Traced, log_end: u64, head: Ptr, seq: u64, basis: Basi fn open_locked(path: &Path, read_only: bool) -> Result { let mut retries = 0; loop { - let file = OpenOptions::new() - .read(true) - .write(!read_only) - .create(!read_only) - .truncate(false) - .open(path) - .map_err(|error| match error.kind() { - std::io::ErrorKind::NotFound if read_only => { - Error::NoDatabase(path.display().to_string()) - } - _ => error.into(), - })?; + let mut options = OpenOptions::new(); + options.read(true).write(!read_only).create(!read_only).truncate(false); + let file = platform::open(&options, path).map_err(|error| match error.kind() { + std::io::ErrorKind::NotFound if read_only => Error::NoDatabase(path.display().to_string()), + _ => error.into(), + })?; if read_only { return Ok(file); } - match file.try_lock() { + match platform::try_lock(&file) { Ok(()) => {} Err(TryLockError::WouldBlock) if retries == LOCK_RETRIES => return Err(Error::Locked), Err(TryLockError::WouldBlock) => { @@ -524,7 +518,7 @@ fn open_locked(path: &Path, read_only: bool) -> Result { } Err(TryLockError::Error(e)) => return Err(e.into()), } - if std::fs::metadata(path).is_ok_and(|on_disk| on_disk.ino() == file.metadata().map(|m| m.ino()).unwrap_or(0)) { + if platform::path_id(path).is_ok_and(|on_disk| platform::file_id(&file).is_ok_and(|id| id == on_disk)) { return Ok(file); } } @@ -567,7 +561,7 @@ pub(crate) struct Traced { impl Traced { pub(crate) fn new(file: File, trace: Option) -> Result { - let inode = file.metadata()?.ino(); + let inode = platform::file_id(&file)?; Ok(Traced { file, trace, inode }) } @@ -678,7 +672,7 @@ impl Store { ))); } if options.read_only { - (observe(&file, sb, len)?, slot) + (observe(&file, actual, sb, len)?, slot) } else { recover(&file, sb, slot, len)? } @@ -704,9 +698,7 @@ impl Store { file.set_len(LOG_START)?; file.write_all_at(&sb.encode(), 0)?; file.sync_all()?; - if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - File::open(parent)?.sync_all()?; - } + platform::sync_parent(path)?; (sb, 0) } }; @@ -793,7 +785,7 @@ impl Store { pub fn refresh(&self) -> Result> { let mut cursor = self.inner.cursor.lock(); let opened = self.inner.file.metadata()?; - if std::fs::metadata(&self.inner.path)?.ino() != opened.ino() { + if platform::path_id(&self.inner.path)? != self.inner.file.inode { return Err(Error::Replaced); } let len = opened.len(); @@ -1044,7 +1036,7 @@ impl Store { { let _ = inner.file.set_len(end); } - let _ = inner.file.unlock(); + let _ = platform::unlock(&inner.file); } pub fn load(&self, ptr: Ptr) -> Result> { diff --git a/ferro/tests/bulk.rs b/ferro/tests/bulk.rs index f255c0fb..dfac2a7d 100644 --- a/ferro/tests/bulk.rs +++ b/ferro/tests/bulk.rs @@ -2,8 +2,8 @@ mod common; use std::collections::{BTreeMap, BTreeSet}; use std::fs::OpenOptions; +use std::io::{Seek, SeekFrom, Write}; use std::ops::Bound; -use std::os::unix::fs::FileExt; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; @@ -58,9 +58,10 @@ fn remove_range_never_reads_the_removed_subtrees() { let path = dir.path().join("r.ferro"); let n = 200_000; let size = filled(&path, n).size_on_disk(); - let file = OpenOptions::new().write(true).open(&path).unwrap(); + let mut file = OpenOptions::new().write(true).open(&path).unwrap(); let garbage = vec![0xa5u8; (size / 5) as usize]; - file.write_all_at(&garbage, size * 2 / 5).unwrap(); + file.seek(SeekFrom::Start(size * 2 / 5)).unwrap(); + file.write_all(&garbage).unwrap(); drop(file); let db = uncached().open::>(&path).unwrap(); let removed = db diff --git a/ferro/tests/coalesce.rs b/ferro/tests/coalesce.rs index 1d3c700f..7bdd4bb1 100644 --- a/ferro/tests/coalesce.rs +++ b/ferro/tests/coalesce.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::cell::Cell; diff --git a/ferro/tests/fuzzed.rs b/ferro/tests/fuzzed.rs index 79c50a8b..811c3a2e 100644 --- a/ferro/tests/fuzzed.rs +++ b/ferro/tests/fuzzed.rs @@ -1,7 +1,6 @@ use std::fmt::Debug; use std::fs; -use std::io::Read; -use std::os::unix::fs::FileExt; +use std::io::{Read, Seek, SeekFrom, Write}; use std::panic::{self, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -127,13 +126,19 @@ fn read_only() -> Options { Options::new().read_only() } -fn open_handles(path: &Path) -> usize { +#[cfg(target_os = "linux")] +fn closed(path: &Path) -> bool { let real = fs::canonicalize(path).unwrap(); - fs::read_dir("/proc/self/fd") + !fs::read_dir("/proc/self/fd") .unwrap() .flatten() - .filter(|entry| fs::read_link(entry.path()).is_ok_and(|target| target == real)) - .count() + .any(|entry| fs::read_link(entry.path()).is_ok_and(|target| target == real)) +} + +#[cfg(windows)] +fn closed(path: &Path) -> bool { + use std::os::windows::fs::OpenOptionsExt; + fs::OpenOptions::new().read(true).share_mode(0).open(path).is_ok() } fn field(bytes: &[u8], at: usize) -> u64 { @@ -319,13 +324,14 @@ fn common_ancestor_reports_a_damaged_merge_record() { assert!(failures > 0); } +#[cfg(any(target_os = "linux", windows))] #[test] fn admin_reads_close_the_file_when_they_fail() { let (_dir, path) = fixture("info-refs"); corrupt(admin::info(&path)); corrupt(admin::layout(&path, Keep::All)); corrupt(admin::layout(&path, Keep::Last(2))); - assert_eq!(open_handles(&path), 0); + assert!(closed(&path)); } #[test] @@ -693,7 +699,8 @@ fn swapping_in_a_compacted_file_reports_a_damaged_branch_table() { let mut bytes = Vec::new(); (&file).read_to_end(&mut bytes).unwrap(); let at = bytes.windows(4).position(|window| window == b"main").unwrap(); - file.write_all_at(&[bytes[at] ^ 1], at as u64).unwrap(); + (&file).seek(SeekFrom::Start(at as u64)).unwrap(); + (&file).write_all(&[bytes[at] ^ 1]).unwrap(); } }; let db = manual().hook(Hook(Arc::new(hook))).open::(&path).unwrap(); diff --git a/ferro/tests/group_commit.rs b/ferro/tests/group_commit.rs index f873969d..00343cdb 100644 --- a/ferro/tests/group_commit.rs +++ b/ferro/tests/group_commit.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::ffi::{c_char, c_int, c_void}; diff --git a/ferro/tests/poison.rs b/ferro/tests/poison.rs index 64e6d79d..c5d396f4 100644 --- a/ferro/tests/poison.rs +++ b/ferro/tests/poison.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::collections::BTreeMap; diff --git a/ferro/tests/process.rs b/ferro/tests/process.rs index 353a47cd..870c6a69 100644 --- a/ferro/tests/process.rs +++ b/ferro/tests/process.rs @@ -5,7 +5,9 @@ use std::path::Path; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant}; -use common::{Rng, fast}; +#[cfg(unix)] +use common::Rng; +use common::fast; use ferro::{Data, Db, Map, Options}; #[derive(Data, Clone, Debug, Default, PartialEq)] @@ -193,6 +195,7 @@ fn reader_race(role: &str) { } } +#[cfg(unix)] #[test] fn sigkill_during_group_commit_keeps_every_acknowledged_version() { let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); @@ -238,6 +241,7 @@ fn sigkill_during_group_commit_keeps_every_acknowledged_version() { } } +#[cfg(unix)] #[test] fn sigkill_in_a_commit_loop_always_reopens_on_a_committed_version() { let dir = tempfile::tempdir().unwrap(); diff --git a/ferro/tests/reclaim.rs b/ferro/tests/reclaim.rs index 450905f1..928bd932 100644 --- a/ferro/tests/reclaim.rs +++ b/ferro/tests/reclaim.rs @@ -826,6 +826,7 @@ fn a_commit_or_pointer_held_across_a_cycle_cannot_be_written_back() { admin::verify(&path).unwrap(); } +#[cfg(unix)] #[test] fn a_leftover_temp_file_behind_a_symlink_is_cleared_on_open() { let dir = dir(); @@ -888,6 +889,7 @@ fn a_trigger_raised_during_a_cycle_does_not_run_another() { slot.lock().unwrap().take(); } +#[cfg(unix)] #[test] fn a_cycle_keeps_the_mode_of_the_file() { use std::os::unix::fs::PermissionsExt; @@ -900,6 +902,7 @@ fn a_cycle_keeps_the_mode_of_the_file() { assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); } +#[cfg(unix)] #[test] fn a_cycle_through_a_symlink_replaces_the_file_it_names() { let dir = dir(); diff --git a/ferro/tests/reclaim_crash.rs b/ferro/tests/reclaim_crash.rs index a1f17874..752877d8 100644 --- a/ferro/tests/reclaim_crash.rs +++ b/ferro/tests/reclaim_crash.rs @@ -2,7 +2,6 @@ mod common; use std::collections::{BTreeMap, HashMap}; use std::fs; -use std::os::unix::fs::MetadataExt; use std::path::Path; use std::sync::Arc; @@ -76,7 +75,6 @@ fn record(cycles: u64, commits: u64, keys: u64, keep: usize) -> Recording { } let trace: Trace = Arc::new(Mutex::new(Vec::new())); let base = fs::read(&path).unwrap(); - let inode = fs::metadata(&path).unwrap().ino(); let slot: Slot = Arc::new(Mutex::new(None)); let shared: Shared = Arc::new(Mutex::new((rng, models))); let hook = { @@ -104,6 +102,13 @@ fn record(cycles: u64, commits: u64, keys: u64, keep: usize) -> Recording { slot.lock().take(); drop(db); let ops = trace.lock().clone(); + let inode = ops + .iter() + .find_map(|op| match op { + Op::Write(inode, ..) => Some(*inode), + _ => None, + }) + .unwrap(); let models = shared.lock().1.clone(); Recording { base, diff --git a/ferro/tests/reclaim_fault.rs b/ferro/tests/reclaim_fault.rs index 01cfb099..36cc29b1 100644 --- a/ferro/tests/reclaim_fault.rs +++ b/ferro/tests/reclaim_fault.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::cell::Cell; diff --git a/ferro/tests/reclaim_kill.rs b/ferro/tests/reclaim_kill.rs index 1c281497..c8313e85 100644 --- a/ferro/tests/reclaim_kill.rs +++ b/ferro/tests/reclaim_kill.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::collections::BTreeMap; diff --git a/ferro/tests/refresh_fault.rs b/ferro/tests/refresh_fault.rs index 2fff00d8..46b4e5a1 100644 --- a/ferro/tests/refresh_fault.rs +++ b/ferro/tests/refresh_fault.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::cell::Cell; diff --git a/ferro/tests/watch_locks.rs b/ferro/tests/watch_locks.rs index 014d83e9..b2b884ae 100644 --- a/ferro/tests/watch_locks.rs +++ b/ferro/tests/watch_locks.rs @@ -1,3 +1,5 @@ +#![cfg(unix)] + mod common; use std::cell::RefCell;