bunbun/src/main.rs

225 lines
6.4 KiB
Rust
Raw Normal View History

2019-12-23 19:09:49 +00:00
use actix_web::middleware::Logger;
2019-12-23 15:02:21 +00:00
use actix_web::{App, HttpServer};
2019-12-24 00:33:09 +00:00
use clap::{crate_authors, crate_version, load_yaml, App as ClapApp};
2019-12-15 16:07:36 +00:00
use handlebars::Handlebars;
2019-12-21 19:04:13 +00:00
use hotwatch::{Event, Hotwatch};
2019-12-23 19:09:49 +00:00
use libc::daemon;
use log::{debug, error, info, trace, warn};
2019-12-15 17:49:16 +00:00
use serde::Deserialize;
2019-12-24 03:13:38 +00:00
use std::cmp::min;
use std::collections::HashMap;
2019-12-21 20:43:04 +00:00
use std::fmt;
use std::fs::{read_to_string, OpenOptions};
2019-12-21 20:43:04 +00:00
use std::io::Write;
2019-12-15 17:49:16 +00:00
use std::sync::{Arc, RwLock};
2019-12-21 19:04:13 +00:00
use std::time::Duration;
2019-12-15 16:07:36 +00:00
2019-12-23 15:02:21 +00:00
mod routes;
mod template_args;
2019-12-24 03:21:42 +00:00
const DEFAULT_CONFIG: &[u8] = include_bytes!("../bunbun.default.toml");
2019-12-15 16:07:36 +00:00
2019-12-21 20:43:04 +00:00
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
2019-12-21 20:43:04 +00:00
enum BunBunError {
IoError(std::io::Error),
2019-12-21 20:56:59 +00:00
ParseError(serde_yaml::Error),
2019-12-22 04:34:03 +00:00
WatchError(hotwatch::Error),
2019-12-23 19:09:49 +00:00
LoggerInitError(log::SetLoggerError),
2019-12-21 20:43:04 +00:00
}
impl fmt::Display for BunBunError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BunBunError::IoError(e) => e.fmt(f),
2019-12-21 20:56:59 +00:00
BunBunError::ParseError(e) => e.fmt(f),
2019-12-22 04:34:03 +00:00
BunBunError::WatchError(e) => e.fmt(f),
2019-12-23 19:09:49 +00:00
BunBunError::LoggerInitError(e) => e.fmt(f),
2019-12-21 20:43:04 +00:00
}
}
}
2019-12-23 01:05:01 +00:00
/// Generates a from implementation from the specified type to the provided
/// bunbun error.
2019-12-22 04:34:03 +00:00
macro_rules! from_error {
($from:ty, $to:ident) => {
impl From<$from> for BunBunError {
fn from(e: $from) -> Self {
BunBunError::$to(e)
}
}
};
2019-12-21 20:43:04 +00:00
}
2019-12-22 04:34:03 +00:00
from_error!(std::io::Error, IoError);
from_error!(serde_yaml::Error, ParseError);
from_error!(hotwatch::Error, WatchError);
2019-12-23 19:09:49 +00:00
from_error!(log::SetLoggerError, LoggerInitError);
2019-12-21 20:56:59 +00:00
2019-12-23 01:05:01 +00:00
/// Dynamic variables that either need to be present at runtime, or can be
/// changed during runtime.
2019-12-23 15:02:21 +00:00
pub struct State {
2019-12-21 19:21:13 +00:00
public_address: String,
default_route: Option<String>,
routes: HashMap<String, String>,
2019-12-21 19:21:13 +00:00
renderer: Handlebars,
2019-12-15 17:49:16 +00:00
}
2019-12-21 20:43:04 +00:00
fn main() -> Result<(), BunBunError> {
2019-12-24 00:33:09 +00:00
let yaml = load_yaml!("cli.yaml");
let matches = ClapApp::from(yaml)
.version(crate_version!())
.author(crate_authors!())
.get_matches();
2019-12-23 19:09:49 +00:00
2019-12-24 03:13:38 +00:00
let log_level = match min(matches.occurrences_of("verbose"), 3) as i8
- min(matches.occurrences_of("quiet"), 2) as i8
2019-12-24 00:42:30 +00:00
{
2019-12-24 03:13:38 +00:00
-2 => None,
2019-12-24 00:42:30 +00:00
-1 => Some(log::Level::Error),
0 => Some(log::Level::Warn),
1 => Some(log::Level::Info),
2 => Some(log::Level::Debug),
2019-12-24 03:13:38 +00:00
3 => Some(log::Level::Trace),
_ => unreachable!(),
2019-12-24 00:33:09 +00:00
};
if let Some(level) = log_level {
simple_logger::init_with_level(level)?;
}
// config has default location provided
let conf_file_location = String::from(matches.value_of("config").unwrap());
let conf = read_config(&conf_file_location)?;
2019-12-21 19:21:13 +00:00
let renderer = compile_templates();
let state = Arc::from(RwLock::new(State {
public_address: conf.public_address,
default_route: conf.default_route,
routes: conf.routes,
renderer,
}));
2019-12-24 00:33:09 +00:00
// Daemonize after trying to read from config and before watching; allow user
// to see a bad config (daemon process sets std{in,out} to /dev/null)
if matches.is_present("daemon") {
unsafe {
debug!("Daemon flag provided. Running as a daemon.");
daemon(0, 0);
}
}
2019-12-21 19:21:13 +00:00
2019-12-22 04:34:03 +00:00
let mut watch = Hotwatch::new_with_custom_delay(Duration::from_millis(500))?;
2019-12-24 00:33:09 +00:00
// TODO: keep retry watching in separate thread
2019-12-22 04:34:03 +00:00
2019-12-24 00:33:09 +00:00
// Closures need their own copy of variables for proper lifecycle management
let state_ref = state.clone();
let conf_file_location_clone = conf_file_location.clone();
let watch_result = watch.watch(&conf_file_location, move |e: Event| {
2019-12-22 04:34:03 +00:00
if let Event::Write(_) = e {
2019-12-23 19:09:49 +00:00
trace!("Grabbing writer lock on state...");
2019-12-22 04:34:03 +00:00
let mut state = state.write().unwrap();
2019-12-23 19:09:49 +00:00
trace!("Obtained writer lock on state!");
2019-12-24 00:33:09 +00:00
match read_config(&conf_file_location_clone) {
2019-12-22 04:34:03 +00:00
Ok(conf) => {
state.public_address = conf.public_address;
state.default_route = conf.default_route;
state.routes = conf.routes;
2019-12-23 19:09:49 +00:00
info!("Successfully updated active state");
2019-12-21 20:56:59 +00:00
}
2019-12-23 19:09:49 +00:00
Err(e) => warn!("Failed to update config file: {}", e),
2019-12-21 19:21:13 +00:00
}
2019-12-23 19:09:49 +00:00
} else {
debug!("Saw event {:#?} but ignored it", e);
2019-12-22 04:34:03 +00:00
}
2019-12-24 00:33:09 +00:00
});
2019-12-21 19:21:13 +00:00
2019-12-24 00:33:09 +00:00
match watch_result {
Ok(_) => info!("Watcher is now watching {}", &conf_file_location),
Err(e) => warn!(
"Couldn't watch {}: {}. Changes to this file won't be seen!",
&conf_file_location, e
),
}
2019-12-23 19:09:49 +00:00
2019-12-21 19:21:13 +00:00
HttpServer::new(move || {
App::new()
.data(state_ref.clone())
2019-12-23 19:09:49 +00:00
.wrap(Logger::default())
2019-12-23 15:02:21 +00:00
.service(routes::hop)
.service(routes::list)
.service(routes::index)
.service(routes::opensearch)
2019-12-21 19:21:13 +00:00
})
.bind(&conf.bind_address)?
2019-12-21 20:43:04 +00:00
.run()?;
Ok(())
2019-12-15 17:49:16 +00:00
}
2019-12-15 16:07:36 +00:00
2019-12-23 01:05:01 +00:00
#[derive(Deserialize)]
struct Config {
bind_address: String,
public_address: String,
default_route: Option<String>,
routes: HashMap<String, String>,
2019-12-23 01:05:01 +00:00
}
/// Attempts to read the config file. If it doesn't exist, generate one a
/// default config file before attempting to parse it.
2019-12-21 20:43:04 +00:00
fn read_config(config_file_path: &str) -> Result<Config, BunBunError> {
2019-12-23 19:09:49 +00:00
trace!("Loading config file...");
let config_str = match read_to_string(config_file_path) {
2019-12-23 19:09:49 +00:00
Ok(conf_str) => {
debug!("Successfully loaded config file into memory.");
conf_str
}
2019-12-21 19:21:13 +00:00
Err(_) => {
2019-12-23 19:09:49 +00:00
info!(
2019-12-21 19:21:13 +00:00
"Unable to find a {} file. Creating default!",
config_file_path
);
2019-12-23 19:09:49 +00:00
let fd = OpenOptions::new()
2019-12-21 19:21:13 +00:00
.write(true)
.create_new(true)
2019-12-23 19:09:49 +00:00
.open(config_file_path);
match fd {
Ok(mut fd) => fd.write_all(DEFAULT_CONFIG)?,
Err(e) => {
error!("Failed to write to {}: {}. Default config will be loaded but not saved.", config_file_path, e);
}
};
String::from_utf8_lossy(DEFAULT_CONFIG).into_owned()
2019-12-21 19:21:13 +00:00
}
};
// Reading from memory is faster than reading directly from a reader for some
// reason; see https://github.com/serde-rs/json/issues/160
Ok(serde_yaml::from_str(&config_str)?)
2019-12-21 19:16:47 +00:00
}
2019-12-23 01:05:01 +00:00
/// Returns an instance with all pre-generated templates included into the
/// binary. This allows for users to have a portable binary without needed the
/// templates at runtime.
2019-12-15 17:49:16 +00:00
fn compile_templates() -> Handlebars {
2019-12-21 19:21:13 +00:00
let mut handlebars = Handlebars::new();
2019-12-22 04:34:03 +00:00
macro_rules! register_template {
2019-12-23 01:05:01 +00:00
[ $( $template:expr ),* ] => {
2019-12-22 04:34:03 +00:00
$(
handlebars
.register_template_string(
$template,
String::from_utf8_lossy(
include_bytes!(concat!("templates/", $template, ".hbs")))
)
.unwrap();
2019-12-23 19:09:49 +00:00
debug!("Loaded {} template.", $template);
2019-12-22 04:34:03 +00:00
)*
};
}
2019-12-23 01:05:01 +00:00
register_template!["index", "list", "opensearch"];
2019-12-21 19:21:13 +00:00
handlebars
2019-12-15 16:07:36 +00:00
}