Improve logging output format

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/1/head
trivernis 4 years ago
parent f86fa86f3e
commit 3a2ea2a03d
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

3
.gitignore vendored

@ -1,3 +1,4 @@
/target
.env
.idea
.idea
*.log

1
Cargo.lock generated

@ -373,6 +373,7 @@ dependencies = [
"base64 0.12.3",
"bcrypt",
"byteorder",
"chrono",
"colored",
"crossbeam-utils",
"dotenv",

@ -25,4 +25,5 @@ crossbeam-utils = "0.7.2"
mime = "0.3.16"
serde_json = "1.0.57"
rouille = "3.0.0"
base64 = "0.12.3"
base64 = "0.12.3"
chrono = "0.4.15"

@ -52,11 +52,17 @@ impl Database {
/// Inits all database models
pub fn init(&self) -> DatabaseResult<()> {
log::info!("Initializing users...");
self.users.init()?;
log::info!("Initializing roles...");
self.roles.init()?;
log::info!("Initializing permissions...");
self.permissions.init()?;
log::info!("Initializing user_roles...");
self.user_roles.init()?;
log::info!("Initializing user_permissions...");
self.role_permission.init()?;
log::info!("Database fully initialized!");
Ok(())
}

@ -9,6 +9,11 @@ use postgres::Client;
use std::sync::{Arc, Mutex};
use zeroize::{Zeroize, Zeroizing};
const DEFAULT_ADMIN_PASSWORD: &str = "flotte-admin";
const DEFAULT_ADMIN_EMAIL: &str = "admin@flotte-berlin.de";
const ENV_ADMIN_PASSWORD: &str = "ADMIN_PASSWORD";
const ENV_ADMIN_EMAIL: &str = "ADMIN_EMAIL";
#[derive(Clone)]
pub struct Users {
database_connection: Arc<Mutex<Client>>,
@ -26,19 +31,27 @@ impl Table for Users {
}
fn init(&self) -> DatabaseResult<()> {
self.database_connection
.lock()
.unwrap()
.batch_execute(
"CREATE TABLE IF NOT EXISTS users (
self.database_connection.lock().unwrap().batch_execute(
"CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash BYTEA NOT NULL,
salt BYTEA NOT NULL
);",
)
.map_err(DBError::from)
)?;
log::debug!("Creating admin user");
if let Err(e) = self.create_user(
"ADMIN".to_string(),
dotenv::var(ENV_ADMIN_EMAIL).unwrap_or(DEFAULT_ADMIN_EMAIL.to_string()),
dotenv::var(ENV_ADMIN_PASSWORD).unwrap_or(DEFAULT_ADMIN_PASSWORD.to_string()),
) {
log::debug!("Failed to create admin user {}", e);
} else {
log::debug!("Admin user created successfully!");
}
Ok(())
}
}
@ -51,11 +64,13 @@ impl Users {
) -> DatabaseResult<UserRecord> {
let mut connection = self.database_connection.lock().unwrap();
let mut password = Zeroizing::new(password);
log::trace!("Creating user {} with email {}", name, email);
if !connection
.query("SELECT email FROM users WHERE email = $1", &[&email])?
.is_empty()
{
log::trace!("Failed to create user: Record exists!");
return Err(DBError::RecordExists);
}
let salt = Zeroizing::new(create_salt());

@ -1,3 +1,4 @@
use chrono::Local;
use colored::Colorize;
use crossbeam_utils::sync::WaitGroup;
use env_logger::Env;
@ -6,6 +7,7 @@ use flotte_user_management::server::http_server::UserHttpServer;
use flotte_user_management::server::user_rpc::UserRpcServer;
use log::Level;
use std::thread;
use std::thread::Builder;
fn main() {
init_logger();
@ -16,18 +18,24 @@ fn main() {
let wg = WaitGroup::new();
{
let wg = WaitGroup::clone(&wg);
thread::spawn(move || {
rpc_server.start();
std::mem::drop(wg);
});
Builder::new()
.name("rpc".to_string())
.spawn(move || {
rpc_server.start();
std::mem::drop(wg);
})
.unwrap();
}
{
let wg = WaitGroup::clone(&wg);
let http_server = http_server;
thread::spawn(move || {
http_server.start();
std::mem::drop(wg);
});
Builder::new()
.name("http".to_string())
.spawn(move || {
http_server.start();
std::mem::drop(wg);
})
.unwrap();
}
wg.wait();
}
@ -39,7 +47,10 @@ fn init_logger() {
let color = get_level_style(record.level());
writeln!(
buf,
"{}: {}",
"{:<12} {:<45}| {} {}: {}",
format!("thread::{}", thread::current().name().unwrap_or("main")).dimmed(),
record.target().dimmed().italic(),
Local::now().format("%Y-%m-%dT%H:%M:%S"),
record
.level()
.to_string()

@ -58,10 +58,11 @@ impl UserHttpServer {
}
pub fn start(&self) {
log::info!("Starting HTTP-Server...");
let listen_address =
dotenv::var(LISTEN_ADDRESS).unwrap_or(DEFAULT_LISTEN_ADDRESS.to_string());
let database = Database::clone(&self.database);
let server = Server::new(listen_address, move |request| {
let server = Server::new(&listen_address, move |request| {
router!(request,
(POST) (/login) => {
Self::login(&database, request).unwrap_or_else(|e|e.into())
@ -73,6 +74,7 @@ impl UserHttpServer {
)
})
.unwrap();
log::info!("HTTP-Server running on {}", listen_address);
server.run()
}

@ -11,7 +11,7 @@ use rmp_serde::Deserializer;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
use std::thread;
use std::thread::Builder;
const RPC_SERVER_ADDRESS: &str = "RPC_SERVER_ADDRESS";
const DEFAULT_SERVER_ADDRESS: &str = "127.0.0.1:5555";
@ -30,15 +30,21 @@ impl UserRpcServer {
}
pub fn start(&self) {
let mut server = RpcServer::new(
dotenv::var(RPC_SERVER_ADDRESS).unwrap_or(DEFAULT_SERVER_ADDRESS.to_string()),
);
let listen_address =
dotenv::var(RPC_SERVER_ADDRESS).unwrap_or(DEFAULT_SERVER_ADDRESS.to_string());
log::info!("Starting RPC-Server...");
let mut server = RpcServer::new(listen_address.clone());
let receiver = Arc::clone(&server.receiver);
thread::spawn(move || {
server.start().unwrap();
});
Builder::new()
.name("tcp-receiver".to_string())
.spawn(move || {
server.start().unwrap();
})
.unwrap();
log::info!("RPC-Server running on {}", listen_address);
while let Ok(h) = receiver.lock().unwrap().recv() {
let mut handler = h.lock().unwrap();
log::debug!("Received message {:?}", handler.message);
let response = match handler.message.method {
INFO => self.handle_info(),
GET_ROLES => self.handle_get_roles(&handler.message.data),
@ -49,7 +55,7 @@ impl UserRpcServer {
_ => Err(ErrorMessage::new("Invalid Method".to_string())),
}
.unwrap_or_else(|e| Message::new_with_serialize(ERROR, e));
log::trace!("Responding with {:?}", &response);
log::debug!("Responding with message {:?}", &response);
handler.done(response);
}
}

Loading…
Cancel
Save