use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt};
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::format::{self, CheckpointSlot, ScanEnd};
use crate::{CorruptReason, Error, Result, inspect, journal, mmap};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Policy {
pub max_segments: Option<usize>,
pub max_bytes: Option<u64>,
pub max_age: Option<Duration>,
}
impl Policy {
pub fn max_segments(mut self, count: usize) -> Self {
self.max_segments = Some(count);
self
}
pub fn max_bytes(mut self, bytes: u64) -> Self {
self.max_bytes = Some(bytes);
self
}
pub fn max_age(mut self, age: Duration) -> Self {
self.max_age = Some(age);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Action {
Delete,
MoveTo(PathBuf),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reason {
MaxSegments,
MaxBytes,
MaxAge,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlannedSegment {
pub path: PathBuf,
pub base_seq: u64,
pub size_bytes: u64,
pub sealed_unix_ns: u64,
pub reasons: Vec<Reason>,
identity: journal::Identity,
successor: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plan {
segments: Vec<PlannedSegment>,
directory: journal::Identity,
}
impl Plan {
pub fn segments(&self) -> &[PlannedSegment] {
&self.segments
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
pub removed_segments: u64,
pub removed_bytes: u64,
pub already_removed_segments: u64,
}
impl Report {
pub(crate) fn absorb(&mut self, other: &Report) {
self.removed_segments = self.removed_segments.saturating_add(other.removed_segments);
self.removed_bytes = self.removed_bytes.saturating_add(other.removed_bytes);
self.already_removed_segments = self
.already_removed_segments
.saturating_add(other.already_removed_segments);
}
}
pub fn plan(dir: impl AsRef<Path>, policy: &Policy) -> Result<Plan> {
plan_at(dir.as_ref(), policy, crate::clock::realtime_ns(), &|_| {
false
})
}
pub(crate) fn plan_until(
dir: &Path,
policy: &Policy,
stop: &dyn Fn(usize) -> bool,
) -> Result<Plan> {
plan_at(dir, policy, crate::clock::realtime_ns(), stop)
}
fn plan_at(dir: &Path, policy: &Policy, now: u64, stop: &dyn Fn(usize) -> bool) -> Result<Plan> {
let directory = directory_identity(dir)?;
let paths = journal::list_segments(dir)?;
if paths.is_empty() {
return Err(Error::NotFound { dir: dir.into() });
}
let mut plan = Plan {
segments: Vec::new(),
directory,
};
if policy == &Policy::default() {
return Ok(plan);
}
let Some(checkpoint) = checkpoint(dir)? else {
return Ok(plan);
};
let headers = paths
.iter()
.map(|(base, path)| {
let file = File::open(path).map_err(|e| Error::io("open segment", path, e))?;
Ok((
journal::read_header(&file, path, *base)?,
journal::file_identity(&file, path)?,
))
})
.collect::<Result<Vec<_>>>()?;
let mut count = paths.len();
let mut bytes: u128 = headers
.iter()
.map(|(h, _)| u128::from(h.segment_size))
.sum();
for (i, (base, path)) in paths.iter().enumerate() {
if *base >= checkpoint.segment_base_seq || i + 1 == paths.len() {
break;
}
let (header, identity) = headers[i];
let sealed = headers[i + 1].0.created_unix_ns;
let reasons = reasons(policy, count, bytes, now, sealed);
if reasons.is_empty() || (!plan.segments.is_empty() && stop(plan.segments.len())) {
break;
}
let file = File::open(path).map_err(|e| Error::io("open segment", path, e))?;
check_seal(&file, path, header.segment_size, *base, paths[i + 1].0)?;
plan.segments.push(PlannedSegment {
path: path.clone(),
base_seq: *base,
size_bytes: header.segment_size,
sealed_unix_ns: sealed,
reasons,
identity,
successor: paths[i + 1].0,
});
count -= 1;
bytes -= u128::from(header.segment_size);
}
Ok(plan)
}
fn reasons(policy: &Policy, count: usize, bytes: u128, now: u64, sealed: u64) -> Vec<Reason> {
let mut out = Vec::new();
if policy.max_segments.is_some_and(|max| count > max) {
out.push(Reason::MaxSegments);
}
if policy.max_bytes.is_some_and(|max| bytes > u128::from(max)) {
out.push(Reason::MaxBytes);
}
if policy
.max_age
.is_some_and(|max| now > sealed && u128::from(now - sealed) > max.as_nanos())
{
out.push(Reason::MaxAge);
}
out
}
pub fn apply(dir: impl AsRef<Path>, plan: &Plan, action: &Action) -> Result<Report> {
let mut report = Report::default();
apply_into(dir.as_ref(), plan, action, &mut report, true, None)?;
Ok(report)
}
pub(crate) fn apply_into(
dir: &Path,
plan: &Plan,
action: &Action,
report: &mut Report,
external: bool,
stop: Option<&dyn Fn(usize) -> bool>,
) -> Result<()> {
if directory_identity(dir)? != plan.directory {
return Err(Error::InvalidConfig(
"retention plan belongs to a different journal directory".into(),
));
}
let mut synced = None;
for (i, segment) in plan.segments.iter().enumerate() {
if let Some(stop) = stop {
if i > 0 && stop(i) {
break;
}
crate::fault::hold_point(crate::fault::Point::RetentionRemove);
}
let paths = journal::list_segments(dir)?;
if already_removed(&paths, segment.base_seq) {
report.already_removed_segments = report.already_removed_segments.saturating_add(1);
continue;
}
if paths.first().map(|(base, _)| *base) != Some(segment.base_seq) {
return Err(Error::corrupt(
journal::segment_path(dir, segment.base_seq),
0,
CorruptReason::BrokenChain(segment.base_seq),
));
}
let marker = if external {
durable_checkpoint(dir, &mut synced)?
} else {
checkpoint(dir)?
};
let Some(marker) = marker else {
return Err(Error::InvalidConfig(
"retention requires a valid checkpoint".into(),
));
};
if segment.base_seq >= marker.segment_base_seq {
return Err(Error::InvalidConfig(
"planned segment is no longer older than the checkpoint".into(),
));
}
let path = journal::segment_path(dir, segment.base_seq);
let mut removed = false;
let result = (|| {
let file =
File::open(&path).map_err(|e| Error::io("open retention segment", &path, e))?;
if journal::file_identity(&file, &path)? != segment.identity {
return Err(Error::InvalidConfig(
"planned segment has been replaced".into(),
));
}
let header = journal::read_header(&file, &path, segment.base_seq)?;
let successor = journal::segment_path(dir, segment.successor);
if paths.get(1).map(|(base, _)| *base) != Some(segment.successor) {
return Err(Error::corrupt(
&path,
0,
CorruptReason::BrokenChain(segment.successor),
));
}
let next = File::open(&successor)
.map_err(|e| Error::io("open retention successor", &successor, e))?;
journal::read_header(&next, &successor, segment.successor)?;
match action {
Action::Delete => check_seal(
&file,
&path,
header.segment_size,
segment.base_seq,
segment.successor,
)?,
Action::MoveTo(_) => {
check_records(&file, &path, segment.base_seq, segment.successor)?
}
}
match action {
Action::Delete => {
fs::remove_file(&path)
.map_err(|e| Error::io("delete retention segment", &path, e))?;
removed = true;
}
Action::MoveTo(dest) => move_segment(&path, dest, &file, &mut removed)?,
}
journal::sync_dir(dir)?;
mmap::full_barrier(&file)
.map_err(|e| Error::io("full sync retention segment", &path, e))?;
Ok(())
})();
if removed {
report.removed_segments = report.removed_segments.saturating_add(1);
report.removed_bytes = report.removed_bytes.saturating_add(segment.size_bytes);
}
if let Err(error) = result {
if !removed
&& matches!(&error, Error::Io { source, .. } if source.kind() == io::ErrorKind::NotFound)
&& already_removed(&journal::list_segments(dir)?, segment.base_seq)
{
report.already_removed_segments = report.already_removed_segments.saturating_add(1);
continue;
}
return Err(error);
}
}
Ok(())
}
fn already_removed(paths: &[(u64, PathBuf)], base: u64) -> bool {
paths.first().is_some_and(|(oldest, _)| base < *oldest)
}
fn directory_identity(dir: &Path) -> Result<journal::Identity> {
let meta = fs::metadata(dir).map_err(|e| Error::io("stat journal directory", dir, e))?;
Ok((meta.dev(), meta.ino()))
}
fn durable_checkpoint(
dir: &Path,
synced: &mut Option<CheckpointSlot>,
) -> Result<Option<CheckpointSlot>> {
let path = dir.join(journal::CHECKPOINT_FILE);
let file = match File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(Error::io("open checkpoint", &path, e)),
};
let slot = checkpoint(dir)?;
if slot.is_some() && slot != *synced {
crate::fault::inject(crate::fault::Point::RetentionMarkerSync)
.and_then(|()| mmap::full_barrier(&file))
.map_err(|e| Error::io("sync checkpoint marker", &path, e))?;
*synced = slot;
}
Ok(slot)
}
fn checkpoint(dir: &Path) -> Result<Option<CheckpointSlot>> {
let Some(slot) = inspect::read_checkpoint(dir)? else {
return Ok(None);
};
let path = journal::segment_path(dir, slot.segment_base_seq);
let file = match File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return Err(Error::corrupt(
dir.join(journal::CHECKPOINT_FILE),
0,
CorruptReason::DanglingCheckpoint(slot.segment_base_seq),
));
}
Err(e) => return Err(Error::io("open checkpoint segment", &path, e)),
};
let header = journal::read_header(&file, &path, slot.segment_base_seq)?;
if slot.offset < format::SEGMENT_HEADER_LEN as u64
|| slot.offset > header.segment_size - format::SEAL_LEN as u64
|| slot.offset % 8 != 0
{
return Err(Error::corrupt(
dir.join(journal::CHECKPOINT_FILE),
0,
CorruptReason::DanglingCheckpoint(slot.segment_base_seq),
));
}
Ok(Some(slot))
}
const TAIL_READ: u64 = 4096;
const TAIL_READ_MAX: u64 = 1 << 20;
fn check_seal(file: &File, path: &Path, size: u64, base: u64, successor: u64) -> Result<()> {
if seal_at_end(file, path, size, successor)? {
return Ok(());
}
check_records(file, path, base, successor)
}
fn seal_at_end(file: &File, path: &Path, size: u64, successor: u64) -> Result<bool> {
let first_slot = format::SEGMENT_HEADER_LEN as u64;
let mut end = size;
let mut chunk = TAIL_READ;
let mut buffer = Vec::new();
while end > first_slot {
let start = end.saturating_sub(chunk).max(first_slot);
buffer.resize((end - start) as usize, 0);
file.read_exact_at(&mut buffer, start)
.map_err(|e| Error::io("read segment end", path, e))?;
if let Some(word) = buffer.chunks_exact(8).rposition(|w| w != [0; 8]) {
let at = start + word as u64 * 8;
let bytes = &buffer[word * 8..word * 8 + 8];
let commit = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let crc = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
return Ok(at >= first_slot + format::RECORD_HEADER_LEN as u64
&& commit == format::SEAL_MARKER
&& crc == format::seal_crc(successor));
}
end = start;
chunk = (chunk * 2).min(TAIL_READ_MAX);
}
Ok(false)
}
fn check_records(file: &File, path: &Path, base: u64, successor: u64) -> Result<()> {
let scan = journal::scan_open(file, path, base)?;
match scan.end {
ScanEnd::Seal if scan.next_seq == successor => Ok(()),
ScanEnd::Invalid(reason) => Err(Error::corrupt(path, scan.end_offset, reason)),
_ => Err(Error::corrupt(
path,
scan.end_offset,
CorruptReason::BrokenChain(scan.next_seq),
)),
}
}
fn move_segment(path: &Path, dest: &Path, source: &File, removed: &mut bool) -> Result<()> {
let target = dest.join(
path.file_name()
.ok_or_else(|| Error::InvalidConfig("segment has no basename".into()))?,
);
let renamed = crate::fault::inject(crate::fault::Point::RetentionRename).and_then(|()| {
rustix::fs::renameat_with(
rustix::fs::CWD,
path,
rustix::fs::CWD,
&target,
rustix::fs::RenameFlags::NOREPLACE,
)
.map_err(io::Error::from)
});
match renamed {
Ok(()) => {
*removed = true;
sync_destination(dest)?;
}
Err(e) if e.raw_os_error() == Some(libc::EXDEV) => {
let mut copy = OpenOptions::new()
.write(true)
.create_new(true)
.open(&target)
.map_err(|e| Error::io("create archive copy", &target, e))?;
let mut offset = 0;
let mut buffer = [0; 64 * 1024];
use std::io::Write;
loop {
let count = source
.read_at(&mut buffer, offset)
.map_err(|e| Error::io("read archive source", path, e))?;
if count == 0 {
break;
}
copy.write_all(&buffer[..count])
.map_err(|e| Error::io("write archive copy", &target, e))?;
offset += count as u64;
}
crate::fault::inject(crate::fault::Point::RetentionCopySync)
.map_err(|e| Error::io("sync archive copy", &target, e))?;
mmap::sync_all(©).map_err(|e| Error::io("sync archive copy", &target, e))?;
sync_destination(dest)?;
mmap::full_barrier(©)
.map_err(|e| Error::io("full sync archive copy", &target, e))?;
fs::remove_file(path).map_err(|e| Error::io("remove archived segment", path, e))?;
*removed = true;
}
Err(e) => return Err(Error::io("rename archive segment", &target, e)),
}
Ok(())
}
fn sync_destination(dest: &Path) -> Result<()> {
crate::fault::inject(crate::fault::Point::RetentionDestinationSync)
.map_err(|e| Error::io("sync archive directory", dest, e))?;
journal::sync_dir(dest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn age_boundary_future_and_or_limits() {
let p = Policy::default().max_age(Duration::from_nanos(10));
assert!(reasons(&p, 4, 100, 110, 100).is_empty());
assert_eq!(reasons(&p, 4, 100, 111, 100), [Reason::MaxAge]);
assert!(reasons(&p, 4, 100, 99, 100).is_empty());
assert_eq!(
reasons(&p.max_segments(3).max_bytes(0), 4, 100, 111, 100),
[Reason::MaxSegments, Reason::MaxBytes, Reason::MaxAge]
);
}
fn image(size: u64, words: &[(u64, [u8; 8])]) -> (tempfile::TempDir, File) {
let dir = tempfile::tempdir().unwrap();
let file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(dir.path().join("segment"))
.unwrap();
file.set_len(size).unwrap();
for (offset, word) in words {
file.write_all_at(word, *offset).unwrap();
}
(dir, file)
}
fn seal(successor: u64) -> [u8; 8] {
let mut word = [0; 8];
word[..4].copy_from_slice(&format::SEAL_MARKER.to_le_bytes());
word[4..].copy_from_slice(&format::seal_crc(successor).to_le_bytes());
word
}
#[test]
fn seal_at_end_accepts_only_a_seal_for_the_successor_as_the_last_non_zero_word() {
const SIZE: u64 = 4 << 20;
let first = format::SEGMENT_HEADER_LEN as u64;
let earliest = first + format::RECORD_HEADER_LEN as u64;
let found = |words: &[(u64, [u8; 8])]| {
let (dir, file) = image(SIZE, words);
seal_at_end(&file, &dir.path().join("segment"), SIZE, 7).unwrap()
};
assert!(found(&[(SIZE - 8, seal(7))]));
assert!(found(&[(SIZE - (2 << 20), seal(7))]));
assert!(found(&[(earliest, seal(7))]));
assert!(found(&[(first, [0xAB; 8]), (4096, seal(7))]));
for at in (first..earliest).step_by(8) {
assert!(!found(&[(at, seal(7))]), "seal at {at}");
}
assert!(!found(&[]));
assert!(!found(&[(4096, seal(8))]));
let mut damaged = seal(7);
damaged[7] ^= 1;
assert!(!found(&[(4096, damaged)]));
assert!(!found(&[(4096, seal(7)), (4104, [0, 0, 0, 0, 0, 0, 0, 1])]));
assert!(!found(&[
(4096, seal(7)),
(SIZE - 8, [1, 0, 0, 0, 0, 0, 0, 0])
]));
assert!(found(&[(4096, seal(8)), (8192, seal(7))]));
}
}