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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//! An actor implementation of Unix signal handling
//!
//! This module implements asynchronous signal handling for Actix. For each
//! signal `ProcessSignals` actor sends `Signal` message to all subscriber. To
//! subscriber, send `Subscribe` message to `ProcessSignals` actor.
//!
//! # Examples
//!
//! ```rust
//! # extern crate actix;
//! use actix::actors::signal;
//! use actix::prelude::*;
//!
//! struct Signals;
//!
//! impl Actor for Signals {
//!     type Context = Context<Self>;
//! }
//!
//! // Shutdown system on and of `SIGINT`, `SIGTERM`, `SIGQUIT` signals
//! impl Handler<signal::Signal> for Signals {
//!     type Result = ();
//!
//!     fn handle(&mut self, msg: signal::Signal, _: &mut Context<Self>) {
//!         match msg.0 {
//!             signal::SignalType::Int => {
//!                 println!("SIGINT received, exiting");
//!                 System::current().stop();
//!             }
//!             signal::SignalType::Hup => {
//!                 println!("SIGHUP received, reloading");
//!             }
//!             signal::SignalType::Term => {
//!                 println!("SIGTERM received, stopping");
//!                 System::current().stop();
//!             }
//!             signal::SignalType::Quit => {
//!                 println!("SIGQUIT received, exiting");
//!                 System::current().stop();
//!             }
//!             _ => (),
//!         }
//!     }
//! }
//!
//! fn main() {
//!     // initialize system
//!     System::run(|| {
//!         // Start signals handler
//!         let addr = Signals.start();
//!
//!         // send SIGTERM
//!         std::thread::spawn(move || {
//!             // emulate SIGNTERM
//!             addr.do_send(signal::Signal(signal::SignalType::Term));
//!         });
//!     });
//!
//!     std::process::exit(0);
//! }
//! ```
extern crate tokio_signal;

#[cfg(unix)]
use self::tokio_signal::unix;
use futures::{Future, Stream};
#[cfg(unix)]
use libc;
use std;

use prelude::*;

/// Different types of process signals
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum SignalType {
    /// SIGHUP
    Hup,
    /// SIGINT
    Int,
    /// SIGTERM
    Term,
    /// SIGQUIT
    Quit,
    /// SIGCHILD
    Child,
}

impl Message for SignalType {
    type Result = ();
}

/// Process signal message
#[derive(Debug)]
pub struct Signal(pub SignalType);

impl Message for Signal {
    type Result = ();
}

/// An actor implementation of Unix signal handling
pub struct ProcessSignals {
    subscribers: Vec<Recipient<Signal>>,
}

impl Default for ProcessSignals {
    fn default() -> Self {
        ProcessSignals {
            subscribers: Vec::new(),
        }
    }
}

impl Actor for ProcessSignals {
    type Context = Context<Self>;
}

impl Supervised for ProcessSignals {}

impl SystemService for ProcessSignals {
    fn service_started(&mut self, ctx: &mut Self::Context) {
        // SIGINT
        tokio_signal::ctrl_c()
            .map_err(|_| ())
            .actfuture()
            .map(|sig, _: &mut Self, ctx: &mut Context<Self>| {
                ctx.add_message_stream(sig.map_err(|_| ()).map(|_| SignalType::Int))
            })
            .spawn(ctx);

        #[cfg(unix)]
        {
            // SIGHUP
            unix::Signal::new(libc::SIGHUP)
                .actfuture()
                .drop_err()
                .map(|sig, _: &mut Self, ctx: &mut Context<Self>| {
                    ctx.add_message_stream(sig.map_err(|_| ()).map(|_| SignalType::Hup))
                })
                .spawn(ctx);

            // SIGTERM
            unix::Signal::new(libc::SIGTERM)
                .map_err(|_| ())
                .actfuture()
                .map(|sig, _: &mut Self, ctx: &mut Context<Self>| {
                    ctx.add_message_stream(sig.map_err(|_| ()).map(|_| SignalType::Term))
                })
                .spawn(ctx);

            // SIGQUIT
            unix::Signal::new(libc::SIGQUIT)
                .map_err(|_| ())
                .actfuture()
                .map(|sig, _: &mut Self, ctx: &mut Context<Self>| {
                    ctx.add_message_stream(sig.map_err(|_| ()).map(|_| SignalType::Quit))
                })
                .spawn(ctx);

            // SIGCHLD
            unix::Signal::new(libc::SIGCHLD)
                .map_err(|_| ())
                .actfuture()
                .map(|sig, _: &mut Self, ctx: &mut Context<Self>| {
                    ctx.add_message_stream(
                        sig.map_err(|_| ()).map(|_| SignalType::Child),
                    )
                })
                .spawn(ctx);
        }
    }
}

#[doc(hidden)]
impl Handler<SignalType> for ProcessSignals {
    type Result = ();

    fn handle(&mut self, sig: SignalType, _: &mut Self::Context) {
        let subscribers = std::mem::replace(&mut self.subscribers, Vec::new());
        for subscr in subscribers {
            if subscr.do_send(Signal(sig)).is_ok() {
                self.subscribers.push(subscr);
            }
        }
    }
}

/// Subscribe to process signals.
pub struct Subscribe(pub Recipient<Signal>);

impl Message for Subscribe {
    type Result = ();
}

/// Add subscriber for signals
impl Handler<Subscribe> for ProcessSignals {
    type Result = ();

    fn handle(&mut self, msg: Subscribe, _: &mut Self::Context) {
        self.subscribers.push(msg.0);
    }
}

/// Default signals handler. This actor sends `SystemExit` message to `System`
/// actor for each of `SIGINT`, `SIGTERM`, `SIGQUIT` signals.
pub struct DefaultSignalsHandler;

impl Default for DefaultSignalsHandler {
    fn default() -> Self {
        DefaultSignalsHandler
    }
}

impl Actor for DefaultSignalsHandler {
    type Context = Context<Self>;

    fn started(&mut self, ctx: &mut Self::Context) {
        let addr = System::current().registry().get::<ProcessSignals>();
        let slf = ctx.address();
        addr.send(Subscribe(slf.recipient()))
            .map(|_| ())
            .map_err(|_| ())
            .into_actor(self)
            .wait(ctx)
    }
}

/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and send `SystemExit(0)`
/// message to `System` actor.
impl Handler<Signal> for DefaultSignalsHandler {
    type Result = ();

    fn handle(&mut self, msg: Signal, _: &mut Self::Context) {
        match msg.0 {
            SignalType::Int => {
                info!("SIGINT received, exiting");
                System::current().stop();
            }
            SignalType::Hup => {
                info!("SIGHUP received, reloading");
            }
            SignalType::Term => {
                info!("SIGTERM received, stopping");
                System::current().stop();
            }
            SignalType::Quit => {
                info!("SIGQUIT received, exiting");
                System::current().stop();
            }
            _ => (),
        }
    }
}