Files
tessera/crates/tessera-agent/src/main.rs
Adnan Zahir 6320b6f244 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>
2026-11-10 23:26:49 +07:00

250 lines
8.4 KiB
Rust

mod http;
mod jobs;
mod restore;
use anyhow::{Context, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use tessera_core::{config::ProviderKind, WormholeCredentials};
use tessera_providers::provider_from_config;
use tracing::info;
#[derive(Parser)]
#[command(name = "tessera-agent", about = "Tessera outpost daemon")]
struct Cli {
#[command(subcommand)]
command: Option<AgentCmd>,
#[arg(long, env = "TESSERA_HUB_URL")]
hub_url: Option<String>,
#[arg(long, env = "TESSERA_UPLOAD_TOKEN")]
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)]
enum AgentCmd {
Run,
Pair {
code: String,
#[arg(long, default_value = "outpost")]
name: String,
},
Beam,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
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 => 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!("{}/api/v1/wormhole/claim", hub.trim_end_matches('/')),
&body,
&[],
)?;
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 {
tracing::warn!("beam failed: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
}
}
async fn beam_once(cli: &Cli) -> Result<()> {
let hub = cli
.hub_url
.clone()
.context("TESSERA_HUB_URL")?
.trim_end_matches('/')
.to_string();
let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?;
let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?;
if let Some(repository) = std::env::var_os("TESSERA_RESTIC_REPOSITORY") {
let repository = repository
.to_str()
.context("TESSERA_RESTIC_REPOSITORY must be UTF-8")?;
let id = uuid::Uuid::parse_str(&orbit_id).context("invalid TESSERA_ORBIT_ID")?;
return beam_restic(repository, &hub, &token, id).await;
}
let config = serde_json::json!({ "paths": ["./"] });
let provider = provider_from_config(&ProviderKind::Filesystem, &config)?;
let capture = provider.capture().await?;
let chunk_b64 = base64::engine::general_purpose::STANDARD.encode(&capture.payload);
let init_body = serde_json::json!({
"orbit_id": orbit_id,
"total_bytes": capture.payload.len(),
});
let init_raw = http::post_json(
&format!("{hub}/api/v1/wormhole/upload/init"),
&init_body,
&[("x-tessera-upload-token", &token)],
)?;
let init: serde_json::Value = serde_json::from_str(&init_raw)?;
let session_id = init["session_id"].as_str().context("session_id")?;
let chunk_body = serde_json::json!({
"session_id": session_id,
"offset": 0,
"data_b64": chunk_b64,
});
http::post_json(
&format!("{hub}/api/v1/wormhole/upload/chunk"),
&chunk_body,
&[("x-tessera-upload-token", &token)],
)?;
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 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"),
&body,
&[("x-tessera-upload-token", token)],
)
.with_context(|| format!("register Restic snapshot {snapshot}"))?;
let reply: serde_json::Value = serde_json::from_str(&reply)?;
let registered = reply["snapshot_id"]
.as_str()
.context("hub did not register the Restic snapshot")?;
info!(
snapshot,
registered,
"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())
}