Skip to content
1        10        20        30        40        50        60        70        80        901mod api;23use std::{net::SocketAddr, sync::Arc, time::Duration};45use super::{6    cli::ServerSetupArgs,7    docker::DockerEngine,8    error::OnceError,9    namespace::{Application, Namespace},10    operations, proxy,11};1213/// How long a superseded server keeps running after its replacement is routed.14const SUPERSEDED_GRACE: Duration = Duration::from_secs(15);1516pub async fn setup(namespace: &mut Namespace, args: ServerSetupArgs) -> Result<(), OnceError> {17    validate_host(&args.host)?;18    if args.port == 0 {19        return Err(OnceError::Io(20            "server port must be between 1 and 65535".into(),21        ));22    }23    let version = args24        .version25        .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned());26    validate_image_tag(&version)?;27    let api_key = required_api_key()?;28    let image = format!("silenloc/ino:{version}");2930    operations::setup_server(namespace, &image, &args.host, args.port, &api_key).await31}3233pub async fn serve(namespace_name: String) -> Result<(), OnceError> {34    let api_key = required_api_key()?;35    let port = std::env::var("PORT")36        .unwrap_or_else(|_| "80".to_owned())37        .parse::<u16>()38        .ok()39        .filter(|port| *port != 0)40        .ok_or_else(|| OnceError::Io("PORT must be an integer between 1 and 65535".into()))?;4142    let engine = Arc::new(DockerEngine::connect()?);43    let mut namespace = Namespace::restore(engine, namespace_name).await?;44    namespace.setup().await?;45    // Docker sets the hostname to this container's short id. During an update46    // both the old and new server containers exist, so match on it rather than47    // taking the first server app.48    let hostname = std::env::var("HOSTNAME").unwrap_or_default();49    let server_apps = || namespace.applications.iter().filter(|app| app.is_server);50    let server_app = server_apps()51        .find(|app| !hostname.is_empty() && app.container_id.starts_with(&hostname))52        .or_else(|| server_apps().next())53        .ok_or_else(|| {54            OnceError::Io("no configured Ino server app found in this namespace".into())55        })?56        .clone();57    let namespace = Arc::new(tokio::sync::Mutex::new(namespace));58    let app_manager = Arc::new(api::NamespaceManager::new(namespace.clone()));59    let state = api::ApiState::new(api_key, app_manager);60    let address = SocketAddr::from(([0, 0, 0, 0], port));61    let http_server = api::bind_http(address, state)62        .map_err(|error| OnceError::Io(format!("binding Actix Web server: {error}")))?;63    let server_handle = http_server.handle();64    let server_task = actix_web::rt::spawn(http_server);6566    let (route, engine, namespace_name) = {67        let namespace = namespace.lock().await;68        let route = proxy::deploy(&namespace, &server_app, &server_app.container_id).await;69        (route, namespace.engine.clone(), namespace.name.clone())70    };71    if let Err(error) = route {72        server_handle.stop(true).await;73        let _ = server_task.await;74        return Err(error);75    }76    // The previous server may still be answering the update request that77    // started this container. Give that response time to go out first.78    let superseded_app = server_app.clone();79    actix_web::rt::spawn(async move {80        tokio::time::sleep(SUPERSEDED_GRACE).await;81        remove_superseded_servers(&engine, &namespace_name, &superseded_app).await;82    });8384    server_task85        .await86        .map_err(|error| OnceError::Io(format!("Actix Web server task failed: {error}")))?87        .map_err(|error| OnceError::Io(format!("running Actix Web server: {error}")))88}8990/// Removes the previous server containers of this namespace once this one is91/// routed. Failures are logged rather than failing startup, because the new92/// server is already serving traffic.93async fn remove_superseded_servers(94    engine: &DockerEngine,95    namespace_name: &str,96    server_app: &Application,97) {98    let prefix = format!("{namespace_name}-app-{}-", server_app.settings.name);99    let containers = match engine.list_containers().await {100        Ok(containers) => containers,101        Err(error) => {102            eprintln!("ino: listing superseded server containers: {error}");103            return;104        }105    };106    for old in containers {107        let is_previous = old.id != server_app.container_id108            && old109                .names110                .iter()111                .any(|name| name.trim_start_matches('/').starts_with(&prefix));112        if is_previous && let Err(error) = engine.remove_container(&old.id).await {113            eprintln!(114                "ino: removing superseded server container {}: {error}",115                old.id116            );117        }118    }119}120121fn required_api_key() -> Result<String, OnceError> {122    std::env::var("INO_API_KEY")123        .ok()124        .filter(|key| !key.is_empty())125        .ok_or_else(|| OnceError::Io("INO_API_KEY must be set to a non-empty value".into()))126}127128fn validate_host(host: &str) -> Result<(), OnceError> {129    let valid = host.len() <= 253130        && !host.is_empty()131        && host.split('.').all(|label| {132            !label.is_empty()133                && label.len() <= 63134                && label135                    .as_bytes()136                    .first()137                    .is_some_and(u8::is_ascii_alphanumeric)138                && label139                    .as_bytes()140                    .last()141                    .is_some_and(u8::is_ascii_alphanumeric)142                && label143                    .bytes()144                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')145        });146    if !valid {147        return Err(OnceError::Io(format!("invalid server hostname {host:?}")));148    }149    Ok(())150}151152fn validate_image_tag(tag: &str) -> Result<(), OnceError> {153    let valid = !tag.is_empty()154        && tag.len() <= 128155        && tag156            .as_bytes()157            .first()158            .is_some_and(u8::is_ascii_alphanumeric)159        && tag160            .bytes()161            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'));162    if !valid {163        return Err(OnceError::Io("invalid server image version tag".into()));164    }165    Ok(())166}167168#[cfg(test)]169mod tests {170    use super::{validate_host, validate_image_tag};171172    #[test]173    fn validates_public_hosts_and_image_tags() {174        assert!(validate_host("ino.example.com").is_ok());175        assert!(validate_host("ino.localhost").is_ok());176        assert!(validate_host("bad host").is_err());177        assert!(validate_host("-bad.example.com").is_err());178        assert!(validate_image_tag("0.5.0").is_ok());179        assert!(validate_image_tag("v1_2-test").is_ok());180        assert!(validate_image_tag("../../latest").is_err());181    }182}