cli.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. env, fs,
  20. io::Write,
  21. marker::PhantomData,
  22. path::{Path, PathBuf},
  23. str,
  24. };
  25. use serde::{de::DeserializeOwned, Serialize};
  26. use simplelog::ConfigBuilder;
  27. use crate::{Error, Result};
  28. #[derive(Clone, Default)]
  29. pub struct Config<T> {
  30. config: PhantomData<T>,
  31. }
  32. impl<T: Serialize + DeserializeOwned> Config<T> {
  33. pub fn load(path: PathBuf) -> Result<T> {
  34. if Path::new(&path).exists() {
  35. let toml = fs::read(&path)?;
  36. let str_buff = str::from_utf8(&toml)?;
  37. let config: T = toml::from_str(str_buff)?;
  38. Ok(config)
  39. } else {
  40. let path = path.to_str();
  41. if path.is_some() {
  42. println!("Could not find/parse configuration file in: {}", path.unwrap());
  43. } else {
  44. println!("Could not find/parse configuration file");
  45. }
  46. println!("Please follow the instructions in the README");
  47. Err(Error::ConfigNotFound)
  48. }
  49. }
  50. }
  51. pub fn spawn_config(path: &Path, contents: &[u8]) -> Result<()> {
  52. if !path.exists() {
  53. if let Some(parent) = path.parent() {
  54. fs::create_dir_all(parent)?;
  55. }
  56. let mut file = fs::File::create(path)?;
  57. file.write_all(contents)?;
  58. println!("Config file created in {:?}. Please review it and try again.", path);
  59. std::process::exit(2);
  60. }
  61. Ok(())
  62. }
  63. pub fn get_log_level(verbosity_level: u8) -> simplelog::LevelFilter {
  64. match verbosity_level {
  65. 0 => simplelog::LevelFilter::Info,
  66. 1 => simplelog::LevelFilter::Info,
  67. 2 => simplelog::LevelFilter::Debug,
  68. _ => simplelog::LevelFilter::Trace,
  69. }
  70. }
  71. pub fn get_log_config(verbosity_level: u8) -> simplelog::Config {
  72. match env::var("LOG_TARGETS") {
  73. Ok(x) => {
  74. let targets: Vec<String> = x.split(',').map(|x| x.to_string()).collect();
  75. let mut cfgbuilder = ConfigBuilder::new();
  76. match verbosity_level {
  77. 0 => cfgbuilder.set_target_level(simplelog::LevelFilter::Debug),
  78. _ => cfgbuilder.set_target_level(simplelog::LevelFilter::Error),
  79. };
  80. for i in targets {
  81. if i.starts_with('!') {
  82. cfgbuilder.add_filter_ignore(i.trim_start_matches('!').to_string());
  83. } else {
  84. cfgbuilder.add_filter_allow(i);
  85. }
  86. }
  87. cfgbuilder.build()
  88. }
  89. Err(_) => {
  90. let mut cfgbuilder = ConfigBuilder::new();
  91. match verbosity_level {
  92. 0 => cfgbuilder.set_target_level(simplelog::LevelFilter::Debug),
  93. _ => cfgbuilder.set_target_level(simplelog::LevelFilter::Error),
  94. };
  95. cfgbuilder.build()
  96. }
  97. }
  98. }
  99. /// This macro is used for a standard way of daemonizing darkfi binaries
  100. /// with TOML config file configuration, and argument parsing. It also
  101. /// spawns a multithreaded async executor and passes it into the given
  102. /// function.
  103. ///
  104. /// The Cargo.toml dependencies needed for this are:
  105. /// ```text
  106. /// async-std = "1.12.0"
  107. /// darkfi = { path = "../../", features = ["util"] }
  108. /// easy-parallel = "3.2.0"
  109. /// simplelog = "0.12.0"
  110. /// smol = "1.2.5"
  111. ///
  112. /// # Argument parsing
  113. /// serde = {version = "1.0.135", features = ["derive"]}
  114. /// structopt = "0.3.26"
  115. /// structopt-toml = "0.5.1"
  116. /// ```
  117. ///
  118. /// Example usage:
  119. /// ```
  120. /// use async_std::sync::Arc;
  121. // use darkfi::{async_daemonize, cli_desc, Result};
  122. /// use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  123. ///
  124. /// const CONFIG_FILE: &str = "daemond_config.toml";
  125. /// const CONFIG_FILE_CONTENTS: &str = include_str!("../daemond_config.toml");
  126. ///
  127. /// #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  128. /// #[serde(default)]
  129. /// #[structopt(name = "daemond", about = cli_desc!())]
  130. /// struct Args {
  131. /// #[structopt(short, long)]
  132. /// /// Configuration file to use
  133. /// config: Option<String>,
  134. ///
  135. /// #[structopt(short, parse(from_occurrences))]
  136. /// /// Increase verbosity (-vvv supported)
  137. /// verbose: u8,
  138. /// }
  139. ///
  140. /// async_daemonize!(realmain);
  141. /// async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  142. /// println!("Hello, world!");
  143. /// Ok(())
  144. /// }
  145. /// ```
  146. #[cfg(feature = "async-runtime")]
  147. #[macro_export]
  148. macro_rules! async_daemonize {
  149. ($realmain:ident) => {
  150. fn main() -> Result<()> {
  151. let args = Args::from_args_with_toml("").unwrap();
  152. let cfg_path = darkfi::util::path::get_config_path(args.config, CONFIG_FILE)?;
  153. darkfi::util::cli::spawn_config(&cfg_path, CONFIG_FILE_CONTENTS.as_bytes())?;
  154. let args = Args::from_args_with_toml(&std::fs::read_to_string(cfg_path)?).unwrap();
  155. let log_level = darkfi::util::cli::get_log_level(args.verbose);
  156. let log_config = darkfi::util::cli::get_log_config(args.verbose);
  157. /* FIXME: This is an issue. We should only log when explicitly told to
  158. let log_file_path = match std::env::var("DARKFI_LOG") {
  159. Ok(p) => p,
  160. Err(_) => {
  161. let bin_name = if let Some(bin_name) = option_env!("CARGO_BIN_NAME") {
  162. bin_name
  163. } else {
  164. "darkfi"
  165. };
  166. std::fs::create_dir_all(darkfi::util::path::expand_path("~/.local/darkfi")?)?;
  167. format!("~/.local/darkfi/{}.log", bin_name)
  168. }
  169. };
  170. let log_file_path = darkfi::util::path::expand_path(&log_file_path)?;
  171. let log_file = std::fs::File::create(log_file_path)?;
  172. */
  173. simplelog::CombinedLogger::init(vec![
  174. simplelog::TermLogger::new(
  175. log_level,
  176. log_config.clone(),
  177. simplelog::TerminalMode::Mixed,
  178. simplelog::ColorChoice::Auto,
  179. ),
  180. //simplelog::WriteLogger::new(log_level, log_config, log_file),
  181. ])?;
  182. // https://docs.rs/smol/latest/smol/struct.Executor.html#examples
  183. let n_threads = std::thread::available_parallelism().unwrap().get();
  184. let ex = async_std::sync::Arc::new(smol::Executor::new());
  185. let (signal, shutdown) = smol::channel::unbounded::<()>();
  186. let (_, result) = easy_parallel::Parallel::new()
  187. // Run four executor threads
  188. .each(0..n_threads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  189. // Run the main future on the current thread.
  190. .finish(|| {
  191. smol::future::block_on(async {
  192. $realmain(args, ex.clone()).await?;
  193. drop(signal);
  194. Ok::<(), darkfi::Error>(())
  195. })
  196. });
  197. result
  198. }
  199. };
  200. }
  201. pub fn fg_red(message: &str) -> String {
  202. format!("\x1b[31m{}\x1b[0m", message)
  203. }
  204. pub fn fg_green(message: &str) -> String {
  205. format!("\x1b[32m{}\x1b[0m", message)
  206. }
  207. pub fn fg_reset() -> String {
  208. "\x1b[0m".to_string()
  209. }