1use anyhow::Context;
108use std::io::IsTerminal;
109use tracing::instrument;
110
111mod auto_meta;
112pub mod chmod;
113pub mod cli;
114pub mod cmp;
115pub mod config;
116pub mod copy;
117pub mod copy_data;
118pub mod delete;
119pub mod dry_run;
120pub mod error;
121pub mod error_collector;
122pub mod filegen;
123pub mod filter;
124pub mod histogram_logger;
125pub mod histogram_panel;
126mod input_protection;
127pub mod link;
128pub mod observability;
129pub mod preserve;
130pub mod remote_tracing;
131pub mod rm;
132mod runtime_setup;
133pub mod safedir;
134mod settings_parse;
135pub mod task_scope;
136pub mod timing;
137pub mod version;
138
139pub mod filecmp;
140pub mod progress;
141mod testutils;
142pub mod toctou_check;
143pub mod walk;
144pub(crate) mod walk_driver;
145
146pub use config::{
147 AdmissionPolicy, AutoMetaThrottleConfig, ConcurrencyLimit, DryRunMode, DryRunWarnings,
148 FilesInFlightSource, MIN_DEFAULT_FILES_IN_FLIGHT, OutputConfig, ResolvedFilesInFlight,
149 RuntimeConfig, ThrottleConfig, TracingConfig,
150};
151pub use congestion::{MetadataOp, Side};
156pub use progress::{RcpdProgressPrinter, SerializableProgress};
157pub use runtime_setup::{
161 EndpointAdmission, NOTICE_TARGET, RemoteResources, collect_runtime_stats,
162 generate_debug_log_filename, generate_trace_filename,
163};
164pub use settings_parse::{
165 parse_compare_settings, parse_metadata_cmp_settings, parse_preserve_settings,
166 validate_update_compare_vs_preserve,
167};
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, enum_map::Enum)]
171pub enum RcpdType {
172 Source,
173 Destination,
174}
175
176impl std::fmt::Display for RcpdType {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 match self {
179 RcpdType::Source => write!(f, "source"),
180 RcpdType::Destination => write!(f, "destination"),
181 }
182 }
183}
184
185pub type ProgressSnapshot<T> = enum_map::EnumMap<RcpdType, T>;
187
188#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
190pub struct RuntimeStats {
191 pub cpu_time_user_ms: u64,
193 pub cpu_time_kernel_ms: u64,
195 pub peak_rss_bytes: u64,
197}
198
199#[derive(Debug, Default)]
201pub struct RemoteRuntimeStats {
202 pub source_host: String,
203 pub source_stats: RuntimeStats,
204 pub dest_host: String,
205 pub dest_stats: RuntimeStats,
206}
207
208#[must_use]
211pub fn is_localhost(host: &str) -> bool {
212 if host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]" {
213 return true;
214 }
215 let mut buf = [0u8; 256];
217 let result = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
219 if result == 0
220 && let Ok(hostname_cstr) = std::ffi::CStr::from_bytes_until_nul(&buf)
221 && let Ok(hostname) = hostname_cstr.to_str()
222 && host == hostname
223 {
224 return true;
225 }
226 false
227}
228
229pub(crate) static PROGRESS: std::sync::LazyLock<progress::Progress> =
230 std::sync::LazyLock::new(progress::Progress::new);
231pub(crate) static PBAR: std::sync::LazyLock<indicatif::ProgressBar> =
232 std::sync::LazyLock::new(indicatif::ProgressBar::new_spinner);
233pub(crate) static REMOTE_RUNTIME_STATS: std::sync::LazyLock<
234 std::sync::Mutex<Option<RemoteRuntimeStats>>,
235> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
236static HISTOGRAM_LOGGER_CANCEL: std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>> =
237 std::sync::Mutex::new(None);
238static HISTOGRAM_LOGGER_HANDLE: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>> =
239 std::sync::Mutex::new(None);
240
241pub(crate) fn store_logger_cancel(tx: tokio::sync::watch::Sender<bool>) {
242 *HISTOGRAM_LOGGER_CANCEL
243 .lock()
244 .expect("histogram logger cancel mutex poisoned") = Some(tx);
245}
246
247pub(crate) fn store_logger_handle(handle: tokio::task::JoinHandle<()>) {
248 *HISTOGRAM_LOGGER_HANDLE
249 .lock()
250 .expect("histogram logger handle mutex poisoned") = Some(handle);
251}
252
253fn take_logger_handle() -> Option<tokio::task::JoinHandle<()>> {
254 HISTOGRAM_LOGGER_HANDLE
255 .lock()
256 .expect("histogram logger handle mutex poisoned")
257 .take()
258}
259
260fn signal_logger_cancel() {
261 if let Some(tx) = HISTOGRAM_LOGGER_CANCEL
262 .lock()
263 .expect("histogram logger cancel mutex poisoned")
264 .take()
265 && let Err(err) = tx.send(true)
266 {
267 tracing::debug!("histogram-logger cancel send failed (already gone): {err:#}");
268 }
269}
270
271#[must_use]
272pub fn get_progress() -> &'static progress::Progress {
273 &PROGRESS
274}
275
276pub fn set_remote_runtime_stats(stats: RemoteRuntimeStats) {
278 *REMOTE_RUNTIME_STATS.lock().unwrap() = Some(stats);
279}
280
281struct ProgressTracker {
282 lock_cvar: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
283 pbar_thread: Option<std::thread::JoinHandle<()>>,
284}
285
286#[derive(Copy, Clone, Debug, Default, clap::ValueEnum)]
287pub enum ProgressType {
288 #[default]
289 #[value(name = "auto", alias = "Auto")]
290 Auto,
291 #[value(name = "ProgressBar", alias = "progress-bar")]
292 ProgressBar,
293 #[value(name = "TextUpdates", alias = "text-updates")]
294 TextUpdates,
295}
296
297pub enum GeneralProgressType {
298 User {
299 progress_type: ProgressType,
300 kind: progress::LocalProgressKind,
301 },
302 Remote(tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>),
303 RemoteMaster {
304 progress_type: ProgressType,
305 get_progress_snapshot:
306 Box<dyn Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static>,
307 },
308}
309
310impl std::fmt::Debug for GeneralProgressType {
311 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312 match self {
313 GeneralProgressType::User {
314 progress_type,
315 kind,
316 } => write!(f, "User(progress_type: {progress_type:?}, kind: {kind:?})"),
317 GeneralProgressType::Remote(_) => write!(f, "Remote(<sender>)"),
318 GeneralProgressType::RemoteMaster { progress_type, .. } => {
319 write!(
320 f,
321 "RemoteMaster(progress_type: {progress_type:?}, <function>)"
322 )
323 }
324 }
325 }
326}
327
328#[derive(Debug)]
329pub struct ProgressSettings {
330 pub progress_type: GeneralProgressType,
331 pub progress_delay: Option<String>,
332}
333
334fn progress_bar(
335 lock: &std::sync::Mutex<bool>,
336 cvar: &std::sync::Condvar,
337 delay_opt: &Option<std::time::Duration>,
338 kind: progress::LocalProgressKind,
339) {
340 let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
341 PBAR.set_style(
342 indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
343 .unwrap()
344 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
345 );
346 let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
347 let mut is_done = lock.lock().unwrap();
348 loop {
349 PBAR.set_position(PBAR.position() + 1); let mut msg = prog_printer.print().unwrap();
351 msg.push_str(&observability::render_lines());
352 msg.push_str(&render_panel_from_registry());
353 PBAR.set_message(msg);
354 let result = cvar.wait_timeout(is_done, delay).unwrap();
355 is_done = result.0;
356 if *is_done {
357 break;
358 }
359 }
360 PBAR.finish_and_clear();
361}
362
363fn get_datetime_prefix() -> String {
364 chrono::Local::now()
365 .format("%Y-%m-%dT%H:%M:%S%.3f%:z")
366 .to_string()
367}
368
369fn text_updates(
370 lock: &std::sync::Mutex<bool>,
371 cvar: &std::sync::Condvar,
372 delay_opt: &Option<std::time::Duration>,
373 kind: progress::LocalProgressKind,
374) {
375 let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
376 let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
377 let mut is_done = lock.lock().unwrap();
378 loop {
379 eprintln!("=======================");
380 eprintln!(
381 "{}\n--{}{}{}",
382 get_datetime_prefix(),
383 prog_printer.print().unwrap(),
384 observability::render_lines(),
385 render_panel_from_registry(),
386 );
387 let result = cvar.wait_timeout(is_done, delay).unwrap();
388 is_done = result.0;
389 if *is_done {
390 break;
391 }
392 }
393}
394
395fn rcpd_updates(
396 lock: &std::sync::Mutex<bool>,
397 cvar: &std::sync::Condvar,
398 delay_opt: &Option<std::time::Duration>,
399 sender: tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>,
400) {
401 tracing::debug!("Starting rcpd progress updates");
402 let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
403 let mut is_done = lock.lock().unwrap();
404 loop {
405 if remote_tracing::send_progress_update(&sender, &PROGRESS).is_err() {
406 tracing::debug!("Progress update channel closed, stopping progress updates");
408 break;
409 }
410 let result = cvar.wait_timeout(is_done, delay).unwrap();
411 is_done = result.0;
412 if *is_done {
413 break;
414 }
415 }
416}
417
418fn remote_master_updates<F>(
419 lock: &std::sync::Mutex<bool>,
420 cvar: &std::sync::Condvar,
421 delay_opt: &Option<std::time::Duration>,
422 get_progress_snapshot: F,
423 progress_type: ProgressType,
424) where
425 F: Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static,
426{
427 let interactive = match progress_type {
428 ProgressType::Auto => std::io::stderr().is_terminal(),
429 ProgressType::ProgressBar => true,
430 ProgressType::TextUpdates => false,
431 };
432 if interactive {
433 PBAR.set_style(
434 indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
435 .unwrap()
436 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
437 );
438 let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
439 let mut printer = RcpdProgressPrinter::new();
440 let mut is_done = lock.lock().unwrap();
441 loop {
442 let progress_map = get_progress_snapshot();
443 let source_progress = &progress_map[RcpdType::Source];
444 let destination_progress = &progress_map[RcpdType::Destination];
445 PBAR.set_position(PBAR.position() + 1); let mut msg = printer
447 .print(source_progress, destination_progress)
448 .unwrap();
449 msg.push_str(&render_panel_from_registry());
450 PBAR.set_message(msg);
451 let result = cvar.wait_timeout(is_done, delay).unwrap();
452 is_done = result.0;
453 if *is_done {
454 break;
455 }
456 }
457 PBAR.finish_and_clear();
458 } else {
459 let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
460 let mut printer = RcpdProgressPrinter::new();
461 let mut is_done = lock.lock().unwrap();
462 loop {
463 let progress_map = get_progress_snapshot();
464 let source_progress = &progress_map[RcpdType::Source];
465 let destination_progress = &progress_map[RcpdType::Destination];
466 eprintln!("=======================");
467 eprintln!(
468 "{}\n--{}{}",
469 get_datetime_prefix(),
470 printer
471 .print(source_progress, destination_progress)
472 .unwrap(),
473 render_panel_from_registry(),
474 );
475 let result = cvar.wait_timeout(is_done, delay).unwrap();
476 is_done = result.0;
477 if *is_done {
478 break;
479 }
480 }
481 }
482}
483
484impl ProgressTracker {
485 pub fn new(progress_type: GeneralProgressType, delay_opt: Option<std::time::Duration>) -> Self {
486 let lock_cvar =
487 std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
488 let lock_cvar_clone = lock_cvar.clone();
489 let pbar_thread = std::thread::spawn(move || {
490 let (lock, cvar) = &*lock_cvar_clone;
491 match progress_type {
492 GeneralProgressType::Remote(sender) => {
493 rcpd_updates(lock, cvar, &delay_opt, sender);
494 }
495 GeneralProgressType::RemoteMaster {
496 progress_type,
497 get_progress_snapshot,
498 } => {
499 remote_master_updates(
500 lock,
501 cvar,
502 &delay_opt,
503 get_progress_snapshot,
504 progress_type,
505 );
506 }
507 GeneralProgressType::User {
508 progress_type,
509 kind,
510 } => {
511 let interactive = match progress_type {
512 ProgressType::Auto => std::io::stderr().is_terminal(),
513 ProgressType::ProgressBar => true,
514 ProgressType::TextUpdates => false,
515 };
516 if interactive {
517 progress_bar(lock, cvar, &delay_opt, kind);
518 } else {
519 text_updates(lock, cvar, &delay_opt, kind);
520 }
521 }
522 }
523 });
524 Self {
525 lock_cvar,
526 pbar_thread: Some(pbar_thread),
527 }
528 }
529}
530
531impl Drop for ProgressTracker {
532 fn drop(&mut self) {
533 let (lock, cvar) = &*self.lock_cvar;
534 let mut is_done = lock.lock().unwrap();
535 *is_done = true;
536 cvar.notify_one();
537 drop(is_done);
538 if let Some(pbar_thread) = self.pbar_thread.take() {
539 pbar_thread.join().unwrap();
540 }
541 }
542}
543
544pub async fn cmp(
545 src: &std::path::Path,
546 dst: &std::path::Path,
547 log: &cmp::LogWriter,
548 settings: &cmp::Settings,
549) -> Result<cmp::Summary, anyhow::Error> {
550 cmp::cmp(&PROGRESS, src, dst, log, settings).await
551}
552
553pub async fn copy(
554 session: ©::CopySession,
555 src: &std::path::Path,
556 dst: &std::path::Path,
557 settings: ©::Settings,
558 preserve: &preserve::Settings,
559) -> Result<copy::Summary, copy::Error> {
560 session
561 .copy(&PROGRESS, src, dst, settings, preserve, false)
562 .await
563}
564
565pub async fn copy_prepared(
567 prepared: copy::PreparedCopy,
568 preserve: &preserve::Settings,
569) -> Result<copy::Summary, copy::Error> {
570 prepared.copy(&PROGRESS, preserve, false).await
571}
572
573pub async fn rm(path: &std::path::Path, settings: &rm::Settings) -> Result<rm::Summary, rm::Error> {
574 rm::rm(&PROGRESS, path, settings).await
575}
576
577pub async fn chmod(
578 path: &std::path::Path,
579 settings: &chmod::Settings,
580) -> Result<chmod::Summary, chmod::Error> {
581 chmod::chmod(&PROGRESS, path, settings).await
582}
583
584pub async fn link(
585 src: &std::path::Path,
586 dst: &std::path::Path,
587 update: &Option<std::path::PathBuf>,
588 settings: &link::Settings,
589) -> Result<link::Summary, link::Error> {
590 let cwd = std::env::current_dir()
591 .with_context(|| "failed to get current working directory")
592 .map_err(|err| link::Error::new(err, link::Summary::default()))?;
593 link::link(&PROGRESS, &cwd, src, dst, update, settings, false).await
594}
595
596fn render_panel_from_registry() -> String {
597 let entries = observability::registered_histograms();
598 if entries.is_empty() {
599 return String::new();
600 }
601 let snapshots: Vec<hdrhistogram::Histogram<u64>> = entries
602 .iter()
603 .map(|e| (*e.snapshot_rx.borrow()).clone())
604 .collect();
605 let units: Vec<histogram_panel::PanelUnit> = entries
606 .iter()
607 .zip(snapshots.iter())
608 .map(|(e, snap)| histogram_panel::PanelUnit {
609 label: e.label,
610 histogram: snap,
611 interval: e.interval,
612 })
613 .collect();
614 histogram_panel::render_histogram_panel(&units)
615}
616
617#[must_use]
619pub fn format_startup_diagnostic(prefix: Option<&str>, diagnostic: &str) -> String {
620 let one_line = diagnostic
621 .lines()
622 .map(str::trim)
623 .filter(|line| !line.is_empty())
624 .collect::<Vec<_>>()
625 .join(" ");
626 format!("{}{one_line}", prefix.unwrap_or_default())
627}
628
629fn print_startup_configuration_error(
630 startup_error_prefix: Option<&str>,
631 error: &impl std::fmt::Display,
632) {
633 eprintln!(
634 "{}",
635 format_startup_diagnostic(
636 startup_error_prefix,
637 &format!("Configuration error: {error:#}"),
638 )
639 );
640}
641
642#[instrument(skip(func))] pub fn run<Fut, Summary, Error>(
647 progress: Option<ProgressSettings>,
648 output: OutputConfig,
649 runtime_config: RuntimeConfig,
650 throttle_config: ThrottleConfig,
651 tracing_config: TracingConfig,
652 func: impl FnOnce(EndpointAdmission) -> Fut,
653) -> Option<Summary>
654where
656 Summary: std::fmt::Display,
657 Error: std::fmt::Display + std::fmt::Debug,
658 Fut: std::future::Future<Output = Result<Summary, Error>>,
659{
660 let _ = get_progress();
664 let OutputConfig {
665 quiet,
666 verbose,
667 print_summary,
668 suppress_runtime_stats,
669 startup_error_prefix,
670 } = output;
671 if let Err(error) = throttle_config.validate() {
672 print_startup_configuration_error(startup_error_prefix, &error);
673 return None;
674 }
675 let trace_identifier = tracing_config.trace_identifier.clone();
678 if let Err(error) =
679 runtime_setup::validate_histogram_log_target(&throttle_config, &trace_identifier)
680 {
681 print_startup_configuration_error(startup_error_prefix, &error);
682 return None;
683 }
684 let mut tracing_guards =
685 match runtime_setup::install_tracing_subscriber(quiet, verbose, tracing_config) {
686 Ok(guards) => guards,
687 Err(error) => {
688 print_startup_configuration_error(startup_error_prefix, &error);
689 return None;
690 }
691 };
692 if let Some(warning) = throttle_config.deprecated_max_open_files_warning() {
693 tracing::warn!(target: NOTICE_TARGET, "{warning}");
694 }
695 let res = {
696 let (runtime, admission) =
697 match runtime_setup::build_tokio_runtime(&runtime_config, &throttle_config) {
698 Ok(runtime) => runtime,
699 Err(error) => {
700 print_startup_configuration_error(startup_error_prefix, &error);
701 return None;
702 }
703 };
704 runtime_setup::spawn_throttle_replenishers(&runtime, &throttle_config, &trace_identifier);
705 let res = {
706 let _progress_tracker = progress.map(|settings| {
707 tracing::debug!("Requesting progress updates {settings:?}");
708 let delay = settings.progress_delay.map(|delay_str| {
709 humantime::parse_duration(&delay_str)
710 .expect("Couldn't parse duration out of --progress-delay")
711 });
712 ProgressTracker::new(settings.progress_type, delay)
713 });
714 let scope = timing_scope!("operation");
715 let result = runtime.block_on(func(admission));
716 scope.finish();
717 result
718 };
719 match &res {
720 Ok(summary) => {
721 if print_summary || verbose > 0 {
722 println!("{summary}");
723 }
724 }
725 Err(err) => {
726 if !quiet {
727 println!("{err:?}");
728 }
729 }
730 }
731 if (print_summary || verbose > 0)
732 && !suppress_runtime_stats
733 && let Err(err) = runtime_setup::print_runtime_stats()
734 {
735 println!("Failed to print runtime stats: {err:?}");
736 }
737 signal_logger_cancel();
741 if let Some(handle) = take_logger_handle() {
742 let _ = runtime.block_on(async {
745 tokio::time::timeout(std::time::Duration::from_secs(1), handle).await
746 });
747 }
748 runtime.shutdown_timeout(std::time::Duration::from_secs(10));
756 res
757 };
758 reset_process_throttle_state();
763 if let Err(error) = tracing_guards.finish() {
764 eprintln!("Failed to write scoped timings: {error:#}");
765 return None;
766 }
767 res.ok()
768}
769
770fn reset_process_throttle_state() {
776 congestion::clear_sample_sink();
777 observability::clear();
778 for &side in &throttle::Side::ALL {
779 for &op in &throttle::MetadataOp::ALL {
780 throttle::set_max_ops_in_flight(throttle::Resource::meta(side, op), 0);
781 }
782 }
783 throttle::disable_ops_throttle();
784 throttle::set_admission_limits(None);
788 throttle::init_iops_tokens(0);
789}