1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
extern crate tokio;
extern crate tokio_signal;
use std::error::Error;
use std::fmt::{self, Debug, Display};
use std::io;
use tokio::prelude::future::{self, Either, Future};
use tokio::prelude::stream::Stream;
use tokio::runtime::Runtime;
use tokio_signal::unix::libc::{c_int, SIGINT, SIGTERM};
#[derive(Debug)]
pub enum Shutdown<T, E> {
FutureFinished(T),
FutureErr(E),
NoRuntime(io::Error),
SignalError(io::Error),
}
impl<T, E> Display for Shutdown<T, E>
where
E: Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Shutdown::FutureFinished(_) => write!(f, "unexpectedly finished!"),
Shutdown::FutureErr(err) => err.fmt(f),
Shutdown::NoRuntime(err) | Shutdown::SignalError(err) => Display::fmt(err, f),
}
}
}
impl<T, E> Error for Shutdown<T, E>
where
T: Debug,
E: Error,
{
fn cause(&self) -> Option<&Error> {
match self {
Shutdown::FutureErr(err) => Some(err),
Shutdown::NoRuntime(err) | Shutdown::SignalError(err) => Some(err),
_ => None,
}
}
}
#[derive(Debug)]
pub struct Safeword {
signals: Vec<c_int>,
}
impl Safeword {
pub fn new() -> Safeword {
Safeword {
signals: Vec::new(),
}
}
pub fn signal(mut self, signal: c_int) -> Safeword {
self.signals.push(signal);
self
}
pub fn run<F>(self, future: F) -> Result<(), Shutdown<F::Item, F::Error>>
where
F: Future + Send + 'static,
F::Item: Send,
F::Error: Send,
{
match Runtime::new()
.map_err(Shutdown::NoRuntime)?
.block_on(
future.select2(future::select_all(self.signals.into_iter().map(|signal| {
tokio_signal::unix::Signal::new(signal)
.flatten_stream()
.into_future()
.map(|_| ())
.map_err(|(err, _)| Shutdown::SignalError(err))
}))),
) {
Ok(Either::A((x, _))) => Err(Shutdown::FutureFinished(x)),
Ok(Either::B(_)) => Ok(()),
Err(Either::A((err, _))) => Err(Shutdown::FutureErr(err)),
Err(Either::B(((err, _, _), _))) => Err(err),
}
}
}
impl Default for Safeword {
fn default() -> Safeword {
Safeword {
signals: vec![SIGINT, SIGTERM],
}
}
}