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

Use a threadpool to handle incoming requests #27

Closed
wants to merge 1 commit into from
Closed
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
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ atoi = "^0.3"
slog = "^2.5"
slog-async = "^2.5"
slog-term = "^2.6"
crossbeam-channel = "^0.4"
Copy link
Collaborator Author

@blinsay blinsay Jun 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the version of crossbeam-channel we pull in through slog-async.

nix = "^0.18"
num-derive = "^0.2"
num-traits = "^0.2"
threadpool = "^1.8"

[dev-dependencies]
criterion = "^0.3"
Expand Down
123 changes: 95 additions & 28 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,95 @@ use std::io::ErrorKind;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
use std::thread;
use std::time::Duration;

use anyhow::{Context, Result};
use crossbeam_channel as channel;
use slog::{debug, error, o, Drain};
use threadpool::ThreadPool;

mod ffi;
mod handlers;
mod protocol;

fn main() -> Result<()> {
const SOCKET_PATH: &str = "/var/run/nscd/socket";
const N_WORKERS: usize = 256;
const HANDOFF_TIMEOUT: Duration = Duration::from_secs(3);

ffi::disable_internal_nscd();

let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();

let logger = slog::Logger::root(drain, slog::o!());

let (pool, handle) = worker_pool(logger.clone(), N_WORKERS);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we call handle channel or tx or something instead? "handle" is so generic


let path = Path::new(SOCKET_PATH);
std::fs::create_dir_all(path.parent().expect("socket path has no parent"))?;
std::fs::remove_file(path).ok();
let listener = UnixListener::bind(path).context("could not bind to socket")?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o777))?;

for stream in listener.incoming() {
match stream {
Ok(stream) => {
// if something goes wrong and it's multiple seconds until we
// get a response, kill the process.
//
// the timeout here is set such that nss will fall back to system
// libc before this timeout is hit - clients will already be
// giving up and going elsewhere so crashing the process should
// not make a bad situation worse.
match handle.send_timeout(stream, HANDOFF_TIMEOUT) {
Err(channel::SendTimeoutError::Timeout(_)) => {
anyhow::bail!("timed out waiting for an available worker: exiting")
}
Err(channel::SendTimeoutError::Disconnected(_)) => {
anyhow::bail!("aborting: worker channel is disconnected")
}
_ => { /*ok!*/ }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make the last clause just Ok? I'm worried about send_timeout starting to return new error types and us silently ignoring them. I'd rather have an exhaustive match block.

}
}
Err(err) => {
error!(logger, "error accepting connection"; "err" => %err);
break;
}
}
}

// drop the worker handle so that the worker pool shuts down. every worker
// task should break and the process should exit.
std::mem::drop(handle);
pool.join();

Ok(())
}

fn worker_pool(log: slog::Logger, n_workers: usize) -> (ThreadPool, channel::Sender<UnixStream>) {
let pool = ThreadPool::new(n_workers);
let (tx, rx) = channel::bounded(0);

// TODO: figure out how to name the worker threads in each worker
// TODO: report actively working threads
for _ in 0..n_workers {
let log = log.clone();
let rx = rx.clone();

pool.execute(move || loop {
let log = log.clone();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need another clone here?

match rx.recv() {
Ok(stream) => handle_stream(log, stream),
Err(channel::RecvError) => break,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we log something useful on error?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope. It's just a sentinel telling us the channel is closed.

https://docs.rs/crossbeam-channel/0.5.1/crossbeam_channel/struct.RecvError.html

}
});
}

(pool, tx)
}

/// Handle a new socket connection, reading the request and sending the response.
fn handle_stream(log: slog::Logger, mut stream: UnixStream) {
debug!(log, "accepted connection"; "stream" => ?stream);
Expand Down Expand Up @@ -101,35 +181,22 @@ fn handle_stream(log: slog::Logger, mut stream: UnixStream) {
}
}

const SOCKET_PATH: &str = "/var/run/nscd/socket";

fn main() -> Result<()> {
ffi::disable_internal_nscd();

let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
#[cfg(test)]
mod pool_test {
use super::*;

let logger = slog::Logger::root(drain, slog::o!());
#[test]
fn worker_shutdown() {
let logger = {
let decorator = slog_term::PlainDecorator::new(slog_term::TestStdoutWriter);
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
slog::Logger::root(drain, slog::o!())
};

let path = Path::new(SOCKET_PATH);
std::fs::create_dir_all(path.parent().expect("socket path has no parent"))?;
std::fs::remove_file(path).ok();
let listener = UnixListener::bind(path).context("could not bind to socket")?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o777))?;
let (pool, handle) = worker_pool(logger, 123);

for stream in listener.incoming() {
match stream {
Ok(stream) => {
let thread_logger = logger.clone();
thread::spawn(move || handle_stream(thread_logger, stream));
}
Err(err) => {
error!(logger, "error accepting connection"; "err" => %err);
break;
}
}
std::mem::drop(handle);
pool.join();
}

Ok(())
}