Skip to main content

common/
lib.rs

1//! Common utilities and types for RCP file operation tools
2//!
3//! This crate provides shared functionality used across all RCP tools (`rcp`, `rrm`, `rlink`, `rcmp`).
4//! It includes core operations (copy, remove, link, compare), progress reporting, metadata preservation, and runtime configuration.
5//!
6//! # Core Modules
7//!
8//! - [`mod@copy`] - File copying operations with metadata preservation and error handling
9//! - [`mod@rm`] - File removal operations
10//! - [`mod@link`] - Hard-linking operations
11//! - [`mod@cmp`] - File comparison operations (metadata-based)
12//! - [`mod@preserve`] - Metadata preservation settings and operations
13//! - [`mod@progress`] - Progress tracking and reporting
14//! - [`mod@filecmp`] - File metadata comparison utilities
15//! - [`mod@remote_tracing`] - Remote tracing support for distributed operations
16//!
17//! # Key Types
18//!
19//! ## `RcpdType`
20//!
21//! Identifies the role of a remote copy daemon:
22//! - `Source` - reads files from source host
23//! - `Destination` - writes files to destination host
24//!
25//! ## `ProgressType`
26//!
27//! Controls progress reporting display:
28//! - `Auto` - automatically choose based on terminal type
29//! - `ProgressBar` - animated progress bar (for interactive terminals)
30//! - `TextUpdates` - periodic text updates (for logging/non-interactive)
31//!
32//! # Progress Reporting
33//!
34//! The crate provides a global progress tracking system accessible via [`get_progress()`].
35//! Progress can be displayed in different formats depending on the execution context.
36//!
37//! Progress output goes to stderr, while logs go to stdout, allowing users to redirect logs to a file while still viewing interactive progress.
38//!
39//! # Runtime Configuration
40//!
41//! The [`run`] function provides a unified entry point for all RCP tools with support for:
42//! - Progress tracking and reporting
43//! - Logging configuration (quiet/verbose modes)
44//! - Resource limits (max workers, leaf-operation descriptor admission, throttling)
45//! - Tokio runtime setup
46//! - Remote tracing integration
47//!
48//! # Examples
49//!
50//! ## Basic Copy Operation
51//!
52//! ```rust,no_run
53//! use std::path::Path;
54//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
55//! let src = Path::new("/source");
56//! let dst = Path::new("/destination");
57//!
58//! let settings = common::copy::Settings {
59//!     reflink: Default::default(),
60//!     local_copy_handoff: Default::default(),
61//!     dereference: false,
62//!     fail_early: false,
63//!     overwrite: false,
64//!     overwrite_compare: Default::default(),
65//!     overwrite_filter: None,
66//!     ignore_existing: false,
67//!     chunk_size: 0,
68//!     skip_specials: false,
69//!     remote_copy_buffer_size: 0,
70//!     filter: None,
71//!     dry_run: None,
72//!     delete: None,
73//! };
74//! let preserve = common::preserve::preserve_none();
75//!
76//! let summary = common::copy(src, dst, &settings, &preserve).await?;
77//! println!("Copied {} files", summary.files_copied);
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! ## Metadata Comparison
83//!
84//! ```rust,no_run
85//! use std::path::Path;
86//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
87//! let src = Path::new("/path1");
88//! let dst = Path::new("/path2");
89//!
90//! // output differences to stdout (use false for quiet mode)
91//! let log = common::cmp::LogWriter::new(None, true, common::cmp::OutputFormat::default()).await?;
92//! let settings = common::cmp::Settings {
93//!     fail_early: false,
94//!     exit_early: false,
95//!     expand_missing: false,
96//!     compare: Default::default(),
97//!     filter: None,
98//! };
99//!
100//! let summary = common::cmp(src, dst, &log, &settings).await?;
101//! println!("Comparison complete: {}", summary);
102//! # Ok(())
103//! # }
104//! ```
105
106use anyhow::Context;
107use std::io::IsTerminal;
108use tracing::instrument;
109
110mod auto_meta;
111pub mod chmod;
112pub mod cli;
113pub mod cmp;
114pub mod config;
115pub mod copy;
116pub mod copy_data;
117pub mod delete;
118pub mod dry_run;
119pub mod error;
120pub mod error_collector;
121pub mod filegen;
122pub mod filter;
123pub mod histogram_logger;
124pub mod histogram_panel;
125pub mod link;
126pub mod observability;
127pub mod preserve;
128pub mod remote_tracing;
129pub mod rm;
130mod runtime_setup;
131pub mod safedir;
132mod settings_parse;
133pub mod task_scope;
134pub mod timing;
135pub mod version;
136
137pub mod filecmp;
138pub mod progress;
139mod testutils;
140pub mod toctou_check;
141pub mod walk;
142pub(crate) mod walk_driver;
143
144pub use config::{
145    AdmissionPolicy, AutoMetaThrottleConfig, ConcurrencyLimit, DryRunMode, DryRunWarnings,
146    FilesInFlightSource, MIN_DEFAULT_FILES_IN_FLIGHT, OutputConfig, ResolvedFilesInFlight,
147    RuntimeConfig, ThrottleConfig, TracingConfig,
148};
149// Re-export `Side` from the congestion crate so downstream binaries
150// (rcp, rrm, …) and integration tests can pass `common::Side::Source` /
151// `common::Side::Destination` to `walk::next_entry_probed` and friends
152// without taking a direct dependency on `congestion`.
153pub use congestion::{MetadataOp, Side};
154pub use progress::{RcpdProgressPrinter, SerializableProgress};
155// Re-export the runtime-stat / trace-filename helpers that moved into
156// `runtime_setup` so downstream binaries keep reaching them as
157// `common::collect_runtime_stats`, etc.
158pub use runtime_setup::{
159    EndpointAdmission, NOTICE_TARGET, RemoteResources, collect_runtime_stats,
160    generate_debug_log_filename, generate_trace_filename,
161};
162pub use settings_parse::{
163    parse_compare_settings, parse_metadata_cmp_settings, parse_preserve_settings,
164    validate_update_compare_vs_preserve,
165};
166
167// Define RcpdType in common since remote depends on common
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, enum_map::Enum)]
169pub enum RcpdType {
170    Source,
171    Destination,
172}
173
174impl std::fmt::Display for RcpdType {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            RcpdType::Source => write!(f, "source"),
178            RcpdType::Destination => write!(f, "destination"),
179        }
180    }
181}
182
183// Type alias for progress snapshots
184pub type ProgressSnapshot<T> = enum_map::EnumMap<RcpdType, T>;
185
186/// runtime statistics collected from a process (CPU time, memory usage)
187#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
188pub struct RuntimeStats {
189    /// user-mode CPU time in milliseconds
190    pub cpu_time_user_ms: u64,
191    /// kernel-mode CPU time in milliseconds
192    pub cpu_time_kernel_ms: u64,
193    /// peak resident set size in bytes
194    pub peak_rss_bytes: u64,
195}
196
197/// runtime stats collected from remote rcpd processes for display at the end of a remote copy
198#[derive(Debug, Default)]
199pub struct RemoteRuntimeStats {
200    pub source_host: String,
201    pub source_stats: RuntimeStats,
202    pub dest_host: String,
203    pub dest_stats: RuntimeStats,
204}
205
206/// checks if a host string refers to the local machine.
207/// returns true for `localhost`, `127.0.0.1`, `::1`, `[::1]`, or the actual hostname
208#[must_use]
209pub fn is_localhost(host: &str) -> bool {
210    if host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]" {
211        return true;
212    }
213    // check against actual hostname using gethostname
214    let mut buf = [0u8; 256];
215    // Safety: gethostname writes to buf and returns 0 on success
216    let result = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
217    if result == 0
218        && let Ok(hostname_cstr) = std::ffi::CStr::from_bytes_until_nul(&buf)
219        && let Ok(hostname) = hostname_cstr.to_str()
220        && host == hostname
221    {
222        return true;
223    }
224    false
225}
226
227pub(crate) static PROGRESS: std::sync::LazyLock<progress::Progress> =
228    std::sync::LazyLock::new(progress::Progress::new);
229pub(crate) static PBAR: std::sync::LazyLock<indicatif::ProgressBar> =
230    std::sync::LazyLock::new(indicatif::ProgressBar::new_spinner);
231pub(crate) static REMOTE_RUNTIME_STATS: std::sync::LazyLock<
232    std::sync::Mutex<Option<RemoteRuntimeStats>>,
233> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
234static HISTOGRAM_LOGGER_CANCEL: std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>> =
235    std::sync::Mutex::new(None);
236static HISTOGRAM_LOGGER_HANDLE: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>> =
237    std::sync::Mutex::new(None);
238
239pub(crate) fn store_logger_cancel(tx: tokio::sync::watch::Sender<bool>) {
240    *HISTOGRAM_LOGGER_CANCEL
241        .lock()
242        .expect("histogram logger cancel mutex poisoned") = Some(tx);
243}
244
245pub(crate) fn store_logger_handle(handle: tokio::task::JoinHandle<()>) {
246    *HISTOGRAM_LOGGER_HANDLE
247        .lock()
248        .expect("histogram logger handle mutex poisoned") = Some(handle);
249}
250
251fn take_logger_handle() -> Option<tokio::task::JoinHandle<()>> {
252    HISTOGRAM_LOGGER_HANDLE
253        .lock()
254        .expect("histogram logger handle mutex poisoned")
255        .take()
256}
257
258fn signal_logger_cancel() {
259    if let Some(tx) = HISTOGRAM_LOGGER_CANCEL
260        .lock()
261        .expect("histogram logger cancel mutex poisoned")
262        .take()
263        && let Err(err) = tx.send(true)
264    {
265        tracing::debug!("histogram-logger cancel send failed (already gone): {err:#}");
266    }
267}
268
269#[must_use]
270pub fn get_progress() -> &'static progress::Progress {
271    &PROGRESS
272}
273
274/// stores remote runtime stats for display at the end of a remote copy operation
275pub fn set_remote_runtime_stats(stats: RemoteRuntimeStats) {
276    *REMOTE_RUNTIME_STATS.lock().unwrap() = Some(stats);
277}
278
279struct ProgressTracker {
280    lock_cvar: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
281    pbar_thread: Option<std::thread::JoinHandle<()>>,
282}
283
284#[derive(Copy, Clone, Debug, Default, clap::ValueEnum)]
285pub enum ProgressType {
286    #[default]
287    #[value(name = "auto", alias = "Auto")]
288    Auto,
289    #[value(name = "ProgressBar", alias = "progress-bar")]
290    ProgressBar,
291    #[value(name = "TextUpdates", alias = "text-updates")]
292    TextUpdates,
293}
294
295pub enum GeneralProgressType {
296    User {
297        progress_type: ProgressType,
298        kind: progress::LocalProgressKind,
299    },
300    Remote(tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>),
301    RemoteMaster {
302        progress_type: ProgressType,
303        get_progress_snapshot:
304            Box<dyn Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static>,
305    },
306}
307
308impl std::fmt::Debug for GeneralProgressType {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        match self {
311            GeneralProgressType::User {
312                progress_type,
313                kind,
314            } => write!(f, "User(progress_type: {progress_type:?}, kind: {kind:?})"),
315            GeneralProgressType::Remote(_) => write!(f, "Remote(<sender>)"),
316            GeneralProgressType::RemoteMaster { progress_type, .. } => {
317                write!(
318                    f,
319                    "RemoteMaster(progress_type: {progress_type:?}, <function>)"
320                )
321            }
322        }
323    }
324}
325
326#[derive(Debug)]
327pub struct ProgressSettings {
328    pub progress_type: GeneralProgressType,
329    pub progress_delay: Option<String>,
330}
331
332fn progress_bar(
333    lock: &std::sync::Mutex<bool>,
334    cvar: &std::sync::Condvar,
335    delay_opt: &Option<std::time::Duration>,
336    kind: progress::LocalProgressKind,
337) {
338    let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
339    PBAR.set_style(
340        indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
341            .unwrap()
342            .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
343    );
344    let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
345    let mut is_done = lock.lock().unwrap();
346    loop {
347        PBAR.set_position(PBAR.position() + 1); // do we need to update?
348        let mut msg = prog_printer.print().unwrap();
349        msg.push_str(&observability::render_lines());
350        msg.push_str(&render_panel_from_registry());
351        PBAR.set_message(msg);
352        let result = cvar.wait_timeout(is_done, delay).unwrap();
353        is_done = result.0;
354        if *is_done {
355            break;
356        }
357    }
358    PBAR.finish_and_clear();
359}
360
361fn get_datetime_prefix() -> String {
362    chrono::Local::now()
363        .format("%Y-%m-%dT%H:%M:%S%.3f%:z")
364        .to_string()
365}
366
367fn text_updates(
368    lock: &std::sync::Mutex<bool>,
369    cvar: &std::sync::Condvar,
370    delay_opt: &Option<std::time::Duration>,
371    kind: progress::LocalProgressKind,
372) {
373    let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
374    let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
375    let mut is_done = lock.lock().unwrap();
376    loop {
377        eprintln!("=======================");
378        eprintln!(
379            "{}\n--{}{}{}",
380            get_datetime_prefix(),
381            prog_printer.print().unwrap(),
382            observability::render_lines(),
383            render_panel_from_registry(),
384        );
385        let result = cvar.wait_timeout(is_done, delay).unwrap();
386        is_done = result.0;
387        if *is_done {
388            break;
389        }
390    }
391}
392
393fn rcpd_updates(
394    lock: &std::sync::Mutex<bool>,
395    cvar: &std::sync::Condvar,
396    delay_opt: &Option<std::time::Duration>,
397    sender: tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>,
398) {
399    tracing::debug!("Starting rcpd progress updates");
400    let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
401    let mut is_done = lock.lock().unwrap();
402    loop {
403        if remote_tracing::send_progress_update(&sender, &PROGRESS).is_err() {
404            // channel closed, receiver is done
405            tracing::debug!("Progress update channel closed, stopping progress updates");
406            break;
407        }
408        let result = cvar.wait_timeout(is_done, delay).unwrap();
409        is_done = result.0;
410        if *is_done {
411            break;
412        }
413    }
414}
415
416fn remote_master_updates<F>(
417    lock: &std::sync::Mutex<bool>,
418    cvar: &std::sync::Condvar,
419    delay_opt: &Option<std::time::Duration>,
420    get_progress_snapshot: F,
421    progress_type: ProgressType,
422) where
423    F: Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static,
424{
425    let interactive = match progress_type {
426        ProgressType::Auto => std::io::stderr().is_terminal(),
427        ProgressType::ProgressBar => true,
428        ProgressType::TextUpdates => false,
429    };
430    if interactive {
431        PBAR.set_style(
432            indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
433                .unwrap()
434                .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
435        );
436        let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
437        let mut printer = RcpdProgressPrinter::new();
438        let mut is_done = lock.lock().unwrap();
439        loop {
440            let progress_map = get_progress_snapshot();
441            let source_progress = &progress_map[RcpdType::Source];
442            let destination_progress = &progress_map[RcpdType::Destination];
443            PBAR.set_position(PBAR.position() + 1); // do we need to update?
444            let mut msg = printer
445                .print(source_progress, destination_progress)
446                .unwrap();
447            msg.push_str(&render_panel_from_registry());
448            PBAR.set_message(msg);
449            let result = cvar.wait_timeout(is_done, delay).unwrap();
450            is_done = result.0;
451            if *is_done {
452                break;
453            }
454        }
455        PBAR.finish_and_clear();
456    } else {
457        let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
458        let mut printer = RcpdProgressPrinter::new();
459        let mut is_done = lock.lock().unwrap();
460        loop {
461            let progress_map = get_progress_snapshot();
462            let source_progress = &progress_map[RcpdType::Source];
463            let destination_progress = &progress_map[RcpdType::Destination];
464            eprintln!("=======================");
465            eprintln!(
466                "{}\n--{}{}",
467                get_datetime_prefix(),
468                printer
469                    .print(source_progress, destination_progress)
470                    .unwrap(),
471                render_panel_from_registry(),
472            );
473            let result = cvar.wait_timeout(is_done, delay).unwrap();
474            is_done = result.0;
475            if *is_done {
476                break;
477            }
478        }
479    }
480}
481
482impl ProgressTracker {
483    pub fn new(progress_type: GeneralProgressType, delay_opt: Option<std::time::Duration>) -> Self {
484        let lock_cvar =
485            std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
486        let lock_cvar_clone = lock_cvar.clone();
487        let pbar_thread = std::thread::spawn(move || {
488            let (lock, cvar) = &*lock_cvar_clone;
489            match progress_type {
490                GeneralProgressType::Remote(sender) => {
491                    rcpd_updates(lock, cvar, &delay_opt, sender);
492                }
493                GeneralProgressType::RemoteMaster {
494                    progress_type,
495                    get_progress_snapshot,
496                } => {
497                    remote_master_updates(
498                        lock,
499                        cvar,
500                        &delay_opt,
501                        get_progress_snapshot,
502                        progress_type,
503                    );
504                }
505                GeneralProgressType::User {
506                    progress_type,
507                    kind,
508                } => {
509                    let interactive = match progress_type {
510                        ProgressType::Auto => std::io::stderr().is_terminal(),
511                        ProgressType::ProgressBar => true,
512                        ProgressType::TextUpdates => false,
513                    };
514                    if interactive {
515                        progress_bar(lock, cvar, &delay_opt, kind);
516                    } else {
517                        text_updates(lock, cvar, &delay_opt, kind);
518                    }
519                }
520            }
521        });
522        Self {
523            lock_cvar,
524            pbar_thread: Some(pbar_thread),
525        }
526    }
527}
528
529impl Drop for ProgressTracker {
530    fn drop(&mut self) {
531        let (lock, cvar) = &*self.lock_cvar;
532        let mut is_done = lock.lock().unwrap();
533        *is_done = true;
534        cvar.notify_one();
535        drop(is_done);
536        if let Some(pbar_thread) = self.pbar_thread.take() {
537            pbar_thread.join().unwrap();
538        }
539    }
540}
541
542pub async fn cmp(
543    src: &std::path::Path,
544    dst: &std::path::Path,
545    log: &cmp::LogWriter,
546    settings: &cmp::Settings,
547) -> Result<cmp::Summary, anyhow::Error> {
548    cmp::cmp(&PROGRESS, src, dst, log, settings).await
549}
550
551pub async fn copy(
552    src: &std::path::Path,
553    dst: &std::path::Path,
554    settings: &copy::Settings,
555    preserve: &preserve::Settings,
556) -> Result<copy::Summary, copy::Error> {
557    copy::copy(&PROGRESS, src, dst, settings, preserve, false).await
558}
559
560pub async fn rm(path: &std::path::Path, settings: &rm::Settings) -> Result<rm::Summary, rm::Error> {
561    rm::rm(&PROGRESS, path, settings).await
562}
563
564pub async fn chmod(
565    path: &std::path::Path,
566    settings: &chmod::Settings,
567) -> Result<chmod::Summary, chmod::Error> {
568    chmod::chmod(&PROGRESS, path, settings).await
569}
570
571pub async fn link(
572    src: &std::path::Path,
573    dst: &std::path::Path,
574    update: &Option<std::path::PathBuf>,
575    settings: &link::Settings,
576) -> Result<link::Summary, link::Error> {
577    let cwd = std::env::current_dir()
578        .with_context(|| "failed to get current working directory")
579        .map_err(|err| link::Error::new(err, link::Summary::default()))?;
580    link::link(&PROGRESS, &cwd, src, dst, update, settings, false).await
581}
582
583fn render_panel_from_registry() -> String {
584    let entries = observability::registered_histograms();
585    if entries.is_empty() {
586        return String::new();
587    }
588    let snapshots: Vec<hdrhistogram::Histogram<u64>> = entries
589        .iter()
590        .map(|e| (*e.snapshot_rx.borrow()).clone())
591        .collect();
592    let units: Vec<histogram_panel::PanelUnit> = entries
593        .iter()
594        .zip(snapshots.iter())
595        .map(|(e, snap)| histogram_panel::PanelUnit {
596            label: e.label,
597            histogram: snap,
598            interval: e.interval,
599        })
600        .collect();
601    histogram_panel::render_histogram_panel(&units)
602}
603
604/// Format one pre-tracing diagnostic, optionally as a machine-readable startup record.
605#[must_use]
606pub fn format_startup_diagnostic(prefix: Option<&str>, diagnostic: &str) -> String {
607    let one_line = diagnostic
608        .lines()
609        .map(str::trim)
610        .filter(|line| !line.is_empty())
611        .collect::<Vec<_>>()
612        .join(" ");
613    format!("{}{one_line}", prefix.unwrap_or_default())
614}
615
616fn print_startup_configuration_error(
617    startup_error_prefix: Option<&str>,
618    error: &impl std::fmt::Display,
619) {
620    eprintln!(
621        "{}",
622        format_startup_diagnostic(
623            startup_error_prefix,
624            &format!("Configuration error: {error:#}"),
625        )
626    );
627}
628
629/// Run an operation after startup, passing the endpoint admission installed for this runtime.
630///
631/// Setup failure reports its diagnostic without invoking the operation callback.
632#[instrument(skip(func))] // "func" is not Debug printable
633pub fn run<Fut, Summary, Error>(
634    progress: Option<ProgressSettings>,
635    output: OutputConfig,
636    runtime_config: RuntimeConfig,
637    throttle_config: ThrottleConfig,
638    tracing_config: TracingConfig,
639    func: impl FnOnce(EndpointAdmission) -> Fut,
640) -> Option<Summary>
641// we return an Option rather than a Result to indicate that callers of this function should NOT print the error
642where
643    Summary: std::fmt::Display,
644    Error: std::fmt::Display + std::fmt::Debug,
645    Fut: std::future::Future<Output = Result<Summary, Error>>,
646{
647    // force initialization of PROGRESS to set start_time at the beginning of the run
648    // (for remote master operations, PROGRESS is otherwise only accessed at the end in
649    // print_runtime_stats(), leading to near-zero walltime)
650    let _ = get_progress();
651    let OutputConfig {
652        quiet,
653        verbose,
654        print_summary,
655        suppress_runtime_stats,
656        startup_error_prefix,
657    } = output;
658    if let Err(error) = throttle_config.validate() {
659        print_startup_configuration_error(startup_error_prefix, &error);
660        return None;
661    }
662    // tracing guards must outlive the runtime so chrome/flame traces flush
663    // extract trace_identifier before install_tracing_subscriber consumes tracing_config
664    let trace_identifier = tracing_config.trace_identifier.clone();
665    if let Err(error) =
666        runtime_setup::validate_histogram_log_target(&throttle_config, &trace_identifier)
667    {
668        print_startup_configuration_error(startup_error_prefix, &error);
669        return None;
670    }
671    let mut tracing_guards =
672        match runtime_setup::install_tracing_subscriber(quiet, verbose, tracing_config) {
673            Ok(guards) => guards,
674            Err(error) => {
675                print_startup_configuration_error(startup_error_prefix, &error);
676                return None;
677            }
678        };
679    if let Some(warning) = throttle_config.deprecated_max_open_files_warning() {
680        tracing::warn!(target: NOTICE_TARGET, "{warning}");
681    }
682    let res = {
683        let (runtime, admission) =
684            match runtime_setup::build_tokio_runtime(&runtime_config, &throttle_config) {
685                Ok(runtime) => runtime,
686                Err(error) => {
687                    print_startup_configuration_error(startup_error_prefix, &error);
688                    return None;
689                }
690            };
691        runtime_setup::spawn_throttle_replenishers(&runtime, &throttle_config, &trace_identifier);
692        let res = {
693            let _progress_tracker = progress.map(|settings| {
694                tracing::debug!("Requesting progress updates {settings:?}");
695                let delay = settings.progress_delay.map(|delay_str| {
696                    humantime::parse_duration(&delay_str)
697                        .expect("Couldn't parse duration out of --progress-delay")
698                });
699                ProgressTracker::new(settings.progress_type, delay)
700            });
701            let scope = timing_scope!("operation");
702            let result = runtime.block_on(func(admission));
703            scope.finish();
704            result
705        };
706        match &res {
707            Ok(summary) => {
708                if print_summary || verbose > 0 {
709                    println!("{summary}");
710                }
711            }
712            Err(err) => {
713                if !quiet {
714                    println!("{err:?}");
715                }
716            }
717        }
718        if (print_summary || verbose > 0)
719            && !suppress_runtime_stats
720            && let Err(err) = runtime_setup::print_runtime_stats()
721        {
722            println!("Failed to print runtime stats: {err:?}");
723        }
724        // Signal the histogram logger to exit cleanly so its final
725        // snapshot is written before the runtime drops and aborts it.
726        // No-op when histograms are disabled.
727        signal_logger_cancel();
728        if let Some(handle) = take_logger_handle() {
729            // Bound the wait so a stuck logger can't hang shutdown — 1s is
730            // generous: the logger only does a snapshot+flush on cancel.
731            let _ = runtime.block_on(async {
732                tokio::time::timeout(std::time::Duration::from_secs(1), handle).await
733            });
734        }
735        // Bounded shutdown instead of a plain drop, which WAITS for every running blocking-pool
736        // closure. A blocking syscall parked on dead media (an NFS readdir that never returns, the
737        // stdin watchdog's read(2) that only unblocks when sshd notices) would otherwise keep the
738        // process alive indefinitely after the operation itself already failed and reported.
739        // Async tasks are still dropped normally — destructors (reused-directory ACL rollbacks
740        // included) run before the wait begins; only stuck blocking threads are abandoned to
741        // process exit once the deadline passes.
742        runtime.shutdown_timeout(std::time::Duration::from_secs(10));
743        res
744    };
745    // Clear process-wide state so a second `run()` in the same process
746    // starts on a clean slate. Without this, a later run inherits the
747    // previous auto-meta sample sink and ops-in-flight cap, and its
748    // probes acquire against stale limits even when auto_meta is off.
749    reset_process_throttle_state();
750    if let Err(error) = tracing_guards.finish() {
751        eprintln!("Failed to write scoped timings: {error:#}");
752        return None;
753    }
754    res.ok()
755}
756
757/// Reset process-wide throttle + congestion state to its pre-`run()`
758/// defaults. Called by [`run`] on exit so callers that invoke it more
759/// than once in a single process (library users, integration tests
760/// outside this crate) aren't affected by the previous invocation's
761/// decisions.
762fn reset_process_throttle_state() {
763    congestion::clear_sample_sink();
764    observability::clear();
765    for &side in &throttle::Side::ALL {
766        for &op in &throttle::MetadataOp::ALL {
767            throttle::set_max_ops_in_flight(throttle::Resource::meta(side, op), 0);
768        }
769    }
770    throttle::disable_ops_throttle();
771    // without these resets, a second run() in the same process inherits the previous run's
772    // file-admission caps and iops-throttle. `None` disables the admission semaphores, so the next
773    // run sees a clean slate and can either configure a fresh value or leave admission unlimited.
774    throttle::set_admission_limits(None);
775    throttle::init_iops_tokens(0);
776}