Skip to content
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

fix: Add Ctrl-C handler for spawned children #193

Merged
merged 2 commits into from
Jun 18, 2024
Merged
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
48 changes: 48 additions & 0 deletions Cargo.lock

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

4 changes: 3 additions & 1 deletion src/bin/bluebuild.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use blue_build::commands::{BlueBuildArgs, BlueBuildCommand, CommandArgs};
use blue_build_utils::logging::Logger;
use blue_build_utils::{ctrlc_handler, logging::Logger};
use clap::Parser;
use log::LevelFilter;

Expand All @@ -12,6 +12,8 @@ fn main() {
.log_out_dir(args.log_out.clone())
.init();

ctrlc_handler::init();

log::trace!("Parsed arguments: {args:#?}");

match args.command {
Expand Down
17 changes: 10 additions & 7 deletions src/commands/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,16 @@ impl GenerateCommand {
.recipe(&recipe_de)
.recipe_path(recipe_path.as_path())
.registry(self.get_registry())
.exports_tag(if shadow::COMMIT_HASH.is_empty() {
// This is done for users who install via
// cargo. Cargo installs do not carry git
// information via shadow
format!("v{}", crate_version!())
} else {
shadow::COMMIT_HASH.to_string()
.exports_tag({
#[allow(clippy::const_is_empty)]
if shadow::COMMIT_HASH.is_empty() {
// This is done for users who install via
// cargo. Cargo installs do not carry git
// information via shadow
format!("v{}", crate_version!())
} else {
shadow::COMMIT_HASH.to_string()
}
})
.build();

Expand Down
2 changes: 2 additions & 0 deletions utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ license.workspace = true
atty = "0.2"
base64 = "0.22.1"
blake2 = "0.10.6"
ctrlc = { version = "3.4.4", features = ["termination"] }
directories = "5"
rand = "0.8.5"
log4rs = { version = "1.3.0", features = ["background_rotation"] }
nix = { version = "0.29.0", features = ["signal"] }
nu-ansi-term = { version = "0.50.0", features = ["gnu_legacy"] }
os_pipe = { version = "1", features = ["io_safety"] }
process_control = { version = "4", features = ["crossbeam-channel"] }
Expand Down
68 changes: 68 additions & 0 deletions utils/src/ctrlc_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::{
process,
sync::{Arc, Mutex},
};

use log::error;
use nix::{
sys::signal::{kill, Signal::SIGTERM},
unistd::Pid,
};
use once_cell::sync::Lazy;

static PID_LIST: Lazy<Arc<Mutex<Vec<i32>>>> = Lazy::new(|| Arc::new(Mutex::new(vec![])));

/// Initialize Ctrl-C handler. This should be done at the start
/// of a binary.
///
/// # Panics
/// Will panic if initialized more than once.
pub fn init() {
let pid_list = PID_LIST.clone();
ctrlc::set_handler(move || {
let pid_list = pid_list.lock().expect("Should lock mutex");
pid_list.iter().for_each(|pid| {
if let Err(e) = kill(Pid::from_raw(*pid), SIGTERM) {
error!("Failed to kill process {pid}: Error {e}");
}
});
drop(pid_list);
process::exit(1);
})
.expect("Should create ctrlc handler");
}

/// Add a pid to the list to kill when the program
/// recieves a kill signal.
///
/// # Panics
/// Will panic if the mutex cannot be locked.
pub fn add_pid<T>(pid: T)
where
T: TryInto<i32>,
{
if let Ok(pid) = pid.try_into() {
let mut pid_list = PID_LIST.lock().expect("Should lock pid_list");

if !pid_list.contains(&pid) {
pid_list.push(pid);
}
}
}

/// Remove a pid from the list of pids to kill.
///
/// # Panics
/// Will panic if the mutex cannot be locked.
pub fn remove_pid<T>(pid: T)
where
T: TryInto<i32>,
{
if let Ok(pid) = pid.try_into() {
let mut pid_list = PID_LIST.lock().expect("Should lock pid_list");

if let Some(index) = pid_list.iter().position(|val| *val == pid) {
pid_list.swap_remove(index);
}
}
}
1 change: 1 addition & 0 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod command_output;
pub mod constants;
pub mod ctrlc_handler;
pub mod logging;
pub mod syntax_highlighting;

Expand Down
6 changes: 6 additions & 0 deletions utils/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ use once_cell::sync::Lazy;
use rand::Rng;
use typed_builder::TypedBuilder;

use crate::ctrlc_handler::{add_pid, remove_pid};

static MULTI_PROGRESS: Lazy<MultiProgress> = Lazy::new(MultiProgress::new);
static LOG_DIR: Lazy<Mutex<PathBuf>> = Lazy::new(|| Mutex::new(PathBuf::new()));

Expand Down Expand Up @@ -205,6 +207,9 @@ impl CommandLogging for Command {

let mut child = self.spawn()?;

let child_pid = child.id();
add_pid(child_pid);

// We drop the `Command` to prevent blocking on writer
// https://docs.rs/os_pipe/latest/os_pipe/#examples
drop(self);
Expand Down Expand Up @@ -243,6 +248,7 @@ impl CommandLogging for Command {
});

let status = child.wait()?;
remove_pid(child_pid);

progress.finish();
Logger::multi_progress().remove(&progress);
Expand Down
Loading