Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/uu/tail/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,4 @@ tail-become-inaccessible = has become inaccessible
# Debug messages
tail-debug-using-notification-mode = using notification mode
tail-debug-using-polling-mode = using polling mode
tail-debug-using-blocking-mode = using blocking mode
9 changes: 2 additions & 7 deletions src/uu/tail/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

// spell-checker:ignore (ToDO) kqueue Signum underflows

use crate::paths::Input;
use crate::paths::{Input, stdin_is_regular};
use crate::{Quotable, parse, platform};
use clap::{Arg, ArgAction, ArgMatches, Command, value_parser};
use std::ffi::OsString;
Expand Down Expand Up @@ -350,15 +350,10 @@ impl Settings {
// as `tty` (but no otherwise blocking stdin), then we print a warning that `--follow`
// cannot be applied under these circumstances and is therefore ineffective.
if self.follow.is_some() && self.has_stdin() {
#[cfg(unix)]
let stdin_is_regular = rustix::fs::fstat(std::io::stdin())
.is_ok_and(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFREG);
#[cfg(not(unix))]
let stdin_is_regular = true;
let blocking_stdin = self.pid.unwrap_or_default() == 0
&& self.follow == Some(FollowMode::Descriptor)
&& self.num_inputs() == 1
&& !stdin_is_regular;
&& !stdin_is_regular();

if !blocking_stdin && std::io::stdin().is_terminal() {
show_warning!("{}", translate!("tail-warning-following-stdin-ineffective"));
Expand Down
6 changes: 2 additions & 4 deletions src/uu/tail/src/follow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@ mod wasi_stubs {
use std::path::Path;
use uucore::error::{UResult, USimpleError};

pub struct Observer {
pub use_polling: bool,
}
pub struct Observer;

impl Observer {
pub fn from(_settings: &Settings) -> Self {
Self { use_polling: false }
Self
}

#[allow(clippy::unnecessary_wraps)]
Expand Down
33 changes: 32 additions & 1 deletion src/uu/tail/src/follow/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

use crate::args::{FollowMode, Settings};
use crate::follow::files::{FileHandling, PathData};
use crate::paths::{Input, InputKind, MetadataExtTail, PathExtTail};
use crate::paths::{Input, InputKind, MetadataExtTail, PathExtTail, stdin_is_regular};
use crate::{platform, text};
use notify::{RecommendedWatcher, RecursiveMode, Watcher, WatcherKind};
use std::io::BufRead;
Expand Down Expand Up @@ -106,6 +106,9 @@ pub struct Observer {
pub files: FileHandling,

pub pid: platform::Pid,

/// Whether --debug already reported the switch to polling mode.
reported_polling: bool,
}

impl Observer {
Expand All @@ -130,6 +133,7 @@ impl Observer {
orphans: Vec::new(),
files,
pid,
reported_polling: false,
}
}

Expand Down Expand Up @@ -453,6 +457,10 @@ impl Observer {
"{}",
translate!("tail-status-backend-cannot-be-used-reverting-to-polling", "backend" => text::BACKEND)
);
if settings.debug && !self.reported_polling {
self.reported_polling = true;
show_error!("{}", translate!("tail-debug-using-polling-mode"));
}
self.orphans.push(event_path.clone());
let _ = self.watcher_rx.as_mut().unwrap().unwatch(event_path);
} else if event_path.is_symlink() && !self.orphans.contains(event_path) {
Expand Down Expand Up @@ -539,12 +547,35 @@ fn report_inaccessible(display_name: &str) {
);
}

/// Report the follow implementation in use, for --debug.
fn print_follow_mode(observer: &Observer, settings: &Settings) {
// Without a regular file (e.g. only devices or FIFOs) there is nothing to
// be notified about: following by name polls, by descriptor blocks.
// Stdin is classified by what fd 0 refers to.
let no_regular_file = settings.inputs.iter().all(|input| match input.kind() {
InputKind::File(path) => path.metadata().is_ok_and(|md| !md.is_file()),
InputKind::Stdin => !stdin_is_regular(),
});
let mode = if observer.use_polling || (no_regular_file && observer.follow_name()) {
translate!("tail-debug-using-polling-mode")
} else if no_regular_file {
translate!("tail-debug-using-blocking-mode")
} else {
translate!("tail-debug-using-notification-mode")
};
show_error!("{mode}");
}

#[allow(clippy::cognitive_complexity)]
pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> {
if observer.files.no_files_remaining(settings) && !observer.files.only_stdin_remaining() {
return Err(USimpleError::new(1, translate!("tail-no-files-remaining")));
}

if settings.debug {
print_follow_mode(&observer, settings);
}

let process = platform::ProcessChecker::new(observer.pid);

let mut timeout_counter = 0;
Expand Down
11 changes: 11 additions & 0 deletions src/uu/tail/src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,17 @@ pub fn path_is_tailable(path: &Path) -> bool {
path.is_file() || path.exists() && path.metadata().is_ok_and(|meta| meta.is_tailable())
}

/// Whether stdin refers to a regular file.
#[cfg(unix)]
pub fn stdin_is_regular() -> bool {
rustix::fs::fstat(io::stdin()).is_ok_and(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFREG)
}

#[cfg(not(unix))]
pub fn stdin_is_regular() -> bool {
true
}

#[inline]
#[cfg(all(unix, not(target_os = "fuchsia")))]
pub fn stdin_is_bad_fd() -> bool {
Expand Down
9 changes: 0 additions & 9 deletions src/uu/tail/src/tail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,6 @@ fn uu_tail(settings: &Settings) -> UResult<()> {

observer.start(settings)?;

// Print debug info about the follow implementation being used
if settings.debug && settings.follow.is_some() {
if observer.use_polling {
show_error!("{}", translate!("tail-debug-using-polling-mode"));
} else {
show_error!("{}", translate!("tail-debug-using-notification-mode"));
}
}

// Do an initial tail print of each path's content.
// Add `path` and `reader` to `files` map if `--follow` is selected.
for input in &settings.inputs {
Expand Down
156 changes: 156 additions & 0 deletions tests/by-util/test_tail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5685,6 +5685,162 @@ fn test_debug_flag_with_inotify() {
.stderr_contains("tail: using notification mode");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(unix)]
fn test_debug_follow_descriptor_device_uses_blocking_mode() {
let mut child = new_ucmd!()
.args(&["--debug", "-f", "/dev/null"])
.run_no_wait();

child.make_assertion_with_delay(500).is_alive();
child
.kill()
.make_assertion()
.with_all_output()
.stderr_is("tail: using blocking mode\n");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(unix)]
fn test_debug_follow_name_device_uses_polling_mode() {
let mut child = new_ucmd!()
.args(&["--debug", "-F", "/dev/null"])
.run_no_wait();

child.make_assertion_with_delay(500).is_alive();
child
.kill()
.make_assertion()
.with_all_output()
.stderr_is("tail: using polling mode\n");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(unix)]
fn test_debug_follow_piped_stdin_and_device_uses_blocking_mode() {
let mut child = new_ucmd!()
.args(&["--debug", "-f", "/dev/null", "-"])
.pipe_in("x\n")
.run_no_wait();

child.make_assertion_with_delay(500).is_alive();
child
.kill()
.make_assertion()
.with_all_output()
.stderr_contains("tail: using blocking mode\n")
.stderr_does_not_contain("notification");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
fn test_debug_follow_missing_file_prints_no_mode() {
new_ucmd!()
.args(&["--debug", "-f", "missing"])
.fails_with_code(1)
.stderr_does_not_contain("using");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(target_os = "linux")]
fn test_debug_mode_printed_after_initial_output() {
let (at, mut ucmd) = at_and_ucmd!();
at.write("f", "hello\n");

let mut child = ucmd.args(&["--debug", "-F", "missing", "f"]).run_no_wait();

child.make_assertion_with_delay(500).is_alive();
child.kill().make_assertion().with_all_output().stderr_is(
"tail: cannot open 'missing' for reading: No such file or directory\n\
tail: using notification mode\n",
);
}

/// Wait up to 5 seconds for the stderr of `child` to satisfy `done`.
#[cfg(target_os = "linux")]
fn wait_for_stderr(child: &mut uutests::util::UChild, done: impl Fn(&str) -> bool) {
for _ in 0..100 {
if done(&child.stderr_all()) {
break;
}
child.delay(50);
}
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(target_os = "linux")]
fn test_debug_reports_switch_to_polling() {
use text::BACKEND;

let ts = TestScenario::new(util_name!());
let at = &ts.fixtures;
at.mkdir("dir");
at.write("dir/f", "hello\n");

let mut child = ts
.ucmd()
.args(&["--debug", "-F", "-s.1", "--max-unchanged-stats=1", "dir/f"])
.run_no_wait();

child.make_assertion_with_delay(500).is_alive();
// Move the directory away before removing the file, so the parent is
// already gone whenever tail handles the removal.
at.rename("dir", "dir.gone");
at.remove("dir.gone/f");
wait_for_stderr(&mut child, |e| e.contains("using polling mode"));
at.mkdir("dir");
at.touch("dir/f");
wait_for_stderr(&mut child, |e| e.contains("has appeared"));

child.make_assertion().is_alive();
child
.kill()
.make_assertion()
.with_all_output()
.stdout_is("hello\n")
.stderr_is(format!(
"tail: using notification mode\n\
tail: 'dir/f' has become inaccessible: No such file or directory\n\
tail: directory containing watched file was removed\n\
tail: {BACKEND} cannot be used, reverting to polling\n\
tail: using polling mode\n\
tail: 'dir/f' has appeared; following new file\n"
));
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(target_os = "linux")]
fn test_debug_reports_switch_to_polling_once() {
let ts = TestScenario::new(util_name!());
let at = &ts.fixtures;
at.mkdir("dir");
at.write("dir/a", "a\n");
at.write("dir/b", "b\n");

let mut child = ts
.ucmd()
.args(&["--debug", "-F", "-s.1", "dir/a", "dir/b"])
.run_no_wait();

child.make_assertion_with_delay(500).is_alive();
// Move the directory away first, so both removals see it gone.
at.rename("dir", "dir.gone");
at.remove("dir.gone/a");
at.remove("dir.gone/b");
wait_for_stderr(&mut child, |e| {
e.matches("reverting to polling").count() == 2
});

let stderr = child.kill().stderr_all();
assert_eq!(stderr.matches("using polling mode").count(), 1, "{stderr}");
}

#[uutests::wasi_ignore(TailFollowDisabled)]
#[test]
#[cfg(target_os = "linux")]
Expand Down
Loading