lunar-mining 5 лет назад
Родитель
Сommit
96955aa504
6 измененных файлов с 119 добавлено и 65 удалено
  1. 2 2
      src/bin/darkfid.rs
  2. 2 1
      src/bin/drk.rs
  3. 51 15
      src/bin/gatewayd.rs
  4. 25 8
      src/cli/client_cli/cli_config.rs
  5. 1 1
      src/cli/mod.rs
  6. 38 38
      src/cli/service_cli.rs

+ 2 - 2
src/bin/darkfid.rs

@@ -233,8 +233,8 @@ fn set_default() -> Result<DarkfidConfig> {
         connect_url: String::from("127.0.0.1:3333"),
         subscriber_url: String::from("127.0.0.1:4444"),
         rpc_url: String::from("127.0.0.1:8000"),
-        database_path: String::from("database_client.db"),
-        log_path: String::from("/tmp/darkfid_service_daemon.log"),
+        database_path: String::from("darkfid.db"),
+        log_path: String::from("/tmp/darkfid.log"),
         password: String::from(""),
     };
     Ok(config_file)

+ 2 - 1
src/bin/drk.rs

@@ -112,10 +112,11 @@ async fn start(config: Arc<&DrkConfig>, options: Arc<DrkCli>) -> Result<()> {
 fn set_default() -> Result<DrkConfig> {
     let config_file = DrkConfig {
         rpc_url: String::from("http://127.0.0.1:8000"),
-        log_path: String::from("/tmp/drk_cli.log"),
+        log_path: String::from("/tmp/drk.log"),
     };
     Ok(config_file)
 }
+
 fn main() -> Result<()> {
     use simplelog::*;
 

+ 51 - 15
src/bin/gatewayd.rs

@@ -1,8 +1,13 @@
 use std::net::SocketAddr;
+use std::str;
 use std::sync::Arc;
 
+use std::fs::OpenOptions;
+use std::io::Read;
+use std::{fs, path::PathBuf};
+use toml;
 use drk::blockchain::{rocks::columns, Rocks, RocksColumn};
-use drk::cli::ServiceCli;
+use drk::cli::{ServiceCli, GatewaydConfig};
 use drk::service::GatewayService;
 use drk::util::join_config_path;
 use drk::Result;
@@ -11,19 +16,12 @@ extern crate clap;
 use async_executor::Executor;
 use easy_parallel::Parallel;
 
-fn setup_addr(address: Option<SocketAddr>, default: SocketAddr) -> SocketAddr {
-    match address {
-        Some(addr) => addr,
-        None => default,
-    }
-}
+async fn start(executor: Arc<Executor<'_>>, config: Arc<&GatewaydConfig>) -> Result<()> {
+    let accept_addr: SocketAddr = config.accept_url.parse()?;
+    let pub_addr: SocketAddr = config.publisher_url.parse()?;
+    let database_path = config.database_path.clone();
+    let database_path = join_config_path(&PathBuf::from(database_path))?;
 
-async fn start(executor: Arc<Executor<'_>>, options: ServiceCli) -> Result<()> {
-    let accept_addr: SocketAddr = setup_addr(options.accept_addr, "127.0.0.1:3333".parse()?);
-    let pub_addr: SocketAddr = setup_addr(options.pub_addr, "127.0.0.1:4444".parse()?);
-    let database_path = options.database_path.clone();
-
-    let database_path = join_config_path(&(*database_path))?;
     let rocks = Rocks::new(&database_path)?;
     let rocks_slabstore_column = RocksColumn::<columns::Slabs>::new(rocks);
 
@@ -33,12 +31,49 @@ async fn start(executor: Arc<Executor<'_>>, options: ServiceCli) -> Result<()> {
     Ok(())
 }
 
+fn set_default() -> Result<GatewaydConfig> {
+    let config_file = GatewaydConfig {
+        accept_url: String::from("127.0.0.1:3333"),
+        publisher_url: String::from("127.0.0.1:4444"),
+        database_path: String::from("gatewayd.db"),
+        log_path: String::from("/tmp/gatewayd.log"),
+    };
+    Ok(config_file)
+}
+
 fn main() -> Result<()> {
     use simplelog::*;
 
     let ex = Arc::new(Executor::new());
     let (signal, shutdown) = async_channel::unbounded::<()>();
 
+    let config_path = PathBuf::from("gatewayd.toml");
+    let path = join_config_path(&config_path).unwrap();
+
+    let mut file = OpenOptions::new()
+        .read(true)
+        .write(true)
+        .create(true)
+        .open(&path)?;
+
+    let mut buffer: Vec<u8> = vec![];
+    file.read_to_end(&mut buffer)?;
+
+    if buffer.is_empty() {
+        // set the default setting
+        let config_file = set_default()?;
+        let config_file = toml::to_string(&config_file)?;
+        fs::write(&path, &config_file)?;
+    }
+
+    // reload the config
+    let toml = fs::read(&path)?;
+    let str_buff = str::from_utf8(&toml)?;
+
+    // read from config file
+    let config: GatewaydConfig = toml::from_str(str_buff)?;
+    let config_pointer = Arc::new(&config);
+
     let options = ServiceCli::load()?;
 
     let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
@@ -49,12 +84,13 @@ fn main() -> Result<()> {
         LevelFilter::Off
     };
 
+    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(options.log_path.as_path()).unwrap(),
+            std::fs::File::create(log_path).unwrap(),
         ),
     ])
     .unwrap();
@@ -67,7 +103,7 @@ fn main() -> Result<()> {
         // Run the main future on the current thread.
         .finish(|| {
             smol::future::block_on(async move {
-                start(ex2, options).await?;
+                start(ex2, config_pointer).await?;
                 drop(signal);
                 Ok::<(), drk::Error>(())
             })

+ 25 - 8
src/cli/client_cli/cli_config.rs

@@ -1,13 +1,14 @@
 //use crate::serial::{deserialize, serialize, Decodable, Encodable};
 //use toml::{map::Map, Value};
-//use crate::util::join_config_path;
+use crate::util::join_config_path;
 //use crate::Result;
+
 use serde::{Deserialize, Serialize};
 //use log::*;
 
-//use std::{fs::OpenOptions, io::prelude::*, path::PathBuf};
+use std::{fs::OpenOptions, io::prelude::*, path::PathBuf};
 
-//pub trait ClientCliConfig<'a>: Default + Deserialize<'a> {
+//pub trait ClientConfig: Default + Deserialize {
 //    fn load(path: PathBuf) -> Result<Self> {
 //        let path = join_config_path(&path)?;
 //        let mut file = OpenOptions::new()
@@ -33,16 +34,16 @@ use serde::{Deserialize, Serialize};
 //        }
 //    }
 //    fn save(&self, path: PathBuf) -> Result<()> {
-//        let path = join_config_path(&path)?;
-//        let mut file = OpenOptions::new().write(true).create(true).open(&path)?;
+//        //let path = join_config_path(&path)?;
+//        //let mut file = OpenOptions::new().write(true).create(true).open(&path)?;
 //        //let serialized = serialize(self);
 //        //file.write_all(&serialized)?;
 //        Ok(())
 //    }
 //}
-
-//impl ClientCliConfig<'_> for DrkCliConfig {}
-//impl ClientCliConfig<'_> for DarkfidCliConfig {}
+//
+//impl ClientConfig for DrkConfig {}
+//impl ClientConfig for DarkfidConfig {}
 
 #[derive(Serialize, Default, Deserialize, Debug)]
 pub struct DrkConfig {
@@ -74,6 +75,22 @@ pub struct DarkfidConfig {
     pub password: String,
 }
 
+
+#[derive(Serialize, Default, Deserialize, Debug)]
+pub struct GatewaydConfig {
+    #[serde(rename = "connect_url")]
+    pub accept_url: String,
+
+    #[serde(rename = "subscriber_url")]
+    pub publisher_url: String,
+
+    #[serde(rename = "database_path")]
+    pub database_path: String,
+
+    #[serde(rename = "log_path")]
+    pub log_path: String,
+}
+
 //impl Default for DrkCliConfig {
 //    // default toml file
 //    fn default() -> Self {

+ 1 - 1
src/cli/mod.rs

@@ -1,6 +1,6 @@
 pub mod client_cli;
 pub mod service_cli;
 
-pub use client_cli::cli_config::{DarkfidConfig, DrkConfig};
+pub use client_cli::cli_config::{DarkfidConfig, GatewaydConfig, DrkConfig};
 pub use client_cli::{darkfid_cli::DarkfidCli, drk_cli::DrkCli, drk_cli::Transfer};
 pub use service_cli::ServiceCli;

+ 38 - 38
src/cli/service_cli.rs

@@ -2,11 +2,11 @@ use crate::Result;
 use std::net::SocketAddr;
 
 pub struct ServiceCli {
-    pub accept_addr: Option<SocketAddr>,
-    pub pub_addr: Option<SocketAddr>,
+    //pub accept_addr: Option<SocketAddr>,
+    //pub pub_addr: Option<SocketAddr>,
     pub verbose: bool,
-    pub database_path: Box<std::path::PathBuf>,
-    pub log_path: Box<std::path::PathBuf>,
+    //pub database_path: Box<std::path::PathBuf>,
+    //pub log_path: Box<std::path::PathBuf>,
 }
 
 impl ServiceCli {
@@ -15,52 +15,52 @@ impl ServiceCli {
             (version: "0.1.0")
             (author: "Amir Taaki <amir@dyne.org>")
             (about: "run service daemon")
-            (@arg ACCEPT: -a --accept +takes_value "Accept add//ress")
-            (@arg PUB_ADDR: -p --pubaddr +takes_value "Publisher addr")
+            //(@arg ACCEPT: -a --accept +takes_value "Accept add//ress")
+            //(@arg PUB_ADDR: -p --pubaddr +takes_value "Publisher addr")
             (@arg VERBOSE: -v --verbose "Increase verbosity")
-            (@arg DATABASE_PATH: --database +takes_value "database path")
-            (@arg LOG_PATH: --log +takes_value "Logfile path")
+            //(@arg DATABASE_PATH: --database +takes_value "database path")
+            //(@arg LOG_PATH: --log +takes_value "Logfile path")
         )
         .get_matches();
 
-        let accept_addr = if let Some(accept_addr) = app.value_of("ACCEPT") {
-            Some(accept_addr.parse()?)
-        } else {
-            None
-        };
+        //let accept_addr = if let Some(accept_addr) = app.value_of("ACCEPT") {
+        //    Some(accept_addr.parse()?)
+        //} else {
+        //    None
+        //};
 
-        let pub_addr = if let Some(pub_addr) = app.value_of("PUB_ADDR") {
-            Some(pub_addr.parse()?)
-        } else {
-            None
-        };
+        //let pub_addr = if let Some(pub_addr) = app.value_of("PUB_ADDR") {
+        //    Some(pub_addr.parse()?)
+        //} else {
+        //    None
+        //};
 
         let verbose = app.is_present("VERBOSE");
 
-        let database_path = Box::new(
-            if let Some(database_path) = app.value_of("DATABASE_PATH") {
-                std::path::Path::new(database_path)
-            } else {
-                std::path::Path::new("database.db")
-            }
-            .to_path_buf(),
-        );
+        //let database_path = Box::new(
+        //    if let Some(database_path) = app.value_of("DATABASE_PATH") {
+        //        std::path::Path::new(database_path)
+        //    } else {
+        //        std::path::Path::new("database.db")
+        //    }
+        //    .to_path_buf(),
+        //);
 
-        let log_path = Box::new(
-            if let Some(log_path) = app.value_of("LOG_PATH") {
-                std::path::Path::new(log_path)
-            } else {
-                std::path::Path::new("/tmp/darkfid_service_daemon.log")
-            }
-            .to_path_buf(),
-        );
+        //let log_path = Box::new(
+        //    if let Some(log_path) = app.value_of("LOG_PATH") {
+        //        std::path::Path::new(log_path)
+        //    } else {
+        //        std::path::Path::new("/tmp/darkfid_service_daemon.log")
+        //    }
+        //    .to_path_buf(),
+        //);
 
         Ok(Self {
-            accept_addr,
-            pub_addr,
+            //accept_addr,
+            //pub_addr,
             verbose,
-            database_path,
-            log_path,
+            //database_path,
+            //log_path,
         })
     }
 }