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,6 +1,6 @@
use anyhow::{Context, Result};
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::{IpAddr, TcpStream};
pub fn get(url: &str) -> Result<String> {
request("GET", url, None, None)
@@ -24,8 +24,21 @@ fn request(
content_type: Option<&str>,
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
if let Ok(token) = std::env::var("TESSERA_ADMIN_TOKEN") {
let token = token.trim();
if !token.is_empty() {
anyhow::ensure!(
host == "localhost" || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback()),
"the HTTP CLI requires a loopback hub URL when using an admin token"
);
anyhow::ensure!(
token.bytes().all(|byte| byte.is_ascii_graphic()),
"invalid admin token"
);
req.push_str(&format!("Authorization: Bearer {token}\r\n"));
}
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
@@ -36,6 +49,7 @@ fn request(
} else {
req.push_str("\r\n");
}
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;

View File

@@ -0,0 +1,287 @@
use anyhow::{ensure, Context, Result};
use chrono::{DateTime, Utc};
use clap::{Args, ValueEnum};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{self, Read, Seek, SeekFrom},
path::PathBuf,
process::{Command, Stdio},
};
use tessera_core::SnapshotManifest;
use tessera_store::Vault;
use uuid::Uuid;
#[derive(Args, Clone)]
pub struct ImportArgs {
#[arg(long)]
bucket: String,
#[arg(long)]
prefix: String,
#[arg(long)]
endpoint: Option<String>,
#[arg(long)]
orbit_id: Uuid,
#[arg(long)]
application: String,
#[arg(long, value_enum)]
engine: Engine,
/// Consistent SQLite export of the old service's job history.
#[arg(long)]
history: Option<PathBuf>,
/// Reconcile counts, times and sizes without downloading or writing snapshots.
#[arg(long)]
inventory_only: bool,
}
#[derive(Clone, Copy, ValueEnum)]
enum Engine {
Postgres,
Mysql,
}
impl Engine {
fn name(self) -> &'static str {
match self {
Self::Postgres => "postgres",
Self::Mysql => "mysql",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Listing {
#[serde(default)]
contents: Vec<Object>,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all(deserialize = "PascalCase"))]
struct Object {
key: String,
#[serde(rename(deserialize = "ETag"))]
etag: String,
size: u64,
last_modified: DateTime<Utc>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Downloaded {
#[serde(rename = "ETag")]
etag: String,
content_length: u64,
last_modified: DateTime<Utc>,
}
#[derive(Serialize)]
struct Entry {
snapshot_id: Uuid,
#[serde(flatten)]
object: Object,
status: &'static str,
}
#[derive(Serialize)]
struct Report {
application: String,
bucket: String,
prefix: String,
count: usize,
bytes: u64,
history_snapshot_id: Option<Uuid>,
objects: Vec<Entry>,
}
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
ensure!(
!args.prefix.is_empty() && args.prefix.ends_with('/'),
"provide a per-application prefix ending in '/'"
);
ensure!(
!args.application.trim().is_empty()
&& args.application.len() <= 128
&& !args.application.chars().any(char::is_control),
"invalid application name"
);
if let Some(endpoint) = &args.endpoint {
ensure!(
(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:"))
&& !endpoint.contains(['@', '?', '#', '\r', '\n']),
"use an HTTPS S3 endpoint without embedded credentials"
);
}
let output = aws(&args, "list-objects-v2")
.arg(format!("--prefix={}", args.prefix))
.output()
.context("run AWS CLI S3 inventory")?;
ensure!(
output.status.success(),
"could not list legacy S3 objects ({})",
output.status
);
let listing: Listing =
serde_json::from_slice(&output.stdout).context("parse legacy S3 inventory")?;
let mut objects = Vec::new();
let mut bytes = 0u64;
for object in listing.contents {
if !object.key.starts_with(&args.prefix)
|| !(object.key.ends_with(".sql") || object.key.ends_with(".sql.gz"))
{
continue;
}
ensure!(
object.size > 0 && !object.etag.is_empty() && object.etag != "*",
"invalid legacy archive metadata"
);
bytes = bytes
.checked_add(object.size)
.context("legacy inventory byte count overflow")?;
let key = serde_json::to_vec(&(
"s3-legacy",
&args.endpoint,
&args.bucket,
&object.key,
&object.etag,
object.size,
object.last_modified,
args.orbit_id,
))?;
let snapshot_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, &key);
let status = if args.inventory_only {
"inventoried"
} else if vault.legacy_import_exists(snapshot_id)? {
"already_imported"
} else if import_object(vault, &args, &object, snapshot_id)? {
"imported"
} else {
"already_imported"
};
objects.push(Entry {
snapshot_id,
object,
status,
});
}
let history_snapshot_id = if args.inventory_only {
None
} else {
args.history
.as_ref()
.map(|path| import_history(vault, path))
.transpose()?
};
let report = Report {
application: args.application,
bucket: args.bucket,
prefix: args.prefix,
count: objects.len(),
bytes,
history_snapshot_id,
objects,
};
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
fn aws(args: &ImportArgs, operation: &str) -> Command {
let mut cmd = Command::new("aws");
cmd.args([
"--no-cli-pager",
"--no-cli-auto-prompt",
"--output",
"json",
"s3api",
operation,
])
.arg(format!("--bucket={}", args.bucket))
.stdin(Stdio::null())
.stderr(Stdio::null());
if let Some(endpoint) = &args.endpoint {
cmd.arg(format!("--endpoint-url={endpoint}"));
}
cmd
}
fn import_object(vault: &Vault, args: &ImportArgs, object: &Object, id: Uuid) -> Result<bool> {
let file = tempfile::NamedTempFile::new()?;
let output = aws(args, "get-object")
.arg(format!("--key={}", object.key))
.arg(format!("--if-match={}", object.etag))
.arg(file.path())
.output()
.context("run conditional AWS CLI S3 download")?;
ensure!(
output.status.success(),
"legacy archive download failed ({})",
output.status
);
let received: Downloaded =
serde_json::from_slice(&output.stdout).context("parse downloaded object metadata")?;
ensure!(
received.etag == object.etag
&& received.last_modified == object.last_modified
&& received.content_length == object.size
&& file.as_file().metadata()?.len() == object.size,
"legacy object changed since inventory"
);
let mut file = file.reopen()?;
let format = if object.key.ends_with(".sql.gz") {
let mut signature = [0; 2];
file.read_exact(&mut signature)?;
ensure!(
signature == [0x1f, 0x8b],
"legacy archive is missing a gzip header"
);
file.seek(SeekFrom::Start(0))?;
"sql_gzip"
} else {
"plain"
};
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: args.orbit_id,
orbit_name: args.application.clone(),
provider: args.engine.name().into(),
labels: vec!["legacy-import".into()],
paths: vec![],
restore_hints: serde_json::json!({
"format": format, "legacy": { "bucket": args.bucket, "key": object.key,
"etag": object.etag, "bytes": object.size, "last_modified": object.last_modified }
}),
};
vault.import_legacy_payload(manifest, file, object.last_modified)
}
fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
let mut original = File::open(path).context("open legacy history export")?;
let mut signature = [0; 16];
original.read_exact(&mut signature)?;
ensure!(
&signature == b"SQLite format 3\0",
"legacy history must be a consistent SQLite export"
);
original.seek(SeekFrom::Start(0))?;
let mut staged = tempfile::tempfile()?;
let bytes = io::copy(&mut original, &mut staged)?;
staged.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
io::copy(&mut staged, &mut digest)?;
let checksum = hex::encode(digest.finalize());
let key = format!("legacy-history:{checksum}");
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes());
let taken_at: DateTime<Utc> = original.metadata()?.modified()?.into();
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: Uuid::nil(),
orbit_name: "Legacy operator history".into(),
provider: "legacy-history".into(),
labels: vec!["legacy-history".into()],
paths: vec![],
restore_hints: serde_json::json!({"format": "sqlite", "sha256": checksum, "legacy_bytes": bytes}),
};
vault.import_legacy_payload(manifest, staged, taken_at)?;
Ok(id)
}

