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

@@ -1,9 +1,11 @@
mod http;
mod jobs;
mod restore;
use anyhow::{Context, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use tessera_core::config::ProviderKind;
use tessera_core::{config::ProviderKind, WormholeCredentials};
use tessera_providers::provider_from_config;
use tracing::info;
@@ -18,6 +20,10 @@ struct Cli {
upload_token: Option<String>,
#[arg(long, env = "TESSERA_ORBIT_ID")]
orbit_id: Option<String>,
#[arg(long, env = "TESSERA_CAPTURE_PROFILES")]
capture_profiles: Option<std::path::PathBuf>,
#[arg(long, env = "TESSERA_WORMHOLE_CREDENTIALS")]
credentials: Option<std::path::PathBuf>,
}
#[derive(Clone, Subcommand)]
@@ -34,34 +40,100 @@ enum AgentCmd {
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let cli = Cli::parse();
let mut cli = Cli::parse();
if !matches!(&cli.command, Some(AgentCmd::Pair { .. })) {
load_credentials(&mut cli)?;
}
match cli.command.clone().unwrap_or(AgentCmd::Run) {
AgentCmd::Run => run_daemon(&cli).await?,
AgentCmd::Run => tokio::select! {
result = run_daemon(&cli) => result?,
result = shutdown_signal() => result?,
},
AgentCmd::Pair { code, name } => pair(&cli, &code, &name)?,
AgentCmd::Beam => beam_once(&cli).await?,
}
Ok(())
}
async fn shutdown_signal() -> Result<()> {
#[cfg(unix)]
{
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
tokio::select! {
result = tokio::signal::ctrl_c() => result?,
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
tokio::signal::ctrl_c().await?;
Ok(())
}
fn pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
let hub = cli
.hub_url
.clone()
.unwrap_or_else(|| "http://127.0.0.1:8787".into());
if let Some(path) = &cli.credentials {
anyhow::ensure!(!path.try_exists()?, "credentials file already exists");
jobs::require_secure_hub(hub.trim_end_matches('/'))?;
}
let body = serde_json::json!({ "code": code, "outpost_name": name });
let raw = http::post_json(
&format!("{hub}/api/v1/wormhole/claim"),
&format!("{}/api/v1/wormhole/claim", hub.trim_end_matches('/')),
&body,
&[],
)?;
let res: serde_json::Value = serde_json::from_str(&raw)?;
println!("TESSERA_UPLOAD_TOKEN={}", res["upload_token"]);
println!("TESSERA_HUB_URL={}", res["hub_url"]);
println!("Outpost {}", res["outpost_id"]);
let mut credentials: WormholeCredentials = serde_json::from_str(&raw)?;
if cli.hub_url.is_some()
&& (hub.starts_with("https://") || !credentials.hub_url.starts_with("https://"))
{
credentials.hub_url = hub;
}
if let Some(path) = &cli.credentials {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
let file =
tempfile::NamedTempFile::new_in(parent).context("create private credentials file")?;
serde_json::to_writer(file.as_file(), &credentials)?;
file.as_file().sync_all()?;
file.persist_noclobber(path)
.context("save pairing credentials (file must not exist)")?;
println!("Saved credentials for outpost {}", credentials.outpost_id);
} else {
println!("TESSERA_UPLOAD_TOKEN={}", credentials.upload_token);
println!("TESSERA_HUB_URL={}", credentials.hub_url);
println!("Outpost {}", credentials.outpost_id);
}
Ok(())
}
fn load_credentials(cli: &mut Cli) -> Result<()> {
let Some(path) = &cli.credentials else {
return Ok(());
};
let file = std::fs::File::open(path).context("open paired credentials")?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
anyhow::ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"paired credentials require owner-only permissions"
);
}
let credentials: WormholeCredentials = serde_json::from_reader(file)
.map_err(|_| anyhow::anyhow!("invalid pairing credentials"))?;
cli.hub_url.get_or_insert(credentials.hub_url);
cli.upload_token.get_or_insert(credentials.upload_token);
Ok(())
}
async fn run_daemon(cli: &Cli) -> Result<()> {
if let Some(path) = &cli.capture_profiles {
return jobs::run(cli, path).await;
}
info!("outpost online — wormhole listening for beam cycles");
loop {
if let Err(e) = beam_once(cli).await {
@@ -117,42 +189,17 @@ async fn beam_once(cli: &Cli) -> Result<()> {
&[("x-tessera-upload-token", &token)],
)?;
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
info!(
"beamed {} bytes via wormhole session {session_id}",
capture.payload.len()
);
Ok(())
}
async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::Uuid) -> Result<()> {
let authority = repository
.strip_prefix("rest:https://")
.and_then(|url| url.split('/').next());
anyhow::ensure!(
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
);
let output = tokio::process::Command::new("restic")
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.args(["backup", "--json", "--quiet", "--force", "--", "."])
.stdin(std::process::Stdio::null())
.kill_on_drop(true)
.output()
.await
.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(
output.status.success(),
"restic backup failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
let snapshot = summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?;
let mut command = restic_command(repository)?;
command.args(["backup", "--json", "--quiet", "--", "."]);
let snapshot = restic_snapshot(command).await?;
let body = serde_json::json!({ "orbit_id": orbit_id, "snapshot_id": snapshot });
let reply = http::post_json(
&format!("{hub}/api/v1/wormhole/restic/commit"),
@@ -167,8 +214,36 @@ async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::U
info!(
snapshot,
registered,
stored_bytes = summary["data_added_packed"].as_u64(),
"committed Restic backup"
);
Ok(())
}
fn restic_command(repository: &str) -> Result<tokio::process::Command> {
let authority = repository
.strip_prefix("rest:https://")
.and_then(|url| url.split('/').next());
anyhow::ensure!(
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
);
let mut command = tokio::process::Command::new("restic");
command.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.stdin(std::process::Stdio::null())
.kill_on_drop(true);
Ok(command)
}
async fn restic_snapshot(mut command: tokio::process::Command) -> Result<String> {
let output = command.output().await.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(output.status.success(), "restic backup failed ({})", output.status);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
Ok(summary["snapshot_id"].as_str().context("missing restic snapshot ID")?.to_owned())
}