Files
tessera/crates/tessera-providers/src/mysql.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

239 lines
7.1 KiB
Rust

use crate::SshEndpoint;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::{fs, io::Write, path::PathBuf, process::Stdio};
use tessera_core::restore::DatabaseIdentity;
use tokio::process::Command;
#[derive(Deserialize)]
#[serde(tag = "transport", rename_all = "snake_case", deny_unknown_fields)]
pub enum MysqlSource {
Direct {
host: String,
#[serde(default = "default_port")]
port: u16,
database: String,
user: String,
password_file: PathBuf,
#[serde(default)]
tls: MysqlTls,
},
Ssh {
bastion: SshEndpoint,
database: String,
defaults_file: String,
},
}
fn default_port() -> u16 {
3306
}
#[derive(Default, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum MysqlTls {
#[default]
VerifyIdentity,
VerifyIdentityWithCa {
ca_file: PathBuf,
},
Required,
Disabled,
}
const FLAGS: &[&str] = &[
"--single-transaction",
"--skip-dump-date",
"--skip-lock-tables",
"--no-tablespaces",
"--set-gtid-purged=OFF",
"--default-character-set=utf8mb4",
"--routines",
"--events",
"--triggers",
];
impl MysqlSource {
pub async fn dump_to(&self, file: fs::File) -> Result<()> {
self.run(
"mysqldump",
FLAGS,
Stdio::null(),
Stdio::from(file.try_clone()?),
)
.await?;
anyhow::ensure!(
file.metadata()?.len() > 0,
"MySQL dump produced an empty file"
);
Ok(())
}
pub fn database(&self) -> &str {
match self {
Self::Direct { database, .. } | Self::Ssh { database, .. } => database,
}
}
pub async fn identity(&self) -> Result<DatabaseIdentity> {
let output = self
.run(
"mysql",
&[
"--batch",
"--raw",
"--skip-column-names",
"--default-character-set=utf8mb4",
"--execute",
"SELECT JSON_OBJECT('instance', LOWER(@@server_uuid), 'database', DATABASE())",
],
Stdio::null(),
Stdio::piped(),
)
.await?;
serde_json::from_slice(&output.stdout).context("invalid MySQL identity")
}
pub(crate) async fn run(
&self,
program: &str,
args: &[&str],
stdin: Stdio,
stdout: Stdio,
) -> Result<std::process::Output> {
let config;
let mut cmd = match self {
Self::Direct {
host,
port,
database,
user,
password_file,
tls,
} => {
validate_database(database)?;
anyhow::ensure!(
!host.is_empty() && *port != 0 && !user.is_empty(),
"invalid MySQL endpoint"
);
let password =
fs::read_to_string(password_file).context("read MySQL password file")?;
let mut defaults =
tempfile::NamedTempFile::new().context("create private MySQL options file")?;
writeln!(
defaults,
"[client]\npassword={}",
option_value(password.trim_end_matches(['\r', '\n']))?
)?;
let mut cmd = Command::new(program);
cmd.arg(format!("--defaults-file={}", defaults.path().display()))
.arg("--protocol=TCP")
.arg("--host")
.arg(host)
.arg("--port")
.arg(port.to_string())
.arg("--user")
.arg(user);
let mode = match tls {
MysqlTls::VerifyIdentity => "VERIFY_IDENTITY",
MysqlTls::VerifyIdentityWithCa { ca_file } => {
cmd.arg("--ssl-ca").arg(ca_file);
"VERIFY_IDENTITY"
}
MysqlTls::Required => "REQUIRED",
MysqlTls::Disabled => "DISABLED",
};
cmd.arg(format!("--ssl-mode={mode}"))
.args(args)
.args(["--", database]);
config = Some(defaults);
cmd
}
Self::Ssh {
bastion,
database,
defaults_file,
} => {
validate_database(database)?;
anyhow::ensure!(
defaults_file.starts_with('/') && !defaults_file.contains(['\0', '\r', '\n']),
"invalid remote options path"
);
let mut cmd = bastion.command()?;
let options = shell_arg(&format!("--defaults-file={defaults_file}"));
let database = shell_arg(database);
let args = args
.iter()
.map(|arg| shell_arg(arg))
.collect::<Vec<_>>()
.join(" ");
let command = format!("env -u MYSQL_PWD MYSQL_TEST_LOGIN_FILE=/dev/null {program} {options} {args} -- {database}");
cmd.args(["--", &bastion.host, &command]);
config = None;
cmd
}
};
let output = cmd
.env_remove("MYSQL_PWD")
.env("MYSQL_TEST_LOGIN_FILE", "/dev/null")
.stdin(stdin)
.stderr(Stdio::null())
.stdout(stdout)
.kill_on_drop(true)
.spawn()
.context("start MySQL client")?
.wait_with_output()
.await
.context("wait for MySQL client")?;
drop(config);
anyhow::ensure!(
output.status.success(),
"{program} failed ({})",
output.status
);
Ok(output)
}
}
fn validate_database(database: &str) -> Result<()> {
anyhow::ensure!(
!database.is_empty() && !database.contains(['\0', '\r', '\n']),
"invalid MySQL database name"
);
Ok(())
}
fn option_value(value: &str) -> Result<String> {
anyhow::ensure!(
!value.is_empty() && !value.contains(['\0', '\r', '\n']),
"invalid MySQL password"
);
Ok(format!(
"\"{}\"",
value.replace('\\', "\\\\").replace('"', "\\\"")
))
}
fn shell_arg(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remote_database_and_options_are_literal_shell_arguments() {
let value = "space 'quote' $(exit 23)";
let script = format!("printf '%s' {}", shell_arg(value));
let result = std::process::Command::new("sh")
.args(["-c", &script])
.output()
.unwrap();
assert!(result.status.success());
assert_eq!(result.stdout, value.as_bytes());
assert!(option_value("secret\n[client]").is_err());
assert_eq!(option_value("a\\b\"#c").unwrap(), "\"a\\\\b\\\"#c\"");
}
}