Просмотр исходного кода

Move to simpler logging system.

parazyd 4 лет назад
Родитель
Сommit
10bb7d3ec6
7 измененных файлов с 96 добавлено и 153 удалено
  1. 10 29
      src/bin/cashierd.rs
  2. 20 42
      src/bin/darkfid.rs
  3. 15 34
      src/bin/drk.rs
  4. 34 39
      src/bin/gatewayd.rs
  5. 2 1
      src/bin/mint.rs
  6. 8 0
      src/error.rs
  7. 7 8
      src/util.rs

+ 10 - 29
src/bin/cashierd.rs

@@ -17,10 +17,6 @@ use drk::{
 use clap::clap_app;
 use log::*;
 use serde_json::{json, Value};
-use simplelog::{
-    CombinedLogger, Config as SimLogConfig, ConfigBuilder, LevelFilter, TermLogger, TerminalMode,
-    WriteLogger,
-};
 
 use async_executor::Executor;
 use ff::Field;
@@ -372,35 +368,20 @@ async fn main() -> Result<()> {
     )
     .get_matches();
 
-    let config_path: PathBuf;
-
-    if args.is_present("CONFIG") {
-        config_path = PathBuf::from(args.value_of("CONFIG").unwrap());
+    let config_path = if args.is_present("CONFIG") {
+        PathBuf::from(args.value_of("CONFIG").unwrap())
     } else {
-        config_path = join_config_path(&PathBuf::from("cashierd.toml"))?;
-    }
-
-    let ex = Arc::new(Executor::new());
-
-    let cashierd = Cashierd::new(args.clone().is_present("verbose"), ex.clone(), config_path)?;
+        join_config_path(&PathBuf::from("cashierd.toml"))?
+    };
 
-    let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
-    let debug_level = if args.is_present("verbose") {
-        LevelFilter::Debug
+    let loglevel = if args.is_present("verbose") {
+        log::Level::Debug
     } else {
-        LevelFilter::Off
+        log::Level::Info
     };
 
-    let log_path = cashierd.clone().config.log_path;
-    CombinedLogger::init(vec![
-        TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
-        WriteLogger::new(
-            LevelFilter::Debug,
-            SimLogConfig::default(),
-            std::fs::File::create(log_path).unwrap(),
-        ),
-    ])
-    .unwrap();
-
+    simple_logger::init_with_level(loglevel)?;
+    let ex = Arc::new(Executor::new());
+    let cashierd = Cashierd::new(args.clone().is_present("verbose"), ex.clone(), config_path)?;
     cashierd.start().await
 }

+ 20 - 42
src/bin/darkfid.rs

@@ -1,14 +1,9 @@
-use std::path::PathBuf;
-use std::sync::Arc;
-
 use async_trait::async_trait;
 use clap::clap_app;
 use log::debug;
 use serde_json::{json, Value};
-use simplelog::{
-    CombinedLogger, Config as SimLogConfig, ConfigBuilder, LevelFilter, TermLogger, TerminalMode,
-    WriteLogger,
-};
+use std::path::PathBuf;
+use std::sync::Arc;
 
 use drk::{
     cli::{Config, DarkfidConfig},
@@ -25,7 +20,6 @@ use drk::{
 
 #[derive(Clone)]
 struct Darkfid {
-    verbose: bool,
     config: DarkfidConfig,
     wallet: Arc<WalletDb>,
     tokenlist: Value,
@@ -60,7 +54,7 @@ impl RequestHandler for Darkfid {
 }
 
 impl Darkfid {
-    fn new(verbose: bool, config_path: PathBuf) -> Result<Self> {
+    fn new(config_path: PathBuf) -> Result<Self> {
         let config: DarkfidConfig = Config::<DarkfidConfig>::load(config_path)?;
         let wallet_path = join_config_path(&PathBuf::from("walletdb.db"))?;
         let wallet = WalletDb::new(&PathBuf::from(wallet_path.clone()), config.password.clone())?;
@@ -68,7 +62,6 @@ impl Darkfid {
         let tokenlist: Value = serde_json::from_str(&file_contents)?;
 
         Ok(Self {
-            verbose,
             config,
             wallet,
             tokenlist,
@@ -118,9 +111,7 @@ impl Darkfid {
         }
     }
 
-    // --> {"jsonrpc": "2.0", "method": "get_token_id",
-    //      "params": [token],
-    //      "id": 42}
+    // --> {"method": "get_token_id", "params": [token]}
     // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
     async fn get_token_id(&self, id: Value, params: Value) -> JsonResult {
         let args = params.as_array().unwrap();
@@ -151,8 +142,8 @@ impl Darkfid {
         unreachable!();
     }
 
-    // --> {"jsonrpc": "2.0", "method": "features", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": ["network": "btc", "sol"], "id": 42}
+    // --> {""method": "features", "params": []}
+    // <-- {"result": { "network": ["btc", "sol"] } }
     async fn features(&self, id: Value, _params: Value) -> JsonResult {
         // TODO: return a dictionary of features
         let req = jsonreq(json!("features"), json!([]));
@@ -171,9 +162,7 @@ impl Darkfid {
         }
     }
 
-    // --> {"jsonrpc": "2.0", "method": "deposit",
-    //      "params": [network, token, publickey],
-    //      "id": 42}
+    // --> {"method": "deposit", "params": [network, token, publickey]}
     // The publickey sent here is used so the cashier can know where to send
     // assets once the deposit is received.
     // <-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
@@ -194,7 +183,7 @@ impl Darkfid {
 
         // check if the token input is an ID
         // if not, find the associated ID
-        // TODO 
+        // TODO
         //let _token_id = self.clone().parse_token(tkn_str);
 
         // TODO: Optional sanity checking here, but cashier *must* do so too.
@@ -296,41 +285,30 @@ async fn main() -> Result<()> {
     )
     .get_matches();
 
-    let config_path: PathBuf;
-    if args.is_present("CONFIG") {
-        config_path = PathBuf::from(args.value_of("CONFIG").unwrap());
+    let config_path = if args.is_present("CONFIG") {
+        PathBuf::from(args.value_of("CONFIG").unwrap())
     } else {
-        config_path = join_config_path(&PathBuf::from("darkfid.toml"))?;
-    }
+        join_config_path(&PathBuf::from("darkfid.toml"))?
+    };
 
-    let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
-    let debug_level = if args.is_present("verbose") {
-        LevelFilter::Debug
+    let loglevel = if args.is_present("verbose") {
+        log::Level::Debug
     } else {
-        LevelFilter::Off
+        log::Level::Info
     };
 
-    let dfi = Darkfid::new(args.is_present("verbose"), config_path)?;
+    simple_logger::init_with_level(loglevel)?;
+
+    let dfi = Darkfid::new(config_path)?;
 
-    let cfg = RpcServerConfig {
+    let server_config = RpcServerConfig {
         socket_addr: dfi.config.clone().rpc_url,
         use_tls: dfi.config.use_tls,
         identity_path: dfi.config.clone().tls_identity_path,
         identity_pass: dfi.config.clone().tls_identity_password,
     };
 
-    let log_path = &dfi.config.log_path;
-    CombinedLogger::init(vec![
-        TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
-        WriteLogger::new(
-            LevelFilter::Debug,
-            SimLogConfig::default(),
-            std::fs::File::create(log_path).unwrap(),
-        ),
-    ])
-    .unwrap();
-
-    listen_and_serve(cfg, dfi).await
+    listen_and_serve(server_config, dfi).await
 }
 
 mod tests {

+ 15 - 34
src/bin/drk.rs

@@ -1,12 +1,7 @@
-use log::debug;
-use std::path::PathBuf;
-
 use clap::{clap_app, ArgMatches};
+use log::debug;
 use serde_json::{json, Value};
-use simplelog::{
-    CombinedLogger, Config as SimplelogConfig, ConfigBuilder, LevelFilter, TermLogger,
-    TerminalMode, WriteLogger,
-};
+use std::path::PathBuf;
 
 use drk::cli::{Config, DrkConfig};
 use drk::util::join_config_path;
@@ -23,7 +18,7 @@ impl Drk {
 
     async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
         let reply: JsonResult;
-        debug!(target: "DRK", "--> {:#?}", serde_json::to_string(&r)?);
+        debug!(target: "DRK", "--> {}", serde_json::to_string(&r)?);
         match jsonrpc::send_request(&self.url, json!(r)).await {
             Ok(v) => reply = v,
             Err(e) => return Err(e),
@@ -31,17 +26,17 @@ impl Drk {
 
         match reply {
             JsonResult::Resp(r) => {
-                debug!(target: "DRK", "<-- {:#?}", serde_json::to_string(&r)?);
+                debug!(target: "DRK", "<-- {}", serde_json::to_string(&r)?);
                 return Ok(r.result);
             }
 
             JsonResult::Err(e) => {
-                debug!(target: "DRK", "<-- {:#?}", serde_json::to_string(&e)?);
+                debug!(target: "DRK", "<-- {}", serde_json::to_string(&e)?);
                 return Err(Error::JsonRpcError(e.error.message.to_string()));
             }
 
             JsonResult::Notif(n) => {
-                debug!(target: "DRK", "<-- {:#?}", serde_json::to_string(&n)?);
+                debug!(target: "DRK", "<-- {}", serde_json::to_string(&n)?);
                 return Err(Error::JsonRpcError("Unexpected reply".to_string()));
             }
         }
@@ -260,34 +255,20 @@ async fn main() -> Result<()> {
     )
     .get_matches();
 
-    let config_path: PathBuf;
-    if args.is_present("CONFIG") {
-        config_path = PathBuf::from(args.value_of("CONFIG").unwrap());
+    let config_path = if args.is_present("CONFIG") {
+        PathBuf::from(args.value_of("CONFIG").unwrap())
     } else {
-        config_path = join_config_path(&PathBuf::from("drk.toml"))?;
-    }
-
-    let config = Config::<DrkConfig>::load(config_path)?;
-
-    let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
+        join_config_path(&PathBuf::from("drk.toml"))?
+    };
 
-    let debug_level = if args.is_present("verbose") {
-        LevelFilter::Debug
+    let loglevel = if args.is_present("verbose") {
+        log::Level::Debug
     } else {
-        LevelFilter::Off
+        log::Level::Info
     };
 
-    let log_path = config.log_path.clone();
-
-    CombinedLogger::init(vec![
-        TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
-        WriteLogger::new(
-            LevelFilter::Debug,
-            SimplelogConfig::default(),
-            std::fs::File::create(log_path).unwrap(),
-        ),
-    ])
-    .unwrap();
+    simple_logger::init_with_level(loglevel)?;
+    let config = Config::<DrkConfig>::load(config_path)?;
 
     start(&config, args).await
 }

+ 34 - 39
src/bin/gatewayd.rs

@@ -1,16 +1,17 @@
+use async_executor::Executor;
+use clap::clap_app;
+use easy_parallel::Parallel;
 use std::net::SocketAddr;
-use std::sync::Arc;
-
-use drk::blockchain::{rocks::columns, Rocks, RocksColumn};
-use drk::cli::{Config, GatewaydCli, GatewaydConfig};
-use drk::service::GatewayService;
-use drk::util::join_config_path;
-use drk::Result;
 use std::path::PathBuf;
+use std::sync::Arc;
 
-extern crate clap;
-use async_executor::Executor;
-use easy_parallel::Parallel;
+use drk::{
+    blockchain::{rocks::columns, Rocks, RocksColumn},
+    cli::{Config, GatewaydConfig},
+    service::GatewayService,
+    util::join_config_path,
+    Result,
+};
 
 async fn start(executor: Arc<Executor<'_>>, config: Arc<&GatewaydConfig>) -> Result<()> {
     let accept_addr: SocketAddr = config.accept_url.parse()?;
@@ -22,43 +23,37 @@ async fn start(executor: Arc<Executor<'_>>, config: Arc<&GatewaydConfig>) -> Res
 
     let gateway = GatewayService::new(accept_addr, pub_addr, rocks_slabstore_column)?;
 
-    gateway.start(executor.clone()).await?;
-    Ok(())
+    Ok(gateway.start(executor.clone()).await?)
 }
 
-fn main() -> Result<()> {
-    let ex = Arc::new(Executor::new());
-    let (signal, shutdown) = async_channel::unbounded::<()>();
+#[async_std::main]
+async fn main() -> Result<()> {
+    let args = clap_app!(gatewayd =>
+        (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
+        (@arg verbose: -v --verbose "Increase verbosity")
+    )
+    .get_matches();
 
-    let path = join_config_path(&PathBuf::from("gatewayd.toml"))?;
+    let config_path = if args.is_present("CONFIG") {
+        PathBuf::from(args.value_of("CONFIG").unwrap())
+    } else {
+        join_config_path(&PathBuf::from("gatewayd.toml"))?
+    };
 
-    let config: GatewaydConfig = Config::<GatewaydConfig>::load(path)?;
-
-    let config_ptr = Arc::new(&config);
+    let loglevel = if args.is_present("verbose") {
+        log::Level::Debug
+    } else {
+        log::Level::Info
+    };
 
-    let options = GatewaydCli::load()?;
+    simple_logger::init_with_level(loglevel)?;
 
-    {
-        use simplelog::*;
-        let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
+    let ex = Arc::new(Executor::new());
+    let (signal, shutdown) = async_channel::unbounded::<()>();
 
-        let debug_level = if options.verbose {
-            LevelFilter::Debug
-        } else {
-            LevelFilter::Off
-        };
+    let config: GatewaydConfig = Config::<GatewaydConfig>::load(config_path)?;
 
-        let log_path = config.log_path.clone();
-        CombinedLogger::init(vec![
-            TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
-            WriteLogger::new(
-                LevelFilter::Debug,
-                Config::default(),
-                std::fs::File::create(log_path).unwrap(),
-            ),
-        ])
-        .unwrap();
-    }
+    let config_ptr = Arc::new(&config);
 
     let ex2 = ex.clone();
 

+ 2 - 1
src/bin/mint.rs

@@ -7,7 +7,8 @@ use ff::{Field, PrimeField};
 use group::{Curve, Group};
 use rand::rngs::OsRng;
 
-type Result<T> = std::result::Result<T, failure::Error>;
+//type Result<T> = std::result::Result<T, failure::Error>;
+use drk::Result;
 
 // Unpack a value (such as jubjub::Fr) into 256 Scalar binary digits
 fn unpack<F: PrimeField>(value: F) -> Vec<Scalar> {

+ 8 - 0
src/error.rs

@@ -61,6 +61,7 @@ pub enum Error {
     Base58EncodeError(String),
     Base58DecodeError(String),
     ConfigNotFound,
+    SetLoggerError,
 }
 
 impl std::error::Error for Error {}
@@ -123,6 +124,7 @@ impl fmt::Display for Error {
             Error::ConfigNotFound => {
                 f.write_str("No config file detected. Please create a config file")
             }
+            Error::SetLoggerError => f.write_str("SetLoggerError"),
         }
     }
 }
@@ -266,3 +268,9 @@ impl From<bs58::decode::Error> for Error {
         Error::Base58DecodeError(err.to_string())
     }
 }
+
+impl From<log::SetLoggerError> for Error {
+    fn from(_err: log::SetLoggerError) -> Error {
+        Error::SetLoggerError
+    }
+}

+ 7 - 8
src/util.rs

@@ -1,12 +1,13 @@
-use crate::Result;
-use crate::serial::{deserialize, serialize};
-
-use sha2::{Digest, Sha256};
+use log::debug;
 use serde_json::Value;
-use log::*;
-
+use sha2::{Digest, Sha256};
 use std::path::{Path, PathBuf};
 
+use crate::{
+    serial::{deserialize, serialize},
+    Result,
+};
+
 pub fn join_config_path(file: &PathBuf) -> Result<PathBuf> {
     let mut path = PathBuf::new();
     let dfi_path = Path::new("darkfi");
@@ -55,8 +56,6 @@ pub fn parse_id(token: &Value) -> Result<jubjub::Fr> {
     unreachable!();
 }
 
-
-
 #[cfg(test)]
 mod tests {
     use crate::serial::{deserialize, serialize};