Skip to content
1        10        20        30        40        50        60        70        80        901mod background;2mod backup;3pub mod cli;4mod docker;5mod error;6mod keys;7mod model;8mod namespace;9mod operations;10mod proxy;11mod remote;12mod server;13mod settings;14mod ui;15mod updater;1617use std::{error::Error, sync::Arc};1819use cli::{20    BackgroundCommand, BackupArgs, DeployArgs, ExecArgs, HostArgs, KeysCommand, OnceCli,21    OnceCommand, RemoteCommand, RemoveArgs, RestoreArgs, ServerCommand, TeardownArgs, UiCommand,22};23use docker::DockerEngine;24use error::OnceError;2526/// Runs the local console. `ino ui` and `ino once server ui` share this entry.27pub fn run_ui(command: UiCommand) -> Result<(), Box<dyn Error>> {28    ui::run(command)29}3031pub fn run(cli: OnceCli) -> Result<(), Box<dyn Error>> {32    let OnceCli { namespace, command } = cli;33    match command {34        Some(OnceCommand::Server {35            command: ServerCommand::Serve,36        }) => {37            actix_web::rt::System::new()38                .block_on(server::serve(namespace))39                .map_err(|error| OnceError::context("starting the Ino management server", error))?;40        }41        Some(OnceCommand::Server {42            command: ServerCommand::Ui { command },43        }) => {44            ui::run(command)?;45        }46        Some(OnceCommand::Version) => {47            println!(48                "ino {} (Once compatibility v0.3.4)",49                env!("CARGO_PKG_VERSION")50            );51        }52        Some(OnceCommand::Remote {53            command: RemoteCommand::Create { env_file, yes },54        }) => {55            remote::create(&remote::CreateOptions { env_file, yes })?;56        }57        Some(OnceCommand::SelfUpdate) => {58            updater::run().map_err(|error| OnceError::context("updating Ino", error))?;59        }60        Some(OnceCommand::Background { command }) => {61            let context = background_context(&namespace, &command);62            background::run(namespace, command)63                .map_err(|error| OnceError::context(context, error))?;64        }65        Some(command) => {66            let context = command_context(&command);67            let runtime = tokio::runtime::Builder::new_multi_thread()68                .enable_all()69                .build()?;70            let result = runtime.block_on(run_docker_command(namespace, command));71            result.map_err(|error| OnceError::context(context, error))?;72        }73        None => print_help(),74    }7576    Ok(())77}7879async fn run_docker_command(namespace: String, command: OnceCommand) -> Result<(), OnceError> {80    let engine = Arc::new(DockerEngine::connect()?);81    let mut namespace = namespace::Namespace::restore(engine, namespace).await?;82    match command {83        OnceCommand::List => operations::list(&namespace),84        OnceCommand::Start(HostArgs { host }) => {85            operations::start(&namespace, &host).await?;86        }87        OnceCommand::Stop(HostArgs { host }) => {88            operations::stop(&namespace, &host).await?;89        }90        OnceCommand::Remove(RemoveArgs { host, remove_data }) => {91            operations::remove(&mut namespace, &host, remove_data).await?;92        }93        OnceCommand::Teardown(TeardownArgs { remove_data }) => {94            operations::teardown(&mut namespace, remove_data).await?;95        }96        OnceCommand::Exec(ExecArgs { host, command }) => {97            operations::exec(&namespace, &host, &command).await?;98        }99        OnceCommand::Deploy(DeployArgs { image, settings }) => {100            operations::deploy(&mut namespace, &image, &settings).await?;101        }102        OnceCommand::Backup(BackupArgs { host, filename }) => {103            operations::backup(&namespace, &host, &filename).await?;104        }105        OnceCommand::Restore(RestoreArgs { filename }) => {106            operations::restore(&mut namespace, &filename).await?;107        }108        OnceCommand::Update(args) => {109            operations::update(&mut namespace, &args.host, &args).await?;110        }111        OnceCommand::Keys {112            command: KeysCommand::Reset(args),113        } => {114            operations::reset_keys(&mut namespace, &args).await?;115        }116        OnceCommand::Keys {117            command: KeysCommand::Set(args),118        } => {119            operations::set_keys(&mut namespace, &args).await?;120        }121        OnceCommand::Remote { .. } | OnceCommand::Background { .. } | OnceCommand::SelfUpdate => {122            unreachable!("handled before Docker setup")123        }124        OnceCommand::Version => unreachable!("handled above"),125        OnceCommand::Server {126            command: ServerCommand::Setup(args),127        } => server::setup(&mut namespace, args).await?,128        OnceCommand::Server {129            command: ServerCommand::Serve,130        } => unreachable!("handled before Tokio runtime creation"),131        OnceCommand::Server {132            command: ServerCommand::Ui { .. },133        } => unreachable!("handled before Docker setup"),134    }135    Ok(())136}137138fn print_help() {139    println!("Usage: ino once [OPTIONS] <COMMAND>");140    println!();141    println!("Options:");142    println!("  -n, --namespace <NAMESPACE>  namespace for containers [default: once]");143    println!("  -h, --help                   Print help");144    println!();145    println!("Commands:");146    println!("  list     List installed applications");147    println!("  start    Start an application");148    println!("  stop     Stop an application");149    println!("  remove   Remove an application");150    println!("  teardown Remove all applications and the proxy");151    println!("  exec     Execute a command in an application container");152    println!("  deploy   Deploy an application from a Docker image");153    println!("  backup   Backup an application to a new archive");154    println!("  restore  Restore an application from a backup archive");155    println!("  update   Update an application's image or settings");156    println!("  keys     Manage application secret keys");157    println!("  self-update Update Ino using Cargo or INO_SELF_UPDATE_SCRIPT");158    println!("  background Manage scheduled backups and updates");159    println!("  version  Print Ino and Once compatibility versions");160    println!("  server   Run or set up the Ino VPS management server");161    println!("  remote   Manage the app on the remote Ino server");162}163164pub fn exit_code(error: &(dyn Error + 'static)) -> Option<i32> {165    let mut current = Some(error);166    while let Some(error) = current {167        if let Some(error) = error.downcast_ref::<OnceError>()168            && let Some(exit_code) = error.exit_code()169        {170            return Some(exit_code);171        }172        current = error.source();173    }174    None175}176177fn command_context(command: &OnceCommand) -> String {178    match command {179        OnceCommand::List => "listing Once applications".into(),180        OnceCommand::Start(HostArgs { host }) => format!("starting Once application at {host:?}"),181        OnceCommand::Stop(HostArgs { host }) => format!("stopping Once application at {host:?}"),182        OnceCommand::Remove(RemoveArgs { host, .. }) => {183            format!("removing Once application at {host:?}")184        }185        OnceCommand::Teardown(TeardownArgs { .. }) => "tearing down the Once namespace".into(),186        OnceCommand::Deploy(DeployArgs { image, .. }) => {187            format!("deploying Once application image `{image}`")188        }189        OnceCommand::Backup(BackupArgs { host, filename }) => format!(190            "backing up Once application at {host:?} to `{}`",191            filename.display()192        ),193        OnceCommand::Restore(RestoreArgs { filename }) => {194            format!("restoring a Once application from `{}`", filename.display())195        }196        OnceCommand::Update(args) => format!("updating Once application at {:?}", args.host),197        OnceCommand::Keys {198            command: KeysCommand::Reset(args),199        } => format!("resetting keys for Once application at {:?}", args.host),200        OnceCommand::Keys {201            command: KeysCommand::Set(args),202        } => format!("setting keys for Once application at {:?}", args.host),203        OnceCommand::Background { .. } => "running Once background tasks".into(),204        OnceCommand::SelfUpdate => "updating Ino".into(),205        OnceCommand::Exec(ExecArgs { host, .. }) => {206            format!("executing a command in Once application at {host:?}")207        }208        OnceCommand::Version => "reading Ino and Once compatibility versions".into(),209        OnceCommand::Server {210            command: ServerCommand::Setup(args),211        } => format!("setting up the Ino server at {:?}", args.host),212        OnceCommand::Server {213            command: ServerCommand::Serve,214        } => "starting the Ino management server".into(),215        OnceCommand::Server {216            command: ServerCommand::Ui { command },217        } => match command {218            UiCommand::Start(args) | UiCommand::Run(args) => {219                format!("starting the Ino console for {:?}", args.server)220            }221            UiCommand::Stop => "stopping the Ino console".into(),222        },223        OnceCommand::Remote {224            command: RemoteCommand::Create { .. },225        } => "creating the remote app".into(),226    }227}228229fn background_context(namespace: &str, command: &BackgroundCommand) -> String {230    let action = match command {231        BackgroundCommand::Install(_) => "installing",232        BackgroundCommand::Uninstall => "uninstalling",233        BackgroundCommand::Run(_) => "running",234    };235    format!("{action} Ino background service in namespace {namespace:?}")236}237238#[cfg(test)]239mod tests {240    use crate::commands::once::cli::{241        BackgroundCommand, ExecArgs, KeysCommand, KeysSetArgs, OnceCommand,242    };243244    use super::{background_context, command_context, exit_code};245    use crate::commands::once::error::OnceError;246247    #[test]248    fn contextual_errors_preserve_child_command_exit_status() {249        let error = OnceError::context(250            "executing a command in an application",251            OnceError::CommandExit(17),252        );253254        assert_eq!(exit_code(&error), Some(17));255    }256257    #[test]258    fn command_context_does_not_echo_secret_values_or_exec_arguments() {259        let keys = OnceCommand::Keys {260            command: KeysCommand::Set(KeysSetArgs {261                host: "books.example.test".into(),262                secret_key_base: Some("super-secret-key".into()),263                vapid: Some("private-vapid-key".into()),264            }),265        };266        let keys_context = command_context(&keys);267        assert!(keys_context.contains("books.example.test"));268        assert!(!keys_context.contains("super-secret-key"));269        assert!(!keys_context.contains("private-vapid-key"));270271        let exec = OnceCommand::Exec(ExecArgs {272            host: "books.example.test".into(),273            command: vec!["echo".into(), "private argument".into()],274        });275        let exec_context = command_context(&exec);276        assert!(exec_context.contains("books.example.test"));277        assert!(!exec_context.contains("private argument"));278    }279280    #[test]281    fn background_context_identifies_action_and_namespace() {282        assert_eq!(283            background_context("staging", &BackgroundCommand::Uninstall),284            "uninstalling Ino background service in namespace \"staging\""285        );286    }287}