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:
@@ -20,5 +20,9 @@ tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
base64 = "0.22"
|
||||
tempfile.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
|
||||
rustls-pemfile = "=2.2.0"
|
||||
rustls-native-certs = "0.8"
|
||||
|
||||
@@ -3,66 +3,154 @@ use rustls::pki_types::ServerName;
|
||||
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
|
||||
let payload = serde_json::to_string(body)?;
|
||||
request(
|
||||
"POST",
|
||||
url,
|
||||
Some(&payload),
|
||||
Some((&mut payload.as_bytes(), payload.len() as u64)),
|
||||
Some("application/json"),
|
||||
headers,
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn post_file(
|
||||
url: &str,
|
||||
file: &mut File,
|
||||
len: u64,
|
||||
headers: &[(&str, &str)],
|
||||
timeout: Duration,
|
||||
) -> Result<String> {
|
||||
request(
|
||||
"POST",
|
||||
url,
|
||||
Some((file, len)),
|
||||
Some("application/octet-stream"),
|
||||
headers,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_file(
|
||||
url: &str,
|
||||
file: &mut File,
|
||||
headers: &[(&str, &str)],
|
||||
timeout: Duration,
|
||||
) -> Result<u64> {
|
||||
let (mut response, length) = response("GET", url, None, None, headers, timeout)?;
|
||||
let length = length.context("missing restore payload length")?;
|
||||
anyhow::ensure!(
|
||||
length > 0 && length <= 100 * 1024 * 1024 * 1024,
|
||||
"invalid restore payload length"
|
||||
);
|
||||
let read = std::io::copy(&mut response.by_ref().take(length), file)?;
|
||||
anyhow::ensure!(read == length, "incomplete restore payload");
|
||||
Ok(length)
|
||||
}
|
||||
|
||||
fn request(
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<&str>,
|
||||
body: Option<(&mut dyn Read, u64)>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
timeout: Duration,
|
||||
) -> Result<String> {
|
||||
let (mut response, length) = response(method, url, body, content_type, headers, timeout)?;
|
||||
let length = length.unwrap_or(64 * 1024);
|
||||
anyhow::ensure!(length <= 64 * 1024, "hub JSON response too large");
|
||||
let mut body = String::new();
|
||||
let read = response.by_ref().take(length).read_to_string(&mut body)?;
|
||||
if length < 64 * 1024 {
|
||||
anyhow::ensure!(read as u64 == length, "incomplete hub response");
|
||||
}
|
||||
Ok(body.trim().to_owned())
|
||||
}
|
||||
|
||||
fn response(
|
||||
method: &str,
|
||||
url: &str,
|
||||
body: Option<(&mut dyn Read, u64)>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
timeout: Duration,
|
||||
) -> Result<(BufReader<Socket>, Option<u64>)> {
|
||||
let (https, host, port, path) = parse_url(url)?;
|
||||
let mut stream: Box<dyn ReadWrite> = if https {
|
||||
Box::new(connect_mtls(&host, port)?)
|
||||
let mut stream: Socket = if https {
|
||||
Box::new(connect_tls(&host, port, timeout)?)
|
||||
} else {
|
||||
Box::new(TcpStream::connect((host.as_str(), port)).context("connect")?)
|
||||
Box::new(connect(&host, port, timeout)?)
|
||||
};
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
|
||||
for (k, v) in headers {
|
||||
anyhow::ensure!(
|
||||
v.bytes().all(|b| b.is_ascii_graphic() || b == b' '),
|
||||
"invalid HTTP header value"
|
||||
);
|
||||
req.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
if let Some(b) = body {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
|
||||
if let Some((_, len)) = &body {
|
||||
req.push_str(&format!("Content-Length: {len}\r\n"));
|
||||
if let Some(ct) = content_type {
|
||||
req.push_str(&format!("Content-Type: {ct}\r\n"));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
req.push_str(b);
|
||||
} else {
|
||||
req.push_str("\r\n");
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
stream.write_all(req.as_bytes())?;
|
||||
let mut buf = String::new();
|
||||
stream.read_to_string(&mut buf)?;
|
||||
let (response_headers, body) = buf.split_once("\r\n\r\n").context("invalid hub response")?;
|
||||
let status = response_headers
|
||||
.lines()
|
||||
.next()
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
if let Some((reader, len)) = body {
|
||||
anyhow::ensure!(
|
||||
std::io::copy(&mut reader.take(len), &mut stream)? == len,
|
||||
"incomplete upload"
|
||||
);
|
||||
}
|
||||
stream.flush()?;
|
||||
let mut response = BufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
response.by_ref().take(16 * 1024).read_line(&mut line)?;
|
||||
let status = line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.context("missing hub response status")?
|
||||
.parse::<u16>()?;
|
||||
anyhow::ensure!((200..300).contains(&status), "hub returned HTTP {status}");
|
||||
Ok(body.trim().to_string())
|
||||
let mut length = None;
|
||||
let mut header_bytes = 0;
|
||||
loop {
|
||||
line.clear();
|
||||
let read = response.by_ref().take(16 * 1024).read_line(&mut line)?;
|
||||
header_bytes += read;
|
||||
anyhow::ensure!(
|
||||
read != 0 && header_bytes < 16 * 1024,
|
||||
"invalid hub response headers"
|
||||
);
|
||||
if line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':') {
|
||||
if name.eq_ignore_ascii_case("content-length") {
|
||||
length = Some(value.trim().parse()?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((response, if status == 204 { Some(0) } else { length }))
|
||||
}
|
||||
|
||||
type Socket = Box<dyn ReadWrite>;
|
||||
|
||||
trait ReadWrite: Read + Write {}
|
||||
impl<T: Read + Write> ReadWrite for T {}
|
||||
|
||||
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
|
||||
anyhow::ensure!(
|
||||
!url.bytes().any(|b| b.is_ascii_control() || b == b' '),
|
||||
"invalid hub URL"
|
||||
);
|
||||
let (https, rest) = if let Some(rest) = url.strip_prefix("https://") {
|
||||
(true, rest)
|
||||
} else if let Some(rest) = url.strip_prefix("http://") {
|
||||
@@ -71,6 +159,10 @@ fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
|
||||
anyhow::bail!("hub url must start with http:// or https://");
|
||||
};
|
||||
let (host_port, path) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
anyhow::ensure!(
|
||||
!host_port.is_empty() && !host_port.contains(['@', '?', '#']),
|
||||
"invalid hub authority"
|
||||
);
|
||||
let path = if path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
@@ -84,37 +176,66 @@ fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
|
||||
Ok((https, host, port, path))
|
||||
}
|
||||
|
||||
fn connect_mtls(host: &str, port: u16) -> Result<StreamOwned<ClientConnection, TcpStream>> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let ca = std::env::var("TESSERA_WORMHOLE_CA")
|
||||
.context("TESSERA_WORMHOLE_CA is required for an https hub")?;
|
||||
let cert = std::env::var("TESSERA_WORMHOLE_CLIENT_CERT")
|
||||
.context("TESSERA_WORMHOLE_CLIENT_CERT is required for an https hub")?;
|
||||
let key = std::env::var("TESSERA_WORMHOLE_CLIENT_KEY")
|
||||
.context("TESSERA_WORMHOLE_CLIENT_KEY is required for an https hub")?;
|
||||
let mut roots = RootCertStore::empty();
|
||||
for ca_cert in load_certs(&ca)? {
|
||||
roots.add(ca_cert).map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
|
||||
fn connect(host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
|
||||
for address in (host, port).to_socket_addrs()? {
|
||||
if let Ok(socket) = TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
|
||||
socket.set_read_timeout(Some(timeout))?;
|
||||
socket.set_write_timeout(Some(Duration::from_secs(30)))?;
|
||||
return Ok(socket);
|
||||
}
|
||||
}
|
||||
let client = ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_client_auth_cert(load_certs(&cert)?, load_key(&key)?)
|
||||
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?;
|
||||
anyhow::bail!("could not connect to hub")
|
||||
}
|
||||
|
||||
fn connect_tls(
|
||||
host: &str,
|
||||
port: u16,
|
||||
timeout: Duration,
|
||||
) -> Result<StreamOwned<ClientConnection, TcpStream>> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let mut roots = RootCertStore::empty();
|
||||
if let Some(ca) = std::env::var_os("TESSERA_WORMHOLE_CA") {
|
||||
for ca_cert in load_certs(std::path::Path::new(&ca))? {
|
||||
roots
|
||||
.add(ca_cert)
|
||||
.map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
|
||||
}
|
||||
} else {
|
||||
let native = rustls_native_certs::load_native_certs();
|
||||
roots.add_parsable_certificates(native.certs);
|
||||
}
|
||||
anyhow::ensure!(!roots.is_empty(), "no trusted hub CA certificates");
|
||||
let builder = ClientConfig::builder().with_root_certificates(roots);
|
||||
let client = match (
|
||||
std::env::var_os("TESSERA_WORMHOLE_CLIENT_CERT"),
|
||||
std::env::var_os("TESSERA_WORMHOLE_CLIENT_KEY"),
|
||||
) {
|
||||
(Some(cert), Some(key)) => builder
|
||||
.with_client_auth_cert(
|
||||
load_certs(std::path::Path::new(&cert))?,
|
||||
load_key(std::path::Path::new(&key))?,
|
||||
)
|
||||
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?,
|
||||
(None, None) => builder.with_no_client_auth(),
|
||||
_ => anyhow::bail!("configure both Wormhole client certificate and key"),
|
||||
};
|
||||
let name = ServerName::try_from(host.to_string()).context("hub hostname")?;
|
||||
let connection = ClientConnection::new(Arc::new(client), name)?;
|
||||
let tcp = TcpStream::connect((host, port)).context("connect")?;
|
||||
let tcp = connect(host, port, timeout)?;
|
||||
Ok(StreamOwned::new(connection, tcp))
|
||||
}
|
||||
|
||||
fn load_certs(path: &str) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
|
||||
fn load_certs(path: &std::path::Path) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
|
||||
let mut reader =
|
||||
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
|
||||
rustls_pemfile::certs(&mut reader)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.context("parse certificate")
|
||||
}
|
||||
|
||||
fn load_key(path: &str) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
|
||||
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?);
|
||||
fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
|
||||
let mut reader =
|
||||
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
|
||||
rustls_pemfile::private_key(&mut reader)
|
||||
.context("parse private key")?
|
||||
.context("no private key in client key file")
|
||||
|
||||
381
crates/tessera-agent/src/jobs.rs
Normal file
381
crates/tessera-agent/src/jobs.rs
Normal file
@@ -0,0 +1,381 @@
|
||||
use crate::{http, restore, Cli};
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine as _;
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{self, Seek, SeekFrom},
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tessera_core::job::{
|
||||
CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit, CAPTURE_HEARTBEAT_SECONDS,
|
||||
};
|
||||
use tessera_core::restore::DatabaseIdentity;
|
||||
use tessera_providers::{MysqlSource, PostgresSource};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Profile {
|
||||
source: Option<Source>,
|
||||
#[serde(default)]
|
||||
paths: Vec<PathBuf>,
|
||||
restic_repository: Option<String>,
|
||||
restic_password_file: Option<PathBuf>,
|
||||
rest_server_password_file: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
targets: HashMap<Uuid, restore::Target>,
|
||||
#[serde(default = "default_timeout")]
|
||||
timeout_seconds: u64,
|
||||
}
|
||||
|
||||
fn default_timeout() -> u64 {
|
||||
3600
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "engine", rename_all = "snake_case")]
|
||||
pub(super) enum Source {
|
||||
Postgres(PostgresSource),
|
||||
Mysql(MysqlSource),
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
match self {
|
||||
Self::Postgres(source) => source.identity().await,
|
||||
Self::Mysql(source) => source.identity().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Hub {
|
||||
pub(super) url: String,
|
||||
pub(super) token: String,
|
||||
}
|
||||
|
||||
pub fn require_secure_hub(url: &str) -> Result<()> {
|
||||
let local = ["http://127.0.0.1:", "http://localhost:"]
|
||||
.into_iter()
|
||||
.any(|prefix| {
|
||||
url.strip_prefix(prefix)
|
||||
.is_some_and(|port| port.parse::<u16>().is_ok())
|
||||
});
|
||||
anyhow::ensure!(
|
||||
url.starts_with("https://") || local,
|
||||
"remote Wormhole connections require an HTTPS hub"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
|
||||
let profiles: HashMap<Uuid, Profile> =
|
||||
serde_json::from_reader(File::open(path).context("open capture profiles")?)
|
||||
.map_err(|_| anyhow::anyhow!("invalid capture profiles"))?;
|
||||
anyhow::ensure!(!profiles.is_empty(), "capture profile file is empty");
|
||||
anyhow::ensure!(
|
||||
profiles.values().all(|profile| profile.timeout_seconds > 0),
|
||||
"capture timeout must be positive"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
profiles
|
||||
.values()
|
||||
.all(|profile| profile.source.is_some() || !profile.paths.is_empty() || !profile.targets.is_empty()),
|
||||
"application requires a source or at least one restore target"
|
||||
);
|
||||
let url = cli
|
||||
.hub_url
|
||||
.as_deref()
|
||||
.context("TESSERA_HUB_URL")?
|
||||
.trim_end_matches('/');
|
||||
require_secure_hub(url)?;
|
||||
let token = cli
|
||||
.upload_token
|
||||
.as_deref()
|
||||
.context("TESSERA_UPLOAD_TOKEN")?;
|
||||
anyhow::ensure!(
|
||||
!token.is_empty() && token.bytes().all(|b| b.is_ascii_graphic()),
|
||||
"invalid upload token"
|
||||
);
|
||||
let hub = Arc::new(Hub {
|
||||
url: url.to_owned(),
|
||||
token: token.to_owned(),
|
||||
});
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for (id, profile) in profiles {
|
||||
let hub = Arc::clone(&hub);
|
||||
workers.spawn(async move {
|
||||
loop {
|
||||
if let Err(error) = async {
|
||||
let restored = restore::poll(
|
||||
&hub,
|
||||
id,
|
||||
profile.source.as_ref(),
|
||||
&profile.targets,
|
||||
profile.timeout_seconds,
|
||||
)
|
||||
.await?;
|
||||
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {
|
||||
poll(&hub, id, &profile).await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await
|
||||
{
|
||||
tracing::warn!(application_id = %id, %error, "capture polling failed");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
workers
|
||||
.join_next()
|
||||
.await
|
||||
.context("capture worker missing")??;
|
||||
anyhow::bail!("capture worker stopped")
|
||||
}
|
||||
|
||||
async fn poll(hub: &Arc<Hub>, id: Uuid, profile: &Profile) -> Result<()> {
|
||||
let reply = hub
|
||||
.post(format!("capture/{id}/claim"), serde_json::Value::Null, None)
|
||||
.await?;
|
||||
let Some(lease) = serde_json::from_str::<Option<CaptureLease>>(&reply)? else {
|
||||
return Ok(());
|
||||
};
|
||||
anyhow::ensure!(
|
||||
lease.profile.application_id == id,
|
||||
"hub returned a different application"
|
||||
);
|
||||
let work = capture(hub, &lease, profile);
|
||||
tokio::pin!(work);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut work => return result,
|
||||
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
|
||||
hub.report(&lease, CaptureProgress::Heartbeat).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn capture(hub: &Arc<Hub>, lease: &CaptureLease, profile: &Profile) -> Result<()> {
|
||||
hub.report(lease, CaptureProgress::Dumping).await?;
|
||||
if lease.profile.format == CaptureFormat::Filesystem {
|
||||
if profile.paths.is_empty() {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("filesystem profile requires paths");
|
||||
}
|
||||
hub.report(lease, CaptureProgress::Uploading).await?;
|
||||
return commit_backup(hub, lease, profile, None, None).await;
|
||||
}
|
||||
let Some(source) = &profile.source else {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("capture source is missing");
|
||||
};
|
||||
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
|
||||
let stage = tempfile::tempfile().context("create private staging file")?;
|
||||
let before = probe_identity(source).await;
|
||||
match (source, lease.profile.format) {
|
||||
(Source::Postgres(source), CaptureFormat::PostgresCustom) => {
|
||||
source.dump_to(stage.try_clone()?, "custom").await?
|
||||
}
|
||||
(Source::Postgres(source), CaptureFormat::PostgresSql) => {
|
||||
source.dump_to(stage.try_clone()?, "plain").await?
|
||||
}
|
||||
(Source::Mysql(source), CaptureFormat::MysqlSql) => {
|
||||
source.dump_to(stage.try_clone()?).await?
|
||||
}
|
||||
_ => anyhow::bail!("capture profile engine does not match the assignment"),
|
||||
}
|
||||
let identity = match before {
|
||||
Some(identity)
|
||||
if lease.profile.format.engine().is_some_and(|engine| identity.valid(engine))
|
||||
&& probe_identity(source).await.as_ref() == Some(&identity) =>
|
||||
{
|
||||
Some(identity)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok::<_, anyhow::Error>((stage, identity))
|
||||
})
|
||||
.await;
|
||||
let (stage, identity) = match result {
|
||||
Ok(Ok(stage)) => stage,
|
||||
_ => {
|
||||
hub.report(lease, CaptureProgress::DumpFailed).await?;
|
||||
anyhow::bail!("database dump failed or timed out");
|
||||
}
|
||||
};
|
||||
hub.report(lease, CaptureProgress::Uploading).await?;
|
||||
if lease.restic {
|
||||
return commit_backup(hub, lease, profile, Some(stage), identity).await;
|
||||
}
|
||||
|
||||
let identity = identity
|
||||
.map(|value| serde_json::to_vec(&value))
|
||||
.transpose()?
|
||||
.map(|value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value));
|
||||
|
||||
if hub
|
||||
.upload(
|
||||
format!("capture/{}/payload", lease.job_id),
|
||||
stage,
|
||||
Duration::from_secs(profile.timeout_seconds),
|
||||
"x-tessera-lease-id",
|
||||
lease.lease_id,
|
||||
identity,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
hub.report(lease, CaptureProgress::UploadFailed).await?;
|
||||
anyhow::bail!("backup upload failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn commit_backup(
|
||||
hub: &Arc<Hub>,
|
||||
lease: &CaptureLease,
|
||||
profile: &Profile,
|
||||
stage: Option<File>,
|
||||
identity: Option<DatabaseIdentity>,
|
||||
) -> Result<()> {
|
||||
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
|
||||
let repository = profile.restic_repository.as_deref().context("configure the profile Restic repository")?;
|
||||
let mut command = crate::restic_command(repository)?;
|
||||
if let Some(path) = &profile.restic_password_file {
|
||||
command.env_remove("RESTIC_PASSWORD").env_remove("RESTIC_PASSWORD_COMMAND")
|
||||
.env("RESTIC_PASSWORD_FILE", path);
|
||||
}
|
||||
if let Some(path) = &profile.rest_server_password_file {
|
||||
let password = tokio::fs::read_to_string(path).await.context("read Rest Server password")?;
|
||||
command.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string())
|
||||
.env("RESTIC_REST_PASSWORD", password.trim_end_matches(['\r', '\n']));
|
||||
}
|
||||
command.args(["backup", "--json", "--quiet", "--tag", &format!("tessera-{}", lease.job_id)]);
|
||||
let sha256 = if let Some(mut file) = stage {
|
||||
let (file, hash) = tokio::task::spawn_blocking(move || {
|
||||
let (_, hash) = digest_file(&mut file)?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
Ok::<_, anyhow::Error>((file, hash))
|
||||
}).await??;
|
||||
command.args(["--stdin", "--stdin-filename", "payload"]).stdin(Stdio::from(file));
|
||||
Some(hash)
|
||||
} else {
|
||||
command.arg("--").args(&profile.paths);
|
||||
None
|
||||
};
|
||||
let snapshot_id = crate::restic_snapshot(command).await?;
|
||||
let body = serde_json::to_value(ResticCaptureCommit { lease_id: lease.lease_id, snapshot_id, identity, sha256 })?;
|
||||
for _ in 0..3 {
|
||||
if hub.post(format!("capture/{}/restic", lease.job_id), body.clone(), None).await.is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("could not register the Restic snapshot")
|
||||
}).await;
|
||||
match result {
|
||||
Ok(Ok(())) => Ok(()),
|
||||
failure => {
|
||||
hub.report(lease, CaptureProgress::UploadFailed).await?;
|
||||
failure.context("Restic backup timed out")?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_identity(source: &Source) -> Option<DatabaseIdentity> {
|
||||
tokio::time::timeout(Duration::from_secs(10), source.identity())
|
||||
.await
|
||||
.ok()?
|
||||
.ok()
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub(super) async fn post(
|
||||
self: &Arc<Self>,
|
||||
path: String,
|
||||
body: serde_json::Value,
|
||||
restore: Option<Uuid>,
|
||||
) -> Result<String> {
|
||||
let hub = Arc::clone(self);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let restore = restore.map(|token| token.to_string());
|
||||
let mut headers = vec![("x-tessera-upload-token", hub.token.as_str())];
|
||||
if let Some(token) = &restore {
|
||||
headers.push(("x-tessera-restore-token", token.as_str()));
|
||||
}
|
||||
http::post_json(
|
||||
&format!("{}/api/v1/wormhole/{path}", hub.url),
|
||||
&body,
|
||||
&headers,
|
||||
)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn report(
|
||||
self: &Arc<Self>,
|
||||
lease: &CaptureLease,
|
||||
progress: CaptureProgress,
|
||||
) -> Result<()> {
|
||||
let body = CaptureReport {
|
||||
lease_id: lease.lease_id,
|
||||
progress,
|
||||
};
|
||||
self.post(
|
||||
format!("capture/{}/report", lease.job_id),
|
||||
serde_json::to_value(body)?,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn upload(
|
||||
self: &Arc<Self>,
|
||||
path: String,
|
||||
mut file: File,
|
||||
timeout: Duration,
|
||||
lease_header: &'static str,
|
||||
lease: Uuid,
|
||||
identity: Option<String>,
|
||||
) -> Result<()> {
|
||||
let hub = Arc::clone(self);
|
||||
let url = format!("{}/api/v1/wormhole/{path}", hub.url);
|
||||
let lease = lease.to_string();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (len, digest) = digest_file(&mut file)?;
|
||||
let mut headers = vec![
|
||||
("x-tessera-upload-token", hub.token.as_str()),
|
||||
(lease_header, lease.as_str()),
|
||||
("x-tessera-sha256", digest.as_str()),
|
||||
];
|
||||
if let Some(value) = &identity {
|
||||
headers.push(("x-tessera-source-identity", value.as_str()));
|
||||
}
|
||||
for _ in 0..3 {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
if http::post_file(&url, &mut file, len, &headers, timeout).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("backup upload retry limit reached")
|
||||
})
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn digest_file(file: &mut File) -> Result<(u64, String)> {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
let mut digest = Sha256::new();
|
||||
let len = io::copy(file, &mut digest)?;
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
Ok((len, hex::encode(digest.finalize())))
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
235
crates/tessera-agent/src/restore.rs
Normal file
235
crates/tessera-agent/src/restore.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
use crate::{
|
||||
http,
|
||||
jobs::{digest_file, Hub, Source},
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration};
|
||||
use tessera_core::{
|
||||
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS},
|
||||
restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
|
||||
};
|
||||
use tessera_providers::{MysqlRestore, PostgresRestore};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "engine", rename_all = "snake_case")]
|
||||
pub(super) enum Target {
|
||||
Postgres(PostgresRestore),
|
||||
Mysql(MysqlRestore),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.connection.identity().await,
|
||||
Self::Mysql(target) => target.connection.identity().await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File> {
|
||||
match (self, lease.artifact.format) {
|
||||
(
|
||||
Self::Postgres(target),
|
||||
format @ (CaptureFormat::PostgresCustom | CaptureFormat::PostgresSql),
|
||||
) => {
|
||||
target
|
||||
.prepare(input, format, &lease.job.target.identity)
|
||||
.await
|
||||
}
|
||||
(Self::Mysql(target), CaptureFormat::MysqlSql) => {
|
||||
target.prepare(input, &lease.job.target.identity).await
|
||||
}
|
||||
_ => anyhow::bail!("local restore target engine does not match the assignment"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn safety(&self, stage: File) -> Result<()> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.connection.safety_dump_to(stage).await,
|
||||
Self::Mysql(target) => target.connection.dump_to(stage).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply(&self, script: File) -> Result<()> {
|
||||
match self {
|
||||
Self::Postgres(target) => target.apply(script).await,
|
||||
Self::Mysql(target) => target.apply(script).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn poll(
|
||||
hub: &Arc<Hub>,
|
||||
application: Uuid,
|
||||
source: Option<&Source>,
|
||||
targets: &HashMap<Uuid, Target>,
|
||||
timeout_seconds: u64,
|
||||
) -> Result<bool> {
|
||||
for (target_id, target) in targets {
|
||||
let reply = hub
|
||||
.post(
|
||||
format!("restore-targets/{target_id}/claim"),
|
||||
serde_json::Value::Null,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let Some(lease) = serde_json::from_str::<Option<RestoreLease>>(&reply)? else {
|
||||
continue;
|
||||
};
|
||||
ensure!(
|
||||
lease.job.target.id == *target_id && lease.job.target.application_id == application,
|
||||
"hub returned an unexpected restore target"
|
||||
);
|
||||
let work = run(
|
||||
hub,
|
||||
&lease,
|
||||
target,
|
||||
source,
|
||||
Duration::from_secs(timeout_seconds),
|
||||
);
|
||||
tokio::pin!(work);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut work => return result.map(|()| true),
|
||||
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
|
||||
report(hub, &lease, RestoreProgress::Heartbeat).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn run(
|
||||
hub: &Arc<Hub>,
|
||||
lease: &RestoreLease,
|
||||
target: &Target,
|
||||
source: Option<&Source>,
|
||||
timeout: Duration,
|
||||
) -> Result<()> {
|
||||
report(hub, lease, RestoreProgress::Checking).await?;
|
||||
let downloaded = tokio::time::timeout(timeout, async {
|
||||
let input = download(hub, lease, timeout).await?;
|
||||
target.prepare(input, lease).await
|
||||
})
|
||||
.await;
|
||||
let script = match downloaded {
|
||||
Ok(Ok(script)) => script,
|
||||
_ => {
|
||||
report(hub, lease, RestoreProgress::InvalidPayload).await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let verified = tokio::time::timeout(timeout, async {
|
||||
let identity = target.identity().await?;
|
||||
ensure!(
|
||||
identity == lease.job.target.identity && identity != lease.artifact.identity,
|
||||
"restore target identity does not match"
|
||||
);
|
||||
if let Some(source) = source {
|
||||
if let Ok(Ok(source_identity)) =
|
||||
tokio::time::timeout(Duration::from_secs(10), source.identity()).await
|
||||
{
|
||||
ensure!(
|
||||
source_identity != identity,
|
||||
"target resolves to the local backup source"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(identity)
|
||||
})
|
||||
.await;
|
||||
let identity = match verified {
|
||||
Ok(Ok(identity)) => identity,
|
||||
_ => {
|
||||
report(hub, lease, RestoreProgress::WrongTarget).await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
report(hub, lease, RestoreProgress::Safety).await?;
|
||||
let safety = tokio::time::timeout(timeout, async {
|
||||
let stage = tempfile::tempfile().context("create private safety staging")?;
|
||||
target.safety(stage.try_clone()?).await?;
|
||||
ensure!(
|
||||
target.identity().await? == identity,
|
||||
"target changed during safety capture"
|
||||
);
|
||||
hub.upload(
|
||||
format!("restore/{}/safety", lease.job.id),
|
||||
stage,
|
||||
timeout,
|
||||
"x-tessera-restore-token",
|
||||
lease.token,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await;
|
||||
if !matches!(safety, Ok(Ok(()))) {
|
||||
report(hub, lease, RestoreProgress::SafetyFailed).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The permit is single-use. A lost response leaves the target locked for reconciliation.
|
||||
hub.post(
|
||||
format!("restore/{}/apply", lease.job.id),
|
||||
serde_json::Value::Null,
|
||||
Some(lease.token),
|
||||
)
|
||||
.await?;
|
||||
let applied = matches!(
|
||||
tokio::time::timeout(timeout, target.apply(script)).await,
|
||||
Ok(Ok(()))
|
||||
);
|
||||
report(
|
||||
hub,
|
||||
lease,
|
||||
if applied {
|
||||
RestoreProgress::Applied
|
||||
} else {
|
||||
RestoreProgress::ApplyFailed
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {
|
||||
hub.post(
|
||||
format!("restore/{}/report", lease.job.id),
|
||||
serde_json::to_value(progress)?,
|
||||
Some(lease.token),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
|
||||
let hub = hub.clone();
|
||||
let id = lease.job.id;
|
||||
let token = lease.token.to_string();
|
||||
let digest = lease.artifact.sha256.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = tempfile::tempfile().context("create private restore staging")?;
|
||||
let size = http::get_file(
|
||||
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
|
||||
&mut file,
|
||||
&[
|
||||
("x-tessera-upload-token", &hub.token),
|
||||
("x-tessera-restore-token", &token),
|
||||
],
|
||||
timeout,
|
||||
)?;
|
||||
let (bytes, computed) = digest_file(&mut file)?;
|
||||
ensure!(
|
||||
size == bytes && computed == digest,
|
||||
"restore payload checksum mismatch"
|
||||
);
|
||||
Ok(file)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
Reference in New Issue
Block a user