use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use super::{BeaconDirState, BeaconReport, BeaconState, Position, READERS_DIR};
use crate::error::{Error, Result};
use crate::fault::{Pause, pause};
use crate::journal::{self, Identity};
use crate::reader::Reader;
pub(super) const BEACON_LEN: usize = 128;
const BEACON_MAGIC: [u8; 8] = *b"TTREADER";
const BEACON_VERSION: u32 = 1;
const BEACON_NAME_MAX: usize = 64;
const FLAG_DURABLE_ONLY: u32 = 1;
const FLAG_SEEK_PENDING: u32 = 2;
const KNOWN_FLAGS: u32 = FLAG_DURABLE_ONLY | FLAG_SEEK_PENDING;
const CRC_AT: usize = BEACON_LEN - 4;
const TMP_SUFFIX: &str = ".beacon-tmp";
const RESERVED_NAMES: [&str; 6] = [
journal::CHECKPOINT_FILE,
journal::LOCK_FILE,
journal::NOTIFY_FILE,
journal::SPARE_FILE,
journal::QUARANTINE_DIR,
READERS_DIR,
];
const PUBLISH_ATTEMPTS: u32 = 8;
const OBSERVE_ATTEMPTS: u32 = 3;
#[derive(Debug)]
pub struct ReaderBeacon {
path: PathBuf,
file: File,
identity: Identity,
interval: Duration,
last_write: Option<Instant>,
last_cursor: Option<CursorKey>,
segment: Option<(Identity, u64, u64)>,
creator: u32,
}
impl ReaderBeacon {
pub fn create(
journal_dir: impl AsRef<Path>,
name: &str,
reader: &Reader,
) -> Result<ReaderBeacon> {
check_name(name)?;
let dir = journal_dir.as_ref().join(READERS_DIR);
match fs::create_dir(&dir) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(Error::io("create reader beacon directory", &dir, e)),
}
ReaderBeacon::create_in(dir, name, reader)
}
pub fn create_in(
beacons_dir: impl AsRef<Path>,
name: &str,
reader: &Reader,
) -> Result<ReaderBeacon> {
check_name(name)?;
let dir = beacons_dir.as_ref();
let path = dir.join(name);
let pid = std::process::id();
let mut segment = None;
let bytes = encode(&payload_of(reader, &mut segment, pid)?);
let dir_lock = DirLock::acquire(dir)?;
remove_leftovers(dir);
let (mut tmp, file) = Temporary::create(dir, name, pid)?;
file.write_all_at(&bytes, 0)
.map_err(|e| Error::io("write reader beacon", &tmp.path, e))?;
pause(Pause::CreatorWroteTemporary);
let identity = tmp.identity;
publish(&tmp, &path)?;
tmp.published = true;
drop(dir_lock);
Ok(ReaderBeacon {
path,
file,
identity,
interval: super::DEFAULT_BEACON_INTERVAL,
last_write: Some(Instant::now()),
last_cursor: Some(cursor_key(reader)),
segment,
creator: pid,
})
}
pub fn set_interval(&mut self, interval: Duration) {
self.interval = interval;
}
pub fn update(&mut self, reader: &Reader) -> Result<bool> {
if self.last_cursor == Some(cursor_key(reader))
|| self
.last_write
.is_some_and(|at| at.elapsed() < self.interval)
{
return Ok(false);
}
self.write(reader)?;
Ok(true)
}
pub fn flush(&mut self, reader: &Reader) -> Result<()> {
self.write(reader)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn is_published(&self) -> bool {
lstat_identity(&self.path) == Some(self.identity)
}
fn write(&mut self, reader: &Reader) -> Result<()> {
if std::process::id() != self.creator {
return Err(Error::io(
"write reader beacon",
&self.path,
io::Error::other(
"the beacon belongs to the process that created it, not to a forked child",
),
));
}
let key = cursor_key(reader);
let payload = payload_of(reader, &mut self.segment, self.creator)?;
self.file
.write_all_at(&encode(&payload), 0)
.map_err(|e| Error::io("write reader beacon", &self.path, e))?;
self.last_write = Some(Instant::now());
self.last_cursor = Some(key);
Ok(())
}
}
type CursorKey = (u64, u64, u64, Identity, bool);
fn cursor_key(reader: &Reader) -> CursorKey {
let parts = reader.cursor_parts();
(
parts.slot_seq,
parts.skip_until,
parts.offset,
parts.identity,
parts.durable_only,
)
}
impl Drop for ReaderBeacon {
fn drop(&mut self) {
if std::process::id() != self.creator {
return;
}
if self.is_published() {
pause(Pause::OwnerBeforeUnlink);
let _ = fs::remove_file(&self.path);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Payload {
pub(super) report: BeaconReport,
pub(super) segment_file: Identity,
pub(super) segment_size: u64,
pub(super) segment_created_unix_ns: u64,
}
#[derive(Debug)]
pub(super) struct Observed {
pub(super) name: String,
pub(super) path: PathBuf,
pub(super) state: BeaconState,
pub(super) payload: Option<Payload>,
}
fn check_name(name: &str) -> Result<()> {
if !valid_name(name) {
return Err(Error::InvalidConfig(format!(
"reader beacon name {name:?}: use 1 to {BEACON_NAME_MAX} ASCII letters, digits, '.', '_' or '-', not starting with '.'"
)));
}
if reserved(name) {
return Err(Error::InvalidConfig(format!(
"reader beacon name {name:?} is the name of a journal file"
)));
}
Ok(())
}
fn valid_name(name: &str) -> bool {
(1..=BEACON_NAME_MAX).contains(&name.len())
&& !name.starts_with('.')
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}
fn reserved(name: &str) -> bool {
let ends_with = |suffix: &str| {
name.len() >= suffix.len()
&& name.as_bytes()[name.len() - suffix.len()..].eq_ignore_ascii_case(suffix.as_bytes())
};
RESERVED_NAMES.iter().any(|r| r.eq_ignore_ascii_case(name))
|| ends_with(".tape")
|| ends_with(".tmp")
}
fn lstat_identity(path: &Path) -> Option<Identity> {
fs::symlink_metadata(path).ok().map(|m| (m.dev(), m.ino()))
}
fn payload_of(
reader: &Reader,
segment: &mut Option<(Identity, u64, u64)>,
pid: u32,
) -> Result<Payload> {
let parts = reader.cursor_parts();
let cursor = parts.cursor();
let (created, size) = match *segment {
Some((id, created, size)) if id == parts.identity => (created, size),
_ => {
let header =
journal::read_header(parts.file, parts.path, cursor.position.segment_base_seq)?;
*segment = Some((parts.identity, header.created_unix_ns, header.segment_size));
(header.created_unix_ns, header.segment_size)
}
};
Ok(Payload {
report: BeaconReport {
pid,
next_seq: cursor.next_seq,
position: cursor.position,
seek_pending: cursor.seek_pending,
durable_only: cursor.durable_only,
updated_unix_ns: crate::clock::realtime_ns(),
},
segment_file: parts.identity,
segment_size: size,
segment_created_unix_ns: created,
})
}
pub(super) fn encode(p: &Payload) -> [u8; BEACON_LEN] {
let mut b = [0u8; BEACON_LEN];
let r = &p.report;
let flags = if r.durable_only { FLAG_DURABLE_ONLY } else { 0 }
| if r.seek_pending { FLAG_SEEK_PENDING } else { 0 };
b[0..8].copy_from_slice(&BEACON_MAGIC);
b[8..12].copy_from_slice(&BEACON_VERSION.to_le_bytes());
b[12..16].copy_from_slice(&flags.to_le_bytes());
b[16..20].copy_from_slice(&r.pid.to_le_bytes());
for (at, value) in [
(24, r.next_seq),
(32, r.position.next_seq),
(40, r.position.segment_base_seq),
(48, r.position.offset),
(56, p.segment_created_unix_ns),
(64, p.segment_size),
(72, p.segment_file.0),
(80, p.segment_file.1),
(88, r.updated_unix_ns),
] {
b[at..at + 8].copy_from_slice(&value.to_le_bytes());
}
let crc = crate::crc::crc32c(&b[..CRC_AT]);
b[CRC_AT..].copy_from_slice(&crc.to_le_bytes());
b
}
pub(super) fn decode(b: &[u8]) -> Option<Payload> {
let b: &[u8; BEACON_LEN] = b.try_into().ok()?;
if !well_formed(b) || u32_at(b, CRC_AT) != crate::crc::crc32c(&b[..CRC_AT]) {
return None;
}
let flags = u32_at(b, 12);
Some(Payload {
report: BeaconReport {
pid: u32_at(b, 16),
next_seq: u64_at(b, 24),
position: Position::new(u64_at(b, 32), u64_at(b, 40), u64_at(b, 48)),
seek_pending: flags & FLAG_SEEK_PENDING != 0,
durable_only: flags & FLAG_DURABLE_ONLY != 0,
updated_unix_ns: u64_at(b, 88),
},
segment_file: (u64_at(b, 72), u64_at(b, 80)),
segment_size: u64_at(b, 64),
segment_created_unix_ns: u64_at(b, 56),
})
}
fn u32_at(b: &[u8; BEACON_LEN], at: usize) -> u32 {
u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
}
fn u64_at(b: &[u8; BEACON_LEN], at: usize) -> u64 {
let mut x = [0u8; 8];
x.copy_from_slice(&b[at..at + 8]);
u64::from_le_bytes(x)
}
fn well_formed(b: &[u8; BEACON_LEN]) -> bool {
let zero = |range: std::ops::Range<usize>| b[range].iter().all(|&x| x == 0);
let pid = u32_at(b, 16);
b[0..8] == BEACON_MAGIC
&& u32_at(b, 8) == BEACON_VERSION
&& u32_at(b, 12) & !KNOWN_FLAGS == 0
&& pid != 0
&& pid <= i32::MAX as u32
&& zero(20..24)
&& b[48] % crate::format::RECORD_ALIGN as u8 == 0
&& zero(53..56)
&& zero(64..66)
&& b[69] <= 1
&& zero(70..72)
&& zero(96..CRC_AT)
&& (u64_at(b, 48) >= crate::format::SEGMENT_HEADER_LEN as u64 || u64_at(b, 64) != 0)
}
fn is_beacon_file(b: &[u8; BEACON_LEN]) -> bool {
well_formed(b)
}
fn read_exact_beacon(file: &File) -> io::Result<Option<[u8; BEACON_LEN]>> {
let mut buf = [0u8; BEACON_LEN + 1];
let mut filled = 0;
while filled < buf.len() {
match file.read_at(&mut buf[filled..], filled as u64) {
Ok(0) => break,
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
if filled != BEACON_LEN {
return Ok(None);
}
let mut out = [0u8; BEACON_LEN];
out.copy_from_slice(&buf[..BEACON_LEN]);
Ok(Some(out))
}
fn probe(file: &File) -> BeaconState {
match rustix::fs::flock(file, rustix::fs::FlockOperation::NonBlockingLockShared) {
Ok(()) => {
pause(Pause::ObserverHoldsProbe);
let _ = rustix::fs::flock(file, rustix::fs::FlockOperation::Unlock);
BeaconState::Stale
}
Err(e) if e == rustix::io::Errno::WOULDBLOCK => BeaconState::Live,
Err(_) => BeaconState::Uncertain,
}
}
fn not_openable(e: &io::Error) -> bool {
matches!(
e.raw_os_error(),
Some(libc::ELOOP | libc::ENXIO | libc::EOPNOTSUPP)
)
}
fn open_beacon(path: &Path) -> io::Result<File> {
OpenOptions::new()
.read(true)
.custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)
}
struct DirLock {
dir: File,
}
impl Drop for DirLock {
fn drop(&mut self) {
let _ = rustix::fs::flock(&self.dir, rustix::fs::FlockOperation::Unlock);
}
}
impl DirLock {
fn acquire(dir: &Path) -> Result<DirLock> {
let file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
.open(dir)
.map_err(|e| Error::io("open reader beacon directory", dir, e))?;
match rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockExclusive) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::WOULDBLOCK => {
pause(Pause::CreatorWaitsForDirectoryLock);
loop {
match rustix::fs::flock(&file, rustix::fs::FlockOperation::LockExclusive) {
Ok(()) => break,
Err(e) if e == rustix::io::Errno::INTR => {}
Err(e) => {
return Err(Error::io("lock reader beacon directory", dir, e.into()));
}
}
}
}
Err(e) => return Err(Error::io("lock reader beacon directory", dir, e.into())),
}
Ok(DirLock { dir: file })
}
}
struct Temporary {
path: PathBuf,
identity: Identity,
published: bool,
}
impl Temporary {
fn create(dir: &Path, name: &str, pid: u32) -> Result<(Temporary, File)> {
for n in 0u32.. {
let path = dir.join(format!(".{name}.{pid}.{n}{TMP_SUFFIX}"));
let file = match OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.custom_flags(libc::O_CLOEXEC)
.open(&path)
{
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && n < 1000 => continue,
Err(e) => return Err(Error::io("create reader beacon", &path, e)),
};
let identity = match journal::file_identity(&file, &path) {
Ok(identity) => identity,
Err(e) => {
let _ = fs::remove_file(&path);
return Err(e);
}
};
let tmp = Temporary {
path,
identity,
published: false,
};
rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockExclusive)
.map_err(|e| Error::io("lock reader beacon", &tmp.path, e.into()))?;
return Ok((tmp, file));
}
unreachable!("the loop returns")
}
}
impl Temporary {
fn remove(&self) {
if lstat_identity(&self.path) == Some(self.identity) {
let _ = fs::remove_file(&self.path);
}
}
}
impl Drop for Temporary {
fn drop(&mut self) {
if !self.published {
self.remove();
}
}
}
fn publish(tmp: &Temporary, path: &Path) -> Result<()> {
let identity = tmp.identity;
for _ in 0..PUBLISH_ATTEMPTS {
match fs::hard_link(&tmp.path, path) {
Ok(()) => {
tmp.remove();
return Ok(());
}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(Error::io("publish reader beacon", path, e)),
}
match check_existing(path)? {
Existing::Changed => continue,
Existing::Stale => {
pause(Pause::CreatorFoundStale);
fs::rename(&tmp.path, path)
.map_err(|e| Error::io("replace stale reader beacon", path, e))?;
if lstat_identity(path) != Some(identity) {
return Err(Error::io(
"replace stale reader beacon",
path,
io::Error::other("the name was replaced during publication"),
));
}
return Ok(());
}
}
}
Err(Error::io(
"publish reader beacon",
path,
io::Error::other("the name kept changing during publication"),
))
}
enum Existing {
Changed,
Stale,
}
fn check_existing(path: &Path) -> Result<Existing> {
let not_a_beacon = || {
Error::InvalidConfig(format!(
"{} exists and is not a stale reader beacon; refusing to replace it",
path.display()
))
};
let file = match open_beacon(path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Existing::Changed),
Err(e) if not_openable(&e) => return Err(not_a_beacon()),
Err(e) => return Err(Error::io("open existing reader beacon", path, e)),
};
pause(Pause::CreatorOpenedExisting);
let meta = file
.metadata()
.map_err(|e| Error::io("stat existing reader beacon", path, e))?;
if !meta.is_file() {
return Err(not_a_beacon());
}
match rustix::fs::flock(&file, rustix::fs::FlockOperation::NonBlockingLockShared) {
Ok(()) => {
let _ = rustix::fs::flock(&file, rustix::fs::FlockOperation::Unlock);
}
Err(e) if e == rustix::io::Errno::WOULDBLOCK => {
return Err(Error::BeaconInUse {
path: path.to_path_buf(),
});
}
Err(e) => return Err(Error::io("probe existing reader beacon", path, e.into())),
}
let contents =
read_exact_beacon(&file).map_err(|e| Error::io("read existing reader beacon", path, e))?;
if !contents.is_some_and(|b| is_beacon_file(&b)) {
return Err(not_a_beacon());
}
if lstat_identity(path) != Some((meta.dev(), meta.ino())) {
return Ok(Existing::Changed);
}
Ok(Existing::Stale)
}
fn remove_leftovers(dir: &Path) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
if !is_temporary_name(name) {
continue;
}
let path = entry.path();
let Ok(file) = open_beacon(&path) else {
continue;
};
let Ok(meta) = file.metadata() else {
continue;
};
if meta.is_file()
&& probe(&file) == BeaconState::Stale
&& read_exact_beacon(&file).is_ok_and(|b| b.is_some_and(|b| is_beacon_file(&b)))
&& lstat_identity(&path) == Some((meta.dev(), meta.ino()))
{
let _ = fs::remove_file(&path);
}
}
}
fn is_temporary_name(name: &str) -> bool {
let Some(stem) = name
.strip_prefix('.')
.and_then(|n| n.strip_suffix(TMP_SUFFIX))
else {
return false;
};
let mut parts = stem.rsplitn(3, '.');
let (Some(n), Some(pid), Some(beacon)) = (parts.next(), parts.next(), parts.next()) else {
return false;
};
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
digits(n) && digits(pid) && valid_name(beacon)
}
pub(super) fn observe_all(dir: &Path) -> (BeaconDirState, Vec<Observed>) {
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return (BeaconDirState::Missing, Vec::new());
}
Err(e) => return (BeaconDirState::Unusable(e.kind()), Vec::new()),
};
let mut out = Vec::new();
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => return (BeaconDirState::Unusable(e.kind()), Vec::new()),
};
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if !valid_name(&name) || reserved(&name) {
continue;
}
if entry.file_type().is_ok_and(|t| !t.is_file()) {
continue;
}
if let Some(observed) = observe(entry.path(), name) {
out.push(observed);
}
}
out.sort_by(|a, b| a.name.cmp(&b.name));
(BeaconDirState::Listed, out)
}
fn observe(path: PathBuf, name: String) -> Option<Observed> {
let unreadable = |path: PathBuf, name: String| Observed {
name,
path,
state: BeaconState::Unreadable,
payload: None,
};
let mut replaced = false;
for _ in 0..OBSERVE_ATTEMPTS {
let file = match open_beacon(&path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
Err(e) if not_openable(&e) => return None,
Err(_) => return Some(unreadable(path, name)),
};
let meta = match file.metadata() {
Ok(meta) => meta,
Err(_) => return Some(unreadable(path, name)),
};
if !meta.is_file() {
return None;
}
pause(Pause::ObserverOpened);
let read = |file: &File| read_exact_beacon(file).map(|b| b.and_then(|b| decode(&b)));
let Ok(mut payload) = read(&file) else {
return Some(unreadable(path, name));
};
let mut attempts = 1;
while payload.is_none()
&& (attempts < 2 || attempts < 8 && probe(&file) == BeaconState::Live)
{
match read(&file) {
Ok(again) => payload = again,
Err(_) => return Some(unreadable(path, name)),
}
attempts += 1;
}
pause(Pause::ObserverRead);
let state = match payload {
None => BeaconState::Invalid,
Some(_) => probe(&file),
};
let observed = Observed {
name: name.clone(),
path: path.clone(),
state,
payload,
};
if lstat_identity(&path) == Some((meta.dev(), meta.ino())) {
return Some(observed);
}
replaced = true;
}
replaced.then_some(Observed {
name,
path,
state: BeaconState::Changing,
payload: None,
})
}
#[cfg(test)]
pub(super) fn name_allowed(name: &str) -> bool {
check_name(name).is_ok()
}
#[cfg(test)]
pub(super) fn beacon_file(b: &[u8; BEACON_LEN]) -> bool {
is_beacon_file(b)
}
#[cfg(test)]
pub(super) fn temporary_name(name: &str) -> bool {
is_temporary_name(name)
}