PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed. Co-authored-by: Cursor <cursoragent@cursor.com>
171 lines
5.3 KiB
Rust
171 lines
5.3 KiB
Rust
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;
|
|
|
|
pub struct Offsite {
|
|
repo: restic::Repository,
|
|
}
|
|
|
|
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<Self> {
|
|
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(),
|
|
},
|
|
})
|
|
}
|
|
|
|
fn command(&self) -> Command {
|
|
let mut command = Command::from(self.repo.command());
|
|
command
|
|
.args(["-o", "s3.retries=1", "--stuck-request-timeout=15s"])
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.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"]), 10).await?;
|
|
if probe.status.code() == Some(10) {
|
|
safe(run(self.command().arg("init"), 30).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),
|
|
3600,
|
|
)
|
|
.await?,
|
|
"copy",
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn tagged_snapshot(&self, snapshot: Uuid) -> Result<Option<String>> {
|
|
#[derive(serde::Deserialize)]
|
|
struct Copy {
|
|
id: String,
|
|
}
|
|
let output = safe(
|
|
run(
|
|
self.command().args([
|
|
"snapshots",
|
|
"--json",
|
|
"--tag",
|
|
&restic::tessera_tag(snapshot),
|
|
]),
|
|
15,
|
|
)
|
|
.await?,
|
|
"list",
|
|
)?;
|
|
let mut snapshots: Vec<Copy> = serde_json::from_slice(&output.stdout)?;
|
|
Ok(snapshots.pop().map(|copy| copy.id))
|
|
}
|
|
|
|
pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result<u64> {
|
|
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<()> {
|
|
self.copy_from(©.source, ©.restic_id).await?;
|
|
ensure!(
|
|
self.tagged_snapshot(copy.snapshot).await?.is_some(),
|
|
"off-site snapshot tag not found after copy"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
async fn run(command: &mut Command, seconds: u64) -> Result<Output> {
|
|
let result = tokio::time::timeout(
|
|
Duration::from_secs(seconds),
|
|
command.spawn()?.wait_with_output(),
|
|
)
|
|
.await
|
|
.context("off-site Restic operation timed out")??;
|
|
Ok(result)
|
|
}
|
|
|
|
fn safe(output: Output, step: &str) -> Result<Output> {
|
|
ensure!(
|
|
output.status.success(),
|
|
"off-site Restic {step} failed ({})",
|
|
output.status
|
|
);
|
|
Ok(output)
|
|
}
|