use clap::Parser;
use std::{io, process::ExitStatus, time::Duration};
use tokio::{process::Command, signal, time};
#[derive(Parser)]
#[command(version, about = "Opens SSH tunnels for database replicas", long_about = None)]
struct Arguments {
hostname: Option<String>,
}
enum TunnelError {
SpawnError(io::Error),
ChildError(io::Error),
}
const HIGHEST_SLICE: usize = 8;
async fn tunnel(
hostname: &str,
port: usize,
) -> Result<ExitStatus, TunnelError> {
println!("opening tunnel to {hostname} on port {port}");
let suffix = if hostname != "toolsdb" {
".analytics"
} else {
""
};
let mut child = Command::new("ssh")
.args([
"-N",
"dev.toolforge.org",
"-L",
&format!("{port}:{hostname}{suffix}.db.svc.wikimedia.cloud:3306"),
])
.kill_on_drop(true)
.spawn()
.map_err(TunnelError::SpawnError)?;
child.wait().await.map_err(TunnelError::ChildError)
}
async fn tunnel_with_retry(hostname: &str, port: usize) {
let mut backoff = 1;
loop {
let result = tunnel(hostname, port).await;
match result {
Ok(status) => {
eprintln!("{hostname} exited unexpectedly: {status}");
backoff = 1;
}
Err(e) => {
match e {
TunnelError::SpawnError(e) => {
eprintln!("{hostname} cannot spawn: {e}")
}
TunnelError::ChildError(e) => {
eprintln!("{hostname} subprocess failed: {e}")
}
};
}
}
println!("{hostname} will retry after {backoff} sec");
let duration = Duration::from_secs(backoff);
backoff = core::cmp::min(backoff * 2, 900); time::sleep(duration).await;
}
}
#[tokio::main]
async fn main() {
let args = Arguments::parse();
println!("Opening SSH tunnels for database replicas");
let mut threads = vec![];
if let Some(hostname) = args.hostname.as_ref() {
let hostname = hostname.to_owned();
threads.push(tokio::spawn(async move {
tunnel_with_retry(&hostname, 3306).await;
}));
} else {
for slice in 1..=HIGHEST_SLICE {
threads.push(tokio::spawn(async move {
tunnel_with_retry(&format!("s{slice}"), 3306 + slice).await;
}));
}
}
tokio::select!(
_ = futures::future::join_all(threads) => {},
result = signal::ctrl_c() => {
result.expect("cannot listen for ctrl-c signal"); println!("ctrl-c received, abort all");
}
)
}