1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 08:52:42 +01:00
actix-web/src/server/srv.rs

985 lines
34 KiB
Rust
Raw Normal View History

2017-10-07 06:48:14 +02:00
use std::rc::Rc;
2018-04-14 01:02:01 +02:00
use std::sync::{mpsc as sync_mpsc, Arc};
2017-12-14 01:44:35 +01:00
use std::time::Duration;
2018-04-14 01:02:01 +02:00
use std::{io, net, thread};
2017-10-07 06:48:14 +02:00
2018-01-06 01:32:36 +01:00
use actix::actors::signal;
2018-04-14 01:02:01 +02:00
use actix::prelude::*;
use futures::sync::mpsc;
2018-04-14 01:02:01 +02:00
use futures::{Future, Sink, Stream};
2017-12-27 20:22:27 +01:00
use mio;
2017-12-28 21:38:37 +01:00
use net2::TcpBuilder;
2018-04-14 01:02:01 +02:00
use num_cpus;
use slab::Slab;
2018-04-14 01:02:01 +02:00
use tokio_io::{AsyncRead, AsyncWrite};
2017-10-07 06:48:14 +02:00
2018-04-14 01:02:01 +02:00
#[cfg(feature = "tls")]
use native_tls::TlsAcceptor;
2018-04-14 01:02:01 +02:00
#[cfg(feature = "alpn")]
use openssl::ssl::{AlpnError, SslAcceptorBuilder};
2018-01-12 03:35:05 +01:00
use super::channel::{HttpChannel, WrapperStream};
use super::settings::{ServerSettings, WorkerSettings};
use super::worker::{Conn, SocketInfo, StopWorker, StreamHandlerType, Worker};
2018-04-14 01:02:01 +02:00
use super::{IntoHttpHandler, IoStream, KeepAlive};
use super::{PauseServer, ResumeServer, StopServer};
2018-05-16 15:20:47 +02:00
#[cfg(feature = "alpn")]
fn configure_alpn(builder: &mut SslAcceptorBuilder) -> io::Result<()> {
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)
}
});
Ok(())
}
2017-10-08 23:56:51 +02:00
/// An HTTP Server
2018-04-14 01:02:01 +02: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-04-14 01:02:01 +02:00
#[cfg_attr(feature = "cargo-clippy", allow(type_complexity))]
2018-03-08 06:10:53 +01:00
workers: Vec<(usize, Addr<Syn, Worker<H::Handler>>)>,
sockets: Vec<Socket>,
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-04-14 01:02:01 +02: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
enum ServerCommand {
WorkerDied(usize, Slab<SocketInfo>),
2018-03-08 06:10:53 +01:00
}
2017-12-28 02:49:10 +01:00
2018-04-14 01:02:01 +02:00
impl<H> Actor for HttpServer<H>
where
H: IntoHttpHandler,
{
2017-10-07 06:48:14 +02:00
type Context = Context<Self>;
2017-12-14 01:44:35 +01:00
}
struct Socket {
lst: net::TcpListener,
addr: net::SocketAddr,
tp: StreamHandlerType,
}
2018-04-14 01:02:01 +02: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
2018-04-14 01:02:01 +02:00
where
F: Fn() -> U + Sync + Send + 'static,
U: IntoIterator<Item = H> + 'static,
2017-12-06 20:00:39 +01:00
{
2018-04-14 01:02:01 +02:00
let f = move || (factory)().into_iter().collect();
HttpServer {
h: None,
threads: num_cpus::get(),
backlog: 2048,
host: None,
keep_alive: KeepAlive::Os,
factory: Arc::new(f),
workers: Vec::new(),
sockets: Vec::new(),
accept: Vec::new(),
exit: false,
shutdown_timeout: 30,
signals: None,
no_http2: false,
no_signals: false,
}
}
/// Set number of workers to start.
///
2018-04-14 01:02:01 +02:00
/// By default http server uses number of available logical cpu as threads
/// count.
2018-05-01 22:15:35 +02:00
pub fn workers(mut self, num: usize) -> Self {
self.threads = num;
self
2017-10-07 06:48:14 +02:00
}
2018-05-01 22:15:35 +02:00
#[doc(hidden)]
#[deprecated(since = "0.6.0", note = "please use `HttpServer::workers()` instead")]
pub fn threads(self, num: usize) -> Self {
self.workers(num)
}
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
2018-04-14 01:02:01 +02:00
/// attempting to connect. It should only affect servers under significant
/// load.
2017-12-17 21:35:04 +01:00
///
/// 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.
///
2018-04-14 01:02:01 +02:00
/// 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.
2017-12-26 23:36:03 +01:00
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.
///
2018-04-14 01:02:01 +02:00
/// After receiving a stop signal, workers have this much time to finish
/// serving requests. Workers still alive after the timeout are force
/// dropped.
2017-12-29 01:25:47 +01:00
///
/// 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.addr).collect()
}
/// Get addresses of bound sockets and the scheme for it.
///
/// This is useful when the server is bound from different sources
/// with some sockets listening on http and some listening on https
/// and the user should be presented with an enumeration of which
/// socket requires which protocol.
pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> {
2018-05-17 21:20:20 +02:00
self.sockets
.iter()
.map(|s| (s.addr, s.tp.scheme()))
.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 {
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
lst,
tp: StreamHandlerType::Normal,
});
2018-03-07 23:46:12 +01:00
self
}
2018-05-16 15:20:47 +02:00
#[cfg(feature = "tls")]
/// Use listener for accepting incoming tls connection requests
///
/// HttpServer does not change any configuration for TcpListener,
/// it needs to be configured before passing it to listen() method.
pub fn listen_tls(mut self, lst: net::TcpListener, acceptor: TlsAcceptor) -> Self {
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
lst,
tp: StreamHandlerType::Tls(acceptor.clone()),
});
self
}
#[cfg(feature = "alpn")]
/// Use listener for accepting incoming tls connection requests
///
/// This method sets alpn protocols to "h2" and "http/1.1"
2018-05-17 21:20:20 +02:00
pub fn listen_ssl(
mut self, lst: net::TcpListener, mut builder: SslAcceptorBuilder,
) -> io::Result<Self> {
2018-05-16 15:20:47 +02:00
// alpn support
if !self.no_http2 {
configure_alpn(&mut builder)?;
}
let acceptor = builder.build();
let addr = lst.local_addr().unwrap();
self.sockets.push(Socket {
addr,
lst,
tp: StreamHandlerType::Alpn(acceptor.clone()),
});
Ok(self)
}
fn bind2<S: net::ToSocketAddrs>(&mut self, addr: S) -> io::Result<Vec<Socket>> {
2017-10-15 23:53:03 +02:00
let mut err = None;
2017-12-17 21:35:04 +01:00
let mut succ = false;
let mut sockets = Vec::new();
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;
let addr = lst.local_addr().unwrap();
sockets.push(Socket {
lst,
addr,
tp: StreamHandlerType::Normal,
});
2018-04-14 01:02:01 +02:00
}
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 {
2018-04-29 18:09:08 +02:00
Err(io::Error::new(
io::ErrorKind::Other,
"Can not bind to address.",
))
2017-10-15 23:53:03 +02:00
}
} else {
Ok(sockets)
}
}
/// The socket address to bind
///
/// To bind multiple addresses this method can be called multiple times.
pub fn bind<S: net::ToSocketAddrs>(mut self, addr: S) -> io::Result<Self> {
let sockets = self.bind2(addr)?;
self.sockets.extend(sockets);
Ok(self)
}
#[cfg(feature = "tls")]
/// The ssl socket address to bind
///
/// To bind multiple addresses this method can be called multiple times.
pub fn bind_tls<S: net::ToSocketAddrs>(
mut self, addr: S, acceptor: TlsAcceptor,
) -> io::Result<Self> {
let sockets = self.bind2(addr)?;
self.sockets.extend(sockets.into_iter().map(|mut s| {
s.tp = StreamHandlerType::Tls(acceptor.clone());
s
}));
Ok(self)
}
#[cfg(feature = "alpn")]
/// Start listening for incoming tls connections.
///
/// This method sets alpn protocols to "h2" and "http/1.1"
pub fn bind_ssl<S: net::ToSocketAddrs>(
mut self, addr: S, mut builder: SslAcceptorBuilder,
) -> io::Result<Self> {
// alpn support
if !self.no_http2 {
2018-05-16 15:20:47 +02:00
configure_alpn(&mut builder)?;
2017-10-15 23:53:03 +02:00
}
let acceptor = builder.build();
let sockets = self.bind2(addr)?;
self.sockets.extend(sockets.into_iter().map(|mut s| {
s.tp = StreamHandlerType::Alpn(acceptor.clone());
s
}));
Ok(self)
2017-10-07 06:48:14 +02:00
}
2018-04-14 01:02:01 +02:00
fn start_workers(
&mut self, settings: &ServerSettings, sockets: &Slab<SocketInfo>,
2018-04-14 01:02:01 +02: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-14 07:36:28 +01:00
let ka = self.keep_alive;
let socks = sockets.clone();
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()
2018-04-14 01:02:01 +02:00
.map(|h| h.into_handler(s.clone()))
.collect();
2018-01-05 22:30:21 +01:00
ctx.add_message_stream(rx);
Worker::new(apps, socks, 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-04-14 01:02:01 +02: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.
2018-04-14 01:02:01 +02:00
/// 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;
2018-04-06 18:45:10 +02:00
/// use actix_web::{server, App, HttpResponse};
2017-12-26 21:46:27 +01:00
///
/// fn main() {
/// let sys = actix::System::new("example"); // <- create Actix system
///
2018-04-06 18:45:10 +02:00
/// server::new(
2018-03-31 09:16:55 +02:00
/// || App::new()
/// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
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-04-14 01:02:01 +02: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();
let mut socks = Slab::new();
let mut addrs: Vec<(usize, Socket)> = Vec::new();
for socket in self.sockets.drain(..) {
let entry = socks.vacant_entry();
let token = entry.key();
entry.insert(SocketInfo {
addr: socket.addr,
htype: socket.tp.clone(),
});
addrs.push((token, socket));
}
let settings = ServerSettings::new(Some(addrs[0].1.addr), &self.host, false);
let workers = self.start_workers(&settings, &socks);
2017-12-17 21:35:04 +01:00
// start acceptors threads
for (token, sock) in addrs {
info!("Starting server on http://{}", sock.addr);
2018-04-14 01:02:01 +02:00
self.accept.push(start_accept_thread(
token,
2018-04-14 01:02:01 +02:00
sock,
self.backlog,
tx.clone(),
socks.clone(),
2018-04-14 01:02:01 +02:00
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-04-29 07:55:47 +02:00
if let Some(signals) = signals {
2018-04-14 01:02:01 +02:00
signals.do_send(signal::Subscribe(addr.clone().recipient()))
2018-04-29 07:55:47 +02:00
}
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
///
2018-04-14 01:02:01 +02:00
/// This method spawns new thread and starts new actix system. Other than
/// that it is 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(
2018-03-31 09:16:55 +02:00
/// || App::new()
/// .resource("/", |r| r.h(|_| HttpResponse::Ok())))
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
}
}
#[doc(hidden)]
2018-04-14 01:02:01 +02:00
#[cfg(feature = "tls")]
#[deprecated(
since = "0.6.0", note = "please use `actix_web::HttpServer::bind_tls` instead"
)]
2018-04-14 01:02:01 +02: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>> {
for sock in &mut self.sockets {
match sock.tp {
StreamHandlerType::Normal => (),
_ => continue,
}
sock.tp = StreamHandlerType::Tls(acceptor.clone());
}
Ok(self.start())
}
}
#[doc(hidden)]
2018-04-14 01:02:01 +02:00
#[cfg(feature = "alpn")]
#[deprecated(
since = "0.6.0", note = "please use `actix_web::HttpServer::bind_ssl` instead"
)]
2018-04-14 01:02:01 +02: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-04-14 01:02:01 +02:00
pub fn start_ssl(
2018-04-29 07:55:47 +02:00
mut self, mut builder: SslAcceptorBuilder,
2018-04-14 01:02:01 +02:00
) -> io::Result<Addr<Syn, Self>> {
// alpn support
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)
}
});
}
2017-12-17 21:35:04 +01:00
let acceptor = builder.build();
for sock in &mut self.sockets {
match sock.tp {
StreamHandlerType::Normal => (),
_ => continue,
2017-12-17 21:35:04 +01:00
}
sock.tp = StreamHandlerType::Alpn(acceptor.clone());
}
Ok(self.start())
}
}
2018-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> HttpServer<H> {
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-04-14 01:02:01 +02:00
where
S: Stream<Item = (T, A), Error = io::Error> + 'static,
T: AsyncRead + AsyncWrite + 'static,
A: 'static,
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-04-14 01:02:01 +02: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-04-14 01:02:01 +02:00
ctx.add_message_stream(stream.map_err(|_| ()).map(move |(t, _)| Conn {
io: WrapperStream::new(t),
token: 0,
2018-04-14 01:02:01 +02:00
peer: None,
http2: false,
}));
2017-12-19 03:56:58 +01:00
self
2018-01-08 02:13:49 +01:00
});
2018-04-29 07:55:47 +02:00
if let Some(signals) = signals {
signals.do_send(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-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> Handler<signal::Signal> for HttpServer<H> {
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;
2018-04-29 18:09:08 +02:00
Handler::<StopServer>::handle(self, StopServer { graceful: false }, ctx);
2017-12-28 20:36:20 +01:00
}
signal::SignalType::Term => {
info!("SIGTERM received, stopping");
self.exit = true;
2018-04-29 18:09:08 +02:00
Handler::<StopServer>::handle(self, StopServer { graceful: true }, ctx);
2017-12-28 20:36:20 +01:00
}
signal::SignalType::Quit => {
info!("SIGQUIT received, exiting");
self.exit = true;
2018-04-29 18:09:08 +02:00
Handler::<StopServer>::handle(self, StopServer { graceful: false }, ctx);
2017-12-28 20:36:20 +01:00
}
_ => (),
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
2018-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> StreamHandler<ServerCommand, ()> for HttpServer<H> {
2018-03-08 06:10:53 +01:00
fn finished(&mut self, _: &mut Context<Self>) {}
fn handle(&mut self, msg: ServerCommand, _: &mut Context<Self>) {
match msg {
ServerCommand::WorkerDied(idx, socks) => {
2018-03-08 06:10:53 +01:00
let mut found = false;
for i in 0..self.workers.len() {
if self.workers[i].0 == idx {
self.workers.swap_remove(i);
found = true;
2018-04-14 01:02:01 +02:00
break;
2018-03-08 06:10:53 +01:00
}
}
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;
2018-04-14 01:02:01 +02:00
continue 'found;
2018-03-08 06:10:53 +01:00
}
}
2018-04-14 01:02:01 +02:00
break;
2018-03-08 06:10:53 +01:00
}
let ka = self.keep_alive;
let factory = Arc::clone(&self.factory);
2018-04-14 01:02:01 +02:00
let settings =
ServerSettings::new(Some(socks[0].addr), &self.host, false);
2018-03-08 06:10:53 +01:00
let addr = Arbiter::start(move |ctx: &mut Context<_>| {
let apps: Vec<_> = (*factory)()
.into_iter()
2018-04-14 01:02:01 +02:00
.map(|h| h.into_handler(settings.clone()))
.collect();
2018-03-08 06:10:53 +01:00
ctx.add_message_stream(rx);
Worker::new(apps, socks, ka)
2018-03-08 06:10:53 +01:00
});
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-04-14 01:02:01 +02:00
}
2018-03-08 06:10:53 +01:00
}
}
}
2018-02-10 20:01:54 +01:00
impl<T, H> Handler<Conn<T>> for HttpServer<H>
2018-04-14 01:02:01 +02:00
where
T: IoStream,
H: IntoHttpHandler,
2018-01-28 10:04:58 +01:00
{
type Result = ();
fn handle(&mut self, msg: Conn<T>, _: &mut Context<Self>) -> Self::Result {
2018-04-14 01:02:01 +02:00
Arbiter::handle().spawn(HttpChannel::new(
Rc::clone(self.h.as_ref().unwrap()),
msg.io,
msg.peer,
msg.http2,
));
2018-01-28 10:04:58 +01:00
}
}
2018-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> Handler<PauseServer> for HttpServer<H> {
2018-01-05 22:30:21 +01:00
type Result = ();
2018-04-14 01:02:01 +02:00
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-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> Handler<ResumeServer> for HttpServer<H> {
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-04-14 01:02:01 +02:00
impl<H: IntoHttpHandler> Handler<StopServer> for HttpServer<H> {
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-04-14 01:02:01 +02:00
worker
.1
2018-04-29 18:09:08 +02:00
.send(StopWorker { graceful: dur })
2018-03-23 02:41:02 +01:00
.into_actor(self)
.then(move |_, slf, ctx| {
slf.workers.pop();
if slf.workers.is_empty() {
let _ = tx2.send(());
// we need to stop system if server was spawned
if slf.exit {
ctx.run_later(Duration::from_millis(300), |_, _| {
2018-03-23 02:41:02 +01:00
Arbiter::system().do_send(actix::msgs::SystemExit(0))
});
}
2017-12-29 01:25:47 +01:00
}
2018-03-23 02:41:02 +01:00
actix::fut::ok(())
2018-04-14 01:02:01 +02: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-04-14 01:02:01 +02: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 {
ctx.run_later(Duration::from_millis(300), |_, _| {
2018-03-23 02:41:02 +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(
token: usize, sock: Socket, backlog: i32, srv: mpsc::UnboundedSender<ServerCommand>,
socks: Slab<SocketInfo>,
2018-04-14 01:02:01 +02:00
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-04-14 01:02:01 +02:00
#[cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))]
2018-04-29 18:09:08 +02:00
let _ = thread::Builder::new()
.name(format!("Accept on {}", sock.addr))
2018-04-29 18:09:08 +02:00
.spawn(move || {
2018-04-14 01:02:01 +02:00
const SRV: mio::Token = mio::Token(0);
const CMD: mio::Token = mio::Token(1);
let addr = sock.addr;
2018-04-14 01:02:01 +02:00
let mut server = Some(
mio::net::TcpListener::from_std(sock.lst)
2018-04-14 01:02:01 +02:00
.expect("Can not create mio::net::TcpListener"),
);
// 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
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);
}
}
2017-12-27 20:22:27 +01:00
2018-04-14 01:02:01 +02:00
// Start listening for incoming commands
2018-05-17 21:20:20 +02:00
if let Err(err) =
poll.register(&reg, CMD, mio::Ready::readable(), mio::PollOpt::edge())
{
2018-04-14 01:02:01 +02:00
panic!("Can not register Registration: {}", err);
2017-12-27 21:58:32 +01:00
}
2018-04-14 01:02:01 +02:00
// Create storage for events
let mut events = mio::Events::with_capacity(128);
2017-12-27 20:22:27 +01:00
2018-04-14 01:02:01 +02:00
// Sleep on error
let sleep = Duration::from_millis(100);
2018-03-08 00:52:05 +01:00
2018-04-14 01:02:01 +02:00
let mut next = 0;
loop {
if let Err(err) = poll.poll(&mut events, None) {
panic!("Poll error: {}", err);
}
2017-12-27 20:22:27 +01:00
2018-04-14 01:02:01 +02:00
for event in events.iter() {
match event.token() {
SRV => if let Some(ref server) = server {
loop {
match server.accept_std() {
Ok((io, addr)) => {
2018-04-14 01:02:01 +02:00
let mut msg = Conn {
io,
token,
2018-04-14 01:02:01 +02:00
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,
socks.clone(),
2018-04-14 01:02:01 +02:00
),
);
msg = err.into_inner();
workers.swap_remove(next);
if workers.is_empty() {
error!("No workers");
thread::sleep(sleep);
break;
} else if workers.len() <= next {
next = 0;
}
continue;
2018-03-16 19:17:27 +01:00
}
2018-03-08 06:10:53 +01:00
}
2018-04-14 01:02:01 +02:00
next = (next + 1) % workers.len();
break;
2018-02-16 07:02:03 +01:00
}
2018-04-14 01:02:01 +02:00
}
Err(ref e)
if e.kind() == io::ErrorKind::WouldBlock =>
{
2017-12-27 21:58:32 +01:00
break
}
2018-04-14 01:02:01 +02:00
Err(ref e) if connection_error(e) => continue,
Err(e) => {
error!("Error accepting connection: {}", e);
// sleep after error
thread::sleep(sleep);
break;
}
2017-12-27 20:22:27 +01:00
}
}
2018-04-14 01:02:01 +02: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
);
2017-12-27 21:58:32 +01:00
} else {
2018-04-14 01:02:01 +02:00
info!(
"Paused accepting connections on {}",
addr
);
}
},
Command::Resume => {
let lst = create_tcp_listener(addr, backlog)
.expect("Can not create net::TcpListener");
server = Some(
mio::net::TcpListener::from_std(lst).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",
2017-12-27 21:58:32 +01:00
addr);
2018-04-14 01:02:01 +02:00
}
2017-12-27 21:58:32 +01:00
}
}
2018-04-14 01:02:01 +02:00
Command::Stop => {
if let Some(server) = server.take() {
let _ = poll.deregister(&server);
}
return;
}
Command::Worker(idx, addr) => {
workers.push((idx, addr));
2018-02-16 18:42:15 +01:00
}
2018-03-08 06:10:53 +01:00
},
2018-04-14 01:02:01 +02:00
Err(err) => match err {
sync_mpsc::TryRecvError::Empty => (),
sync_mpsc::TryRecvError::Disconnected => {
if let Some(server) = server.take() {
let _ = poll.deregister(&server);
}
return;
2018-02-16 18:42:15 +01:00
}
},
2018-04-14 01:02:01 +02:00
},
_ => unreachable!(),
}
2017-12-13 21:47:07 +01:00
}
}
2018-04-29 18:09:08 +02:00
});
2017-12-27 21:58:32 +01:00
(readiness, tx)
}
2018-04-14 01:02:01 +02:00
fn create_tcp_listener(
2018-04-29 07:55:47 +02:00
addr: net::SocketAddr, backlog: i32,
2018-04-14 01:02:01 +02:00
) -> io::Result<net::TcpListener> {
2017-12-27 21:58:32 +01:00
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 {
2018-04-14 01:02:01 +02:00
e.kind() == io::ErrorKind::ConnectionRefused
|| e.kind() == io::ErrorKind::ConnectionAborted
|| e.kind() == io::ErrorKind::ConnectionReset
2018-03-12 00:52:20 +01:00
}