From cf8f27ce0f21eaa86f27f2e9ada0ab3fd515e3ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 2 Nov 2016 19:42:21 +0100 Subject: [PATCH] Initializing logger for each command (#3090) * Initializing logger for each command * Single logger setup * Whitespace [ci:skip] --- logger/src/lib.rs | 2 +- parity/blockchain.rs | 12 ++------- parity/configuration.rs | 59 +++++++++++++++++++++++------------------ parity/main.rs | 15 ++++++----- parity/run.rs | 9 +++---- parity/signer.rs | 9 +++++-- parity/snapshot.rs | 5 ---- 7 files changed, 55 insertions(+), 56 deletions(-) diff --git a/logger/src/lib.rs b/logger/src/lib.rs index a79f6fc43..7e13f406c 100644 --- a/logger/src/lib.rs +++ b/logger/src/lib.rs @@ -36,7 +36,7 @@ use regex::Regex; use util::RotatingLogger; use util::log::Colour; -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] pub struct Config { pub mode: Option, pub color: bool, diff --git a/parity/blockchain.rs b/parity/blockchain.rs index 2e0fb4233..8e84c488c 100644 --- a/parity/blockchain.rs +++ b/parity/blockchain.rs @@ -21,7 +21,6 @@ use std::time::{Instant, Duration}; use std::thread::sleep; use std::sync::Arc; use rustc_serialize::hex::FromHex; -use ethcore_logger::{setup_log, Config as LogConfig}; use io::{PanicHandler, ForwardPanic}; use util::{ToPretty, Uint}; use rlp::PayloadInfo; @@ -71,7 +70,6 @@ pub enum BlockchainCmd { #[derive(Debug, PartialEq)] pub struct ImportBlockchain { pub spec: SpecType, - pub logger_config: LogConfig, pub cache_config: CacheConfig, pub dirs: Directories, pub file_path: Option, @@ -85,12 +83,12 @@ pub struct ImportBlockchain { pub fat_db: Switch, pub vm_type: VMType, pub check_seal: bool, + pub with_color: bool, } #[derive(Debug, PartialEq)] pub struct ExportBlockchain { pub spec: SpecType, - pub logger_config: LogConfig, pub cache_config: CacheConfig, pub dirs: Directories, pub file_path: Option, @@ -120,9 +118,6 @@ fn execute_import(cmd: ImportBlockchain) -> Result { // Setup panic handler let panic_handler = PanicHandler::new_in_arc(); - // Setup logging - let _logger = setup_log(&cmd.logger_config); - // create dirs used by parity try!(cmd.dirs.create_dirs()); @@ -196,7 +191,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result { } }; - let informant = Informant::new(client.clone(), None, None, None, cmd.logger_config.color); + let informant = Informant::new(client.clone(), None, None, None, cmd.with_color); try!(service.register_io_handler(Arc::new(ImportIoHandler { info: Arc::new(informant), @@ -269,9 +264,6 @@ fn execute_export(cmd: ExportBlockchain) -> Result { // Setup panic handler let panic_handler = PanicHandler::new_in_arc(); - // Setup logging - let _logger = setup_log(&cmd.logger_config); - // create dirs used by parity try!(cmd.dirs.create_dirs()); diff --git a/parity/configuration.rs b/parity/configuration.rs index 1972b9f1e..8c9a4d0bd 100644 --- a/parity/configuration.rs +++ b/parity/configuration.rs @@ -35,7 +35,7 @@ use params::{ResealPolicy, AccountsConfig, GasPricerConfig, MinerExtras}; use ethcore_logger::Config as LogConfig; use dir::Directories; use dapps::Configuration as DappsConfiguration; -use signer::Configuration as SignerConfiguration; +use signer::{Configuration as SignerConfiguration, SignerCommand}; use run::RunCmd; use blockchain::{BlockchainCmd, ImportBlockchain, ExportBlockchain, DataFormat}; use presale::ImportWallet; @@ -49,11 +49,16 @@ pub enum Cmd { Account(AccountCmd), ImportPresaleWallet(ImportWallet), Blockchain(BlockchainCmd), - SignerToken(String), + SignerToken(SignerCommand), Snapshot(SnapshotCommand), Hash(Option), } +pub struct Execute { + pub logger: LogConfig, + pub cmd: Cmd, +} + #[derive(Debug, PartialEq)] pub struct Configuration { pub args: Args, @@ -70,7 +75,7 @@ impl Configuration { Ok(config) } - pub fn into_command(self) -> Result { + pub fn into_command(self) -> Result { let dirs = self.directories(); let pruning = try!(self.args.flag_pruning.parse()); let pruning_history = self.args.flag_pruning_history; @@ -99,7 +104,9 @@ impl Configuration { let cmd = if self.args.flag_version { Cmd::Version } else if self.args.cmd_signer && self.args.cmd_new_token { - Cmd::SignerToken(dirs.signer) + Cmd::SignerToken(SignerCommand { + path: dirs.signer + }) } else if self.args.cmd_tools && self.args.cmd_hash { Cmd::Hash(self.args.arg_file) } else if self.args.cmd_account { @@ -141,7 +148,6 @@ impl Configuration { } else if self.args.cmd_import { let import_cmd = ImportBlockchain { spec: spec, - logger_config: logger_config, cache_config: cache_config, dirs: dirs, file_path: self.args.arg_file.clone(), @@ -155,12 +161,12 @@ impl Configuration { fat_db: fat_db, vm_type: vm_type, check_seal: !self.args.flag_no_seal_check, + with_color: logger_config.color, }; Cmd::Blockchain(BlockchainCmd::Import(import_cmd)) } else if self.args.cmd_export { let export_cmd = ExportBlockchain { spec: spec, - logger_config: logger_config, cache_config: cache_config, dirs: dirs, file_path: self.args.arg_file.clone(), @@ -184,7 +190,6 @@ impl Configuration { spec: spec, pruning: pruning, pruning_history: pruning_history, - logger_config: logger_config, mode: mode, tracing: tracing, fat_db: fat_db, @@ -202,7 +207,6 @@ impl Configuration { spec: spec, pruning: pruning, pruning_history: pruning_history, - logger_config: logger_config, mode: mode, tracing: tracing, fat_db: fat_db, @@ -227,7 +231,7 @@ impl Configuration { pruning: pruning, pruning_history: pruning_history, daemon: daemon, - logger_config: logger_config, + logger_config: logger_config.clone(), miner_options: miner_options, http_conf: http_conf, ipc_conf: ipc_conf, @@ -258,7 +262,10 @@ impl Configuration { Cmd::Run(run_cmd) }; - Ok(cmd) + Ok(Execute { + logger: logger_config, + cmd: cmd, + }) } fn enable_network(&self, mode: &Mode) -> bool { @@ -684,7 +691,7 @@ mod tests { use ethcore::miner::{MinerOptions, PrioritizationStrategy}; use helpers::{replace_home, default_network_config}; use run::RunCmd; - use signer::Configuration as SignerConfiguration; + use signer::{Configuration as SignerConfiguration, SignerCommand}; use blockchain::{BlockchainCmd, ImportBlockchain, ExportBlockchain, DataFormat}; use presale::ImportWallet; use account::{AccountCmd, NewAccount, ImportAccounts}; @@ -705,14 +712,14 @@ mod tests { fn test_command_version() { let args = vec!["parity", "--version"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Version); + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Version); } #[test] fn test_command_account_new() { let args = vec!["parity", "account", "new"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Account(AccountCmd::New(NewAccount { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Account(AccountCmd::New(NewAccount { iterations: 10240, path: replace_home("$HOME/.parity/keys"), password_file: None, @@ -723,16 +730,16 @@ mod tests { fn test_command_account_list() { let args = vec!["parity", "account", "list"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Account( - AccountCmd::List(replace_home("$HOME/.parity/keys"))) - ); + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Account( + AccountCmd::List(replace_home("$HOME/.parity/keys")), + )); } #[test] fn test_command_account_import() { let args = vec!["parity", "account", "import", "my_dir", "another_dir"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Account(AccountCmd::Import(ImportAccounts { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Account(AccountCmd::Import(ImportAccounts { from: vec!["my_dir".into(), "another_dir".into()], to: replace_home("$HOME/.parity/keys"), }))); @@ -742,7 +749,7 @@ mod tests { fn test_command_wallet_import() { let args = vec!["parity", "wallet", "import", "my_wallet.json", "--password", "pwd"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::ImportPresaleWallet(ImportWallet { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::ImportPresaleWallet(ImportWallet { iterations: 10240, path: replace_home("$HOME/.parity/keys"), wallet_path: "my_wallet.json".into(), @@ -754,9 +761,8 @@ mod tests { fn test_command_blockchain_import() { let args = vec!["parity", "import", "blockchain.json"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Blockchain(BlockchainCmd::Import(ImportBlockchain { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Blockchain(BlockchainCmd::Import(ImportBlockchain { spec: Default::default(), - logger_config: Default::default(), cache_config: Default::default(), dirs: Default::default(), file_path: Some("blockchain.json".into()), @@ -770,6 +776,7 @@ mod tests { fat_db: Default::default(), vm_type: VMType::Interpreter, check_seal: true, + with_color: true, }))); } @@ -777,9 +784,8 @@ mod tests { fn test_command_blockchain_export() { let args = vec!["parity", "export", "blockchain.json"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Blockchain(BlockchainCmd::Export(ExportBlockchain { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Blockchain(BlockchainCmd::Export(ExportBlockchain { spec: Default::default(), - logger_config: Default::default(), cache_config: Default::default(), dirs: Default::default(), file_path: Some("blockchain.json".into()), @@ -801,9 +807,8 @@ mod tests { fn test_command_blockchain_export_with_custom_format() { let args = vec!["parity", "export", "--format", "hex", "blockchain.json"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Blockchain(BlockchainCmd::Export(ExportBlockchain { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Blockchain(BlockchainCmd::Export(ExportBlockchain { spec: Default::default(), - logger_config: Default::default(), cache_config: Default::default(), dirs: Default::default(), file_path: Some("blockchain.json".into()), @@ -826,14 +831,16 @@ mod tests { let args = vec!["parity", "signer", "new-token"]; let conf = parse(&args); let expected = replace_home("$HOME/.parity/signer"); - assert_eq!(conf.into_command().unwrap(), Cmd::SignerToken(expected)); + assert_eq!(conf.into_command().unwrap().cmd, Cmd::SignerToken(SignerCommand { + path: expected, + })); } #[test] fn test_run_cmd() { let args = vec!["parity"]; let conf = parse(&args); - assert_eq!(conf.into_command().unwrap(), Cmd::Run(RunCmd { + assert_eq!(conf.into_command().unwrap().cmd, Cmd::Run(RunCmd { cache_config: Default::default(), dirs: Default::default(), spec: Default::default(), diff --git a/parity/main.rs b/parity/main.rs index 83598231a..8fe752216 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -118,8 +118,9 @@ use std::io::BufReader; use std::fs::File; use util::sha3::sha3; use cli::Args; -use configuration::{Cmd, Configuration}; +use configuration::{Cmd, Execute, Configuration}; use deprecated::find_deprecated; +use ethcore_logger::setup_log; fn print_hash_of(maybe_file: Option) -> Result { if let Some(file) = maybe_file { @@ -131,10 +132,12 @@ fn print_hash_of(maybe_file: Option) -> Result { } } -fn execute(command: Cmd) -> Result { - match command { +fn execute(command: Execute) -> Result { + let logger = setup_log(&command.logger).expect("Logger is initialized only once; qed"); + + match command.cmd { Cmd::Run(run_cmd) => { - try!(run::execute(run_cmd)); + try!(run::execute(run_cmd, logger)); Ok("".into()) }, Cmd::Version => Ok(Args::print_version()), @@ -142,7 +145,7 @@ fn execute(command: Cmd) -> Result { Cmd::Account(account_cmd) => account::execute(account_cmd), Cmd::ImportPresaleWallet(presale_cmd) => presale::execute(presale_cmd), Cmd::Blockchain(blockchain_cmd) => blockchain::execute(blockchain_cmd), - Cmd::SignerToken(path) => signer::new_token(path), + Cmd::SignerToken(signer_cmd) => signer::execute(signer_cmd), Cmd::Snapshot(snapshot_cmd) => snapshot::execute(snapshot_cmd), } } @@ -198,7 +201,7 @@ fn sync_main() -> bool { fn main() { // Always print backtrace on panic. ::std::env::set_var("RUST_BACKTRACE", "1"); - + if sync_main() { return; } diff --git a/parity/run.rs b/parity/run.rs index 8a3ae06ec..b0f8dce68 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -17,11 +17,11 @@ use std::sync::{Arc, Mutex, Condvar}; use ctrlc::CtrlC; use fdlimit::raise_fd_limit; -use ethcore_logger::{Config as LogConfig, setup_log}; use ethcore_rpc::{NetworkSettings, is_major_importing}; use ethsync::NetworkConfiguration; -use util::{Colour, version, U256}; +use util::{Colour, version, U256, RotatingLogger}; use io::{MayPanic, ForwardPanic, PanicHandler}; +use ethcore_logger::{Config as LogConfig}; use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, ChainNotify, BlockChainClient}; use ethcore::service::ClientService; use ethcore::account_provider::AccountProvider; @@ -93,13 +93,10 @@ pub struct RunCmd { pub check_seal: bool, } -pub fn execute(cmd: RunCmd) -> Result<(), String> { +pub fn execute(cmd: RunCmd, logger: Arc) -> Result<(), String> { // set up panic handler let panic_handler = PanicHandler::new_in_arc(); - // set up logger - let logger = try!(setup_log(&cmd.logger_config)); - // increase max number of open files raise_fd_limit(); diff --git a/parity/signer.rs b/parity/signer.rs index 5097192ad..b3047c739 100644 --- a/parity/signer.rs +++ b/parity/signer.rs @@ -68,8 +68,13 @@ fn codes_path(path: String) -> PathBuf { p } -pub fn new_token(path: String) -> Result { - generate_new_token(path) +#[derive(Debug, PartialEq)] +pub struct SignerCommand { + pub path: String, +} + +pub fn execute(cmd: SignerCommand) -> Result { + generate_new_token(cmd.path) .map(|code| format!("This key code will authorise your System Signer UI: {}", Colour::White.bold().paint(code))) .map_err(|err| format!("Error generating token: {:?}", err)) } diff --git a/parity/snapshot.rs b/parity/snapshot.rs index 4cd972230..85e1f90eb 100644 --- a/parity/snapshot.rs +++ b/parity/snapshot.rs @@ -20,7 +20,6 @@ use std::time::Duration; use std::path::{Path, PathBuf}; use std::sync::Arc; -use ethcore_logger::{setup_log, Config as LogConfig}; use ethcore::snapshot::{Progress, RestorationStatus, SnapshotService as SS}; use ethcore::snapshot::io::{SnapshotReader, PackedReader, PackedWriter}; use ethcore::snapshot::service::Service as SnapshotService; @@ -55,7 +54,6 @@ pub struct SnapshotCommand { pub spec: SpecType, pub pruning: Pruning, pub pruning_history: u64, - pub logger_config: LogConfig, pub mode: Mode, pub tracing: Switch, pub fat_db: Switch, @@ -141,9 +139,6 @@ impl SnapshotCommand { // load user defaults let user_defaults = try!(UserDefaults::load(&user_defaults_path)); - // Setup logging - let _logger = setup_log(&self.logger_config); - fdlimit::raise_fd_limit(); // select pruning algorithm