use super::types::CompressionAlgorithm;
use flate2::Compression;
use flate2::write::GzEncoder;
use std::ffi::OsString;
use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
const LOG_COMPONENT_OBS: &str = "obs";
const LOG_SUBSYSTEM_LOG_CLEANER: &str = "log_cleaner";
const EVENT_LOG_CLEANER_COMPRESSION_STATE: &str = "log_cleaner_compression_state";
const DRY_RUN_ESTIMATED_ARCHIVE_RATIO: f64 = 0.5;
#[derive(Debug, Clone)]
pub(super) struct CompressionOptions {
pub algorithm: CompressionAlgorithm,
pub gzip_level: u32,
pub zstd_level: i32,
pub zstd_workers: usize,
pub zstd_fallback_to_gzip: bool,
pub dry_run: bool,
}
#[derive(Debug, Clone)]
pub(super) struct CompressionOutput {
pub archive_path: PathBuf,
pub algorithm_used: CompressionAlgorithm,
pub input_bytes: u64,
pub output_bytes: u64,
}
pub(super) fn compress_file(path: &Path, options: &CompressionOptions) -> Result<CompressionOutput, std::io::Error> {
match options.algorithm {
CompressionAlgorithm::Gzip => compress_gzip(path, options.gzip_level, options.dry_run),
CompressionAlgorithm::Zstd => match compress_zstd(path, options.zstd_level, options.zstd_workers, options.dry_run) {
Ok(output) => Ok(output),
Err(err) if options.zstd_fallback_to_gzip => {
warn!(
event = EVENT_LOG_CLEANER_COMPRESSION_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
file = ?path,
error = %err,
result = "zstd_failed_fallback_gzip",
"log cleaner compression state changed"
);
compress_gzip(path, options.gzip_level, options.dry_run)
}
Err(err) => Err(err),
},
}
}
fn compress_gzip(path: &Path, level: u32, dry_run: bool) -> Result<CompressionOutput, std::io::Error> {
let archive_path = archive_path(path, CompressionAlgorithm::Gzip);
compress_with_writer(path, &archive_path, dry_run, CompressionAlgorithm::Gzip, |reader, writer| {
let mut encoder = GzEncoder::new(writer, Compression::new(level.clamp(0, 9)));
let written = std::io::copy(reader, &mut encoder)?;
let mut out = encoder.finish()?;
out.flush()?;
let file = out.into_inner().map_err(|e| e.into_error())?;
Ok((written, file))
})
}
fn compress_zstd(path: &Path, level: i32, workers: usize, dry_run: bool) -> Result<CompressionOutput, std::io::Error> {
let archive_path = archive_path(path, CompressionAlgorithm::Zstd);
compress_with_writer(path, &archive_path, dry_run, CompressionAlgorithm::Zstd, |reader, writer| {
let mut encoder = zstd::stream::Encoder::new(writer, level.clamp(0, 22))?;
encoder.multithread(workers.max(1) as u32)?;
let written = std::io::copy(reader, &mut encoder)?;
let mut out = encoder.finish()?;
out.flush()?;
let file = out.into_inner().map_err(|e| e.into_error())?;
Ok((written, file))
})
}
struct TmpFileGuard {
path: Option<PathBuf>,
}
impl TmpFileGuard {
fn new(path: PathBuf) -> Self {
Self { path: Some(path) }
}
fn disarm(&mut self) {
self.path = None;
}
}
impl Drop for TmpFileGuard {
fn drop(&mut self) {
if let Some(path) = self.path.take() {
let _ = std::fs::remove_file(&path);
}
}
}
fn create_tmp_archive(path: &Path, source_mode: Option<u32>) -> std::io::Result<File> {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.custom_flags(libc::O_NOFOLLOW);
opts.mode(source_mode.unwrap_or(0o600));
}
let _ = source_mode;
opts.open(path)
}
fn open_source_no_follow(path: &Path) -> std::io::Result<File> {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
}
#[cfg(not(unix))]
{
File::open(path)
}
}
fn sync_parent_dir(path: &Path) {
if let Some(parent) = path.parent() {
let dir = if parent.as_os_str().is_empty() {
Path::new(".")
} else {
parent
};
if let Ok(handle) = File::open(dir) {
let _ = handle.sync_all();
}
}
}
fn compress_with_writer<F>(
path: &Path,
archive_path: &Path,
dry_run: bool,
algorithm_used: CompressionAlgorithm,
mut writer_fn: F,
) -> Result<CompressionOutput, std::io::Error>
where
F: FnMut(&mut BufReader<File>, BufWriter<File>) -> Result<(u64, File), std::io::Error>,
{
if std::fs::symlink_metadata(archive_path).is_ok() {
debug!(event = EVENT_LOG_CLEANER_COMPRESSION_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?archive_path, result = "leftover_archive_recompressing", "log cleaner compression state changed");
}
if dry_run {
let input_bytes = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
let estimated_output_bytes = (input_bytes as f64 * DRY_RUN_ESTIMATED_ARCHIVE_RATIO) as u64;
info!(event = EVENT_LOG_CLEANER_COMPRESSION_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_compress", file = ?path, archive = ?archive_path, input_bytes, estimated_output_bytes, "log cleaner compression state changed");
return Ok(CompressionOutput {
archive_path: archive_path.to_path_buf(),
algorithm_used,
input_bytes,
output_bytes: estimated_output_bytes,
});
}
let input = open_source_no_follow(path)?;
#[cfg(unix)]
let source_mode = {
use std::os::unix::fs::PermissionsExt;
input.metadata().ok().map(|m| m.permissions().mode())
};
#[cfg(not(unix))]
let source_mode: Option<u32> = None;
let mut tmp_name = archive_path.as_os_str().to_owned();
tmp_name.push(".tmp");
let tmp_archive_path = std::path::PathBuf::from(tmp_name);
let output = create_tmp_archive(&tmp_archive_path, source_mode)?;
let mut tmp_guard = TmpFileGuard::new(tmp_archive_path.clone());
let mut reader = BufReader::new(input);
let writer = BufWriter::new(output);
let (written, out_file) = writer_fn(&mut reader, writer)?;
out_file.sync_all()?;
drop(out_file);
#[cfg(unix)]
if let Some(mode) = source_mode {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&tmp_archive_path, std::fs::Permissions::from_mode(mode));
}
std::fs::rename(&tmp_archive_path, archive_path)?;
tmp_guard.disarm();
sync_parent_dir(archive_path);
let input_bytes = written;
let output_bytes = match std::fs::metadata(archive_path) {
Ok(meta) => meta.len(),
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_COMPRESSION_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, archive = ?archive_path, error = %err, result = "archive_metadata_read_failed", "log cleaner compression state changed");
input_bytes
}
};
debug!(
event = EVENT_LOG_CLEANER_COMPRESSION_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
file = ?path,
archive = ?archive_path,
input_bytes,
output_bytes,
algorithm = %algorithm_used,
state = "compression_finished",
"log cleaner compression state changed"
);
Ok(CompressionOutput {
archive_path: archive_path.to_path_buf(),
algorithm_used,
input_bytes,
output_bytes,
})
}
fn archive_path(path: &Path, algorithm: CompressionAlgorithm) -> PathBuf {
let ext = algorithm.extension();
let mut file_name: OsString = path
.file_name()
.map_or_else(|| OsString::from("archive"), |n| n.to_os_string());
file_name.push(format!(".{ext}"));
path.with_file_name(file_name)
}
#[cfg(test)]
mod tests {
use super::*;
fn default_options(algorithm: CompressionAlgorithm) -> CompressionOptions {
CompressionOptions {
algorithm,
gzip_level: 6,
zstd_level: 3,
zstd_workers: 1,
zstd_fallback_to_gzip: false,
dry_run: false,
}
}
#[cfg(unix)]
#[test]
fn source_symlink_is_rejected() {
let dir = tempfile::tempdir().expect("tempdir");
let secret = dir.path().join("secret.txt");
std::fs::write(&secret, b"top secret contents").expect("write secret");
let source = dir.path().join("app.log");
std::os::unix::fs::symlink(&secret, &source).expect("symlink");
let err = compress_file(&source, &default_options(CompressionAlgorithm::Gzip))
.expect_err("compressing a symlinked source must fail");
assert!(
!dir.path().join("app.log.gz").exists(),
"no archive should be created from a symlinked source, err={err}"
);
assert!(secret.exists(), "secret should be untouched");
}
#[test]
fn truncated_magic_archive_is_not_trusted() {
use std::io::Read;
let dir = tempfile::tempdir().expect("tempdir");
let source = dir.path().join("app.log");
let payload = b"line1\nline2\nline3\n";
std::fs::write(&source, payload).expect("write source");
let archive = dir.path().join("app.log.gz");
std::fs::write(&archive, [0x1f_u8, 0x8b, 0x00]).expect("write forged archive");
let out = compress_file(&source, &default_options(CompressionAlgorithm::Gzip)).expect("compression should succeed");
assert_eq!(out.archive_path, archive);
let file = File::open(&archive).expect("open archive");
let mut decoder = flate2::read::GzDecoder::new(file);
let mut decoded = Vec::new();
decoder
.read_to_end(&mut decoded)
.expect("archive must be a complete gzip stream");
assert_eq!(decoded, payload, "recompressed archive must contain the full source");
assert!(source.exists(), "source log must survive compression");
}
}