Implement graceful shutdown

next
Sayan Nandan 4 years ago
parent 755e8d80f4
commit 35a86c96ac
No known key found for this signature in database
GPG Key ID: C31EFD7DDA12AEE0

@ -23,3 +23,6 @@
//! This contains modules which are shared by both the `cli` and the `server` modules
pub mod terrapipe;
use std::error::Error;
pub type TResult<T> = Result<T, Box<dyn Error>>;

@ -22,30 +22,32 @@
use corelib::terrapipe::QueryDataframe;
use corelib::terrapipe::{tags, ActionType, RespBytes, RespCodes, ResponseBuilder};
use std::collections::{hash_map::Entry, HashMap};
use std::sync::{Arc, RwLock};
use std::sync::{self, Arc, RwLock};
/// Results from actions on the Database
pub type ActionResult<T> = Result<T, RespCodes>;
#[derive(Debug, Clone)]
pub struct CoreDB {
shared: Arc<Coretable>,
terminate: bool,
}
#[derive(Debug)]
pub struct Coretable {
coremap: RwLock<HashMap<String, String>>,
}
impl Coretable {
impl CoreDB {
pub fn get(&self, key: &str) -> ActionResult<String> {
if let Some(value) = self.coremap.read().unwrap().get(key) {
if let Some(value) = self.acquire_read().get(key) {
Ok(value.to_string())
} else {
Err(RespCodes::NotFound)
}
}
pub fn set(&self, key: &str, value: &str) -> ActionResult<()> {
match self.coremap.write().unwrap().entry(key.to_string()) {
match self.acquire_write().entry(key.to_string()) {
Entry::Occupied(_) => return Err(RespCodes::OverwriteError),
Entry::Vacant(e) => {
let _ = e.insert(value.to_string());
@ -54,7 +56,7 @@ impl Coretable {
}
}
pub fn update(&self, key: &str, value: &str) -> ActionResult<()> {
match self.coremap.write().unwrap().entry(key.to_string()) {
match self.acquire_write().entry(key.to_string()) {
Entry::Occupied(ref mut e) => {
e.insert(value.to_string());
Ok(())
@ -63,7 +65,7 @@ impl Coretable {
}
}
pub fn del(&self, key: &str) -> ActionResult<()> {
if let Some(_) = self.coremap.write().unwrap().remove(&key.to_owned()) {
if let Some(_) = self.acquire_write().remove(&key.to_owned()) {
Ok(())
} else {
Err(RespCodes::NotFound)
@ -163,9 +165,6 @@ impl Coretable {
}
RespCodes::InvalidMetaframe.into_response()
}
}
impl CoreDB {
pub fn new() -> Self {
CoreDB {
shared: Arc::new(Coretable {
@ -174,8 +173,11 @@ impl CoreDB {
terminate: false,
}
}
pub fn get_handle(&self) -> Arc<Coretable> {
Arc::clone(&self.shared)
fn acquire_write(&self) -> sync::RwLockWriteGuard<'_, HashMap<String, String>> {
self.shared.coremap.write().unwrap()
}
fn acquire_read(&self) -> sync::RwLockReadGuard<'_, HashMap<String, String>> {
self.shared.coremap.read().unwrap()
}
}

@ -0,0 +1,174 @@
/*
* Created on Tue Jul 21 2020
*
* This file is a part of the source code for the Terrabase database
* Copyright (c) 2020, Sayan Nandan <ohsayan at outlook dot com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
use crate::{Connection, CoreDB};
use corelib::TResult;
use std::future::Future;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::sync::Semaphore;
use tokio::sync::{broadcast, mpsc};
use tokio::time::{self, Duration};
/// Responsible for gracefully shutting down the server instead of dying randomly
// Sounds very sci-fi ;)
pub struct Terminator {
terminate: bool,
signal: broadcast::Receiver<()>,
}
impl Terminator {
pub fn new(signal: broadcast::Receiver<()>) -> Self {
Terminator {
// Don't terminate on creation!
terminate: false,
signal,
}
}
pub fn is_termination_signal(&self) -> bool {
self.terminate
}
pub async fn receive_signal(&mut self) {
// The server may have already been terminated
// In that event, just return
if self.terminate {
return;
}
let _ = self.signal.recv().await;
self.terminate = true;
}
}
pub struct Listener {
/// An atomic reference to the coretable
db: CoreDB,
/// The incoming connection listener (binding)
listener: TcpListener,
/// The maximum number of connections
climit: Arc<Semaphore>,
/// The shutdown broadcaster
signal: broadcast::Sender<()>,
// When all `Sender`s are dropped - the `Receiver` gets a `None` value
// We send a clone of `terminate_tx` to each `CHandler`
terminate_tx: mpsc::Sender<()>,
terminate_rx: mpsc::Receiver<()>,
}
struct CHandler {
db: CoreDB,
con: Connection,
climit: Arc<Semaphore>,
terminator: Terminator,
_term_sig_tx: mpsc::Sender<()>,
}
impl Listener {
async fn accept(&mut self) -> TResult<TcpStream> {
// We will steal the idea of Ethernet's backoff for connection errors
let mut backoff = 1;
loop {
match self.listener.accept().await {
// We don't need the bindaddr
Ok((stream, _)) => return Ok(stream),
Err(e) => {
if backoff > 64 {
// Too many retries, goodbye user
return Err(e.into());
}
}
}
// Wait for the `backoff` duration
time::delay_for(Duration::from_secs(backoff)).await;
// We're using exponential backoff
backoff *= 2;
}
}
pub async fn run(&mut self) -> TResult<()> {
loop {
// Take the permit first, but we won't use it right now
// that's why we will forget it
self.climit.acquire().await.forget();
let stream = self.accept().await?;
let mut chandle = CHandler {
db: self.db.clone(),
con: Connection::new(stream),
climit: self.climit.clone(),
terminator: Terminator::new(self.signal.subscribe()),
_term_sig_tx: self.terminate_tx.clone(),
};
tokio::spawn(async move {
chandle.run().await;
});
}
}
}
impl CHandler {
async fn run(&mut self) {
while !self.terminator.is_termination_signal() {
let try_df = tokio::select! {
tdf = self.con.read_query() => tdf,
_ = self.terminator.receive_signal() => {
return;
}
};
match try_df {
Ok(df) => return self.con.write_response(self.db.execute_query(df)).await,
Err(e) => return self.con.close_conn_with_error(e).await,
}
}
}
}
impl Drop for CHandler {
fn drop(&mut self) {
self.climit.add_permits(1);
}
}
pub async fn run(listener: TcpListener, sig: impl Future) {
let (signal, _) = broadcast::channel(1);
let (terminate_tx, terminate_rx) = mpsc::channel(1);
let mut server = Listener {
listener,
db: CoreDB::new(),
climit: Arc::new(Semaphore::new(10000)),
signal,
terminate_tx,
terminate_rx,
};
tokio::select! {
_ = server.run() => {}
_ = sig => {
println!("Shuttting down...")
}
}
let Listener {
mut terminate_rx,
terminate_tx,
signal,
..
} = server;
drop(signal);
drop(terminate_tx);
let _ = terminate_rx.recv().await;
}

@ -24,25 +24,14 @@ mod coredb;
mod dbnet;
mod protocol;
use coredb::CoreDB;
use dbnet::run;
use protocol::Connection;
use tokio::signal;
static ADDR: &'static str = "127.0.0.1:2003";
#[tokio::main]
async fn main() {
let mut listener = TcpListener::bind(ADDR).await.unwrap();
let listener = TcpListener::bind(ADDR).await.unwrap();
println!("Server running on terrapipe://127.0.0.1:2003");
let db = CoreDB::new();
loop {
let handle = db.get_handle();
let (socket, _) = listener.accept().await.unwrap();
tokio::spawn(async move {
let mut con = Connection::new(socket);
let q = con.read_query().await;
let df = match q {
Ok(q) => q,
Err(e) => return con.close_conn_with_error(e).await,
};
con.write_response(handle.execute_query(df)).await;
});
}
run(listener, signal::ctrl_c()).await;
}

Loading…
Cancel
Save