initial port to tracing

This commit is contained in:
2021-04-11 13:14:11 +02:00
parent ea75e1e3ee
commit a3b757abad
8 changed files with 279 additions and 265 deletions
+31 -68
View File
@@ -12,7 +12,7 @@ use std::{
use pslink::{models::NewUser, models::User, ServerConfig, ServerError};
use slog::{Drain, Logger};
use tracing::{error, info, trace, warn};
static MIGRATOR: Migrator = sqlx::migrate!();
@@ -122,7 +122,7 @@ fn generate_cli() -> App<'static, 'static> {
)
}
async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConfig {
async fn parse_args_to_config(config: ArgMatches<'_>) -> ServerConfig {
let secret = config
.value_of("secret")
.expect("Failed to read the secret")
@@ -132,20 +132,11 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
use rand::{thread_rng, Rng};
if secret.is_empty() {
slog_warn!(
log,
"No secret was found! Use the environment variable PSLINK_SECRET to set one."
);
slog_warn!(
log,
"If you change the secret all passwords will be invalid"
);
slog_warn!(log, "Using an auto generated one for this run.");
warn!("No secret was found! Use the environment variable PSLINK_SECRET to set one.");
warn!("If you change the secret all passwords will be invalid");
warn!("Using an auto generated one for this run.");
} else {
slog_warn!(
log,
"The provided secret was too short. Using an autogenerated one."
)
warn!("The provided secret was too short. Using an autogenerated one.")
}
thread_rng()
@@ -195,8 +186,6 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
.parse::<pslink::Protocol>()
.expect("Failed to parse the protocol");
let log = log.new(slog_o!("host" => public_url.clone()));
crate::ServerConfig {
secret,
db,
@@ -205,7 +194,6 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
internal_ip,
port,
protocol,
log,
empty_forward_url,
brand_name,
}
@@ -214,16 +202,9 @@ async fn parse_args_to_config(config: ArgMatches<'_>, log: Logger) -> ServerConf
pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError> {
dotenv().ok();
// initiallize the logger
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 log = slog::Logger::root(drain, slog_o!("name" => "Pslink"));
// Print launch info
slog_info!(log, "Launching Pslink a 'Private short link generator'");
slog_trace!(log, "logging initialized");
info!("Launching Pslink a 'Private short link generator'");
trace!("logging initialized");
let app = generate_cli();
@@ -239,7 +220,7 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
.parse::<PathBuf>()
.expect("Failed to parse Database path.");
if !db.exists() {
slog_trace!(log, "No database file found {}", db.display());
trace!("No database file found {}", db.display());
if config.subcommand_matches("migrate-database").is_none() {
let msg = format!(
concat!(
@@ -249,17 +230,17 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
),
db.display()
);
slog_error!(log, "{}", msg);
error!("{}", msg);
eprintln!("{}", msg);
return Ok(None);
}
slog_trace!(log, "Creating database: {}", db.display());
trace!("Creating database: {}", db.display());
// create an empty database file. The if above makes sure that this file does not exist.
File::create(db)?;
};
let server_config: crate::ServerConfig = parse_args_to_config(config.clone(), log).await;
let server_config: crate::ServerConfig = parse_args_to_config(config.clone()).await;
if let Some(_migrate_config) = config.subcommand_matches("generate-env") {
return match generate_env_file(&server_config) {
@@ -284,21 +265,15 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
let num_users = User::count_admins(&server_config).await?;
if num_users.number < 1 {
slog_warn!(
&server_config.log,
concat!(
"No admin user created you will not be",
" able to do anything as the service is invite only.",
" Create a user with `pslink create-admin`"
)
);
warn!(concat!(
"No admin user created you will not be",
" able to do anything as the service is invite only.",
" Create a user with `pslink create-admin`"
));
} else {
slog_trace!(&server_config.log, "At least one admin user is found.");
trace!("At least one admin user is found.");
}
slog_trace!(
&server_config.log,
"Initialization finished starting the service."
);
trace!("Initialization finished starting the service.");
Ok(Some(server_config))
} else {
println!("{}", config.usage());
@@ -308,7 +283,7 @@ pub(crate) async fn setup() -> Result<Option<crate::ServerConfig>, ServerError>
/// Interactively create a new admin user.
async fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
slog_info!(&config.log, "Creating an admin user.");
info!("Creating an admin user.");
let sin = io::stdin();
// wait for logging:
@@ -325,11 +300,9 @@ async fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
print!("Please enter the password for {}: ", new_username);
io::stdout().flush().unwrap();
let password = rpassword::read_password().unwrap();
slog_info!(
&config.log,
info!(
"Creating {} ({}) with given password ",
&new_username,
&new_email
&new_username, &new_email
);
let new_admin = NewUser::new(new_username.clone(), new_email.clone(), &password, config)?;
@@ -338,14 +311,13 @@ async fn create_admin(config: &ServerConfig) -> Result<(), ServerError> {
let created_user = User::get_user_by_name(&new_username, config).await?;
created_user.toggle_admin(config).await?;
slog_info!(&config.log, "Admin user created: {}", new_username);
info!("Admin user created: {}", new_username);
Ok(())
}
async fn apply_migrations(config: &ServerConfig) -> Result<(), ServerError> {
slog_info!(
config.log,
info!(
"Creating a database file and running the migrations in the file {}:",
&config.db.display()
);
@@ -355,22 +327,13 @@ async fn apply_migrations(config: &ServerConfig) -> Result<(), ServerError> {
fn generate_env_file(server_config: &ServerConfig) -> Result<(), ServerError> {
if std::path::Path::new(".env").exists() {
slog_error!(
server_config.log,
"ERROR: There already is a .env file - ABORT!"
)
error!("ERROR: There already is a .env file - ABORT!")
} else {
slog_info!(
server_config.log,
"Creating a .env file with default options"
);
slog_info!(
server_config.log,
concat!(
"The SECRET_KEY variable is used for password encryption.",
"If it is changed all existing passwords are invalid."
)
);
info!("Creating a .env file with default options");
info!(concat!(
"The SECRET_KEY variable is used for password encryption.",
"If it is changed all existing passwords are invalid."
));
let mut file = std::fs::File::create(".env")?;
let conf_file_content = server_config.to_env_strings();
@@ -379,7 +342,7 @@ fn generate_env_file(server_config: &ServerConfig) -> Result<(), ServerError> {
file.write_all(l.as_bytes())
.expect("failed to write .env file")
});
slog_info!(server_config.log, "Successfully created the env file!")
info!("Successfully created the env file!")
}
Ok(())
}
+40 -29
View File
@@ -1,19 +1,4 @@
extern crate sqlx;
#[allow(unused_imports)]
#[macro_use(
slog_o,
slog_trace,
slog_info,
slog_warn,
slog_error,
slog_log,
slog_record,
slog_record_static,
slog_b,
slog_kv
)]
extern crate slog;
extern crate slog_async;
mod cli;
mod views;
@@ -26,6 +11,33 @@ use tera::Tera;
use pslink::{ServerConfig, ServerError};
use tracing::instrument;
use tracing::{error, info, trace};
use tracing::{subscriber::set_global_default, Subscriber};
use tracing_actix_web::TracingLogger;
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
/// Compose multiple layers into a `tracing`'s subscriber.
pub fn get_subscriber(name: String, env_filter: String) -> impl Subscriber + Send + Sync {
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter));
let formatting_layer = BunyanFormattingLayer::new(name, std::io::stdout);
Registry::default()
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}
/// Register a subscriber as global default to process span data.
///
/// It should only be called once!
pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {
LogTracer::init().expect("Failed to set logger");
set_global_default(subscriber).expect("Failed to set subscriber");
}
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
static_loader! {
@@ -35,8 +47,10 @@ static_loader! {
};
}
#[instrument]
fn build_tera() -> Result<Tera> {
let mut tera = Tera::default();
tracing::info!("Tracing activated!");
// Add translation support
tera.register_function("fluent", FluentLoader::new(&*LOCALES));
@@ -86,29 +100,22 @@ fn build_tera() -> Result<Tera> {
#[allow(clippy::future_not_send, clippy::too_many_lines)]
async fn webservice(server_config: ServerConfig) -> Result<()> {
let host_port = format!("{}:{}", &server_config.internal_ip, &server_config.port);
let cfg = server_config.clone();
slog_info!(
cfg.log,
info!(
"Running on: {}://{}/admin/login/",
&server_config.protocol,
host_port
&server_config.protocol, host_port
);
slog_info!(
cfg.log,
info!(
"If the public url is set up correctly it should be accessible via: {}://{}/admin/login/",
&server_config.protocol,
&server_config.public_url
&server_config.protocol, &server_config.public_url
);
let tera = build_tera()?;
slog_trace!(cfg.log, "The tera templates are ready");
trace!("The tera templates are ready");
HttpServer::new(move || {
let generated = generate();
App::new()
.data(server_config.clone())
.wrap(actix_slog::StructuredLogger::new(
server_config.log.new(slog_o!("log_type" => "access")),
))
.wrap(TracingLogger)
.wrap(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
.name("auth-cookie")
@@ -191,7 +198,7 @@ async fn webservice(server_config: ServerConfig) -> Result<()> {
.bind(host_port)
.context("Failed to bind to port")
.map_err(|e| {
slog_error!(cfg.log, "Failed to bind to port!");
error!("Failed to bind to port!");
e
})?
.run()
@@ -199,8 +206,12 @@ async fn webservice(server_config: ServerConfig) -> Result<()> {
.context("Failed to run the webservice")
}
#[instrument]
#[actix_web::main]
async fn main() -> std::result::Result<(), ServerError> {
let subscriber = get_subscriber("app".into(), "info".into());
init_subscriber(subscriber);
match cli::setup().await {
Ok(Some(server_config)) => webservice(server_config).await.map_err(|e| {
println!("{:?}", e);
+13 -16
View File
@@ -15,6 +15,7 @@ use image::{DynamicImage, ImageOutputFormat, Luma};
use qrcode::{render::svg, QrCode};
use queries::{authenticate, Role};
use tera::{Context, Tera};
use tracing::{info, trace, warn};
use pslink::forms::LinkForm;
use pslink::models::{LoginUser, NewUser};
@@ -150,7 +151,7 @@ pub async fn view_profile(
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Viewing Profile!");
info!("Viewing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config).await {
let mut data = Context::new();
data.insert("user", &query.user);
@@ -177,7 +178,7 @@ pub async fn edit_profile(
id: Identity,
user_id: web::Path<String>,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Editing Profile!");
info!("Editing Profile!");
if let Ok(query) = queries::get_user(&id, &user_id.0, &config).await {
let mut data = Context::new();
data.insert("user", &query.user);
@@ -259,7 +260,7 @@ pub async fn process_signup(
config: web::Data<pslink::ServerConfig>,
id: Identity,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Creating a User: {:?}", &data);
info!("Creating a User: {:?}", &data);
match queries::create_user(&id, &data, &config).await {
Ok(item) => {
Ok(HttpResponse::Ok().body(format!("Successfully saved user: {}", item.item.username)))
@@ -296,7 +297,7 @@ pub async fn login(
req: HttpRequest,
) -> Result<HttpResponse, ServerError> {
let language_code = detect_language(&req)?;
slog_info!(config.log, "Detected languagecode: {}", &language_code);
info!("Detected languagecode: {}", &language_code);
let mut data = Context::new();
data.insert("title", "Login");
data.insert("language", &language_code);
@@ -305,8 +306,7 @@ pub async fn login(
if let Ok(r) = authenticate(&id, &config).await {
match r {
Role::Admin { user } | Role::Regular { user } => {
slog_trace!(
config.log,
trace!(
"This user ({}) is already logged in redirecting to /admin/index/",
user.username
);
@@ -315,7 +315,7 @@ pub async fn login(
Role::Disabled | Role::NotAuthenticated => (),
}
}
slog_warn!(config.log, "Invalid user session. The user might be deleted or something tampered with the cookies.");
warn!("Invalid user session. The user might be deleted or something tampered with the cookies.");
id.forget();
}
@@ -340,7 +340,7 @@ pub async fn process_login(
.verify()?;
if valid {
slog_info!(config.log, "Log-in of user: {}", &u.username);
info!("Log-in of user: {}", &u.username);
let session_token = u.username;
id.remember(session_token);
Ok(redirect_builder("/admin/index/"))
@@ -349,7 +349,7 @@ pub async fn process_login(
}
}
Err(e) => {
slog_info!(config.log, "Failed to login: {}", e);
info!("Failed to login: {}", e);
Ok(redirect_builder("/admin/login/"))
}
}
@@ -366,21 +366,18 @@ pub async fn redirect(
data: web::Path<String>,
req: HttpRequest,
) -> Result<HttpResponse, ServerError> {
slog_info!(config.log, "Redirecting to {:?}", data);
info!("Redirecting to {:?}", data);
let link = queries::get_link_simple(&data.0, &config).await;
slog_info!(config.log, "link: {:?}", link);
info!("link: {:?}", link);
match link {
Ok(link) => {
queries::click_link(link.id, &config).await?;
Ok(redirect_builder(&link.target))
}
Err(ServerError::Database(e)) => {
slog_info!(
config.log,
info!(
"Link was not found: http://{}/{} \n {}",
&config.public_url,
&data.0,
e
&config.public_url, &data.0, e
);
let mut data = Context::new();
data.insert("title", "Wurde gel\u{f6}scht");
-15
View File
@@ -1,18 +1,4 @@
extern crate sqlx;
#[allow(unused_imports)]
#[macro_use(
slog_o,
slog_info,
slog_warn,
slog_error,
slog_log,
slog_record,
slog_record_static,
slog_b,
slog_kv
)]
extern crate slog;
extern crate slog_async;
pub mod forms;
pub mod models;
@@ -171,7 +157,6 @@ pub struct ServerConfig {
pub internal_ip: String,
pub port: u32,
pub protocol: Protocol,
pub log: slog::Logger,
pub empty_forward_url: String,
pub brand_name: String,
}
+1 -1
View File
@@ -197,7 +197,7 @@ impl Link {
let link = sqlx::query_as!(Self, "Select * from links where code = ? ", code)
.fetch_one(&server_config.db_pool)
.await;
slog_info!(server_config.log, "Found link: {:?}", &link);
tracing::info!("Found link: {:?}", &link);
link.map_err(ServerError::Database)
}
+13 -21
View File
@@ -1,6 +1,7 @@
use actix_identity::Identity;
use actix_web::web;
use serde::Serialize;
use tracing::info;
use super::models::{Count, Link, NewUser, User};
use crate::{
@@ -170,7 +171,7 @@ pub async fn get_user(
server_config: &ServerConfig,
) -> Result<Item<User>, ServerError> {
if let Ok(uid) = user_id.parse::<i64>() {
slog_info!(server_config.log, "Getting user {}", uid);
info!("Getting user {}", uid);
let auth = authenticate(id, server_config).await?;
if auth.admin_or_self(uid) {
match auth {
@@ -214,7 +215,7 @@ pub async fn create_user(
data: &web::Form<NewUser>,
server_config: &ServerConfig,
) -> Result<Item<User>, ServerError> {
slog_info!(server_config.log, "Creating a User: {:?}", &data);
info!("Creating a User: {:?}", &data);
let auth = authenticate(id, server_config).await?;
match auth {
Role::Admin { user } => {
@@ -258,7 +259,7 @@ pub async fn update_user(
if auth.admin_or_self(uid) {
match auth {
Role::Admin { .. } | Role::Regular { .. } => {
slog_info!(server_config.log, "Updating userinfo: ");
info!("Updating userinfo: ");
let password = if data.password.len() > 3 {
NewUser::hash_password(&data.password, server_config)?
} else {
@@ -303,21 +304,17 @@ pub async fn toggle_admin(
let auth = authenticate(id, server_config).await?;
match auth {
Role::Admin { .. } => {
slog_info!(server_config.log, "Changing administrator priviledges: ");
info!("Changing administrator priviledges: ");
let unchanged_user = User::get_user(uid, server_config).await?;
let old = unchanged_user.role;
unchanged_user.toggle_admin(server_config).await?;
slog_info!(server_config.log, "Toggling role: old was {}", old);
info!("Toggling role: old was {}", old);
let changed_user = User::get_user(uid, server_config).await?;
slog_info!(
server_config.log,
"Toggled role: new is {}",
changed_user.role
);
info!("Toggled role: new is {}", changed_user.role);
Ok(Item {
user: changed_user.clone(),
item: changed_user,
@@ -382,10 +379,10 @@ pub async fn get_link_simple(
link_code: &str,
server_config: &ServerConfig,
) -> Result<Link, ServerError> {
slog_info!(server_config.log, "Getting link for {:?}", link_code);
info!("Getting link for {:?}", link_code);
let link = Link::get_link_by_code(link_code, server_config).await?;
slog_info!(server_config.log, "Foun d link for {:?}", link);
info!("Foun d link for {:?}", link);
Ok(link)
}
@@ -394,7 +391,7 @@ pub async fn get_link_simple(
/// # Errors
/// Fails with [`ServerError`] if access to the database fails.
pub async fn click_link(link_id: i64, server_config: &ServerConfig) -> Result<(), ServerError> {
slog_info!(server_config.log, "Clicking on {:?}", link_id);
info!("Clicking on {:?}", link_id);
let new_click = NewClick::new(link_id);
new_click.insert_click(server_config).await?;
Ok(())
@@ -429,12 +426,7 @@ pub async fn update_link(
data: web::Form<LinkForm>,
server_config: &ServerConfig,
) -> Result<Item<Link>, ServerError> {
slog_info!(
server_config.log,
"Changing link to: {:?} {:?}",
&data,
&link_code
);
info!("Changing link to: {:?} {:?}", &data, &link_code);
let auth = authenticate(id, server_config).await?;
match auth {
Role::Admin { .. } | Role::Regular { .. } => {
@@ -472,9 +464,9 @@ pub async fn create_link(
match auth {
Role::Admin { user } | Role::Regular { user } => {
let code = data.code.clone();
slog_info!(server_config.log, "Creating link for: {}", &code);
info!("Creating link for: {}", &code);
let new_link = NewLink::from_link_form(data.into_inner(), user.id);
slog_info!(server_config.log, "Creating link for: {:?}", &new_link);
info!("Creating link for: {:?}", &new_link);
new_link.insert(server_config).await?;
let new_link = get_link_simple(&code, server_config).await?;