main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. use async_std::sync::Arc;
  2. use std::{fs::File, io, io::Read, path::PathBuf};
  3. use easy_parallel::Parallel;
  4. use fxhash::{FxHashMap, FxHashSet};
  5. use log::{debug, info};
  6. use serde_json::{json, Value};
  7. use simplelog::*;
  8. use smol::Executor;
  9. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  10. use tui::{
  11. backend::{Backend, TermionBackend},
  12. Terminal,
  13. };
  14. use url::Url;
  15. use darkfi::{
  16. error::{Error, Result},
  17. rpc::{jsonrpc, jsonrpc::JsonResult},
  18. util::{
  19. async_util,
  20. cli::{log_config, spawn_config, Config},
  21. join_config_path,
  22. },
  23. };
  24. use dnetview::{
  25. config::{DnvConfig, CONFIG_FILE_CONTENTS},
  26. model::{
  27. AddrInfo, AddrList, Channel, IdList, InboundInfo, InfoList, ManualInfo, NodeInfo,
  28. OutboundInfo, Slot,
  29. },
  30. options::ProgramOptions,
  31. ui,
  32. view::{AddrListView, IdListView, InfoListView},
  33. Model, View,
  34. };
  35. struct DNetView {
  36. url: Url,
  37. name: String,
  38. }
  39. impl DNetView {
  40. pub fn new(url: Url, name: String) -> Self {
  41. Self { url, name }
  42. }
  43. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  44. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r), None).await {
  45. Ok(v) => v,
  46. Err(e) => return Err(e),
  47. };
  48. match reply {
  49. JsonResult::Resp(r) => {
  50. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  51. Ok(r.result)
  52. }
  53. JsonResult::Err(e) => {
  54. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  55. Err(Error::JsonRpcError(e.error.message.to_string()))
  56. }
  57. JsonResult::Notif(n) => {
  58. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  59. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  60. }
  61. }
  62. }
  63. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  64. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  65. async fn _ping(&self) -> Result<Value> {
  66. let req = jsonrpc::request(json!("ping"), json!([]));
  67. Ok(self.request(req).await?)
  68. }
  69. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  70. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  71. async fn get_info(&self) -> Result<Value> {
  72. let req = jsonrpc::request(json!("get_info"), json!([]));
  73. Ok(self.request(req).await?)
  74. }
  75. }
  76. #[async_std::main]
  77. async fn main() -> Result<()> {
  78. let options = ProgramOptions::load()?;
  79. let verbosity_level = options.app.occurrences_of("verbose");
  80. let (lvl, cfg) = log_config(verbosity_level)?;
  81. let file = File::create(&*options.log_path).unwrap();
  82. WriteLogger::init(lvl, cfg, file)?;
  83. info!("Log level: {}", lvl);
  84. let config_path = join_config_path(&PathBuf::from("dnetview_config.toml"))?;
  85. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  86. let config = Config::<DnvConfig>::load(config_path)?;
  87. let stdout = io::stdout().into_raw_mode()?;
  88. let backend = TermionBackend::new(stdout);
  89. let mut terminal = Terminal::new(backend)?;
  90. terminal.clear()?;
  91. let info_list = InfoList::new();
  92. let ids = FxHashSet::default();
  93. let id_list = IdList::new(ids);
  94. let addr_list = AddrList::new();
  95. let model = Arc::new(Model::new(id_list, info_list, addr_list));
  96. let nthreads = num_cpus::get();
  97. let (signal, shutdown) = async_channel::unbounded::<()>();
  98. let ex = Arc::new(Executor::new());
  99. let ex2 = ex.clone();
  100. let (_, result) = Parallel::new()
  101. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  102. .finish(|| {
  103. smol::future::block_on(async move {
  104. run_rpc(&config, ex2.clone(), model.clone()).await?;
  105. render(&mut terminal, model.clone()).await?;
  106. drop(signal);
  107. Ok::<(), darkfi::Error>(())
  108. })
  109. });
  110. result
  111. }
  112. async fn run_rpc(config: &DnvConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  113. for node in config.nodes.clone() {
  114. let client = DNetView::new(Url::parse(&node.rpc_url)?, node.name);
  115. ex.spawn(poll(client, model.clone())).detach();
  116. }
  117. Ok(())
  118. }
  119. // TODO: clean up into seperate functions.
  120. // TODO: replace if/else with match where possible
  121. // TODO: test unwraps will never ever crash
  122. async fn poll(client: DNetView, model: Arc<Model>) -> Result<()> {
  123. loop {
  124. let reply = client.get_info().await?;
  125. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  126. // TODO: we are ignoring this value for now
  127. let _ext_addr = reply.as_object().unwrap().get("external_addr");
  128. let inbound_obj = &reply.as_object().unwrap()["session_inbound"];
  129. let manual_obj = &reply.as_object().unwrap()["session_manual"];
  130. let outbound_obj = &reply.as_object().unwrap()["session_outbound"];
  131. let mut iconnects = Vec::new();
  132. let mut mconnects = Vec::new();
  133. let mut oconnects = Vec::new();
  134. let mut slots = Vec::new();
  135. let mut addrs = Vec::new();
  136. let mut msgs = Vec::new();
  137. // parse inbound connection data
  138. let i_connected = &inbound_obj["connected"];
  139. if i_connected.as_object().unwrap().is_empty() {
  140. // channel is empty. initialize with empty values
  141. let connected = "Empty".to_string();
  142. let msg = "Null".to_string();
  143. let status = "Null".to_string();
  144. let channel = Channel::new(msg, status);
  145. let is_empty = true;
  146. let iinfo = InboundInfo::new(is_empty, connected, channel);
  147. iconnects.push(iinfo);
  148. } else {
  149. // channel is not empty. initialize with whole values
  150. let ic = i_connected.as_object().unwrap();
  151. for k in ic.keys() {
  152. let node = ic.get(k);
  153. let addr = k.to_string();
  154. let msg = node.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  155. let status =
  156. node.unwrap().get("last_status").unwrap().as_str().unwrap().to_string();
  157. let channel = Channel::new(msg.clone(), status);
  158. let is_empty = false;
  159. let iinfo = InboundInfo::new(is_empty, addr.clone(), channel);
  160. iconnects.push(iinfo);
  161. addrs.push(addr);
  162. msgs.push(msg.clone());
  163. }
  164. }
  165. // parse manual connection data
  166. let minfo: ManualInfo = serde_json::from_value(manual_obj.clone())?;
  167. mconnects.push(minfo);
  168. // parse outbound connection data
  169. let outbound_slots = &outbound_obj["slots"];
  170. for slot in outbound_slots.as_array().unwrap() {
  171. if slot["channel"].is_null() {
  172. // channel is empty. initialize with empty values
  173. let is_empty = true;
  174. let state = &slot["state"];
  175. let msg = "Null".to_string();
  176. let status = "Null".to_string();
  177. let channel = Channel::new(msg, status);
  178. let new_slot = Slot::new(
  179. is_empty,
  180. String::new(),
  181. channel,
  182. state.as_str().unwrap().to_string(),
  183. );
  184. slots.push(new_slot.clone())
  185. } else {
  186. // channel is not empty. initialize with whole values
  187. let is_empty = false;
  188. let addr = &slot["addr"];
  189. let state = &slot["state"];
  190. let channel: Channel = serde_json::from_value(slot["channel"].clone())?;
  191. let new_slot = Slot::new(
  192. is_empty,
  193. addr.as_str().unwrap().to_string(),
  194. channel.clone(),
  195. state.as_str().unwrap().to_string(),
  196. );
  197. slots.push(new_slot);
  198. addrs.push(addr.as_str().unwrap().to_string());
  199. msgs.push(channel.last_msg.clone());
  200. }
  201. }
  202. // create node_info
  203. let is_empty = is_empty_outbound(slots.clone());
  204. let oinfo = OutboundInfo::new(is_empty, slots.clone());
  205. oconnects.push(oinfo);
  206. let infos = NodeInfo { outbound: oconnects, manual: mconnects, inbound: iconnects };
  207. let mut node_info = FxHashMap::default();
  208. let node_name = &client.name.as_str();
  209. node_info.insert(&node_name, infos.clone());
  210. // insert into model
  211. for (key, value) in node_info.clone() {
  212. model.id_list.node_id.lock().await.insert(key.to_string().clone());
  213. model.info_list.infos.lock().await.insert(key.to_string(), value);
  214. }
  215. // TODO: this is just a placeholder. Later this will contain a message log.
  216. // There's an obvious bug here (all addrs are matched with the same ainfo)
  217. let mut addr_info = FxHashMap::default();
  218. let ainfos = AddrInfo::new(msgs);
  219. for addr in addrs {
  220. addr_info.insert(addr, ainfos.clone());
  221. }
  222. for (key, value) in addr_info.clone() {
  223. model.addr_list.infos.lock().await.insert(key.to_string(), value);
  224. }
  225. } else {
  226. // TODO: error handling
  227. //debug!("Reply is empty");
  228. }
  229. async_util::sleep(2).await;
  230. }
  231. }
  232. fn is_empty_outbound(slots: Vec<Slot>) -> bool {
  233. return slots.iter().all(|slot| slot.is_empty == true)
  234. }
  235. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  236. let mut asi = async_stdin();
  237. terminal.clear()?;
  238. let id_list = IdListView::new(FxHashSet::default());
  239. let info_list = InfoListView::new(FxHashMap::default());
  240. let mut view = View::new(id_list.clone(), info_list.clone());
  241. view.id_list.state.select(Some(0));
  242. view.info_list.index = 0;
  243. loop {
  244. view.update(model.info_list.infos.lock().await.clone());
  245. terminal.draw(|f| {
  246. ui::ui(f, view.clone());
  247. })?;
  248. for k in asi.by_ref().keys() {
  249. match k.unwrap() {
  250. Key::Char('q') => {
  251. terminal.clear()?;
  252. return Ok(())
  253. }
  254. Key::Char('j') => {
  255. view.id_list.next();
  256. view.info_list.next().await;
  257. }
  258. Key::Char('k') => {
  259. view.id_list.previous();
  260. view.info_list.previous().await;
  261. }
  262. _ => (),
  263. }
  264. }
  265. //async_util::sleep(3).await;
  266. }
  267. }