Skip to main content

reth_cli_runner/
lib.rs

1//! A tokio based CLI runner.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10
11//! Entrypoint for running commands.
12
13use reth_tasks::{PanickedTaskError, TaskExecutor};
14use std::{
15    future::Future,
16    pin::{pin, Pin},
17    sync::mpsc,
18    time::Duration,
19};
20use tokio::task::JoinHandle;
21use tracing::{debug, error, info};
22
23/// Executes CLI commands.
24///
25/// Provides utilities for running a cli command to completion.
26#[derive(Debug)]
27pub struct CliRunner {
28    config: CliRunnerConfig,
29    runtime: reth_tasks::Runtime,
30}
31
32impl CliRunner {
33    /// Attempts to create a new [`CliRunner`] using the default
34    /// [`Runtime`](reth_tasks::Runtime).
35    ///
36    /// The default runtime is multi-threaded, with both I/O and time drivers enabled.
37    pub fn try_default_runtime() -> Result<Self, reth_tasks::RuntimeBuildError> {
38        Self::try_with_runtime_config(reth_tasks::RuntimeConfig::default())
39    }
40
41    /// Creates a new [`CliRunner`] with the given [`RuntimeConfig`](reth_tasks::RuntimeConfig).
42    pub fn try_with_runtime_config(
43        config: reth_tasks::RuntimeConfig,
44    ) -> Result<Self, reth_tasks::RuntimeBuildError> {
45        let runtime = reth_tasks::RuntimeBuilder::new(config).build()?;
46        Ok(Self { config: CliRunnerConfig::default(), runtime })
47    }
48
49    /// Sets the [`CliRunnerConfig`] for this runner.
50    pub const fn with_config(mut self, config: CliRunnerConfig) -> Self {
51        self.config = config;
52        self
53    }
54
55    /// Returns a clone of the underlying [`Runtime`](reth_tasks::Runtime).
56    pub fn runtime(&self) -> reth_tasks::Runtime {
57        self.runtime.clone()
58    }
59
60    /// Executes an async block on the runtime and blocks until completion.
61    pub fn block_on<F, T>(&self, fut: F) -> T
62    where
63        F: Future<Output = T>,
64    {
65        self.runtime.handle().block_on(Box::pin(fut) as Pin<Box<dyn Future<Output = T> + '_>>)
66    }
67
68    /// Executes the given _async_ command on the tokio runtime until the command future resolves
69    /// or, unless [`CliRunnerConfig::handle_signals`] is disabled, until the process receives a
70    /// `SIGINT` or `SIGTERM` signal.
71    ///
72    /// Tasks spawned by the command via the [`TaskExecutor`] are shut down and an attempt is made
73    /// to drive their shutdown to completion after the command has finished.
74    pub fn run_command_until_exit<F, E>(
75        self,
76        command: impl FnOnce(CliContext) -> F,
77    ) -> Result<(), E>
78    where
79        F: Future<Output = Result<(), E>>,
80        E: Send
81            + Sync
82            + std::fmt::Display
83            + From<std::io::Error>
84            + From<reth_tasks::PanickedTaskError>
85            + 'static,
86    {
87        let (context, task_manager_handle) = cli_context(&self.runtime);
88        self.run_until_exit(task_manager_handle, Box::pin(command(context)))
89    }
90
91    /// Runs the type-erased command until it finished or ctrl-c was fired, then shuts down.
92    fn run_until_exit<E>(
93        self,
94        task_manager_handle: JoinHandle<Result<(), PanickedTaskError>>,
95        command: Pin<Box<dyn Future<Output = Result<(), E>> + '_>>,
96    ) -> Result<(), E>
97    where
98        E: Send
99            + Sync
100            + std::fmt::Display
101            + From<std::io::Error>
102            + From<reth_tasks::PanickedTaskError>
103            + 'static,
104    {
105        // Executes the command until it finished or ctrl-c was fired
106        let command_res = self.runtime.handle().block_on(run_to_completion_or_panic(
107            task_manager_handle,
108            run_until_ctrl_c_if(self.config.handle_signals, command),
109        ));
110
111        if let Err(err) = &command_res {
112            error!(target: "reth::cli", %err, "shutting down due to error");
113        } else {
114            debug!(target: "reth::cli", "shutting down gracefully");
115            // after the command has finished or exit signal was received we shutdown the
116            // runtime which fires the shutdown signal to all tasks spawned via the task
117            // executor and awaiting on tasks spawned with graceful shutdown
118            self.runtime.graceful_shutdown_with_timeout(self.config.graceful_shutdown_timeout);
119        }
120
121        runtime_shutdown(self.runtime, true);
122
123        command_res
124    }
125
126    /// Executes a command in a blocking context with access to `CliContext`.
127    ///
128    /// See [`Runtime::spawn_blocking`](tokio::runtime::Runtime::spawn_blocking).
129    pub fn run_blocking_command_until_exit<F, E>(
130        self,
131        command: impl FnOnce(CliContext) -> F + Send + 'static,
132    ) -> Result<(), E>
133    where
134        F: Future<Output = Result<(), E>> + Send + 'static,
135        E: Send
136            + Sync
137            + std::fmt::Display
138            + From<std::io::Error>
139            + From<reth_tasks::PanickedTaskError>
140            + 'static,
141    {
142        self.run_blocking_until_exit(Box::new(move |context| Box::pin(command(context))))
143    }
144
145    /// Runs the type-erased command on the blocking thread pool until it finished or ctrl-c was
146    /// fired, then shuts down.
147    fn run_blocking_until_exit<E>(
148        self,
149        command: Box<dyn FnOnce(CliContext) -> BoxedCommand<E> + Send>,
150    ) -> Result<(), E>
151    where
152        E: Send
153            + Sync
154            + std::fmt::Display
155            + From<std::io::Error>
156            + From<reth_tasks::PanickedTaskError>
157            + 'static,
158    {
159        let (context, task_manager_handle) = cli_context(&self.runtime);
160
161        // Spawn the command on the blocking thread pool
162        let handle = self.runtime.handle().clone();
163        let command_handle = self.runtime.spawn_blocking(move || handle.block_on(command(context)));
164
165        // Wait for the command to complete or ctrl-c
166        let command_res = self.runtime.handle().block_on(run_to_completion_or_panic(
167            task_manager_handle,
168            run_until_ctrl_c_if(self.config.handle_signals, async move {
169                command_handle.await.expect("Failed to join blocking task")
170            }),
171        ));
172
173        if let Err(err) = &command_res {
174            error!(target: "reth::cli", %err, "shutting down due to error");
175        } else {
176            debug!(target: "reth::cli", "shutting down gracefully");
177            self.runtime.graceful_shutdown_with_timeout(self.config.graceful_shutdown_timeout);
178        }
179
180        runtime_shutdown(self.runtime, true);
181
182        command_res
183    }
184
185    /// Executes a regular future until completion or until external signal received.
186    pub fn run_until_ctrl_c<F, E>(self, fut: F) -> Result<(), E>
187    where
188        F: Future<Output = Result<(), E>>,
189        E: Send + Sync + From<std::io::Error> + 'static,
190    {
191        self.runtime.handle().block_on(run_until_ctrl_c(
192            Box::pin(fut) as Pin<Box<dyn Future<Output = Result<(), E>> + '_>>
193        ))?;
194        Ok(())
195    }
196
197    /// Executes a regular future as a spawned blocking task until completion or until external
198    /// signal received.
199    ///
200    /// See [`Runtime::spawn_blocking`](tokio::runtime::Runtime::spawn_blocking).
201    pub fn run_blocking_until_ctrl_c<F, E>(self, fut: F) -> Result<(), E>
202    where
203        F: Future<Output = Result<(), E>> + Send + 'static,
204        E: Send + Sync + From<std::io::Error> + 'static,
205    {
206        self.run_blocking_until_ctrl_c_boxed(Box::pin(fut))
207    }
208
209    fn run_blocking_until_ctrl_c_boxed<E>(self, fut: BoxedCommand<E>) -> Result<(), E>
210    where
211        E: Send + Sync + From<std::io::Error> + 'static,
212    {
213        let handle = self.runtime.handle().clone();
214        let fut = self.runtime.spawn_blocking(move || handle.block_on(fut));
215        self.runtime
216            .handle()
217            .block_on(run_until_ctrl_c(async move { fut.await.expect("Failed to join task") }))?;
218
219        runtime_shutdown(self.runtime, false);
220
221        Ok(())
222    }
223}
224
225/// A type-erased command future, so that code driving it is not instantiated per command.
226type BoxedCommand<E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send>>;
227
228/// Extracts the task manager handle from the runtime and creates the [`CliContext`].
229fn cli_context(
230    runtime: &reth_tasks::Runtime,
231) -> (CliContext, JoinHandle<Result<(), PanickedTaskError>>) {
232    let handle =
233        runtime.take_task_manager_handle().expect("Runtime must contain a TaskManager handle");
234    let context = CliContext { task_executor: runtime.clone() };
235    (context, handle)
236}
237
238/// Additional context provided by the [`CliRunner`] when executing commands
239#[derive(Debug)]
240pub struct CliContext {
241    /// Used to execute/spawn tasks
242    pub task_executor: TaskExecutor,
243}
244
245/// Default timeout for graceful shutdown of tasks.
246const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
247
248/// Configuration for [`CliRunner`].
249#[derive(Debug, Clone)]
250pub struct CliRunnerConfig {
251    /// Timeout for graceful shutdown of tasks.
252    ///
253    /// After the command completes, this is the maximum time to wait for spawned tasks
254    /// to finish before forcefully terminating them.
255    pub graceful_shutdown_timeout: Duration,
256    /// Whether the runner stops a command when the process receives `SIGINT` or `SIGTERM`.
257    ///
258    /// Enabled by default. When disabled, [`CliRunner::run_command_until_exit`] and
259    /// [`CliRunner::run_blocking_command_until_exit`] only stop once the command resolves, so the
260    /// command must handle these signals itself, for example to stop components that depend on
261    /// the spawned tasks before their graceful shutdown starts.
262    pub handle_signals: bool,
263}
264
265impl Default for CliRunnerConfig {
266    fn default() -> Self {
267        Self::new()
268    }
269}
270
271impl CliRunnerConfig {
272    /// Creates a new config with default values.
273    pub const fn new() -> Self {
274        Self { graceful_shutdown_timeout: DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT, handle_signals: true }
275    }
276
277    /// Sets the graceful shutdown timeout.
278    pub const fn with_graceful_shutdown_timeout(mut self, timeout: Duration) -> Self {
279        self.graceful_shutdown_timeout = timeout;
280        self
281    }
282
283    /// Sets whether the runner stops a command on `SIGINT` or `SIGTERM`.
284    ///
285    /// See [`CliRunnerConfig::handle_signals`].
286    pub const fn with_signal_handling(mut self, handle_signals: bool) -> Self {
287        self.handle_signals = handle_signals;
288        self
289    }
290}
291
292/// Runs the given future to completion or until a critical task panicked.
293///
294/// Returns the error if a task panicked, or the given future returned an error.
295async fn run_to_completion_or_panic<F, E>(
296    task_manager_handle: JoinHandle<Result<(), PanickedTaskError>>,
297    fut: F,
298) -> Result<(), E>
299where
300    F: Future<Output = Result<(), E>>,
301    E: Send + Sync + From<reth_tasks::PanickedTaskError> + 'static,
302{
303    let fut = pin!(fut);
304    tokio::select! {
305        task_manager_result = task_manager_handle => {
306            if let Ok(Err(panicked_error)) = task_manager_result {
307                return Err(panicked_error.into());
308            }
309        },
310        res = fut => res?,
311    }
312    Ok(())
313}
314
315/// Runs the future to completion, and with `handle_signals` stops early on the signals
316/// [`run_until_ctrl_c`] handles.
317async fn run_until_ctrl_c_if<F, E>(handle_signals: bool, fut: F) -> Result<(), E>
318where
319    F: Future<Output = Result<(), E>>,
320    E: Send + Sync + 'static + From<std::io::Error>,
321{
322    if handle_signals {
323        run_until_ctrl_c(fut).await
324    } else {
325        fut.await
326    }
327}
328
329/// Runs the future to completion or until:
330/// - `ctrl-c` is received.
331/// - `SIGTERM` is received (unix only).
332async fn run_until_ctrl_c<F, E>(fut: F) -> Result<(), E>
333where
334    F: Future<Output = Result<(), E>>,
335    E: Send + Sync + 'static + From<std::io::Error>,
336{
337    let ctrl_c = tokio::signal::ctrl_c();
338
339    #[cfg(unix)]
340    {
341        let mut stream = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
342        let sigterm = stream.recv();
343        let sigterm = pin!(sigterm);
344        let ctrl_c = pin!(ctrl_c);
345        let fut = pin!(fut);
346
347        tokio::select! {
348            _ = ctrl_c => {
349                info!(target: "reth::cli", "Received ctrl-c");
350            },
351            _ = sigterm => {
352                info!(target: "reth::cli", "Received SIGTERM");
353            },
354            res = fut => res?,
355        }
356    }
357
358    #[cfg(not(unix))]
359    {
360        let ctrl_c = pin!(ctrl_c);
361        let fut = pin!(fut);
362
363        tokio::select! {
364            _ = ctrl_c => {
365                info!(target: "reth::cli", "Received ctrl-c");
366            },
367            res = fut => res?,
368        }
369    }
370
371    Ok(())
372}
373
374/// Default timeout for waiting on the tokio runtime to shut down.
375const DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
376
377/// Shut down the given [`Runtime`](reth_tasks::Runtime), and wait for it if `wait` is set.
378///
379/// Shuts down the owned tokio runtime even if tasks retain clones of the shared handle.
380/// Pool teardown can block, so it runs on a separate thread.
381fn runtime_shutdown(rt: reth_tasks::Runtime, wait: bool) {
382    let (tx, rx) = mpsc::channel();
383    std::thread::Builder::new()
384        .name("rt-shutdown".to_string())
385        .spawn(move || {
386            rt.shutdown_timeout(DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT);
387            let _ = tx.send(());
388        })
389        .unwrap();
390
391    if wait {
392        let _ = rx.recv_timeout(DEFAULT_RUNTIME_SHUTDOWN_TIMEOUT).inspect_err(|err| {
393            tracing::warn!(target: "reth::cli", %err, "runtime shutdown timed out");
394        });
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn runtime_shutdown_stops_tasks_with_live_runtime_clones() {
404        let runtime = reth_tasks::Runtime::test();
405        let retained = runtime.clone();
406        let task_runtime = runtime.clone();
407        let (started, ready) = mpsc::channel();
408        let task = runtime.handle().spawn(async move {
409            let _runtime = task_runtime;
410            started.send(()).unwrap();
411            std::future::pending::<()>().await;
412        });
413        ready.recv_timeout(Duration::from_secs(5)).unwrap();
414
415        runtime_shutdown(runtime, true);
416
417        assert!(task.is_finished(), "shutdown returned while a task still owned the runtime");
418        assert!(retained.handle().block_on(task).unwrap_err().is_cancelled());
419    }
420
421    #[cfg(unix)]
422    #[test]
423    fn command_outlives_signal_without_signal_handling() {
424        let runner = CliRunner::try_default_runtime()
425            .unwrap()
426            .with_config(CliRunnerConfig::new().with_signal_handling(false));
427        let mut ran_after_signal = false;
428        let res: Result<(), Box<dyn std::error::Error + Send + Sync>> = runner
429            .run_command_until_exit(|_| async {
430                let mut sigterm =
431                    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
432                // SAFETY: the process-wide SIGTERM handler is installed above.
433                assert_eq!(unsafe { libc::raise(libc::SIGTERM) }, 0);
434                sigterm.recv().await;
435                // Give a runner that handles SIGTERM the chance to drop this command.
436                tokio::time::sleep(Duration::from_millis(100)).await;
437                ran_after_signal = true;
438                Ok(())
439            });
440        res.unwrap();
441        assert!(ran_after_signal, "runner stopped the command on SIGTERM");
442    }
443}