use crate::restic; use anyhow::{ensure, Context, Result}; use std::{ fs, io::Write, path::{Path, PathBuf}, process::{Output, Stdio}, time::Duration, }; use tokio::process::Command; use uuid::Uuid; /// Wall-clock limits per restic call. A WAN object store answers in under a second most of the time and /// in well over ten seconds some of the time, so these are sized for the slow case. #[derive(Clone, Copy)] struct Limits { probe: u64, list: u64, init: u64, copy: u64, } const LIMITS: Limits = Limits { probe: 120, list: 120, init: 90, copy: 3600, }; /// A listing that times out is retried this many times before the copy is called failed. const VERIFY_ATTEMPTS: usize = 3; pub struct Offsite { repo: restic::Repository, limits: Limits, } pub struct OffsiteCopy { pub(crate) snapshot: Uuid, pub(crate) source: restic::Repository, pub(crate) restic_id: String, } impl Offsite { pub fn new(repository: &str, password_file: &Path) -> Result { let location = repository .strip_prefix("s3:https://") .or_else(|| { repository .strip_prefix("s3:http://") .filter(|rest| rest.starts_with("127.0.0.1:")) }) .context("off-site repository requires an S3 HTTPS endpoint")?; let parts: Vec<_> = location.splitn(3, '/').collect(); ensure!( parts.len() == 3 && parts.iter().all(|part| !part.is_empty()) && !repository.contains(['@', '?', '#', '\n', '\r']), "use a dedicated S3 bucket prefix without embedded credentials" ); let password = fs::read_to_string(password_file).context("read off-site Restic password")?; let password = password.trim_end_matches(['\r', '\n']); ensure!(!password.is_empty(), "off-site Restic password is empty"); Ok(Self { repo: restic::Repository { path: PathBuf::from(repository), password: password.into(), }, limits: LIMITS, }) } fn command(&self) -> Command { let mut command = Command::from(self.repo.command()); command .args(["-o", "s3.retries=3", "--stuck-request-timeout=60s"]) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); command } async fn copy_from(&self, source: &restic::Repository, id: &str) -> Result<()> { restic::validate_id(id)?; let mut password = tempfile::NamedTempFile::new()?; writeln!(password, "{}", source.password)?; let probe = run( self.command().args(["snapshots", "--json"]), self.limits.probe, ) .await?; if probe.status.code() == Some(10) { safe( run(self.command().arg("init"), self.limits.init).await?, "init", )?; } else { safe(probe, "probe")?; } safe( run( self.command() .env_remove("RESTIC_FROM_PASSWORD") .env_remove("RESTIC_FROM_PASSWORD_COMMAND") .env_remove("RESTIC_FROM_REPOSITORY_FILE") .env_remove("RESTIC_FROM_KEY_HINT") .arg("copy") .arg("--from-repo") .arg(&source.path) .arg("--from-password-file") .arg(password.path()) .arg(id), self.limits.copy, ) .await?, "copy", )?; Ok(()) } /// The restic id of the copy tagged for this snapshot, `None` when there is none (or no repository yet). async fn tagged_snapshot(&self, snapshot: Uuid) -> Result> { #[derive(serde::Deserialize)] struct Copy { id: String, } let output = run( self.command().args([ "snapshots", "--json", "--tag", &restic::tessera_tag(snapshot), ]), self.limits.list, ) .await?; // Exit code 10: the repository does not exist yet, so nothing has been copied. if output.status.code() == Some(10) { return Ok(None); } let output = safe(output, "list")?; let mut snapshots: Vec = serde_json::from_slice(&output.stdout)?; Ok(snapshots.pop().map(|copy| copy.id)) } /// `tagged_snapshot` with retries: a slow listing must not turn a finished copy into a failed one. async fn tagged_snapshot_retrying(&self, snapshot: Uuid) -> Result> { retry(VERIFY_ATTEMPTS, &[2, 5], || self.tagged_snapshot(snapshot)).await } pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result { let id = self .tagged_snapshot(snapshot) .await? .context("snapshot not found in off-site repository")?; restic::validate_id(&id)?; let parent = dest .parent() .filter(|path| !path.as_os_str().is_empty()) .unwrap_or(Path::new(".")); fs::create_dir_all(parent)?; let file = tempfile::NamedTempFile::new_in(parent)?; safe( run( self.command() .args(["dump", &id, restic::PAYLOAD]) .stdout(Stdio::from(file.reopen()?)), 3600, ) .await?, "dump", )?; let size = file.as_file().metadata()?.len(); file.as_file().sync_all()?; file.persist(dest)?; Ok(size) } pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> { // A copy is complete once its tagged snapshot exists (restic writes the snapshot last), so an earlier // attempt that finished but could not be confirmed is simply accepted instead of copied again. if self .tagged_snapshot_retrying(copy.snapshot) .await? .is_some() { return Ok(()); } self.copy_from(©.source, ©.restic_id).await?; ensure!( self.tagged_snapshot_retrying(copy.snapshot) .await? .is_some(), "off-site snapshot tag not found after copy" ); Ok(()) } } async fn run(command: &mut Command, seconds: u64) -> Result { let result = tokio::time::timeout( Duration::from_secs(seconds), command.spawn()?.wait_with_output(), ) .await .with_context(|| format!("off-site Restic operation timed out after {seconds}s"))??; Ok(result) } fn safe(output: Output, step: &str) -> Result { ensure!( output.status.success(), "off-site Restic {step} failed ({}){}", output.status, stderr_tail(&output.stderr) ); Ok(output) } /// The end of restic's error output, on one line, so a failure says why. Restic never prints the /// repository password or S3 keys (they travel in the environment). fn stderr_tail(stderr: &[u8]) -> String { let text = String::from_utf8_lossy(stderr); let text = text.split_whitespace().collect::>().join(" "); if text.is_empty() { return String::new(); } let start = text .char_indices() .rev() .nth(299) .map_or(0, |(index, _)| index); format!(": {}", &text[start..]) } async fn retry(attempts: usize, delays: &[u64], mut attempt: F) -> Result where F: FnMut() -> Fut, Fut: std::future::Future>, { let mut tries = 0; loop { match attempt().await { Ok(value) => return Ok(value), Err(error) => { tries += 1; if tries >= attempts { return Err(error); } let wait = delays .get(tries - 1) .or(delays.last()) .copied() .unwrap_or(0); tokio::time::sleep(Duration::from_secs(wait)).await; } } } } #[cfg(test)] mod tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; #[tokio::test] async fn a_slow_listing_is_retried_until_it_answers() { let calls = AtomicUsize::new(0); let value = retry(3, &[0], || async { if calls.fetch_add(1, Ordering::SeqCst) < 2 { anyhow::bail!("timed out") } Ok(7) }) .await .unwrap(); assert_eq!((value, calls.load(Ordering::SeqCst)), (7, 3)); } #[tokio::test] async fn retries_stop_and_report_the_last_error() { let calls = AtomicUsize::new(0); let error = retry::<(), _, _>(3, &[0], || async { calls.fetch_add(1, Ordering::SeqCst); anyhow::bail!("still down") }) .await .unwrap_err(); assert_eq!( (error.to_string(), calls.load(Ordering::SeqCst)), ("still down".into(), 3) ); } #[test] fn a_failure_names_its_reason_without_dumping_the_output() { let long = "x".repeat(2000); let tail = stderr_tail(format!("line one\n {long} end").as_bytes()); assert!(tail.starts_with(": ") && tail.ends_with(" end") && tail.len() <= 304); assert_eq!(stderr_tail(b""), ""); } fn restic_available() -> bool { std::process::Command::new("restic") .arg("version") .output() .is_ok_and(|out| out.status.success()) } /// Real restic, local directories standing in for the object store: an absent destination repository is /// created and filled, and an already-copied snapshot is accepted without touching the source again. #[tokio::test] async fn a_finished_copy_is_confirmed_and_not_copied_twice() { if !restic_available() { return; } let dir = tempfile::tempdir().unwrap(); let source = restic::Repository { path: dir.path().join("source"), password: "source-pass".into(), }; fs::create_dir(&source.path).unwrap(); let init = source.command().arg("init").output().unwrap(); assert!(init.status.success()); let data = dir.path().join("payload"); fs::write(&data, b"synthetic dump").unwrap(); let snapshot = Uuid::new_v4(); let backup = source .command() .args(["backup", "--tag", &restic::tessera_tag(snapshot)]) .arg(&data) .output() .unwrap(); assert!(backup.status.success()); let listing = source .command() .args(["snapshots", "--json"]) .output() .unwrap(); let id = serde_json::from_slice::>(&listing.stdout).unwrap()[0] ["id"] .as_str() .unwrap() .to_string(); let offsite = Offsite { repo: restic::Repository { path: dir.path().join("offsite"), password: "offsite-pass".into(), }, limits: LIMITS, }; let copy = |source: &restic::Repository| OffsiteCopy { snapshot, source: restic::Repository { path: source.path.clone(), password: source.password.clone(), }, restic_id: id.clone(), }; offsite.copy_capture(copy(&source)).await.unwrap(); assert!(offsite.tagged_snapshot(snapshot).await.unwrap().is_some()); fs::remove_dir_all(&source.path).unwrap(); offsite .copy_capture(copy(&source)) .await .expect("an existing tagged copy needs no source"); let other = Uuid::new_v4(); let mut missing = copy(&source); missing.snapshot = other; let error = offsite.copy_capture(missing).await.unwrap_err(); assert!(format!("{error:#}").contains("copy failed"), "{error:#}"); } }