Skip to main content

spin_trigger/
cli.rs

1mod initial_kv_setter;
2mod launch_metadata;
3mod max_instance_memory;
4mod sqlite_statements;
5mod stdio;
6mod summary;
7mod variable;
8
9use std::path::PathBuf;
10use std::{future::Future, sync::Arc};
11
12use anyhow::{Context, Result};
13#[cfg(feature = "experimental-wasm-features")]
14use clap::ValueEnum;
15use clap::{Args, IntoApp, Parser};
16use spin_app::App;
17use spin_common::sloth;
18use spin_common::ui::quoted_path;
19use spin_common::url::parse_file_url;
20use spin_factors::RuntimeFactors;
21use spin_factors_executor::{ComponentLoader, FactorsExecutor};
22
23use crate::{loader::ComponentLoader as ComponentLoaderImpl, Trigger, TriggerApp};
24pub use initial_kv_setter::InitialKvSetterHook;
25pub use launch_metadata::LaunchMetadata;
26pub use max_instance_memory::MaxInstanceMemoryHook;
27pub use sqlite_statements::SqlStatementExecutorHook;
28use stdio::FollowComponents;
29pub use stdio::StdioLoggingExecutorHooks;
30pub use summary::{KeyValueDefaultStoreSummaryHook, SqliteDefaultStoreSummaryHook};
31pub use variable::VariablesValidatorHook;
32
33pub const APP_LOG_DIR: &str = "APP_LOG_DIR";
34pub const SPIN_TRUNCATE_LOGS: &str = "SPIN_TRUNCATE_LOGS";
35pub const DISABLE_WASMTIME_CACHE: &str = "DISABLE_WASMTIME_CACHE";
36pub const FOLLOW_LOG_OPT: &str = "FOLLOW_ID";
37pub const WASMTIME_CACHE_FILE: &str = "WASMTIME_CACHE_FILE";
38pub const RUNTIME_CONFIG_FILE: &str = "RUNTIME_CONFIG_FILE";
39
40// Set by `spin up`
41pub const SPIN_LOCKED_URL: &str = "SPIN_LOCKED_URL";
42pub const SPIN_LOCAL_APP_DIR: &str = "SPIN_LOCAL_APP_DIR";
43pub const SPIN_WORKING_DIR: &str = "SPIN_WORKING_DIR";
44
45/// A command that runs a TriggerExecutor.
46#[derive(Parser, Debug)]
47#[clap(
48    override_usage = "spin [COMMAND] [OPTIONS]",
49    next_help_heading = help_heading::<T, B::Factors>()
50)]
51pub struct FactorsTriggerCommand<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> {
52    /// Log directory for the stdout and stderr of components. Setting to
53    /// the empty string disables logging to disk.
54    #[clap(
55        name = APP_LOG_DIR,
56        short = 'L',
57        long = "log-dir",
58        env = "SPIN_LOG_DIR",
59    )]
60    pub log: Option<PathBuf>,
61
62    /// If set, Spin truncates the log files before starting the application.
63    #[clap(
64        name = SPIN_TRUNCATE_LOGS,
65        long = "truncate-logs",
66    )]
67    pub truncate_logs: bool,
68
69    /// Disable Wasmtime cache.
70    #[clap(
71        name = DISABLE_WASMTIME_CACHE,
72        long = "disable-cache",
73        env = DISABLE_WASMTIME_CACHE,
74        conflicts_with = WASMTIME_CACHE_FILE,
75        takes_value = false,
76    )]
77    pub disable_cache: bool,
78
79    /// Wasmtime cache configuration file.
80    #[clap(
81        name = WASMTIME_CACHE_FILE,
82        long = "cache",
83        env = WASMTIME_CACHE_FILE,
84        conflicts_with = DISABLE_WASMTIME_CACHE,
85    )]
86    pub cache: Option<PathBuf>,
87
88    /// Disable Wasmtime's pooling instance allocator.
89    #[clap(long = "disable-pooling")]
90    pub disable_pooling: bool,
91
92    /// Enable Wasmtime's debug info for Wasm guests, allowing debugging
93    /// with gdb or lldb.
94    #[clap(long = "debug-info", takes_value = false)]
95    pub debug_info: bool,
96
97    /// Print output to stdout/stderr only for given component(s)
98    #[clap(
99        name = FOLLOW_LOG_OPT,
100        long = "follow",
101    )]
102    pub follow_components: Vec<String>,
103
104    /// Silence all component output to stdout/stderr
105    #[clap(
106        long = "quiet",
107        short = 'q',
108        aliases = &["sh", "shush"],
109        conflicts_with = FOLLOW_LOG_OPT,
110        )]
111    pub silence_component_logs: bool,
112
113    /// Configuration file for config providers and wasmtime config.
114    #[clap(
115        name = RUNTIME_CONFIG_FILE,
116        long = "runtime-config-file",
117        env = RUNTIME_CONFIG_FILE,
118    )]
119    pub runtime_config_file: Option<PathBuf>,
120
121    #[cfg(feature = "experimental-wasm-features")]
122    #[clap(long, value_enum)]
123    pub experimental_wasm_feature: Vec<ExperimentalWasmFeature>,
124
125    /// Set the application state directory path. This is used in the default
126    /// locations for logs, key value stores, etc.
127    ///
128    /// For local apps, this defaults to `.spin/` relative to the `spin.toml` file.
129    /// For remote apps, this has no default (unset).
130    /// Passing an empty value forces the value to be unset.
131    #[clap(long)]
132    pub state_dir: Option<String>,
133
134    #[clap(flatten)]
135    pub trigger_args: T::CliArgs,
136
137    #[clap(flatten)]
138    pub builder_args: B::CliArgs,
139
140    #[clap(long = "help-args-only", hide = true)]
141    pub help_args_only: bool,
142
143    #[clap(long = "launch-metadata-only", hide = true)]
144    pub launch_metadata_only: bool,
145}
146
147#[cfg(feature = "experimental-wasm-features")]
148#[derive(Clone, Debug, ValueEnum)]
149pub enum ExperimentalWasmFeature {
150    Gc,
151    ReferenceTypes,
152    Exceptions,
153    FunctionReferences,
154}
155
156/// Configuration options that are common to all triggers.
157#[derive(Debug, Default)]
158pub struct FactorsConfig {
159    /// The Spin working directory.
160    pub working_dir: PathBuf,
161    /// Path to the runtime config file.
162    pub runtime_config_file: Option<PathBuf>,
163    /// Path to the state directory.
164    pub state_dir: UserProvidedPath,
165    /// Path to the local app directory.
166    pub local_app_dir: Option<String>,
167    /// Which components should have their logs followed.
168    pub follow_components: FollowComponents,
169    /// Log directory for component stdout/stderr.
170    pub log_dir: UserProvidedPath,
171    /// If set, Spin truncates the log files before starting the application.
172    pub truncate_logs: bool,
173}
174
175/// An empty implementation of clap::Args to be used as TriggerExecutor::RunConfig
176/// for executors that do not need additional CLI args.
177#[derive(Args)]
178pub struct NoCliArgs;
179
180impl<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> FactorsTriggerCommand<T, B> {
181    /// Create a new TriggerExecutorBuilder from this TriggerExecutorCommand.
182    pub async fn run(self) -> Result<()> {
183        // Handle --help-args-only
184        if self.help_args_only {
185            Self::command()
186                .disable_help_flag(true)
187                .help_template("{all-args}")
188                .print_long_help()?;
189            return Ok(());
190        }
191
192        // Handle --launch-metadata-only
193        if self.launch_metadata_only {
194            let lm = LaunchMetadata::infer::<T, B>();
195            let json = serde_json::to_string_pretty(&lm)?;
196            eprintln!("{json}");
197            return Ok(());
198        }
199
200        // Required env vars
201        let working_dir = std::env::var(SPIN_WORKING_DIR).context(SPIN_WORKING_DIR)?;
202        let locked_url = std::env::var(SPIN_LOCKED_URL).context(SPIN_LOCKED_URL)?;
203        let local_app_dir = std::env::var(SPIN_LOCAL_APP_DIR).ok();
204
205        let follow_components = self.follow_components();
206
207        // Load App
208        let app = {
209            let path = parse_file_url(&locked_url)?;
210            let contents = std::fs::read(&path)
211                .with_context(|| format!("failed to read manifest at {}", quoted_path(&path)))?;
212            let locked =
213                serde_json::from_slice(&contents).context("failed to parse app lock file JSON")?;
214            App::new(locked_url, locked)
215        };
216
217        // Validate required host features
218        if let Err(unmet) = app.ensure_needs_only(T::TYPE, &T::supported_host_requirements()) {
219            anyhow::bail!("This application requires the following features that are not available in this version of the '{}' trigger: {unmet}", T::TYPE);
220        }
221
222        let trigger = T::new(self.trigger_args, &app)?;
223        let mut builder: TriggerAppBuilder<T, B> = TriggerAppBuilder::new(trigger);
224        let config = builder.engine_config();
225
226        // Apply --cache / --disable-cache
227        if !self.disable_cache {
228            config.enable_cache(&self.cache)?;
229        }
230
231        if self.disable_pooling {
232            config.disable_pooling();
233        }
234
235        if self.debug_info {
236            config.enable_debug_info();
237        }
238
239        #[cfg(feature = "experimental-wasm-features")]
240        {
241            let wasmtime_config = config.wasmtime_config();
242            for wasm_feature in self.experimental_wasm_feature {
243                match wasm_feature {
244                    ExperimentalWasmFeature::Gc => wasmtime_config.wasm_gc(true),
245                    ExperimentalWasmFeature::ReferenceTypes => {
246                        wasmtime_config.wasm_reference_types(true)
247                    }
248                    ExperimentalWasmFeature::Exceptions => wasmtime_config.wasm_exceptions(true),
249                    ExperimentalWasmFeature::FunctionReferences => {
250                        wasmtime_config.wasm_function_references(true)
251                    }
252                };
253            }
254        }
255
256        let state_dir = match &self.state_dir {
257            // Make sure `--state-dir=""` unsets the state dir
258            Some(s) if s.is_empty() => UserProvidedPath::Unset,
259            Some(s) => UserProvidedPath::Provided(PathBuf::from(s)),
260            None => UserProvidedPath::Default,
261        };
262        let log_dir = match &self.log {
263            // Make sure `--log-dir=""` unsets the log dir
264            Some(p) if p.as_os_str().is_empty() => UserProvidedPath::Unset,
265            Some(p) => UserProvidedPath::Provided(p.clone()),
266            None => UserProvidedPath::Default,
267        };
268        let common_options = FactorsConfig {
269            working_dir: PathBuf::from(working_dir),
270            runtime_config_file: self.runtime_config_file.clone(),
271            state_dir,
272            local_app_dir: local_app_dir.clone(),
273            follow_components,
274            log_dir,
275            truncate_logs: self.truncate_logs,
276        };
277
278        let run_fut = builder
279            .run(
280                app,
281                common_options,
282                self.builder_args,
283                &ComponentLoaderImpl::new(),
284            )
285            .await?;
286
287        let (abortable, abort_handle) = futures::future::abortable(run_fut);
288        ctrlc::set_handler(move || abort_handle.abort())?;
289        match abortable.await {
290            Ok(Ok(())) => {
291                tracing::info!("Trigger executor shut down: exiting");
292                Ok(())
293            }
294            Ok(Err(err)) => {
295                tracing::error!("Trigger executor failed");
296                Err(err)
297            }
298            Err(_aborted) => {
299                tracing::info!("User requested shutdown: exiting");
300                Ok(())
301            }
302        }
303    }
304
305    fn follow_components(&self) -> FollowComponents {
306        if self.silence_component_logs {
307            FollowComponents::None
308        } else if self.follow_components.is_empty() {
309            FollowComponents::All
310        } else {
311            let followed = self.follow_components.clone().into_iter().collect();
312            FollowComponents::Named(followed)
313        }
314    }
315}
316
317const SLOTH_WARNING_DELAY_MILLIS: u64 = 1250;
318
319fn warn_if_wasm_build_slothful() -> sloth::SlothGuard {
320    #[cfg(debug_assertions)]
321    let message = "\
322        This is a debug build - preparing Wasm modules might take a few seconds\n\
323        If you're experiencing long startup times please switch to the release build";
324
325    #[cfg(not(debug_assertions))]
326    let message = "Preparing Wasm modules is taking a few seconds...";
327
328    sloth::warn_if_slothful(SLOTH_WARNING_DELAY_MILLIS, format!("{message}\n"))
329}
330
331fn help_heading<T: Trigger<F>, F: RuntimeFactors>() -> Option<&'static str> {
332    if T::TYPE == <help::HelpArgsOnlyTrigger as Trigger<F>>::TYPE {
333        Some("TRIGGER OPTIONS")
334    } else {
335        let heading = format!("{} TRIGGER OPTIONS", T::TYPE.to_uppercase());
336        let as_str = Box::new(heading).leak();
337        Some(as_str)
338    }
339}
340
341/// A builder for a [`TriggerApp`].
342pub struct TriggerAppBuilder<T, B> {
343    engine_config: spin_core::Config,
344    pub trigger: T,
345    _factors_builder: std::marker::PhantomData<B>,
346}
347
348impl<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> TriggerAppBuilder<T, B> {
349    pub fn new(trigger: T) -> Self {
350        Self {
351            engine_config: spin_core::Config::default(),
352            trigger,
353            _factors_builder: Default::default(),
354        }
355    }
356
357    pub fn engine_config(&mut self) -> &mut spin_core::Config {
358        &mut self.engine_config
359    }
360
361    /// Build a [`TriggerApp`] from the given [`App`] and options.
362    pub async fn build(
363        &mut self,
364        app: App,
365        common_options: FactorsConfig,
366        options: B::CliArgs,
367        loader: &impl ComponentLoader<B::Factors, T::InstanceState>,
368    ) -> anyhow::Result<TriggerApp<T, B::Factors>> {
369        let mut core_engine_builder = {
370            self.trigger.update_core_config(&mut self.engine_config)?;
371
372            spin_core::Engine::builder(&self.engine_config)?
373        };
374        self.trigger.add_to_linker(core_engine_builder.linker())?;
375
376        let (factors, runtime_config) = B::build(&common_options, &options)?;
377
378        let mut executor = FactorsExecutor::new(core_engine_builder, factors)?;
379        B::configure_app(&mut executor, &runtime_config, &common_options, &options)?;
380        let executor = Arc::new(executor);
381
382        let configured_app = {
383            let _sloth_guard = warn_if_wasm_build_slothful();
384            executor
385                .load_app(app, runtime_config.into(), loader, Some(T::TYPE))
386                .await?
387        };
388
389        Ok(configured_app)
390    }
391
392    /// Run the [`TriggerApp`] with the given [`App`] and options.
393    pub async fn run(
394        mut self,
395        app: App,
396        common_options: FactorsConfig,
397        options: B::CliArgs,
398        loader: &impl ComponentLoader<B::Factors, T::InstanceState>,
399    ) -> anyhow::Result<impl Future<Output = anyhow::Result<()>>> {
400        let configured_app = self.build(app, common_options, options, loader).await?;
401        Ok(self.trigger.run(configured_app))
402    }
403}
404
405/// A builder for runtime factors.
406pub trait RuntimeFactorsBuilder {
407    /// The factors type to build.
408    type Factors: RuntimeFactors;
409    /// CLI arguments not included in [`FactorsConfig`] needed  to build the [`RuntimeFactors`].
410    type CliArgs: clap::Args;
411    /// The wrapped runtime config type.
412    type RuntimeConfig: Into<<Self::Factors as RuntimeFactors>::RuntimeConfig>;
413
414    /// Build the factors and runtime config from the given options.
415    fn build(
416        config: &FactorsConfig,
417        args: &Self::CliArgs,
418    ) -> anyhow::Result<(Self::Factors, Self::RuntimeConfig)>;
419
420    /// Configure the factors in the executor.
421    fn configure_app<U: Send + 'static>(
422        executor: &mut FactorsExecutor<Self::Factors, U>,
423        runtime_config: &Self::RuntimeConfig,
424        config: &FactorsConfig,
425        args: &Self::CliArgs,
426    ) -> anyhow::Result<()> {
427        let _ = (executor, runtime_config, config, args);
428        Ok(())
429    }
430}
431
432pub mod help {
433    use super::*;
434
435    /// Null object to support --help-args-only in the absence of
436    /// a `spin.toml` file.
437    pub struct HelpArgsOnlyTrigger;
438
439    impl<F: RuntimeFactors> Trigger<F> for HelpArgsOnlyTrigger {
440        const TYPE: &'static str = "help-args-only";
441        type CliArgs = NoCliArgs;
442        type InstanceState = ();
443
444        fn new(_cli_args: Self::CliArgs, _app: &App) -> anyhow::Result<Self> {
445            Ok(Self)
446        }
447
448        async fn run(self, _configured_app: TriggerApp<Self, F>) -> anyhow::Result<()> {
449            Ok(())
450        }
451    }
452}
453
454/// A user provided option which be either be provided, default, or explicitly none.
455#[derive(Clone, Debug, Default)]
456pub enum UserProvidedPath {
457    /// Use the explicitly provided directory.
458    Provided(PathBuf),
459    /// Use the default.
460    #[default]
461    Default,
462    /// Explicitly unset.
463    Unset,
464}