cli.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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: u64) -> simplelog::LevelFilter {
  64. match verbosity_level {
  65. 0 => simplelog::LevelFilter::Info,
  66. 1 => simplelog::LevelFilter::Debug,
  67. _ => simplelog::LevelFilter::Trace,
  68. }
  69. }
  70. pub fn get_log_config() -> simplelog::Config {
  71. match env::var("LOG_TARGETS") {
  72. Ok(x) => {
  73. let targets: Vec<String> = x.split(',').map(|x| x.to_string()).collect();
  74. let mut cfgbuilder = ConfigBuilder::new();
  75. cfgbuilder.set_target_level(simplelog::LevelFilter::Error);
  76. for i in targets {
  77. if i.starts_with('!') {
  78. cfgbuilder.add_filter_ignore(i.trim_start_matches('!').to_string());
  79. } else {
  80. cfgbuilder.add_filter_allow(i);
  81. }
  82. }
  83. cfgbuilder.build()
  84. }
  85. Err(_) => {
  86. let mut cfgbuilder = ConfigBuilder::new();
  87. cfgbuilder.set_target_level(simplelog::LevelFilter::Error);
  88. cfgbuilder.build()
  89. }
  90. }
  91. }
  92. /// This macro is used for a standard way of daemonizing darkfi binaries
  93. /// with TOML config file configuration, and argument parsing. It also
  94. /// spawns a multithreaded async executor and passes it into the given
  95. /// function.
  96. ///
  97. /// The Cargo.toml dependencies needed for this are:
  98. /// ```text
  99. /// async-std = "1.12.0"
  100. /// darkfi = { path = "../../", features = ["util"] }
  101. /// easy-parallel = "3.2.0"
  102. /// simplelog = "0.12.0"
  103. /// smol = "1.2.5"
  104. ///
  105. /// # Argument parsing
  106. /// serde = {version = "1.0.135", features = ["derive"]}
  107. /// structopt = "0.3.26"
  108. /// structopt-toml = "0.5.1"
  109. /// ```
  110. ///
  111. /// Example usage:
  112. /// ```
  113. /// use async_std::sync::Arc;
  114. // use darkfi::{async_daemonize, cli_desc, Result};
  115. /// use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  116. ///
  117. /// const CONFIG_FILE: &str = "daemond_config.toml";
  118. /// const CONFIG_FILE_CONTENTS: &str = include_str!("../daemond_config.toml");
  119. ///
  120. /// #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  121. /// #[serde(default)]
  122. /// #[structopt(name = "daemond", about = cli_desc!())]
  123. /// struct Args {
  124. /// #[structopt(short, long)]
  125. /// /// Configuration file to use
  126. /// config: Option<String>,
  127. ///
  128. /// #[structopt(short, parse(from_occurrences))]
  129. /// /// Increase verbosity (-vvv supported)
  130. /// verbose: u8,
  131. /// }
  132. ///
  133. /// async_daemonize!(realmain);
  134. /// async fn realmain(args: Args, ex: Arc<smol::Executor<'_>>) -> Result<()> {
  135. /// println!("Hello, world!");
  136. /// Ok(())
  137. /// }
  138. /// ```
  139. #[cfg(feature = "async-runtime")]
  140. #[macro_export]
  141. macro_rules! async_daemonize {
  142. ($realmain:ident) => {
  143. fn main() -> Result<()> {
  144. let args = Args::from_args_with_toml("").unwrap();
  145. let cfg_path = darkfi::util::path::get_config_path(args.config, CONFIG_FILE)?;
  146. darkfi::util::cli::spawn_config(&cfg_path, CONFIG_FILE_CONTENTS.as_bytes())?;
  147. let args = Args::from_args_with_toml(&std::fs::read_to_string(cfg_path)?).unwrap();
  148. let log_level = darkfi::util::cli::get_log_level(args.verbose.into());
  149. let log_config = darkfi::util::cli::get_log_config();
  150. let log_file_path = match std::env::var("DARKFI_LOG") {
  151. Ok(p) => p,
  152. Err(_) => {
  153. let bin_name = if let Some(bin_name) = option_env!("CARGO_BIN_NAME") {
  154. bin_name
  155. } else {
  156. "darkfi"
  157. };
  158. std::fs::create_dir_all(darkfi::util::path::expand_path("~/.local/darkfi")?)?;
  159. format!("~/.local/darkfi/{}.log", bin_name)
  160. }
  161. };
  162. let log_file_path = darkfi::util::path::expand_path(&log_file_path)?;
  163. let log_file = std::fs::File::create(log_file_path)?;
  164. simplelog::CombinedLogger::init(vec![
  165. simplelog::TermLogger::new(
  166. log_level,
  167. log_config.clone(),
  168. simplelog::TerminalMode::Mixed,
  169. simplelog::ColorChoice::Auto,
  170. ),
  171. simplelog::WriteLogger::new(log_level, log_config, log_file),
  172. ])?;
  173. // https://docs.rs/smol/latest/smol/struct.Executor.html#examples
  174. let ex = async_std::sync::Arc::new(smol::Executor::new());
  175. let (signal, shutdown) = smol::channel::unbounded::<()>();
  176. let (_, result) = easy_parallel::Parallel::new()
  177. // Run four executor threads
  178. .each(0..4, |_| smol::future::block_on(ex.run(shutdown.recv())))
  179. // Run the main future on the current thread.
  180. .finish(|| {
  181. smol::future::block_on(async {
  182. $realmain(args, ex.clone()).await?;
  183. drop(signal);
  184. Ok::<(), darkfi::Error>(())
  185. })
  186. });
  187. result
  188. }
  189. };
  190. }
  191. pub fn fg_red(message: &str) -> String {
  192. format!("\x1b[31m{}\x1b[0m", message)
  193. }
  194. pub fn fg_green(message: &str) -> String {
  195. format!("\x1b[32m{}\x1b[0m", message)
  196. }
  197. pub fn fg_reset() -> String {
  198. "\x1b[0m".to_string()
  199. }