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

implement graceful shutdown on windows #1603

Merged
merged 1 commit into from
Dec 24, 2016
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
4 changes: 4 additions & 0 deletions components/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ pub enum Error {
GetExitCodeProcessFailed(String),
/// Occurs when a `HabChild` constructor fails to return a process.
GetHabChildFailed(String),
/// Occurs when a `TerminateProcess` win32 call returns an error.
TerminateProcessFailed(String),
/// When an error occurs attempting to interpret a sequence of u8 as a string.
Utf8Error(str::Utf8Error),
}
Expand Down Expand Up @@ -170,6 +172,7 @@ impl fmt::Display for Error {
Error::SignalFailed(ref e) => format!("Failed to send a signal to the child process: {}", e),
Error::GetExitCodeProcessFailed(ref e) => format!("{}", e),
Error::GetHabChildFailed(ref e) => format!("{}", e),
Error::TerminateProcessFailed(ref e) => format!("{}", e),
Error::Utf8Error(ref e) => format!("{}", e),
};
write!(f, "{}", msg)
Expand Down Expand Up @@ -225,6 +228,7 @@ impl error::Error for Error {
Error::WaitpidFailed(_) => "waitpid failed",
Error::GetExitCodeProcessFailed(_) => "GetExitCodeProcess failed",
Error::GetHabChildFailed(_) => "Failed to return a HabChild",
Error::TerminateProcessFailed(_) => "Failed to call TerminateProcess",
Error::Utf8Error(_) => "Failed to interpret a sequence of bytes as a string",
}
}
Expand Down
8 changes: 4 additions & 4 deletions components/core/src/os/process/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use time::{Duration, SteadyTime};

use error::{Error, Result};

use super::{HabExitStatus, ExitStatusExt};
use super::{HabExitStatus, ExitStatusExt, ShutdownMethod};

pub fn become_command(command: PathBuf, args: Vec<OsString>) -> Result<()> {
become_exec_command(command, args)
Expand Down Expand Up @@ -84,7 +84,7 @@ impl Child {
}
}

pub fn kill(&mut self) -> Result<i32> {
pub fn kill(&mut self) -> Result<ShutdownMethod> {
try!(send_signal(self.pid, libc::SIGTERM));

let stop_time = SteadyTime::now() + Duration::seconds(8);
Expand All @@ -96,10 +96,10 @@ impl Child {

if SteadyTime::now() > stop_time {
try!(send_signal(self.pid, libc::SIGKILL));
return Ok(libc::SIGKILL);
return Ok(ShutdownMethod::Killed);
}
}
Ok(libc::SIGTERM)
Ok(ShutdownMethod::GracefulTermination)
}
}

Expand Down
19 changes: 18 additions & 1 deletion components/core/src/os/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,23 @@ mod imp;

pub use self::imp::{become_command};

pub enum ShutdownMethod {
AlreadyExited,
GracefulTermination,
Killed,
}

impl fmt::Display for ShutdownMethod {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable = match *self {
ShutdownMethod::AlreadyExited => "Already Exited",
ShutdownMethod::GracefulTermination => "Graceful Termination",
ShutdownMethod::Killed => "Killed",
};
write!(f, "{}", printable)
}
}

pub struct HabChild {
inner: imp::Child,
}
Expand All @@ -48,7 +65,7 @@ impl HabChild {
self.inner.status()
}

pub fn kill(&mut self) -> Result<i32> {
pub fn kill(&mut self) -> Result<ShutdownMethod> {
self.inner.kill()
}
}
Expand Down
70 changes: 66 additions & 4 deletions components/core/src/os/process/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ use std::path::PathBuf;
use std::process::{self, Command};
use std::ptr;
use std::io;
use time::{Duration, SteadyTime};

use kernel32;
use winapi;

use error::{Error, Result};

use super::{HabExitStatus, ExitStatusExt};
use super::{HabExitStatus, ExitStatusExt, ShutdownMethod};

const STILL_ACTIVE: u32 = 259;

Expand All @@ -49,7 +50,7 @@ fn become_child_command(command: PathBuf, args: Vec<OsString>) -> Result<()> {

fn handle_from_pid(pid: u32) -> Option<winapi::HANDLE> {
unsafe {
let proc_handle = kernel32::OpenProcess(winapi::PROCESS_QUERY_LIMITED_INFORMATION,
let proc_handle = kernel32::OpenProcess(winapi::PROCESS_QUERY_LIMITED_INFORMATION | winapi::PROCESS_TERMINATE,
winapi::FALSE,
pid as winapi::DWORD);

Expand Down Expand Up @@ -134,8 +135,69 @@ impl Child {
Ok(HabExitStatus { status: Some(exit_status) })
}

pub fn kill(&mut self) -> Result<i32> {
unimplemented!();
pub fn kill(&mut self) -> Result<ShutdownMethod> {
if self.last_status.is_some() {
return Ok(ShutdownMethod::AlreadyExited);
}

let mut ret;
unsafe {
// Turn off ctrl-C handling for current process
ret = kernel32::SetConsoleCtrlHandler(None, winapi::TRUE);
if ret == 0 {
debug!("Failed to call SetConsoleCtrlHandler on pid {}: {}",
self.pid,
io::Error::last_os_error());
}

if ret != 0 {
// Send a ctrl-C
ret = kernel32::GenerateConsoleCtrlEvent(0, 0);
if ret == 0 {
debug!("Failed to send ctrl-c to pid {}: {}",
self.pid,
io::Error::last_os_error());
}
}
}

let stop_time = SteadyTime::now() + Duration::seconds(8);

let result;
loop {
if ret == 0 || SteadyTime::now() > stop_time {
unsafe {
ret = kernel32::TerminateProcess(self.handle.unwrap(), 1);
if ret == 0 {
result = Err(Error::TerminateProcessFailed(format!("Failed to call terminate pid {}: {}",
self.pid,
io::Error::last_os_error())));
}
else {
result = Ok(ShutdownMethod::Killed);
}
break;
}
}

match self.status() {
Ok(status) => if !status.no_status() {
result = Ok(ShutdownMethod::GracefulTermination);
break;
},
_ => {}
}
};

// turn Ctrl-C handling back on for current process
ret = unsafe { kernel32::SetConsoleCtrlHandler(None, winapi::FALSE) };
if ret == 0 {
debug!("Failed to call SetConsoleCtrlHandler on pid {}: {}",
self.pid,
io::Error::last_os_error());
}

result
}
}

Expand Down
4 changes: 2 additions & 2 deletions components/sup/src/supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ impl Supervisor {
match self.child {
Some(ref mut child) => {
outputln!(preamble & self.preamble, "Stopping...");
let signal = try!(child.kill());
outputln!("{} - Killed with signal {}", self.preamble, signal);
let shutdown = try!(child.kill());
outputln!("{} - Shutdown method: {}", self.preamble, shutdown);
}
None => {},
};
Expand Down