1use 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};
149pub use congestion::{MetadataOp, Side};
154pub use progress::{RcpdProgressPrinter, SerializableProgress};
155pub 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#[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
183pub type ProgressSnapshot<T> = enum_map::EnumMap<RcpdType, T>;
185
186#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
188pub struct RuntimeStats {
189 pub cpu_time_user_ms: u64,
191 pub cpu_time_kernel_ms: u64,
193 pub peak_rss_bytes: u64,
195}
196
197#[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#[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 let mut buf = [0u8; 256];
215 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
274pub 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); 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 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); 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: ©::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#[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#[instrument(skip(func))] pub 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>
641where
643 Summary: std::fmt::Display,
644 Error: std::fmt::Display + std::fmt::Debug,
645 Fut: std::future::Future<Output = Result<Summary, Error>>,
646{
647 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 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_logger_cancel();
728 if let Some(handle) = take_logger_handle() {
729 let _ = runtime.block_on(async {
732 tokio::time::timeout(std::time::Duration::from_secs(1), handle).await
733 });
734 }
735 runtime.shutdown_timeout(std::time::Duration::from_secs(10));
743 res
744 };
745 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
757fn 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 throttle::set_admission_limits(None);
775 throttle::init_iops_tokens(0);
776}