1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 08:22:43 +01:00
actix-extras/src/server/srv.rs

846 lines
30 KiB
Rust
Raw Normal View History

use std::{io, net, thread};
2017-10-07 06:48:14 +02:00
use std::rc::Rc;
2017-12-27 21:58:32 +01:00
use std::sync::{Arc, mpsc as sync_mpsc};
2017-12-14 01:44:35 +01:00
use std::time::Duration;
2017-10-07 06:48:14 +02:00
2018-01-05 22:30:21 +01:00
use actix::prelude::*;
2018-01-06 01:32:36 +01:00
use actix::actors::signal;
2017-12-29 01:25:47 +01:00
use futures::{Future, Sink, Stream};
use futures::sync::mpsc;
use tokio_io::{AsyncRead, AsyncWrite};
2017-12-27 20:22:27 +01:00
use mio;
use num_cpus;
2017-12-28 21:38:37 +01:00
use net2::TcpBuilder;
2017-10-07 06:48:14 +02:00
#[cfg(feature="tls")]
use native_tls::TlsAcceptor;
2017-11-04 21:24:57 +01:00
#[cfg(feature="alpn")]
use openssl::ssl::{AlpnError, SslAcceptorBuilder};
2017-12-14 07:54:52 +01:00
use helpers;
use super::{IntoHttpHandler, IoStream, KeepAlive};
2018-01-12 03:35:05 +01:00
use super::{PauseServer, ResumeServer, StopServer};
use super::channel::{HttpChannel, WrapperStream};
use super::worker::{Conn, Worker, StreamHandlerType, StopWorker};
use super::settings::{ServerSettings, WorkerSettings};
2017-10-08 23:56:51 +02:00
/// An HTTP Server
2018-02-10 20:01:54 +01:00
pub struct HttpServer<H> where H: IntoHttpHandler + 'static
{
2018-02-10 20:01:54 +01:00
h: Option<Rc<WorkerSettings<H::Handler>>>,
threads: usize,
2017-12-17 21:35:04 +01:00
backlog: i32,
2017-12-26 23:36:03 +01:00
host: Option<String>,
keep_alive: KeepAlive,
2018-02-10 20:01:54 +01:00
factory: Arc<Fn() -> Vec<H> + Send + Sync>,
2018-03-08 06:10:53 +01:00
#[cfg_attr(feature="cargo-clippy", allow(type_complexity))]
workers: Vec<(usize, Addr<Syn, Worker<H::Handler>>)>,
sockets: Vec<(net::SocketAddr, net::TcpListener)>,
2017-12-27 21:58:32 +01:00
accept: Vec<(mio::SetReadiness, sync_mpsc::Sender<Command>)>,
2017-12-28 20:36:20 +01:00
exit: bool,
2017-12-29 01:25:47 +01:00
shutdown_timeout: u16,
2018-02-13 01:08:04 +01:00
signals: Option<Addr<Syn, signal::ProcessSignals>>,
2018-03-16 16:48:44 +01:00
no_http2: bool,
2018-01-06 01:32:36 +01:00
no_signals: bool,
2017-10-07 06:48:14 +02:00
}
2018-02-10 20:01:54 +01:00
unsafe impl<H> Sync for HttpServer<H> where H: IntoHttpHandler {}
unsafe impl<H> Send for HttpServer<H> where H: IntoHttpHandler {}
2017-12-28 02:49:10 +01:00
2018-03-08 06:10:53 +01:00
#[derive(Clone)]
struct Info {
addr: net::SocketAddr,
handler: StreamHandlerType,
}
enum ServerCommand {
WorkerDied(usize, Info),
}
2017-12-28 02:49:10 +01:00
2018-02-10 20:01:54 +01:00
impl<H> Actor for HttpServer<H> where H: IntoHttpHandler
2018-01-08 02:13:49 +01:00
{
2017-10-07 06:48:14 +02:00
type Context = Context<Self>;
2017-12-14 01:44:35 +01:00
fn started(&mut self, ctx: &mut Self::Context) {
self.update_time(ctx);
}
}
2018-02-10 20:01:54 +01:00
impl<H> HttpServer<H> where H: IntoHttpHandler + 'static
2017-10-22 03:54:24 +02:00
{
2017-12-14 08:09:20 +01:00
/// Create new http server with application factory
2018-02-10 20:01:54 +01:00
pub fn new<F, U>(factory: F) -> Self
where F: Fn() -> U + Sync + Send + 'static,
U: IntoIterator<Item=H> + 'static,
2017-12-06 20:00:39 +01:00
{
2018-02-10 20:01:54 +01:00
let f = move || {
(factory)().into_iter().collect()
};
2017-12-14 06:38:47 +01:00
HttpServer{ h: None,
threads: num_cpus::get(),
2017-12-17 21:35:04 +01:00
backlog: 2048,
2017-12-26 23:36:03 +01:00
host: None,
keep_alive: KeepAlive::Os,
2018-02-10 20:01:54 +01:00
factory: Arc::new(f),
workers: Vec::new(),
sockets: Vec::new(),
2017-12-27 21:58:32 +01:00
accept: Vec::new(),
2017-12-28 20:36:20 +01:00
exit: false,
2017-12-29 01:25:47 +01:00
shutdown_timeout: 30,
2018-01-06 01:32:36 +01:00
signals: None,
2018-03-16 16:48:44 +01:00
no_http2: false,
2018-01-06 01:32:36 +01:00
no_signals: false,
}
}
2018-01-08 02:13:49 +01:00
fn update_time(&self, ctx: &mut Context<Self>) {
helpers::update_date();
ctx.run_later(Duration::new(1, 0), |slf, ctx| slf.update_time(ctx));
}
/// Set number of workers to start.
///
/// By default http server uses number of available logical cpu as threads count.
pub fn threads(mut self, num: usize) -> Self {
self.threads = num;
self
2017-10-07 06:48:14 +02:00
}
2017-12-17 21:35:04 +01:00
/// Set the maximum number of pending connections.
///
/// This refers to the number of clients that can be waiting to be served.
/// Exceeding this number results in the client getting an error when
/// attempting to connect. It should only affect servers under significant load.
///
/// Generally set in the 64-2048 range. Default value is 2048.
2017-12-27 20:22:27 +01:00
///
/// This method should be called before `bind()` method call.
2017-12-17 21:35:04 +01:00
pub fn backlog(mut self, num: i32) -> Self {
self.backlog = num;
self
}
2017-12-14 06:38:47 +01:00
/// Set server keep-alive setting.
///
/// By default keep alive is set to a `Os`.
pub fn keep_alive<T: Into<KeepAlive>>(mut self, val: T) -> Self {
self.keep_alive = val.into();
2017-12-14 06:38:47 +01:00
self
}
2017-12-26 23:36:03 +01:00
/// Set server host name.
///
/// Host name is used by application router aa a hostname for url generation.
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host) documentation
/// for more information.
pub fn server_hostname(mut self, val: String) -> Self {
self.host = Some(val);
self
}
2017-12-28 20:36:20 +01:00
/// Send `SystemExit` message to actix system
///
/// `SystemExit` message stops currently running system arbiter and all
/// nested arbiters.
pub fn system_exit(mut self) -> Self {
self.exit = true;
self
}
2018-01-06 01:32:36 +01:00
/// Set alternative address for `ProcessSignals` actor.
2018-02-13 01:08:04 +01:00
pub fn signals(mut self, addr: Addr<Syn, signal::ProcessSignals>) -> Self {
2018-01-06 01:32:36 +01:00
self.signals = Some(addr);
self
}
/// Disable signal handling
pub fn disable_signals(mut self) -> Self {
self.no_signals = true;
self
}
2017-12-29 01:25:47 +01:00
/// Timeout for graceful workers shutdown.
///
/// After receiving a stop signal, workers have this much time to finish serving requests.
/// Workers still alive after the timeout are force dropped.
///
/// By default shutdown timeout sets to 30 seconds.
pub fn shutdown_timeout(mut self, sec: u16) -> Self {
self.shutdown_timeout = sec;
self
}
2018-03-16 16:48:44 +01:00
/// Disable `HTTP/2` support
pub fn no_http2(mut self) -> Self {
self.no_http2 = true;
self
}
/// Get addresses of bound sockets.
pub fn addrs(&self) -> Vec<net::SocketAddr> {
self.sockets.iter().map(|s| s.0).collect()
}
/// Use listener for accepting incoming connection requests
///
/// HttpServer does not change any configuration for TcpListener,
/// it needs to be configured before passing it to listen() method.
2018-03-07 23:46:12 +01:00
pub fn listen(mut self, lst: net::TcpListener) -> Self {
self.sockets.push((lst.local_addr().unwrap(), lst));
2018-03-07 23:46:12 +01:00
self
}
2017-12-17 21:35:04 +01:00
/// The socket address to bind
///
/// To mind multiple addresses this method can be call multiple times.
pub fn bind<S: net::ToSocketAddrs>(mut self, addr: S) -> io::Result<Self> {
2017-10-15 23:53:03 +02:00
let mut err = None;
2017-12-17 21:35:04 +01:00
let mut succ = false;
2017-12-28 02:49:10 +01:00
for addr in addr.to_socket_addrs()? {
match create_tcp_listener(addr, self.backlog) {
Ok(lst) => {
succ = true;
self.sockets.push((lst.local_addr().unwrap(), lst));
2017-12-28 02:49:10 +01:00
},
Err(e) => err = Some(e),
2017-10-15 23:53:03 +02:00
}
}
2017-12-17 21:35:04 +01:00
if !succ {
2017-10-15 23:53:03 +02:00
if let Some(e) = err.take() {
Err(e)
} else {
Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address."))
}
} else {
2017-12-17 21:35:04 +01:00
Ok(self)
2017-10-15 23:53:03 +02:00
}
2017-10-07 06:48:14 +02:00
}
2017-12-13 21:47:07 +01:00
fn start_workers(&mut self, settings: &ServerSettings, handler: &StreamHandlerType)
2018-03-08 06:10:53 +01:00
-> Vec<(usize, mpsc::UnboundedSender<Conn<net::TcpStream>>)>
{
// start workers
let mut workers = Vec::new();
2018-03-08 06:10:53 +01:00
for idx in 0..self.threads {
let s = settings.clone();
2017-12-28 21:38:37 +01:00
let (tx, rx) = mpsc::unbounded::<Conn<net::TcpStream>>();
2017-12-13 21:47:07 +01:00
let h = handler.clone();
2017-12-14 07:36:28 +01:00
let ka = self.keep_alive;
let factory = Arc::clone(&self.factory);
let addr = Arbiter::start(move |ctx: &mut Context<_>| {
2017-12-29 20:33:04 +01:00
let apps: Vec<_> = (*factory)()
.into_iter()
.map(|h| h.into_handler(s.clone())).collect();
2018-01-05 22:30:21 +01:00
ctx.add_message_stream(rx);
2017-12-14 06:38:47 +01:00
Worker::new(apps, h, ka)
});
2018-03-08 06:10:53 +01:00
workers.push((idx, tx));
self.workers.push((idx, addr));
}
info!("Starting {} http workers", self.threads);
workers
}
2018-01-06 01:32:36 +01:00
// subscribe to os signals
2018-02-13 01:08:04 +01:00
fn subscribe_to_signals(&self) -> Option<Addr<Syn, signal::ProcessSignals>> {
2018-01-08 02:13:49 +01:00
if !self.no_signals {
2018-01-06 01:32:36 +01:00
if let Some(ref signals) = self.signals {
2018-01-08 02:13:49 +01:00
Some(signals.clone())
2018-01-06 01:32:36 +01:00
} else {
2018-01-08 02:13:49 +01:00
Some(Arbiter::system_registry().get::<signal::ProcessSignals>())
2018-01-06 01:32:36 +01:00
}
2018-01-08 02:13:49 +01:00
} else {
None
2018-01-06 01:32:36 +01:00
}
}
}
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> HttpServer<H>
{
2018-01-15 22:47:25 +01:00
/// Start listening for incoming connections.
///
2018-01-15 22:47:25 +01:00
/// This method starts number of http handler workers in separate threads.
/// For each address this method starts separate thread which does `accept()` in a loop.
2017-12-19 18:08:36 +01:00
///
/// This methods panics if no socket addresses get bound.
2017-12-26 21:46:27 +01:00
///
/// This method requires to run within properly configured `Actix` system.
///
/// ```rust
/// extern crate actix;
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let sys = actix::System::new("example"); // <- create Actix system
///
/// HttpServer::new(
/// || Application::new()
2018-03-02 04:12:59 +01:00
/// .resource("/", |r| r.h(httpcodes::HttpOk)))
2017-12-28 02:49:10 +01:00
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
2017-12-26 21:46:27 +01:00
/// .start();
2018-02-13 07:56:47 +01:00
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
2017-12-26 21:46:27 +01:00
///
/// let _ = sys.run(); // <- Run actix system, this method actually starts all async processes
/// }
/// ```
2018-02-13 01:08:04 +01:00
pub fn start(mut self) -> Addr<Syn, Self>
{
2017-12-17 21:35:04 +01:00
if self.sockets.is_empty() {
2018-01-15 22:47:25 +01:00
panic!("HttpServer::bind() has to be called before start()");
2017-12-17 21:35:04 +01:00
} else {
2018-03-08 06:10:53 +01:00
let (tx, rx) = mpsc::unbounded();
2017-12-27 20:22:27 +01:00
let addrs: Vec<(net::SocketAddr, net::TcpListener)> =
self.sockets.drain(..).collect();
2017-12-26 23:36:03 +01:00
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
2017-12-17 21:35:04 +01:00
let workers = self.start_workers(&settings, &StreamHandlerType::Normal);
2018-03-08 06:10:53 +01:00
let info = Info{addr: addrs[0].0, handler: StreamHandlerType::Normal};
2017-12-17 21:35:04 +01:00
// start acceptors threads
for (addr, sock) in addrs {
2018-03-06 20:37:18 +01:00
info!("Starting server on http://{}", addr);
2017-12-27 21:58:32 +01:00
self.accept.push(
2018-03-08 06:10:53 +01:00
start_accept_thread(
sock, addr, self.backlog,
tx.clone(), info.clone(), workers.clone()));
2017-12-17 21:35:04 +01:00
}
2017-12-08 18:24:05 +01:00
2017-12-17 21:35:04 +01:00
// start http server actor
2018-01-08 02:13:49 +01:00
let signals = self.subscribe_to_signals();
2018-03-08 06:10:53 +01:00
let addr: Addr<Syn, _> = Actor::create(move |ctx| {
ctx.add_stream(rx);
self
});
2018-02-13 07:56:47 +01:00
signals.map(|signals| signals.do_send(
2018-02-13 07:09:31 +01:00
signal::Subscribe(addr.clone().recipient())));
2018-01-08 02:13:49 +01:00
addr
2017-12-17 21:35:04 +01:00
}
}
2017-12-28 02:49:10 +01:00
2018-01-15 22:47:25 +01:00
/// Spawn new thread and start listening for incoming connections.
2017-12-28 02:49:10 +01:00
///
/// This method spawns new thread and starts new actix system. Other than that it is
2018-01-06 01:32:36 +01:00
/// similar to `start()` method. This method blocks.
2017-12-28 02:49:10 +01:00
///
/// This methods panics if no socket addresses get bound.
///
2018-01-06 01:32:36 +01:00
/// ```rust,ignore
2017-12-28 02:49:10 +01:00
/// # extern crate futures;
/// # extern crate actix;
/// # extern crate actix_web;
/// # use futures::Future;
/// use actix_web::*;
///
/// fn main() {
2018-01-06 01:32:36 +01:00
/// HttpServer::new(
2017-12-28 02:49:10 +01:00
/// || Application::new()
2018-03-02 04:12:59 +01:00
/// .resource("/", |r| r.h(httpcodes::HttpOk)))
2017-12-28 02:49:10 +01:00
/// .bind("127.0.0.1:0").expect("Can not bind to 127.0.0.1:0")
2018-01-06 01:32:36 +01:00
/// .run();
2017-12-28 02:49:10 +01:00
/// }
/// ```
2018-01-06 01:32:36 +01:00
pub fn run(mut self) {
2017-12-28 20:36:20 +01:00
self.exit = true;
2018-01-06 01:32:36 +01:00
self.no_signals = false;
2017-12-28 02:49:10 +01:00
2018-01-06 01:32:36 +01:00
let _ = thread::spawn(move || {
2017-12-28 02:49:10 +01:00
let sys = System::new("http-server");
2018-01-06 01:32:36 +01:00
self.start();
let _ = sys.run();
}).join();
2017-12-28 02:49:10 +01:00
}
}
#[cfg(feature="tls")]
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> HttpServer<H>
{
2018-01-15 22:47:25 +01:00
/// Start listening for incoming tls connections.
2018-02-13 04:15:39 +01:00
pub fn start_tls(mut self, acceptor: TlsAcceptor) -> io::Result<Addr<Syn, Self>> {
2017-12-17 21:35:04 +01:00
if self.sockets.is_empty() {
Err(io::Error::new(io::ErrorKind::Other, "No socket addresses are bound"))
} else {
2018-03-08 06:37:42 +01:00
let (tx, rx) = mpsc::unbounded();
let addrs: Vec<(net::SocketAddr, net::TcpListener)> = self.sockets.drain(..).collect();
2017-12-27 00:17:20 +01:00
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
2018-03-08 06:37:42 +01:00
let workers = self.start_workers(
&settings, &StreamHandlerType::Tls(acceptor.clone()));
let info = Info{addr: addrs[0].0, handler: StreamHandlerType::Tls(acceptor)};
2017-12-17 21:35:04 +01:00
// start acceptors threads
for (addr, sock) in addrs {
2018-03-06 20:37:18 +01:00
info!("Starting server on https://{}", addr);
2017-12-27 21:58:32 +01:00
self.accept.push(
2018-03-08 06:37:42 +01:00
start_accept_thread(
sock, addr, self.backlog,
tx.clone(), info.clone(), workers.clone()));
}
2017-12-17 21:35:04 +01:00
// start http server actor
2018-01-08 02:13:49 +01:00
let signals = self.subscribe_to_signals();
2018-03-08 06:10:53 +01:00
let addr: Addr<Syn, _> = Actor::create(|ctx| {
ctx.add_stream(rx);
self
});
2018-02-13 07:56:47 +01:00
signals.map(|signals| signals.do_send(
2018-02-13 07:09:31 +01:00
signal::Subscribe(addr.clone().recipient())));
2018-01-08 02:13:49 +01:00
Ok(addr)
}
}
}
#[cfg(feature="alpn")]
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> HttpServer<H>
{
2018-01-15 22:47:25 +01:00
/// Start listening for incoming tls connections.
///
2017-12-17 21:35:04 +01:00
/// This method sets alpn protocols to "h2" and "http/1.1"
2018-02-13 04:15:39 +01:00
pub fn start_ssl(mut self, mut builder: SslAcceptorBuilder) -> io::Result<Addr<Syn, Self>>
{
2017-12-17 21:35:04 +01:00
if self.sockets.is_empty() {
Err(io::Error::new(io::ErrorKind::Other, "No socket addresses are bound"))
} else {
// alpn support
2018-03-16 16:48:44 +01:00
if !self.no_http2 {
builder.set_alpn_protos(b"\x02h2\x08http/1.1")?;
builder.set_alpn_select_callback(|_, protos| {
const H2: &[u8] = b"\x02h2";
if protos.windows(3).any(|window| window == H2) {
Ok(b"h2")
} else {
Err(AlpnError::NOACK)
}
});
}
2018-03-08 06:37:42 +01:00
let (tx, rx) = mpsc::unbounded();
let acceptor = builder.build();
let addrs: Vec<(net::SocketAddr, net::TcpListener)> = self.sockets.drain(..).collect();
2017-12-27 00:17:20 +01:00
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
2018-03-08 06:37:42 +01:00
let workers = self.start_workers(
&settings, &StreamHandlerType::Alpn(acceptor.clone()));
let info = Info{addr: addrs[0].0, handler: StreamHandlerType::Alpn(acceptor)};
2017-12-17 21:35:04 +01:00
// start acceptors threads
for (addr, sock) in addrs {
2018-03-06 20:37:18 +01:00
info!("Starting server on https://{}", addr);
2017-12-27 21:58:32 +01:00
self.accept.push(
2018-03-08 06:37:42 +01:00
start_accept_thread(
sock, addr, self.backlog,
tx.clone(), info.clone(), workers.clone()));
2017-12-17 21:35:04 +01:00
}
2017-12-17 21:35:04 +01:00
// start http server actor
2018-01-08 02:13:49 +01:00
let signals = self.subscribe_to_signals();
2018-03-08 06:10:53 +01:00
let addr: Addr<Syn, _> = Actor::create(|ctx| {
ctx.add_stream(rx);
self
});
2018-02-13 07:56:47 +01:00
signals.map(|signals| signals.do_send(
2018-02-13 07:09:31 +01:00
signal::Subscribe(addr.clone().recipient())));
2018-01-08 02:13:49 +01:00
Ok(addr)
}
}
}
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> HttpServer<H>
2017-12-19 03:56:58 +01:00
{
2018-01-15 22:47:25 +01:00
/// Start listening for incoming connections from a stream.
2017-12-19 03:56:58 +01:00
///
/// This method uses only one thread for handling incoming connections.
2018-02-13 01:08:04 +01:00
pub fn start_incoming<T, A, S>(mut self, stream: S, secure: bool) -> Addr<Syn, Self>
2018-02-10 19:22:03 +01:00
where S: Stream<Item=(T, A), Error=io::Error> + 'static,
T: AsyncRead + AsyncWrite + 'static,
2018-02-10 20:01:54 +01:00
A: 'static
2017-12-19 03:56:58 +01:00
{
2018-03-08 06:10:53 +01:00
let (tx, rx) = mpsc::unbounded();
2017-12-19 03:56:58 +01:00
if !self.sockets.is_empty() {
2017-12-27 20:22:27 +01:00
let addrs: Vec<(net::SocketAddr, net::TcpListener)> =
self.sockets.drain(..).collect();
2017-12-26 23:36:03 +01:00
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
2017-12-19 03:56:58 +01:00
let workers = self.start_workers(&settings, &StreamHandlerType::Normal);
2018-03-08 06:10:53 +01:00
let info = Info{addr: addrs[0].0, handler: StreamHandlerType::Normal};
2017-12-19 03:56:58 +01:00
// start acceptors threads
for (addr, sock) in addrs {
2018-03-06 20:37:18 +01:00
info!("Starting server on http://{}", addr);
2017-12-27 21:58:32 +01:00
self.accept.push(
2018-03-08 06:10:53 +01:00
start_accept_thread(
sock, addr, self.backlog,
tx.clone(), info.clone(), workers.clone()));
2017-12-19 03:56:58 +01:00
}
}
// set server settings
let addr: net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
2017-12-26 23:36:03 +01:00
let settings = ServerSettings::new(Some(addr), &self.host, secure);
2017-12-29 20:33:04 +01:00
let apps: Vec<_> = (*self.factory)()
2018-02-10 20:01:54 +01:00
.into_iter().map(|h| h.into_handler(settings.clone())).collect();
2017-12-19 03:56:58 +01:00
self.h = Some(Rc::new(WorkerSettings::new(apps, self.keep_alive)));
// start server
2018-01-08 02:13:49 +01:00
let signals = self.subscribe_to_signals();
2018-02-13 01:08:04 +01:00
let addr: Addr<Syn, _> = HttpServer::create(move |ctx| {
2018-03-08 06:10:53 +01:00
ctx.add_stream(rx);
2018-01-28 10:04:58 +01:00
ctx.add_message_stream(
stream
.map_err(|_| ())
.map(move |(t, _)| Conn{io: WrapperStream::new(t), peer: None, http2: false}));
2017-12-19 03:56:58 +01:00
self
2018-01-08 02:13:49 +01:00
});
2018-02-13 07:56:47 +01:00
signals.map(|signals| signals.do_send(
2018-02-13 07:09:31 +01:00
signal::Subscribe(addr.clone().recipient())));
2018-01-08 02:13:49 +01:00
addr
2017-12-19 03:56:58 +01:00
}
}
2018-01-05 22:30:21 +01:00
/// Signals support
2017-12-28 20:36:20 +01:00
/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and send `SystemExit(0)`
/// message to `System` actor.
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> Handler<signal::Signal> for HttpServer<H>
2017-12-28 20:36:20 +01:00
{
2018-01-05 22:30:21 +01:00
type Result = ();
fn handle(&mut self, msg: signal::Signal, ctx: &mut Context<Self>) {
2017-12-28 20:36:20 +01:00
match msg.0 {
signal::SignalType::Int => {
info!("SIGINT received, exiting");
self.exit = true;
Handler::<StopServer>::handle(self, StopServer{graceful: false}, ctx);
}
signal::SignalType::Term => {
info!("SIGTERM received, stopping");
self.exit = true;
Handler::<StopServer>::handle(self, StopServer{graceful: true}, ctx);
}
signal::SignalType::Quit => {
info!("SIGQUIT received, exiting");
self.exit = true;
Handler::<StopServer>::handle(self, StopServer{graceful: false}, ctx);
}
_ => (),
2018-01-05 22:30:21 +01:00
}
2017-12-28 20:36:20 +01:00
}
}
2018-03-08 06:10:53 +01:00
/// Commands from accept threads
impl<H: IntoHttpHandler> StreamHandler<ServerCommand, ()> for HttpServer<H>
{
fn finished(&mut self, _: &mut Context<Self>) {}
fn handle(&mut self, msg: ServerCommand, _: &mut Context<Self>) {
match msg {
ServerCommand::WorkerDied(idx, info) => {
let mut found = false;
for i in 0..self.workers.len() {
if self.workers[i].0 == idx {
self.workers.swap_remove(i);
found = true;
break
}
}
if found {
error!("Worker has died {:?}, restarting", idx);
let (tx, rx) = mpsc::unbounded::<Conn<net::TcpStream>>();
let mut new_idx = self.workers.len();
'found: loop {
for i in 0..self.workers.len() {
if self.workers[i].0 == new_idx {
new_idx += 1;
continue 'found
}
}
break
}
let h = info.handler;
let ka = self.keep_alive;
let factory = Arc::clone(&self.factory);
let settings = ServerSettings::new(Some(info.addr), &self.host, false);
let addr = Arbiter::start(move |ctx: &mut Context<_>| {
let apps: Vec<_> = (*factory)()
.into_iter()
.map(|h| h.into_handler(settings.clone())).collect();
ctx.add_message_stream(rx);
Worker::new(apps, h, ka)
});
for item in &self.accept {
let _ = item.1.send(Command::Worker(new_idx, tx.clone()));
let _ = item.0.set_readiness(mio::Ready::readable());
}
self.workers.push((new_idx, addr));
}
},
}
}
}
2018-02-10 20:01:54 +01:00
impl<T, H> Handler<Conn<T>> for HttpServer<H>
2018-01-28 10:04:58 +01:00
where T: IoStream,
2018-02-10 20:01:54 +01:00
H: IntoHttpHandler,
2018-01-28 10:04:58 +01:00
{
type Result = ();
fn handle(&mut self, msg: Conn<T>, _: &mut Context<Self>) -> Self::Result {
Arbiter::handle().spawn(
HttpChannel::new(
Rc::clone(self.h.as_ref().unwrap()), msg.io, msg.peer, msg.http2));
}
}
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> Handler<PauseServer> for HttpServer<H>
2017-12-27 21:58:32 +01:00
{
2018-01-05 22:30:21 +01:00
type Result = ();
fn handle(&mut self, _: PauseServer, _: &mut Context<Self>)
2017-12-27 21:58:32 +01:00
{
for item in &self.accept {
let _ = item.1.send(Command::Pause);
let _ = item.0.set_readiness(mio::Ready::readable());
}
}
}
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> Handler<ResumeServer> for HttpServer<H>
2017-12-27 21:58:32 +01:00
{
2018-01-05 22:30:21 +01:00
type Result = ();
fn handle(&mut self, _: ResumeServer, _: &mut Context<Self>) {
2017-12-27 21:58:32 +01:00
for item in &self.accept {
let _ = item.1.send(Command::Resume);
let _ = item.0.set_readiness(mio::Ready::readable());
}
}
}
2018-02-10 20:01:54 +01:00
impl<H: IntoHttpHandler> Handler<StopServer> for HttpServer<H>
2017-12-27 21:58:32 +01:00
{
2018-02-12 21:17:30 +01:00
type Result = actix::Response<(), ()>;
2018-01-05 22:30:21 +01:00
fn handle(&mut self, msg: StopServer, ctx: &mut Context<Self>) -> Self::Result {
2017-12-28 22:07:29 +01:00
// stop accept threads
2017-12-27 21:58:32 +01:00
for item in &self.accept {
let _ = item.1.send(Command::Stop);
let _ = item.0.set_readiness(mio::Ready::readable());
}
2017-12-28 02:49:10 +01:00
2017-12-28 22:07:29 +01:00
// stop workers
2017-12-29 01:25:47 +01:00
let (tx, rx) = mpsc::channel(1);
let dur = if msg.graceful {
Some(Duration::new(u64::from(self.shutdown_timeout), 0))
} else {
None
};
2017-12-28 22:07:29 +01:00
for worker in &self.workers {
2017-12-29 01:25:47 +01:00
let tx2 = tx.clone();
2018-03-08 06:10:53 +01:00
let fut = worker.1.send(StopWorker{graceful: dur}).into_actor(self);
2017-12-29 01:25:47 +01:00
ActorFuture::then(fut, move |_, slf, _| {
slf.workers.pop();
if slf.workers.is_empty() {
let _ = tx2.send(());
// we need to stop system if server was spawned
if slf.exit {
2018-02-13 07:56:47 +01:00
Arbiter::system().do_send(actix::msgs::SystemExit(0))
2017-12-29 01:25:47 +01:00
}
}
2018-01-05 22:30:21 +01:00
actix::fut::ok(())
2017-12-29 01:25:47 +01:00
}).spawn(ctx);
2017-12-28 22:07:29 +01:00
}
2017-12-29 01:25:47 +01:00
if !self.workers.is_empty() {
2018-02-12 21:17:30 +01:00
Response::async(
rx.into_future().map(|_| ()).map_err(|_| ()))
2017-12-29 01:25:47 +01:00
} else {
// we need to stop system if server was spawned
if self.exit {
2018-02-13 07:56:47 +01:00
Arbiter::system().do_send(actix::msgs::SystemExit(0))
2017-12-29 01:25:47 +01:00
}
2018-02-01 10:08:08 +01:00
Response::reply(Ok(()))
2017-12-28 02:49:10 +01:00
}
2017-12-27 21:58:32 +01:00
}
}
enum Command {
Pause,
Resume,
Stop,
2018-03-08 06:10:53 +01:00
Worker(usize, mpsc::UnboundedSender<Conn<net::TcpStream>>),
2017-12-27 21:58:32 +01:00
}
2018-03-08 06:10:53 +01:00
fn start_accept_thread(
sock: net::TcpListener, addr: net::SocketAddr, backlog: i32,
srv: mpsc::UnboundedSender<ServerCommand>, info: Info,
mut workers: Vec<(usize, mpsc::UnboundedSender<Conn<net::TcpStream>>)>)
-> (mio::SetReadiness, sync_mpsc::Sender<Command>)
2017-12-27 21:58:32 +01:00
{
let (tx, rx) = sync_mpsc::channel();
let (reg, readiness) = mio::Registration::new2();
2017-12-27 20:22:27 +01:00
// start accept thread
2018-03-08 06:10:53 +01:00
#[cfg_attr(feature="cargo-clippy", allow(cyclomatic_complexity))]
2017-12-13 21:47:07 +01:00
let _ = thread::Builder::new().name(format!("Accept on {}", addr)).spawn(move || {
2017-12-27 21:58:32 +01:00
const SRV: mio::Token = mio::Token(0);
const CMD: mio::Token = mio::Token(1);
let mut server = Some(
2018-02-09 02:00:22 +01:00
mio::net::TcpListener::from_std(sock)
2017-12-27 21:58:32 +01:00
.expect("Can not create mio::net::TcpListener"));
2017-12-27 20:22:27 +01:00
// Create a poll instance
let poll = match mio::Poll::new() {
Ok(poll) => poll,
Err(err) => panic!("Can not create mio::Poll: {}", err),
};
// Start listening for incoming connections
2017-12-27 21:58:32 +01:00
if let Some(ref srv) = server {
if let Err(err) = poll.register(
srv, SRV, mio::Ready::readable(), mio::PollOpt::edge()) {
panic!("Can not register io: {}", err);
}
}
2018-01-15 22:47:25 +01:00
// Start listening for incoming commands
2017-12-27 21:58:32 +01:00
if let Err(err) = poll.register(&reg, CMD,
2017-12-27 20:22:27 +01:00
mio::Ready::readable(), mio::PollOpt::edge()) {
2017-12-27 21:58:32 +01:00
panic!("Can not register Registration: {}", err);
2017-12-27 20:22:27 +01:00
}
// Create storage for events
let mut events = mio::Events::with_capacity(128);
2018-03-08 00:52:05 +01:00
// Sleep on error
let sleep = Duration::from_millis(100);
2017-12-27 21:58:32 +01:00
let mut next = 0;
2017-12-13 21:47:07 +01:00
loop {
2017-12-27 20:22:27 +01:00
if let Err(err) = poll.poll(&mut events, None) {
panic!("Poll error: {}", err);
}
for event in events.iter() {
match event.token() {
2018-03-08 06:10:53 +01:00
SRV => if let Some(ref server) = server {
loop {
match server.accept_std() {
Ok((sock, addr)) => {
let mut msg = Conn{
io: sock, peer: Some(addr), http2: false};
while !workers.is_empty() {
match workers[next].1.unbounded_send(msg) {
Ok(_) => (),
Err(err) => {
let _ = srv.unbounded_send(
ServerCommand::WorkerDied(
workers[next].0, info.clone()));
msg = err.into_inner();
workers.swap_remove(next);
continue
}
2018-02-16 07:02:03 +01:00
}
2018-03-08 06:10:53 +01:00
next = (next + 1) % workers.len();
2017-12-27 21:58:32 +01:00
break
}
2018-03-08 06:10:53 +01:00
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock =>
break,
Err(ref e) if connection_error(e) =>
continue,
2018-03-12 00:52:20 +01:00
Err(e) => {
error!("Error accepting connection: {}", e);
2018-03-08 06:10:53 +01:00
// sleep after error
thread::sleep(sleep);
break
2017-12-27 20:22:27 +01:00
}
}
}
2017-12-27 21:58:32 +01:00
},
CMD => match rx.try_recv() {
Ok(cmd) => match cmd {
Command::Pause => if let Some(server) = server.take() {
if let Err(err) = poll.deregister(&server) {
error!("Can not deregister server socket {}", err);
} else {
info!("Paused accepting connections on {}", addr);
}
},
Command::Resume => {
let lst = create_tcp_listener(addr, backlog)
.expect("Can not create net::TcpListener");
server = Some(
2018-02-09 02:00:22 +01:00
mio::net::TcpListener::from_std(lst)
2017-12-27 21:58:32 +01:00
.expect("Can not create mio::net::TcpListener"));
if let Some(ref server) = server {
if let Err(err) = poll.register(
server, SRV, mio::Ready::readable(), mio::PollOpt::edge())
{
error!("Can not resume socket accept process: {}", err);
} else {
info!("Accepting connections on {} has been resumed",
addr);
}
}
},
2018-02-16 18:42:15 +01:00
Command::Stop => {
if let Some(server) = server.take() {
let _ = poll.deregister(&server);
}
return
},
2018-03-08 06:10:53 +01:00
Command::Worker(idx, addr) => {
workers.push((idx, addr));
},
2017-12-27 21:58:32 +01:00
},
Err(err) => match err {
sync_mpsc::TryRecvError::Empty => (),
2018-02-16 18:42:15 +01:00
sync_mpsc::TryRecvError::Disconnected => {
if let Some(server) = server.take() {
let _ = poll.deregister(&server);
}
return
},
2017-12-27 21:58:32 +01:00
}
2017-12-27 22:26:31 +01:00
},
2017-12-27 20:22:27 +01:00
_ => unreachable!(),
2017-12-13 21:47:07 +01:00
}
}
}
});
2017-12-27 21:58:32 +01:00
(readiness, tx)
}
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
let builder = match addr {
net::SocketAddr::V4(_) => TcpBuilder::new_v4()?,
net::SocketAddr::V6(_) => TcpBuilder::new_v6()?,
};
builder.reuse_address(true)?;
2018-03-03 07:57:11 +01:00
builder.bind(addr)?;
2017-12-27 21:58:32 +01:00
Ok(builder.listen(backlog)?)
2017-12-13 21:47:07 +01:00
}
2018-03-12 00:52:20 +01:00
/// This function defines errors that are per-connection. Which basically
/// means that if we get this error from `accept()` system call it means
/// next connection might be ready to be accepted.
///
/// All other errors will incur a timeout before next `accept()` is performed.
/// The timeout is useful to handle resource exhaustion errors like ENFILE
/// and EMFILE. Otherwise, could enter into tight loop.
fn connection_error(e: &io::Error) -> bool {
e.kind() == io::ErrorKind::ConnectionRefused ||
e.kind() == io::ErrorKind::ConnectionAborted ||
e.kind() == io::ErrorKind::ConnectionReset
}