Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Commit

Permalink
Initializing logger for each command (#3090)
Browse files Browse the repository at this point in the history
* Initializing logger for each command

* Single logger setup

* Whitespace [ci:skip]
  • Loading branch information
tomusdrw authored and gavofyork committed Nov 2, 2016
1 parent b3d502b commit cf8f27c
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 56 deletions.
2 changes: 1 addition & 1 deletion logger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub color: bool,
Expand Down
12 changes: 2 additions & 10 deletions parity/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,
Expand All @@ -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<String>,
Expand Down Expand Up @@ -120,9 +118,6 @@ fn execute_import(cmd: ImportBlockchain) -> Result<String, String> {
// 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());

Expand Down Expand Up @@ -196,7 +191,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<String, String> {
}
};

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),
Expand Down Expand Up @@ -269,9 +264,6 @@ fn execute_export(cmd: ExportBlockchain) -> Result<String, String> {
// 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());

Expand Down
59 changes: 33 additions & 26 deletions parity/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -49,11 +49,16 @@ pub enum Cmd {
Account(AccountCmd),
ImportPresaleWallet(ImportWallet),
Blockchain(BlockchainCmd),
SignerToken(String),
SignerToken(SignerCommand),
Snapshot(SnapshotCommand),
Hash(Option<String>),
}

pub struct Execute {
pub logger: LogConfig,
pub cmd: Cmd,
}

#[derive(Debug, PartialEq)]
pub struct Configuration {
pub args: Args,
Expand All @@ -70,7 +75,7 @@ impl Configuration {
Ok(config)
}

pub fn into_command(self) -> Result<Cmd, String> {
pub fn into_command(self) -> Result<Execute, String> {
let dirs = self.directories();
let pruning = try!(self.args.flag_pruning.parse());
let pruning_history = self.args.flag_pruning_history;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
Expand All @@ -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(),
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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};
Expand All @@ -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,
Expand All @@ -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"),
})));
Expand All @@ -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(),
Expand All @@ -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()),
Expand All @@ -770,16 +776,16 @@ mod tests {
fat_db: Default::default(),
vm_type: VMType::Interpreter,
check_seal: true,
with_color: true,
})));
}

#[test]
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()),
Expand All @@ -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()),
Expand All @@ -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(),
Expand Down
15 changes: 9 additions & 6 deletions parity/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>) -> Result<String, String> {
if let Some(file) = maybe_file {
Expand All @@ -131,18 +132,20 @@ fn print_hash_of(maybe_file: Option<String>) -> Result<String, String> {
}
}

fn execute(command: Cmd) -> Result<String, String> {
match command {
fn execute(command: Execute) -> Result<String, String> {
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()),
Cmd::Hash(maybe_file) => print_hash_of(maybe_file),
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),
}
}
Expand Down Expand Up @@ -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;
}
Expand Down
9 changes: 3 additions & 6 deletions parity/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<RotatingLogger>) -> 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();

Expand Down
9 changes: 7 additions & 2 deletions parity/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,13 @@ fn codes_path(path: String) -> PathBuf {
p
}

pub fn new_token(path: String) -> Result<String, String> {
generate_new_token(path)
#[derive(Debug, PartialEq)]
pub struct SignerCommand {
pub path: String,
}

pub fn execute(cmd: SignerCommand) -> Result<String, String> {
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))
}
Expand Down
Loading

0 comments on commit cf8f27c

Please sign in to comment.