feat: add managed database capture and operator restore

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>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

View File

@@ -8,7 +8,9 @@
mod crypto;
mod index;
mod offsite;
mod restic;
mod vault;
pub use offsite::{Offsite, OffsiteCopy};
pub use vault::*;

View File

@@ -0,0 +1,170 @@
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(&copy.source, &copy.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)
}

View File

@@ -8,6 +8,11 @@ pub(crate) const PREFIX: &str = "restic:";
pub(crate) const OUTPOST_PREFIX: &str = "restic-outpost:";
pub(crate) const PAYLOAD: &str = "/payload";
pub(crate) fn tessera_tag(snapshot: uuid::Uuid) -> String {
format!("tessera-{snapshot}")
}
#[derive(Clone)]
pub(crate) struct Repository {
pub path: PathBuf,
pub password: String,
@@ -25,6 +30,10 @@ pub(crate) struct Summary {
struct Snapshot {
id: String,
summary: Option<Summary>,
#[serde(default)]
tags: Vec<String>,
#[serde(default)]
paths: Vec<String>,
}
impl Repository {
@@ -109,7 +118,12 @@ impl Repository {
Ok(())
}
pub fn snapshot_summary(&self, id: &str) -> Result<Summary> {
pub fn snapshot_summary(
&self,
id: &str,
tag: Option<&str>,
expected_path: Option<&str>,
) -> Result<Summary> {
validate_id(id)?;
let output = checked(
self.command().args(["snapshots", "--json", id]).output()?,
@@ -118,7 +132,11 @@ impl Repository {
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
snapshots
.into_iter()
.find(|snap| snap.id == id)
.find(|snap| {
snap.id == id
&& tag.is_none_or(|tag| snap.tags.iter().any(|value| value == tag))
&& expected_path.is_none_or(|path| snap.paths == [path])
})
.and_then(|snap| snap.summary)
.context("outpost snapshot or backup summary is missing")
}

View File

@@ -148,7 +148,7 @@ impl Vault {
return Ok(Some((id, false)));
}
let repo = self.outpost_repository(manifest.orbit_id, config);
let summary = repo.snapshot_summary(restic_id)?;
let summary = repo.snapshot_summary(restic_id, None, None)?;
manifest.snapshot_id = id;
manifest.restore_hints = serde_json::json!({ "format": "tar" });
self.write_snapshot(
@@ -166,6 +166,29 @@ impl Vault {
Ok(Some((id, true)))
}
pub fn prepare_outpost_capture(
&self,
manifest: SnapshotManifest,
outpost_id: Uuid,
restic_id: &str,
) -> Result<StoredSnapshot> {
let config = self.outpost_config(manifest.orbit_id)?;
anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost");
let repo = self.outpost_repository(manifest.orbit_id, config);
let id = manifest.snapshot_id;
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
Ok(StoredSnapshot {
id,
taken_at: Utc::now(),
manifest,
size_bytes: summary.total_bytes_processed,
tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX),
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
})
}
pub fn snapshot_files(
&self,
mut manifest: SnapshotManifest,
@@ -209,7 +232,7 @@ impl Vault {
manifest.restore_hints = serde_json::json!({ "format": "tar" });
let exclude = restic::literal_pattern(&vault)?;
self.restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--force", "--exclude", &exclude]);
cmd.args(["--exclude", &exclude]);
if let Some(max) = max_file_bytes {
cmd.arg("--exclude-larger-than").arg(max.to_string());
}
@@ -218,6 +241,19 @@ impl Vault {
}
pub fn snapshot_payload(
&self,
manifest: SnapshotManifest,
payload: File,
dry_run: bool,
) -> Result<StoredSnapshot> {
let snap = self.prepare_payload(manifest, payload, dry_run)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
pub fn prepare_payload(
&self,
manifest: SnapshotManifest,
mut payload: File,
@@ -227,13 +263,13 @@ impl Vault {
// Restic rejects empty stdin. A relative filename keeps the same restore path.
let temp = tempfile::tempdir()?;
File::create(temp.path().join("payload"))?;
return self.restic_snapshot(manifest, dry_run, |cmd| {
return self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.current_dir(temp.path())
.args(["--force", "--", "payload"]);
});
}
payload.seek(SeekFrom::Start(0))?;
self.restic_snapshot(manifest, dry_run, |cmd| {
self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--stdin", "--stdin-filename", restic::PAYLOAD])
.stdin(Stdio::from(payload));
})
@@ -244,6 +280,19 @@ impl Vault {
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let snap = self.prepare_restic_snapshot(manifest, dry_run, source)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
fn prepare_restic_snapshot(
&self,
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let taken_at = Utc::now();
let temp;
@@ -261,7 +310,7 @@ impl Vault {
repo.init()
.context("opening the deduplicated vault (restic must be on PATH)")?;
let mut cmd = repo.command();
cmd.args(["backup", "--json", "--quiet"]);
cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]);
if dry_run {
cmd.arg("--dry-run");
}
@@ -286,12 +335,79 @@ impl Vault {
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
};
if !dry_run {
self.write_snapshot(&snap, false)?;
}
Ok(snap)
}
pub fn import_legacy_payload(
&self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime<Utc>,
) -> Result<bool> {
let id = manifest.snapshot_id;
let receipts = self.root.join("keys/legacy-imports");
fs::create_dir_all(&receipts)?;
restrict_dir(&receipts)?;
let receipt = receipts.join(id.to_string());
if receipt.try_exists()? {
return Ok(false);
}
let snapshots = self.root.join("snapshots");
let already_imported = || -> Result<bool> {
Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?)
};
let imported = if already_imported()? {
false
} else {
let mut prepared = self.prepare_payload(manifest, payload, false)?;
prepared.taken_at = taken_at;
match self.publish_prepared(&prepared) {
Ok(()) => true,
Err(_) if already_imported()? => {
self.discard_prepared(&prepared)?;
false
}
Err(error) => return Err(error),
}
};
let marker = tempfile::NamedTempFile::new_in(&receipts)?;
marker.as_file().sync_all()?;
match marker.persist_noclobber(&receipt) {
Ok(_) => sync_directory(&receipts)?,
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(error) => return Err(error.into()),
}
Ok(imported)
}
pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("keys/legacy-imports").join(id.to_string()).try_exists()?)
}
pub fn verify_prepared_payload(&self, snap: &StoredSnapshot, expected: &[u8; 32]) -> Result<()> {
use sha2::{Digest, Sha256};
let id = snap.tree_root.strip_prefix(restic::PREFIX).context("prepared payload is missing")?;
let mut file = tempfile::tempfile()?;
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)?;
anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch");
Ok(())
}
pub fn publish_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
self.write_snapshot(snap, false)
}
pub fn discard_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
self.restic.forget(&[id.to_owned()])?;
}
Ok(())
}
pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("snapshots").join(format!("{id}.json.enc")).try_exists()?)
}
fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json")
}
@@ -435,13 +551,30 @@ impl Vault {
Ok(out)
}
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> {
let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job");
let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit = snapshot.manifest.orbit_id;
(self.outpost_repository(orbit, self.outpost_config(orbit)?), id)
} else {
(self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?)
};
Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() })
}
pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.try_exists()? {
return self.read_snapshot_file(&path).map(Some);
}
}
Ok(None)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let plain = self.root.join("snapshots").join(format!("{id}.json"));
let path = if enc.exists() { enc } else { plain };
let snap = self
.read_snapshot_file(&path)
.context("snapshot metadata")?;
let snap = self.get_snapshot(id)?.context("snapshot metadata not found")?;
let parent = dest
.parent()
.filter(|p| !p.as_os_str().is_empty())
@@ -450,8 +583,9 @@ impl Vault {
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit_id = snap.manifest.orbit_id;
let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD };
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, "/", temp.reopen()?)?;
.dump(id, path, temp.reopen()?)?;
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
let path = if snap.manifest.provider == "filesystem" {
"/"
@@ -548,7 +682,9 @@ impl Vault {
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?;
self.prune_snapshots(preset, None, snaps.into_iter())
self.prune_snapshots(preset, None, snaps.into_iter()
.filter(|snapshot| snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none()))
}
pub fn prune_orbit_with_decay(