369 lines
11 KiB
Rust
369 lines
11 KiB
Rust
mod http;
|
|
mod legacy_import;
|
|
|
|
use anyhow::{Context, Result};
|
|
use clap::{Args, Parser, Subcommand};
|
|
use tessera_core::decay::RetentionPolicy;
|
|
use tessera_store::Vault;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Parser, Clone)]
|
|
#[command(name = "tessera", about = "Tessera backup vault CLI")]
|
|
struct Cli {
|
|
#[command(subcommand)]
|
|
command: Commands,
|
|
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
|
|
data_dir: String,
|
|
/// Required for vault commands. No default; the published example passphrase is rejected for new vaults.
|
|
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE")]
|
|
vault_pass: Option<String>,
|
|
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
|
|
hub_url: String,
|
|
}
|
|
|
|
#[derive(Subcommand, Clone)]
|
|
enum Commands {
|
|
Init,
|
|
Status,
|
|
Orbit {
|
|
name: String,
|
|
#[arg(long, default_value = "filesystem")]
|
|
provider: String,
|
|
#[arg(long)]
|
|
path: Option<String>,
|
|
#[arg(long)]
|
|
schedule: Option<String>,
|
|
#[arg(long)]
|
|
dry_run: bool,
|
|
#[command(flatten)]
|
|
retention: RetentionArgs,
|
|
},
|
|
/// Change an orbit's retention for future captures.
|
|
Retention {
|
|
orbit_id: Uuid,
|
|
#[arg(long)]
|
|
preset: Option<String>,
|
|
#[command(flatten)]
|
|
counts: RetentionArgs,
|
|
},
|
|
Snap {
|
|
#[arg(long)]
|
|
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,
|
|
},
|
|
Decay {
|
|
#[arg(long, default_value = "week-of-dailies")]
|
|
preset: String,
|
|
},
|
|
/// Reclaim unreferenced data from expired Restic snapshots.
|
|
Gc,
|
|
Wormhole {
|
|
#[command(subcommand)]
|
|
cmd: WormholeCmd,
|
|
},
|
|
/// Dev-only: populate demo orbits and snapshot history for UI previews.
|
|
SeedDemo {
|
|
/// Replace existing demo seed data.
|
|
#[arg(long)]
|
|
force: bool,
|
|
/// Remove demo data (orbits/snapshots marker) only.
|
|
#[arg(long)]
|
|
reset: bool,
|
|
},
|
|
}
|
|
|
|
#[derive(Args, Clone)]
|
|
struct RetentionArgs {
|
|
#[arg(long)]
|
|
keep_daily: Option<u32>,
|
|
#[arg(long)]
|
|
keep_weekly: Option<u32>,
|
|
#[arg(long)]
|
|
keep_monthly: Option<u32>,
|
|
#[arg(long)]
|
|
keep_yearly: Option<u32>,
|
|
}
|
|
|
|
impl RetentionArgs {
|
|
fn policy(self) -> Result<Option<RetentionPolicy>> {
|
|
if [
|
|
self.keep_daily,
|
|
self.keep_weekly,
|
|
self.keep_monthly,
|
|
self.keep_yearly,
|
|
]
|
|
.iter()
|
|
.all(Option::is_none)
|
|
{
|
|
return Ok(None);
|
|
}
|
|
let policy = RetentionPolicy {
|
|
keep_daily: self.keep_daily.unwrap_or(0),
|
|
keep_weekly: self.keep_weekly.unwrap_or(0),
|
|
keep_monthly: self.keep_monthly.unwrap_or(0),
|
|
keep_yearly: self.keep_yearly.unwrap_or(0),
|
|
};
|
|
anyhow::ensure!(
|
|
policy.has_tiers(),
|
|
"set at least one retention count above zero"
|
|
);
|
|
Ok(Some(policy))
|
|
}
|
|
}
|
|
|
|
#[derive(Subcommand, Clone)]
|
|
enum WormholeCmd {
|
|
Pair {
|
|
code: String,
|
|
#[arg(long, default_value = "outpost")]
|
|
name: String,
|
|
},
|
|
}
|
|
|
|
fn main() -> Result<()> {
|
|
let cli = Cli::parse();
|
|
let command = cli.command.clone();
|
|
match command {
|
|
Commands::Init => cmd_init(&cli)?,
|
|
Commands::Status => cmd_status(&cli)?,
|
|
Commands::Orbit {
|
|
name,
|
|
provider,
|
|
path,
|
|
schedule,
|
|
dry_run,
|
|
retention,
|
|
} => cmd_orbit(
|
|
&cli,
|
|
name,
|
|
provider,
|
|
path,
|
|
schedule,
|
|
dry_run,
|
|
retention.policy()?,
|
|
)?,
|
|
Commands::Retention {
|
|
orbit_id,
|
|
preset,
|
|
counts,
|
|
} => {
|
|
let retention = counts.policy()?;
|
|
anyhow::ensure!(
|
|
preset.is_some() != retention.is_some(),
|
|
"choose --preset or custom --keep-* counts"
|
|
);
|
|
http::put_json(
|
|
&format!("{}/api/v1/orbits/{orbit_id}/retention", cli.hub_url),
|
|
&serde_json::json!({ "decay_preset": preset, "retention": retention }),
|
|
)?;
|
|
println!("Retention saved for {orbit_id}.");
|
|
}
|
|
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,
|
|
} => cmd_reconstitute(&cli, snapshot_id, target)?,
|
|
Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
|
|
Commands::Gc => {
|
|
Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()?
|
|
}
|
|
Commands::Wormhole { ref cmd } => match cmd {
|
|
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
|
|
},
|
|
Commands::SeedDemo { force, reset } => cmd_seed_demo(&cli, force, reset)?,
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn require_passphrase(cli: &Cli) -> Result<&str> {
|
|
match cli.vault_pass.as_deref() {
|
|
Some(pass) if !pass.is_empty() => Ok(pass),
|
|
_ => anyhow::bail!(
|
|
"Set TESSERA_VAULT_PASSPHRASE or pass --vault-pass. Tessera does not ship a default passphrase."
|
|
),
|
|
}
|
|
}
|
|
|
|
fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> {
|
|
let data = std::path::Path::new(&cli.data_dir);
|
|
let vault_pass = require_passphrase(cli)?;
|
|
if reset {
|
|
tessera_demo::clear_demo(data, vault_pass)?;
|
|
println!("Demo seed cleared.");
|
|
return Ok(());
|
|
}
|
|
let report = tessera_demo::apply(data, vault_pass, force)?;
|
|
if report.skipped {
|
|
println!(
|
|
"Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.",
|
|
report.orbits, report.snapshots
|
|
);
|
|
} else {
|
|
println!(
|
|
"Demo seed complete: {} orbits, {} snapshots, {} outposts.",
|
|
report.orbits, report.snapshots, report.outposts
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn vault_path(data_dir: &str) -> std::path::PathBuf {
|
|
std::path::PathBuf::from(data_dir).join("vault")
|
|
}
|
|
|
|
fn cmd_init(cli: &Cli) -> Result<()> {
|
|
let vp = vault_path(&cli.data_dir);
|
|
if vp.join("config").exists() {
|
|
println!("Vault already initialized.");
|
|
return Ok(());
|
|
}
|
|
Vault::init(&vp, require_passphrase(cli)?).context("init vault")?;
|
|
println!("Vault initialized at {}", vp.display());
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_status(cli: &Cli) -> Result<()> {
|
|
match http::get(&format!("{}/health", cli.hub_url)) {
|
|
Ok(body) => println!("Hub: {body}"),
|
|
Err(_) => println!("Hub: offline (is tessera-hub running?)"),
|
|
}
|
|
let vp = vault_path(&cli.data_dir);
|
|
if vp.join("config").exists() {
|
|
let vault = Vault::open(&vp, require_passphrase(cli)?)?;
|
|
let n = vault.list_snapshots()?.len();
|
|
println!("Vault: online — {n} snapshots");
|
|
} else {
|
|
println!("Vault: not initialized (run tessera init)");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_orbit(
|
|
cli: &Cli,
|
|
name: String,
|
|
provider: String,
|
|
path: Option<String>,
|
|
schedule: Option<String>,
|
|
dry_run: bool,
|
|
retention: Option<RetentionPolicy>,
|
|
) -> Result<()> {
|
|
let config = match provider.as_str() {
|
|
"filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }),
|
|
"postgres" => {
|
|
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"
|
|
);
|
|
serde_json::json!({})
|
|
}
|
|
_ => anyhow::bail!("unknown provider"),
|
|
};
|
|
let body = serde_json::json!({
|
|
"name": name,
|
|
"provider": provider,
|
|
"provider_config": config,
|
|
"schedule": schedule,
|
|
"dry_run": dry_run,
|
|
"retention": retention,
|
|
});
|
|
let raw = http::post_json(&format!("{}/api/v1/orbits", cli.hub_url), &body)?;
|
|
let orbit: serde_json::Value = serde_json::from_str(&raw)?;
|
|
println!("Orbit registered: {}", orbit["id"]);
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
|
|
let raw = http::get(&format!("{}/api/v1/orbits", cli.hub_url))?;
|
|
let orbits: serde_json::Value = serde_json::from_str(&raw)?;
|
|
let arr = orbits.as_array().context("orbits response")?;
|
|
let id = if let Some(name) = orbit_name {
|
|
arr.iter()
|
|
.find(|o| o["name"] == name)
|
|
.and_then(|o| o["id"].as_str())
|
|
.context("orbit not found")?
|
|
} else {
|
|
arr.first()
|
|
.and_then(|o| o["id"].as_str())
|
|
.context("no orbits defined")?
|
|
};
|
|
http::post_empty(&format!("{}/api/v1/orbits/{id}/run", cli.hub_url))?;
|
|
println!("Orbit run triggered.");
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_list(cli: &Cli) -> Result<()> {
|
|
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
|
for s in vault.list_snapshots()? {
|
|
let stored = s
|
|
.stored_bytes
|
|
.map(|n| format!(" +{n} bytes stored"))
|
|
.unwrap_or_default();
|
|
println!(
|
|
"{} {} {} bytes orbit={}{}",
|
|
s.taken_at.to_rfc3339(),
|
|
s.id,
|
|
s.size_bytes,
|
|
s.manifest.orbit_name,
|
|
stored,
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
|
|
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
|
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
|
|
println!("Reconstituted {n} bytes to {target}");
|
|
Ok(())
|
|
}
|
|
|
|
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
|
|
let mut vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
|
|
let pruned = vault.prune_with_decay(preset)?;
|
|
println!("{} snapshots decayed.", pruned.len());
|
|
Ok(())
|
|
}
|
|
|
|
fn wormhole_pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
|
|
let body = serde_json::json!({ "code": code, "outpost_name": name });
|
|
let raw = http::post_json(&format!("{}/api/v1/wormhole/claim", cli.hub_url), &body)?;
|
|
let res: serde_json::Value = serde_json::from_str(&raw)?;
|
|
println!("Paired outpost {}", res["outpost_id"]);
|
|
println!("Set TESSERA_UPLOAD_TOKEN on the agent.");
|
|
Ok(())
|
|
}
|