wasmer_cli/commands/
mod.rs

1//! The commands available in the Wasmer binary.
2mod add;
3mod app;
4mod auth;
5#[cfg(target_os = "linux")]
6mod binfmt;
7mod cache;
8#[cfg(feature = "compiler")]
9mod compile;
10mod config;
11mod connect;
12mod container;
13#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
14mod create_exe;
15#[cfg(feature = "static-artifact-create")]
16mod create_obj;
17pub(crate) mod domain;
18#[cfg(feature = "static-artifact-create")]
19mod gen_c_header;
20mod gen_completions;
21mod gen_manpage;
22mod init;
23mod inspect;
24#[cfg(feature = "journal")]
25mod journal;
26pub(crate) mod namespace;
27mod package;
28mod run;
29mod self_update;
30pub mod ssh;
31mod validate;
32#[cfg(feature = "wast")]
33mod wast;
34use std::ffi::OsString;
35use std::io::IsTerminal as _;
36use tokio::task::JoinHandle;
37
38#[cfg(target_os = "linux")]
39pub use binfmt::*;
40use clap::{CommandFactory, Parser};
41#[cfg(feature = "compiler")]
42pub use compile::*;
43#[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
44pub use create_exe::*;
45#[cfg(feature = "wast")]
46pub use wast::*;
47#[cfg(feature = "static-artifact-create")]
48#[allow(unused_imports)]
49pub use {create_obj::*, gen_c_header::*};
50
51#[cfg(feature = "journal")]
52pub use self::journal::*;
53pub use self::{
54    add::*, auth::*, cache::*, config::*, container::*, init::*, inspect::*, package::*,
55    publish::*, run::Run, self_update::*, validate::*,
56};
57use crate::error::PrettyError;
58use git_version::git_version;
59
60/// An executable CLI command.
61pub(crate) trait CliCommand {
62    type Output;
63
64    fn run(self) -> Result<(), anyhow::Error>;
65}
66
67/// An executable CLI command that runs in an async context.
68///
69/// An [`AsyncCliCommand`] automatically implements [`CliCommand`] by creating
70/// a new tokio runtime and blocking.
71#[async_trait::async_trait]
72pub(crate) trait AsyncCliCommand: Send + Sync {
73    type Output: Send + Sync;
74
75    async fn run_async(self) -> Result<Self::Output, anyhow::Error>;
76
77    fn setup(
78        &self,
79        done: tokio::sync::oneshot::Receiver<()>,
80    ) -> Option<JoinHandle<anyhow::Result<()>>> {
81        if std::io::stdin().is_terminal() {
82            return Some(tokio::task::spawn(async move {
83                tokio::select! {
84                    _ = done => {}
85
86                    _ = tokio::signal::ctrl_c() => {
87                        let term = console::Term::stdout();
88                        let _ = term.show_cursor();
89                        // https://learn.microsoft.com/en-us/cpp/c-runtime-library/signal-constants
90                        #[cfg(target_os = "windows")]
91                        std::process::exit(3);
92
93                        // POSIX compliant OSs: 128 + SIGINT (2)
94                        #[cfg(not(target_os = "windows"))]
95                        std::process::exit(130);
96                    }
97                }
98
99                Ok::<(), anyhow::Error>(())
100            }));
101        }
102
103        None
104    }
105}
106
107impl<O: Send + Sync, C: AsyncCliCommand<Output = O>> CliCommand for C {
108    type Output = O;
109
110    fn run(self) -> Result<(), anyhow::Error> {
111        tokio::runtime::Runtime::new()?.block_on(async {
112            let (snd, rcv) = tokio::sync::oneshot::channel();
113            let handle = self.setup(rcv);
114
115            if let Err(e) = AsyncCliCommand::run_async(self).await {
116                if let Some(handle) = handle {
117                    handle.abort();
118                }
119                return Err(e);
120            }
121
122            if let Some(handle) = handle {
123                if snd.send(()).is_err() {
124                    tracing::warn!("Failed to send 'done' signal to setup thread!");
125                    handle.abort();
126                } else {
127                    handle.await??;
128                }
129            }
130
131            Ok::<(), anyhow::Error>(())
132        })?;
133
134        Ok(())
135    }
136}
137
138/// Command-line arguments for the Wasmer CLI.
139#[derive(clap::Parser, Debug)]
140#[clap(author, version)]
141#[clap(disable_version_flag = true)] // handled manually
142#[cfg_attr(feature = "headless", clap(
143    name = "wasmer-headless",
144    about = concat!("wasmer-headless ", env!("CARGO_PKG_VERSION")),
145))]
146#[cfg_attr(not(feature = "headless"), clap(
147    name = "wasmer",
148    about = concat!("wasmer ", env!("CARGO_PKG_VERSION")),
149))]
150pub struct WasmerCmd {
151    /// Print version info and exit.
152    #[clap(short = 'V', long)]
153    version: bool,
154    #[clap(flatten)]
155    output: crate::logging::Output,
156    #[clap(subcommand)]
157    cmd: Option<Cmd>,
158}
159
160impl WasmerCmd {
161    fn execute(self) -> Result<(), anyhow::Error> {
162        let WasmerCmd {
163            cmd,
164            version,
165            output,
166        } = self;
167
168        output.initialize_logging();
169
170        if version {
171            return print_version(output.is_verbose());
172        }
173
174        match cmd {
175            Some(Cmd::GenManPage(cmd)) => cmd.execute(),
176            Some(Cmd::GenCompletions(cmd)) => cmd.execute(),
177            Some(Cmd::Run(options)) => options.execute(output),
178            Some(Cmd::SelfUpdate(options)) => options.execute(),
179            Some(Cmd::Cache(cache)) => cache.execute(),
180            Some(Cmd::Validate(validate)) => validate.execute(),
181            #[cfg(feature = "compiler")]
182            Some(Cmd::Compile(compile)) => compile.execute(),
183            // CreateExe and CreateObj commands are temporarily disabled
184            // #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
185            // Some(Cmd::CreateExe(create_exe)) => create_exe.run(),
186            // #[cfg(feature = "static-artifact-create")]
187            // Some(Cmd::CreateObj(create_obj)) => create_obj.execute(),
188            Some(Cmd::Config(config)) => config.run(),
189            Some(Cmd::Inspect(inspect)) => inspect.execute(),
190            Some(Cmd::Init(init)) => init.run(),
191            Some(Cmd::Login(login)) => login.run(),
192            Some(Cmd::Auth(auth)) => auth.run(),
193            Some(Cmd::Publish(publish)) => publish.run().map(|_| ()),
194            Some(Cmd::Package(cmd)) => match cmd {
195                Package::Download(cmd) => cmd.execute(),
196                Package::Build(cmd) => cmd.execute().map(|_| ()),
197                Package::Tag(cmd) => cmd.run(),
198                Package::Push(cmd) => cmd.run(),
199                Package::Publish(cmd) => cmd.run().map(|_| ()),
200                Package::Unpack(cmd) => cmd.execute(),
201            },
202            Some(Cmd::Container(cmd)) => match cmd {
203                crate::commands::Container::Unpack(cmd) => cmd.execute(),
204            },
205            #[cfg(feature = "static-artifact-create")]
206            Some(Cmd::GenCHeader(gen_heder)) => gen_heder.execute(),
207            #[cfg(feature = "wast")]
208            Some(Cmd::Wast(wast)) => wast.execute(),
209            #[cfg(target_os = "linux")]
210            Some(Cmd::Binfmt(binfmt)) => binfmt.execute(),
211            Some(Cmd::Whoami(whoami)) => whoami.run(),
212            Some(Cmd::Add(add)) => add.run(),
213
214            // Deploy commands.
215            Some(Cmd::Deploy(c)) => c.run(),
216            Some(Cmd::App(apps)) => apps.run(),
217            #[cfg(feature = "journal")]
218            Some(Cmd::Journal(journal)) => journal.run(),
219            Some(Cmd::Ssh(ssh)) => ssh.run(),
220            Some(Cmd::Namespace(namespace)) => namespace.run(),
221            Some(Cmd::Domain(namespace)) => namespace.run(),
222            None => {
223                WasmerCmd::command().print_long_help()?;
224                // Note: clap uses an exit code of 2 when CLI parsing fails
225                std::process::exit(2);
226            }
227        }
228    }
229
230    /// The main function for the Wasmer CLI tool.
231    pub fn run() {
232        // We allow windows to print properly colors
233        #[cfg(windows)]
234        colored::control::set_virtual_terminal(true).unwrap();
235
236        PrettyError::report(Self::run_inner())
237    }
238
239    fn run_inner() -> Result<(), anyhow::Error> {
240        let mut args_os = std::env::args_os();
241
242        let args = args_os.next().into_iter();
243
244        let mut binfmt_args: Vec<OsString> = Vec::new();
245        if is_binfmt_interpreter() {
246            // In case of binfmt misc the first argument is wasmer-binfmt-interpreter, the second is the full path to the executable
247            // and the third is the original string for the executable as originally called by the user.
248
249            // For now we are only using the real path and ignoring the original executable name.
250            // Ideally we would use the real path to load the file and the original name to pass it as argv[0] to the wasm module.
251
252            let current_dir = std::env::current_dir()
253                .unwrap()
254                .into_os_string()
255                .into_string()
256                .unwrap();
257            let mut mount_paths = vec!["/home", "/etc", "/tmp", "/var", "/nix", "/opt", "/root"]
258                .into_iter()
259                .filter(|path| {
260                    let path = std::path::Path::new(path);
261                    if !path.is_dir() {
262                        // Not a directory
263                        return false;
264                    }
265                    if std::fs::read_dir(path).is_err() {
266                        // No permissions
267                        return false;
268                    }
269                    true
270                })
271                .collect::<Vec<_>>();
272            if !current_dir.starts_with("/home") {
273                mount_paths.push(current_dir.as_str());
274            }
275
276            binfmt_args.push("run".into());
277            binfmt_args.push("--net".into());
278            // TODO: This does not seem to work, needs further investigation.
279            binfmt_args.push("--forward-host-env".into());
280            for mount_path in mount_paths {
281                binfmt_args.push(format!("--mapdir={mount_path}:{mount_path}").into());
282            }
283            binfmt_args.push(format!("--cwd={current_dir}").into());
284            binfmt_args.push("--quiet".into());
285            binfmt_args.push("--".into());
286            binfmt_args.push(args_os.next().unwrap());
287            args_os.next().unwrap();
288        };
289        let args_vec = args.chain(binfmt_args).chain(args_os).collect::<Vec<_>>();
290
291        match WasmerCmd::try_parse_from(args_vec.iter()) {
292            Ok(args) => args.execute(),
293            Err(e) => {
294                let first_arg_is_subcommand = if let Some(first_arg) = args_vec.get(1) {
295                    let mut ret = false;
296                    let cmd = WasmerCmd::command();
297
298                    for cmd in cmd.get_subcommands() {
299                        if cmd.get_name() == first_arg {
300                            ret = true;
301                            break;
302                        }
303                    }
304
305                    ret
306                } else {
307                    false
308                };
309
310                let might_be_wasmer_run = matches!(
311                    e.kind(),
312                    clap::error::ErrorKind::InvalidSubcommand
313                        | clap::error::ErrorKind::UnknownArgument
314                ) && !first_arg_is_subcommand;
315
316                if might_be_wasmer_run && let Ok(run) = Run::try_parse_from(args_vec.iter()) {
317                    // Try to parse the command using the `wasmer some/package`
318                    // shorthand. Note that this has discoverability issues
319                    // because it's not shown as part of the main argument
320                    // parser's help, but that's fine.
321                    let output = crate::logging::Output::default();
322                    output.initialize_logging();
323                    run.execute(output);
324                }
325
326                e.exit();
327            }
328        }
329    }
330}
331
332#[derive(clap::Parser, Debug)]
333#[allow(clippy::large_enum_variant)]
334/// The options for the wasmer Command Line Interface
335enum Cmd {
336    /// Login into Wasmer
337    Login(Login),
338
339    #[clap(subcommand)]
340    Auth(CmdAuth),
341
342    /// Publish a package to a registry [alias: package publish]
343    #[clap(name = "publish")]
344    Publish(PackagePublish),
345
346    /// Manage the local Wasmer cache
347    Cache(Cache),
348
349    /// Validate a WebAssembly binary
350    Validate(Validate),
351
352    /// Compile a WebAssembly binary
353    #[cfg(feature = "compiler")]
354    Compile(Compile),
355
356    // Compile a WebAssembly binary into a native executable
357    //
358    // To use, you need to set the `WASMER_DIR` environment variable
359    // to the location of your Wasmer installation. This will probably be `~/.wasmer`. It
360    // should include a `lib`, `include` and `bin` subdirectories. To create an executable
361    // you will need `libwasmer`, so by setting `WASMER_DIR` the CLI knows where to look for
362    // header files and libraries.
363    //
364    // Example usage:
365    //
366    // ```text
367    // $ # in two lines:
368    // $ export WASMER_DIR=/home/user/.wasmer/
369    // $ wasmer create-exe qjs.wasm -o qjs.exe # or in one line:
370    // $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm -o qjs.exe
371    // $ file qjs.exe
372    // qjs.exe: ELF 64-bit LSB pie executable, x86-64 ...
373    // ```
374    //
375    // ## Cross-compilation
376    //
377    // Accepted target triple values must follow the
378    // ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
379    //
380    // The recommended targets we try to support are:
381    //
382    // - "x86_64-linux-gnu"
383    // - "aarch64-linux-gnu"
384    // - "x86_64-apple-darwin"
385    // - "arm64-apple-darwin"
386    // #[cfg(any(feature = "static-artifact-create", feature = "wasmer-artifact-create"))]
387    // #[clap(name = "create-exe", verbatim_doc_comment)]
388    // CreateExe(CreateExe),
389    /// Compile a WebAssembly binary into an object file
390    ///
391    /// To use, you need to set the `WASMER_DIR` environment variable to the location of your
392    /// Wasmer installation. This will probably be `~/.wasmer`. It should include a `lib`,
393    /// `include` and `bin` subdirectories. To create an object you will need `libwasmer`, so by
394    /// setting `WASMER_DIR` the CLI knows where to look for header files and libraries.
395    ///
396    /// Example usage:
397    ///
398    /// ```text
399    /// $ # in two lines:
400    /// $ export WASMER_DIR=/home/user/.wasmer/
401    /// $ wasmer create-obj qjs.wasm --object-format symbols -o qjs.obj # or in one line:
402    /// $ WASMER_DIR=/home/user/.wasmer/ wasmer create-exe qjs.wasm --object-format symbols -o qjs.obj
403    /// $ file qjs.obj
404    /// qjs.obj: ELF 64-bit LSB relocatable, x86-64 ...
405    /// ```
406    ///
407    /// ## Cross-compilation
408    ///
409    /// Accepted target triple values must follow the
410    /// ['target_lexicon'](https://crates.io/crates/target-lexicon) crate format.
411    ///
412    /// The recommended targets we try to support are:
413    ///
414    /// - "x86_64-linux-gnu"
415    /// - "aarch64-linux-gnu"
416    /// - "x86_64-apple-darwin"
417    /// - "arm64-apple-darwin"
418    // #[cfg(feature = "static-artifact-create")]
419    // #[structopt(name = "create-obj", verbatim_doc_comment)]
420    // CreateObj(CreateObj),
421
422    ///
423    /// Generate the C static_defs.h header file for the input .wasm module
424    ///
425    #[cfg(feature = "static-artifact-create")]
426    GenCHeader(GenCHeader),
427
428    /// Get various configuration information needed
429    /// to compile programs which use Wasmer
430    Config(Config),
431
432    /// Update wasmer to the latest version
433    #[clap(name = "self-update")]
434    SelfUpdate(SelfUpdate),
435
436    /// Inspect a WebAssembly file
437    Inspect(Inspect),
438
439    /// Initializes a new wasmer.toml file
440    #[clap(name = "init")]
441    Init(Init),
442
443    /// Run spec testsuite
444    #[cfg(feature = "wast")]
445    Wast(Wast),
446
447    /// Unregister and/or register wasmer as binfmt interpreter
448    #[cfg(target_os = "linux")]
449    Binfmt(Binfmt),
450
451    /// Shows the current logged in user for the current active registry
452    Whoami(Whoami),
453
454    /// Add a Wasmer package's bindings to your application
455    Add(CmdAdd),
456
457    /// Run a WebAssembly file or Wasmer container
458    #[clap(alias = "run-unstable")]
459    Run(Run),
460
461    /// Manage journals (compacting, inspecting, filtering, ...)
462    #[cfg(feature = "journal")]
463    #[clap(subcommand)]
464    Journal(CmdJournal),
465
466    #[clap(subcommand)]
467    Package(crate::commands::Package),
468
469    #[clap(subcommand)]
470    Container(crate::commands::Container),
471
472    // Edge commands
473    /// Deploy apps to Wasmer Edge [alias: app deploy]
474    Deploy(crate::commands::app::deploy::CmdAppDeploy),
475
476    /// Create and manage Wasmer Edge apps
477    #[clap(subcommand, alias = "apps")]
478    App(crate::commands::app::CmdApp),
479
480    /// Run commands/packages on Wasmer Edge in an interactive shell session
481    Ssh(crate::commands::ssh::CmdSsh),
482
483    /// Manage Wasmer namespaces
484    #[clap(subcommand, alias = "namespaces")]
485    Namespace(crate::commands::namespace::CmdNamespace),
486
487    /// Manage DNS records
488    #[clap(subcommand, alias = "domains")]
489    Domain(crate::commands::domain::CmdDomain),
490
491    /// Generate autocompletion for different shells
492    #[clap(name = "gen-completions")]
493    GenCompletions(crate::commands::gen_completions::CmdGenCompletions),
494
495    /// Generate man pages
496    #[clap(name = "gen-man", hide = true)]
497    GenManPage(crate::commands::gen_manpage::CmdGenManPage),
498}
499
500fn is_binfmt_interpreter() -> bool {
501    cfg_if::cfg_if! {
502        if #[cfg(target_os = "linux")] {
503            // Note: we'll be invoked by the kernel as Binfmt::FILENAME
504            let binary_path = match std::env::args_os().next() {
505                Some(path) => std::path::PathBuf::from(path),
506                None => return false,
507            };
508            binary_path.file_name().and_then(|f| f.to_str()) == Some(Binfmt::FILENAME)
509        } else {
510            false
511        }
512    }
513}
514
515fn print_version(verbose: bool) -> Result<(), anyhow::Error> {
516    if !verbose {
517        println!("wasmer {}", env!("CARGO_PKG_VERSION"));
518        return Ok(());
519    }
520
521    println!(
522        "wasmer {} ({} {})",
523        env!("CARGO_PKG_VERSION"),
524        git_version!(
525            args = ["--abbrev=8", "--always", "--dirty=-modified", "--exclude=*"],
526            fallback = ""
527        ),
528        env!("WASMER_BUILD_DATE")
529    );
530    println!("binary: {}", env!("CARGO_PKG_NAME"));
531    println!(
532        "commit-hash: {}",
533        git_version!(
534            args = [
535                "--abbrev=40",
536                "--always",
537                "--dirty=-modified",
538                "--exclude=*"
539            ],
540            fallback = "",
541        ),
542    );
543    println!("commit-date: {}", env!("WASMER_BUILD_DATE"));
544    println!("host: {}", target_lexicon::HOST);
545
546    let cpu_features = {
547        let feats = wasmer_types::target::CpuFeature::for_host();
548        let all = wasmer_types::target::CpuFeature::all();
549        all.iter()
550            .map(|f| {
551                let available = feats.contains(f);
552                format!("{}={}", f, if available { "true" } else { "false" })
553            })
554            .collect::<Vec<_>>()
555            .join(",")
556    };
557    println!("cpu: {cpu_features}");
558
559    let mut runtimes = Vec::<&'static str>::new();
560    if cfg!(feature = "singlepass") {
561        runtimes.push("singlepass");
562    }
563    if cfg!(feature = "cranelift") {
564        runtimes.push("cranelift");
565    }
566    if cfg!(feature = "llvm") {
567        runtimes.push("llvm");
568    }
569
570    if cfg!(feature = "wamr") {
571        runtimes.push("wamr");
572    }
573
574    if cfg!(feature = "wasmi") {
575        runtimes.push("wasmi");
576    }
577
578    if cfg!(feature = "v8") {
579        runtimes.push("v8");
580    }
581
582    println!("runtimes: {}", runtimes.join(", "));
583    Ok(())
584}