use std::{env, process::Stdio, time::Duration}; use anyhow::{Context as _, Result, bail}; use kube::Client; use kuranto::Config; use tokio::{ io::{AsyncBufReadExt as _, BufReader}, net::TcpListener, process::{Child, Command}, sync::oneshot, task::JoinHandle, time::{sleep, timeout}, }; use tonic::transport::{Endpoint, Error}; use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient}; pub struct Runtime { server: JoinHandle>, shutdown: Option>, forward: Option, tunnel: Option, } impl Runtime { pub async fn start() -> Result { let key = env::var("E2E_SSH_KEY") .context("run scripts/e2e.sh to provision E2E infrastructure")?; let user = env::var("E2E_SSH_USER").unwrap_or_else(|_| "root".to_owned()); let config = Config::from_env().map_err(anyhow::Error::msg)?; let namespace = config.namespace.clone(); let client = Client::try_default().await?; let listener = TcpListener::bind("127.0.0.1:0").await?; let port = listener.local_addr()?.port(); let (shutdown, receiver) = oneshot::channel(); let server = tokio::spawn(kuranto::serve(client, config, listener, async { let _ = receiver.await; })); let mut runtime = Self { server, shutdown: Some(shutdown), forward: None, tunnel: None, }; let (ssh_port, health_port) = runtime.start_forward(&namespace).await?; runtime.tunnel = Some( Command::new("ssh") .args([ "-N", "-v", "-T", "-i", &key, "-p", &ssh_port.to_string(), "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "ExitOnForwardFailure=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=3", "-R", &format!("127.0.0.1:50051:127.0.0.1:{port}"), &format!("{user}@127.0.0.1"), ]) .stdin(Stdio::null()) .stderr(Stdio::piped()) .kill_on_drop(true) .spawn() .context("starting reverse SSH tunnel")?, ); runtime.wait_for_tunnel().await?; timeout(Duration::from_secs(30), async { loop { runtime.ensure_running()?; if let Ok(channel) = Endpoint::from_shared(format!("http://127.0.0.1:{health_port}"))? .connect() .await { let response = HealthClient::new(channel) .check(HealthCheckRequest { service: "plugin.v1alpha.BackendPlugin".to_owned(), }) .await; if response.is_ok_and(|response| response.into_inner().status == 1) { return Ok::<_, anyhow::Error>(()); } } sleep(Duration::from_millis(200)).await; } }) .await .context("Kuranto health through reverse tunnel timed out")??; Ok(runtime) } async fn wait_for_tunnel(&mut self) -> Result<()> { let stderr = self .tunnel .as_mut() .context("missing SSH process")? .stderr .take() .context("missing SSH output")?; timeout(Duration::from_secs(30), async { let mut lines = BufReader::new(stderr).lines(); while let Some(line) = lines.next_line().await? { eprintln!("{line}"); // Probing before this acknowledgement can terminate kubectl's // entire port-forward session when the remote port is closed. if line.contains("remote forward success") { tokio::spawn(async move { while let Ok(Some(line)) = lines.next_line().await { eprintln!("{line}"); } }); return Ok::<_, anyhow::Error>(()); } } bail!("SSH exited before establishing the reverse forward") }) .await .context("SSH reverse forward readiness timed out")? } async fn start_forward(&mut self, namespace: &str) -> Result<(u16, u16)> { let mut command = Command::new("kubectl"); if let Ok(context) = env::var("E2E_KUBE_CONTEXT") { command.args(["--context", &context]); } let mut forward = command .args([ "-n", namespace, "port-forward", "--address", "127.0.0.1", "deployment/forgejo-runner", ":22", ":50051", ]) .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .kill_on_drop(true) .spawn() .context("starting runner port-forward")?; let stdout = forward .stdout .take() .context("missing port-forward output")?; self.forward = Some(forward); timeout(Duration::from_secs(30), async { let mut lines = BufReader::new(stdout).lines(); let mut ssh_port = None; let mut health_port = None; while let Some(line) = lines.next_line().await? { if let Some((local, remote)) = line .strip_prefix("Forwarding from 127.0.0.1:") .and_then(|value| value.split_once(" -> ")) { match remote { "22" => ssh_port = Some(local.parse::()?), "50051" => health_port = Some(local.parse::()?), _ => {} } } if let (Some(ssh), Some(health)) = (ssh_port, health_port) { // Keep draining kubectl output while requests are forwarded. tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} }); return Ok((ssh, health)); } } bail!("runner port-forward exited before becoming ready") }) .await .context("runner port-forward readiness timed out")? } pub fn ensure_running(&mut self) -> Result<()> { if self.server.is_finished() { bail!("Kuranto stopped unexpectedly"); } for (name, child) in [ ("port-forward", &mut self.forward), ("SSH tunnel", &mut self.tunnel), ] { if let Some(status) = child.as_mut().map(Child::try_wait).transpose()?.flatten() { bail!("{name} exited: {status}"); } } Ok(()) } pub async fn stop(mut self) -> Result<()> { if let Some(shutdown) = self.shutdown.take() { let _ = shutdown.send(()); } timeout(Duration::from_secs(10), &mut self.server) .await .context("Kuranto shutdown timed out")???; for child in [&mut self.tunnel, &mut self.forward].into_iter().flatten() { child.kill().await?; } Ok(()) } } impl Drop for Runtime { fn drop(&mut self) { self.server.abort(); } }