View File

@@ -1,4 +1,5 @@
mod http;
mod legacy_import;
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
@@ -50,6 +51,13 @@ enum Commands {
orbit: Option<String>,
},
List,
/// Reconcile and import immutable legacy SQL archives from an S3 prefix.
LegacyImport(legacy_import::ImportArgs),
/// Export the private legacy operator-history SQLite archive.
LegacyHistory {
snapshot_id: Uuid,
output: String,
},
Reconstitute {
snapshot_id: Uuid,
target: String,
@@ -163,6 +171,25 @@ fn main() -> Result<()> {
}
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
Commands::List => cmd_list(&cli)?,
Commands::LegacyImport(args) => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
legacy_import::run(&vault, args)?;
}
Commands::LegacyHistory {
snapshot_id,
output,
} => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
let snapshot = vault
.get_snapshot(snapshot_id)?
.context("legacy history archive not found")?;
anyhow::ensure!(
snapshot.manifest.provider == "legacy-history",
"snapshot is not a legacy history archive"
);
vault.restore_snapshot(snapshot_id, std::path::Path::new(&output))?;
println!("Exported legacy history {snapshot_id}");
}
Commands::Reconstitute {
snapshot_id,
target,
@@ -257,8 +284,10 @@ fn cmd_orbit(
serde_json::json!({ "connection_url": path.context("--path or connection url required")? })
}
"wormhole" => {
anyhow::ensure!(path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost");
anyhow::ensure!(
path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost"
);
serde_json::json!({})
}
_ => anyhow::bail!("unknown provider"),