Skip to content

Close non-stdio file handles when daemonizing #2314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ test-case = "3.3.1"
thirtyfour_sync = "0.27"

[target.'cfg(unix)'.dependencies]
close_fds = "0.3.2"
daemonize = "0.5"

[target.'cfg(not(target_os = "freebsd"))'.dependencies.libmount]
Expand Down
2 changes: 1 addition & 1 deletion src/bin/sccache-dist/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ fn run(command: Command) -> Result<i32> {
}
};

daemonize()?;
daemonize(None)?;
let scheduler = Scheduler::new();
let http_scheduler = dist::http::Scheduler::new(
public_addr,
Expand Down
34 changes: 4 additions & 30 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,26 +126,6 @@ fn run_server_process(startup_timeout: Option<Duration>) -> Result<ServerStartup
})
}

#[cfg(not(windows))]
fn redirect_stderr(f: File) {
use libc::dup2;
use std::os::unix::io::IntoRawFd;
// Ignore errors here.
unsafe {
dup2(f.into_raw_fd(), 2);
}
}

#[cfg(windows)]
fn redirect_stderr(f: File) {
use std::os::windows::io::IntoRawHandle;
use windows_sys::Win32::System::Console::{SetStdHandle, STD_ERROR_HANDLE};
// Ignore errors here.
unsafe {
SetStdHandle(STD_ERROR_HANDLE, f.into_raw_handle() as _);
}
}

/// Create the log file and return an error if cannot be created
fn create_error_log() -> Result<File> {
trace!("Create the log file");
Expand All @@ -165,13 +145,6 @@ fn create_error_log() -> Result<File> {
Ok(f)
}

/// If `SCCACHE_ERROR_LOG` is set, redirect stderr to it.
fn redirect_error_log(f: File) -> Result<()> {
debug!("redirecting stderr into {:?}", f);
redirect_stderr(f);
Ok(())
}

/// Re-execute the current executable as a background server.
#[cfg(windows)]
fn run_server_process(startup_timeout: Option<Duration>) -> Result<ServerStartup> {
Expand Down Expand Up @@ -654,14 +627,15 @@ pub fn run_command(cmd: Command) -> Result<i32> {
}
Command::InternalStartServer => {
trace!("Command::InternalStartServer");
// If `SCCACHE_ERROR_LOG` is set, redirect stderr to it.
if env::var("SCCACHE_ERROR_LOG").is_ok() {
let f = create_error_log()?;
debug!("redirecting stderr into {:?}", f);
// Can't report failure here, we're already daemonized.
daemonize()?;
redirect_error_log(f)?;
daemonize(Some(f))?;
} else {
// We aren't asking for a log file
daemonize()?;
daemonize(None)?;
}
server::start_server(config, &get_addr())?;
}
Expand Down
33 changes: 29 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@ impl Hasher for HashToDigest<'_> {

/// Pipe `cmd`'s stdio to `/dev/null`, unless a specific env var is set.
#[cfg(not(windows))]
pub fn daemonize() -> Result<()> {
pub fn daemonize(log_file: Option<File>) -> Result<()> {
use crate::jobserver::discard_inherited_jobserver;
use daemonize::Daemonize;
use std::env;
Expand All @@ -850,7 +850,18 @@ pub fn daemonize() -> Result<()> {
match env::var("SCCACHE_NO_DAEMON") {
Ok(ref val) if val == "1" => {}
_ => {
Daemonize::new().start().context("failed to daemonize")?;
Daemonize::new()
.stderr(
log_file
.map(|f| f.into_parts().0.into())
.unwrap_or_else(daemonize::Stdio::devnull),
)
.start()
.context("failed to daemonize")?;
// Be extra-zealous and clase all non-stdio file descriptors.
unsafe {
close_fds::close_open_fds(3, &[]);
}
}
}

Expand Down Expand Up @@ -926,12 +937,26 @@ pub fn daemonize() -> Result<()> {
}
}

/// This is a no-op on Windows.
/// Daemonizing is a no-op on Windows, but we still must set the log file as
/// stderr.
#[cfg(windows)]
pub fn daemonize() -> Result<()> {
pub fn daemonize(log_file: Option<File>) -> Result<()> {
if let Some(log_file) = log_file {
redirect_stderr(log_file);
}
Ok(())
}

#[cfg(windows)]
fn redirect_stderr(f: File) {
use std::os::windows::io::IntoRawHandle;
use windows_sys::Win32::System::Console::{SetStdHandle, STD_ERROR_HANDLE};
// Ignore errors here.
unsafe {
SetStdHandle(STD_ERROR_HANDLE, f.into_raw_handle() as _);
}
}

/// Disable connection pool to avoid broken connection between runtime
///
/// # TODO
Expand Down
Loading