main.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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 async_std::sync::{Arc, Mutex};
  19. use std::path::Path;
  20. use async_executor::Executor;
  21. use fxhash::FxHashMap;
  22. use log::{error, info, warn};
  23. use smol::future;
  24. use structopt::StructOpt;
  25. use url::Url;
  26. use darkfi::{
  27. net,
  28. raft::{DataStore, NetMsg, ProtocolRaft, Raft, RaftSettings},
  29. util::{
  30. cli::{get_log_config, get_log_level},
  31. expand_path,
  32. serial::{SerialDecodable, SerialEncodable},
  33. sleep,
  34. },
  35. Result,
  36. };
  37. #[derive(Clone, Debug, StructOpt)]
  38. #[structopt(name = "raft-diag")]
  39. pub struct Args {
  40. /// JSON-RPC listen URL
  41. #[structopt(long = "rpc", default_value = "tcp://127.0.0.1:12055")]
  42. pub rpc_listen: Url,
  43. /// Inbound listen URL
  44. #[structopt(long = "inbound")]
  45. pub inbound_url: Vec<Url>,
  46. /// Seed Urls
  47. #[structopt(long = "seeds")]
  48. pub seed_urls: Vec<Url>,
  49. /// Outbound connections
  50. #[structopt(long = "outbound", default_value = "0")]
  51. pub outbound_connections: u32,
  52. /// Sets Datastore Path
  53. #[structopt(long = "path", default_value = "test1.db")]
  54. pub datastore: String,
  55. /// Check if all datastore paths provided are synced
  56. #[structopt(long = "check")]
  57. pub check: Vec<String>,
  58. /// Datastore path to extract and print it
  59. #[structopt(long = "extract")]
  60. pub extract: Option<String>,
  61. /// Number of messages to broadcast
  62. #[structopt(short, default_value = "0")]
  63. pub broadcast: u32,
  64. /// Increase verbosity
  65. #[structopt(short, parse(from_occurrences))]
  66. pub verbose: u8,
  67. }
  68. #[derive(Debug, Clone, SerialEncodable, SerialDecodable, PartialEq, Eq)]
  69. pub struct Message {
  70. payload: String,
  71. }
  72. fn extract(path: &str) -> Result<()> {
  73. if !Path::new(path).exists() {
  74. return Ok(())
  75. }
  76. let db = DataStore::<Message>::new(path)?;
  77. let commits = db.commits.get_all()?;
  78. println!("{:?}", commits);
  79. Ok(())
  80. }
  81. fn check(args: Args) -> Result<()> {
  82. let mut commits_check = vec![];
  83. for path in args.check {
  84. if !Path::new(&path).exists() {
  85. continue
  86. }
  87. let db = DataStore::<Message>::new(&path)?;
  88. let commits = db.commits.get_all()?;
  89. commits_check.push(commits);
  90. }
  91. let result = commits_check.windows(2).all(|w| w[0] == w[1]);
  92. println!("Synced: {}", result);
  93. Ok(())
  94. }
  95. async fn start_broadcasting(n: u32, sender: async_channel::Sender<Message>) -> Result<()> {
  96. sleep(8).await;
  97. info!(target: "raft", "Start broadcasting...");
  98. for id in 0..n {
  99. let msg = format!("msg_test_{}", id);
  100. info!(target: "raft", "Send a message {:?}", msg);
  101. let msg = Message { payload: msg };
  102. sender.send(msg).await?;
  103. }
  104. Ok(())
  105. }
  106. async fn receive_loop(receiver: async_channel::Receiver<Message>) -> Result<()> {
  107. loop {
  108. let msg = receiver.recv().await?;
  109. info!(target: "raft", "Receive new msg {:?}", msg);
  110. }
  111. }
  112. async fn start(args: Args, executor: Arc<Executor<'_>>) -> Result<()> {
  113. let net_settings = net::Settings {
  114. outbound_connections: args.outbound_connections,
  115. inbound: args.inbound_url.clone(),
  116. external_addr: args.inbound_url,
  117. seeds: args.seed_urls,
  118. ..net::Settings::default()
  119. };
  120. //
  121. // Raft
  122. //
  123. let datastore_raft = expand_path(&args.datastore)?;
  124. let seen_net_msgs = Arc::new(Mutex::new(FxHashMap::default()));
  125. let raft_settings = RaftSettings { datastore_path: datastore_raft, ..RaftSettings::default() };
  126. let mut raft = Raft::<Message>::new(raft_settings, seen_net_msgs.clone())?;
  127. //
  128. // P2p setup
  129. //
  130. let (p2p_send_channel, p2p_recv_channel) = async_channel::unbounded::<NetMsg>();
  131. let p2p = net::P2p::new(net_settings).await;
  132. let p2p = p2p.clone();
  133. let registry = p2p.protocol_registry();
  134. let raft_node_id = raft.id();
  135. registry
  136. .register(net::SESSION_ALL, move |channel, p2p| {
  137. let raft_node_id = raft_node_id.clone();
  138. let sender = p2p_send_channel.clone();
  139. let seen_net_msgs_cloned = seen_net_msgs.clone();
  140. async move {
  141. ProtocolRaft::init(raft_node_id, channel, sender, p2p, seen_net_msgs_cloned).await
  142. }
  143. })
  144. .await;
  145. p2p.clone().start(executor.clone()).await?;
  146. executor.spawn(p2p.clone().run(executor.clone())).detach();
  147. //
  148. // Waiting Exit signal
  149. //
  150. let (signal, shutdown) = async_channel::bounded::<()>(1);
  151. ctrlc::set_handler(move || {
  152. warn!("Catch exit signal");
  153. // cleaning up tasks running in the background
  154. if let Err(e) = async_std::task::block_on(signal.send(())) {
  155. error!("Error on sending exit signal: {}", e);
  156. }
  157. })
  158. .unwrap();
  159. if args.broadcast != 0 {
  160. executor.spawn(start_broadcasting(args.broadcast, raft.sender())).detach();
  161. }
  162. executor.spawn(receive_loop(raft.receiver())).detach();
  163. raft.run(p2p.clone(), p2p_recv_channel.clone(), executor.clone(), shutdown.clone()).await?;
  164. Ok(())
  165. }
  166. fn main() -> Result<()> {
  167. let args = Args::from_args();
  168. let log_level = get_log_level(args.verbose.into());
  169. let log_config = get_log_config();
  170. let mut log_path = expand_path(&args.datastore)?;
  171. let log_name: String = log_path.file_name().as_ref().unwrap().to_str().unwrap().to_owned();
  172. log_path.pop();
  173. let log_path = log_path.join(&format!("{}.log", log_name));
  174. let env_log_file_path = std::fs::File::create(log_path).unwrap();
  175. simplelog::CombinedLogger::init(vec![
  176. simplelog::TermLogger::new(
  177. log_level,
  178. log_config.clone(),
  179. simplelog::TerminalMode::Mixed,
  180. simplelog::ColorChoice::Auto,
  181. ),
  182. simplelog::WriteLogger::new(log_level, log_config, env_log_file_path),
  183. ])?;
  184. if !args.check.is_empty() {
  185. return check(args)
  186. }
  187. if args.extract.is_some() {
  188. return extract(&args.extract.unwrap())
  189. }
  190. // https://docs.rs/smol/latest/smol/struct.Executor.html#examples
  191. let ex = Arc::new(async_executor::Executor::new());
  192. let (signal, shutdown) = async_channel::unbounded::<()>();
  193. let (_, result) = easy_parallel::Parallel::new()
  194. // Run four executor threads
  195. .each(0..4, |_| future::block_on(ex.run(shutdown.recv())))
  196. // Run the main future on the current thread.
  197. .finish(|| {
  198. future::block_on(async {
  199. start(args, ex.clone()).await?;
  200. drop(signal);
  201. Ok::<(), darkfi::Error>(())
  202. })
  203. });
  204. result
  205. }