main.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. use async_std::sync::{Arc, Mutex};
  2. use std::{collections::hash_map::Entry, fs::File, io, io::Read, path::PathBuf};
  3. use easy_parallel::Parallel;
  4. use fxhash::{FxHashMap, FxHashSet};
  5. use log::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::Result,
  17. rpc::{jsonrpc, rpcclient::RpcClient},
  18. util::{
  19. async_util,
  20. cli::{log_config, spawn_config, Config},
  21. join_config_path, Timestamp,
  22. },
  23. };
  24. use dnetview::{
  25. config::{DnvConfig, CONFIG_FILE_CONTENTS},
  26. error::{DnetViewError, DnetViewResult},
  27. model::{ConnectInfo, Model, NodeInfo, SelectableObject, Session, SessionInfo},
  28. options::ProgramOptions,
  29. util::{is_empty_session, make_connect_id, make_empty_id, make_node_id, make_session_id},
  30. view::{IdListView, NodeInfoView, View},
  31. };
  32. use log::debug;
  33. struct DnetView {
  34. name: String,
  35. rpc_client: RpcClient,
  36. }
  37. impl DnetView {
  38. async fn new(url: Url, name: String) -> Result<Self> {
  39. let rpc_client = RpcClient::new(url).await?;
  40. Ok(Self { name, rpc_client })
  41. }
  42. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  43. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  44. async fn _ping(&self) -> Result<Value> {
  45. let req = jsonrpc::request(json!("ping"), json!([]));
  46. Ok(self.rpc_client.request(req).await?)
  47. }
  48. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  49. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  50. async fn get_info(&self) -> Result<Value> {
  51. let req = jsonrpc::request(json!("get_info"), json!([]));
  52. Ok(self.rpc_client.request(req).await?)
  53. }
  54. }
  55. #[async_std::main]
  56. async fn main() -> DnetViewResult<()> {
  57. let options = ProgramOptions::load()?;
  58. let verbosity_level = options.app.occurrences_of("verbose");
  59. let (lvl, cfg) = log_config(verbosity_level)?;
  60. let file = File::create(&*options.log_path).unwrap();
  61. WriteLogger::init(lvl, cfg, file)?;
  62. info!("Log level: {}", lvl);
  63. let config_path = join_config_path(&PathBuf::from("dnetview_config.toml"))?;
  64. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  65. let config = Config::<DnvConfig>::load(config_path)?;
  66. let stdout = io::stdout().into_raw_mode()?;
  67. let backend = TermionBackend::new(stdout);
  68. let mut terminal = Terminal::new(backend)?;
  69. terminal.clear()?;
  70. let ids = Mutex::new(FxHashSet::default());
  71. let nodes = Mutex::new(FxHashMap::default());
  72. let selectables = Mutex::new(FxHashMap::default());
  73. let msg_log = Mutex::new(FxHashMap::default());
  74. let model = Arc::new(Model::new(ids, nodes, selectables, msg_log));
  75. let nthreads = num_cpus::get();
  76. let (signal, shutdown) = async_channel::unbounded::<()>();
  77. let ex = Arc::new(Executor::new());
  78. let ex2 = ex.clone();
  79. let (_, result) = Parallel::new()
  80. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  81. .finish(|| {
  82. smol::future::block_on(async move {
  83. poll_and_update_model(&config, ex2.clone(), model.clone()).await?;
  84. render_view(&mut terminal, model.clone()).await?;
  85. drop(signal);
  86. Ok(())
  87. })
  88. });
  89. result
  90. }
  91. // create a new RPC instance for every node in the config file
  92. // spawn poll() and detach in the background
  93. async fn poll_and_update_model(
  94. config: &DnvConfig,
  95. ex: Arc<Executor<'_>>,
  96. model: Arc<Model>,
  97. ) -> DnetViewResult<()> {
  98. for node in &config.nodes {
  99. let client = DnetView::new(Url::parse(&node.rpc_url)?, node.name.clone()).await?;
  100. ex.spawn(poll(client, model.clone())).detach();
  101. }
  102. Ok(())
  103. }
  104. async fn poll(client: DnetView, model: Arc<Model>) -> DnetViewResult<()> {
  105. loop {
  106. let reply = client.get_info().await?;
  107. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  108. parse_data(reply.as_object().unwrap(), &client, model.clone()).await?;
  109. } else {
  110. return Err(DnetViewError::EmptyRpcReply)
  111. }
  112. async_util::sleep(2).await;
  113. }
  114. }
  115. async fn parse_data(
  116. reply: &serde_json::Map<String, Value>,
  117. client: &DnetView,
  118. model: Arc<Model>,
  119. ) -> DnetViewResult<()> {
  120. let addr = &reply.get("external_addr");
  121. let inbound = &reply["session_inbound"];
  122. let manual = &reply["session_manual"];
  123. let outbound = &reply["session_outbound"];
  124. let mut sessions: Vec<SessionInfo> = Vec::new();
  125. let node_name = &client.name;
  126. let node_id = make_node_id(node_name)?;
  127. //let external_addr = ext_addr.unwrap().as_str().unwrap();
  128. let ext_addr = parse_external_addr(addr).await?;
  129. let in_session = parse_inbound(inbound, &node_id).await?;
  130. let out_session = parse_outbound(outbound, &node_id).await?;
  131. let man_session = parse_manual(manual, &node_id).await?;
  132. sessions.push(in_session.clone());
  133. sessions.push(out_session.clone());
  134. sessions.push(man_session.clone());
  135. let node = NodeInfo::new(node_id.clone(), node_name.to_string(), sessions.clone(), ext_addr);
  136. update_node(model.clone(), node.clone(), node_id.clone()).await;
  137. update_selectable_and_ids(model.clone(), sessions.clone(), node.clone()).await?;
  138. update_msgs(model.clone(), sessions.clone()).await?;
  139. //debug!("IDS: {:?}", model.ids.lock().await);
  140. //debug!("INFOS: {:?}", model.infos.lock().await);
  141. Ok(())
  142. }
  143. async fn update_msgs(model: Arc<Model>, sessions: Vec<SessionInfo>) -> DnetViewResult<()> {
  144. for session in sessions {
  145. for connection in session.children {
  146. if !model.msg_log.lock().await.contains_key(&connection.id) {
  147. model.msg_log.lock().await.insert(connection.id, connection.msg_log);
  148. } else {
  149. match model.msg_log.lock().await.entry(connection.id) {
  150. Entry::Vacant(e) => {
  151. e.insert(connection.msg_log);
  152. }
  153. Entry::Occupied(mut e) => {
  154. for msg in connection.msg_log {
  155. e.get_mut().push(msg);
  156. }
  157. }
  158. }
  159. }
  160. }
  161. }
  162. //debug!("MSGS: {:?}", model.msg_log.lock().await);
  163. Ok(())
  164. }
  165. async fn update_ids(model: Arc<Model>, id: String) {
  166. model.ids.lock().await.insert(id);
  167. }
  168. async fn update_node(model: Arc<Model>, node: NodeInfo, id: String) {
  169. model.nodes.lock().await.insert(id, node);
  170. }
  171. async fn update_selectable_and_ids(
  172. model: Arc<Model>,
  173. sessions: Vec<SessionInfo>,
  174. node: NodeInfo,
  175. ) -> DnetViewResult<()> {
  176. let node_obj = SelectableObject::Node(node.clone());
  177. model.selectables.lock().await.insert(node.id.clone(), node_obj);
  178. update_ids(model.clone(), node.id.clone()).await;
  179. for session in sessions.clone() {
  180. let session_obj = SelectableObject::Session(session.clone());
  181. model.selectables.lock().await.insert(session.clone().id, session_obj);
  182. update_ids(model.clone(), session.clone().id).await;
  183. for connect in session.children {
  184. let connect_obj = SelectableObject::Connect(connect.clone());
  185. model.selectables.lock().await.insert(connect.clone().id, connect_obj);
  186. update_ids(model.clone(), connect.clone().id).await;
  187. }
  188. }
  189. Ok(())
  190. }
  191. async fn parse_external_addr(addr: &Option<&Value>) -> DnetViewResult<String> {
  192. match addr {
  193. Some(addr) => match addr.as_str() {
  194. Some(addr) => return Ok(addr.to_string()),
  195. None => return Ok("null".to_string()),
  196. },
  197. None => Err(DnetViewError::NoExternalAddr),
  198. }
  199. }
  200. async fn parse_inbound(inbound: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  201. let name = "Inbound".to_string();
  202. let session_type = Session::Inbound;
  203. let parent = node_id.to_string();
  204. let id = make_session_id(&parent, &session_type)?;
  205. let mut connects: Vec<ConnectInfo> = Vec::new();
  206. let connections = &inbound["connected"];
  207. let mut connect_count = 0;
  208. let mut accept_vec = Vec::new();
  209. match connections.as_object() {
  210. Some(connect) => {
  211. match connect.is_empty() {
  212. true => {
  213. connect_count += 1;
  214. // channel is empty. initialize with empty values
  215. let id = make_empty_id(&node_id, &session_type, connect_count)?;
  216. let addr = "Null".to_string();
  217. let state = "Null".to_string();
  218. let parent = parent.clone();
  219. let msg_log = Vec::new();
  220. let is_empty = true;
  221. let last_msg = "Null".to_string();
  222. let last_status = "Null".to_string();
  223. let connect_info = ConnectInfo::new(
  224. id,
  225. addr,
  226. state,
  227. parent,
  228. msg_log,
  229. is_empty,
  230. last_msg,
  231. last_status,
  232. );
  233. connects.push(connect_info.clone());
  234. }
  235. false => {
  236. // channel is not empty. initialize with whole values
  237. for k in connect.keys() {
  238. let node = connect.get(k);
  239. let addr = k.to_string();
  240. let info = node.unwrap().as_array();
  241. // get the accept address
  242. let accept_addr = info.unwrap().get(0);
  243. let acc_addr = accept_addr
  244. .unwrap()
  245. .get("accept_addr")
  246. .unwrap()
  247. .as_str()
  248. .unwrap()
  249. .to_string();
  250. accept_vec.push(acc_addr);
  251. let info2 = info.unwrap().get(1);
  252. let id = info2.unwrap().get("random_id").unwrap().as_u64().unwrap();
  253. let id = make_connect_id(&id)?;
  254. let state = "state".to_string();
  255. let parent = parent.clone();
  256. let msg_values = info2.unwrap().get("log").unwrap().as_array().unwrap();
  257. let mut msg_log: Vec<(Timestamp, String, String)> = Vec::new();
  258. for msg in msg_values {
  259. let msg: (Timestamp, String, String) =
  260. serde_json::from_value(msg.clone())?;
  261. msg_log.push(msg);
  262. }
  263. let is_empty = false;
  264. let last_msg =
  265. info2.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  266. let last_status = info2
  267. .unwrap()
  268. .get("last_status")
  269. .unwrap()
  270. .as_str()
  271. .unwrap()
  272. .to_string();
  273. let connect_info = ConnectInfo::new(
  274. id,
  275. addr,
  276. state,
  277. parent,
  278. msg_log,
  279. is_empty,
  280. last_msg,
  281. last_status,
  282. );
  283. connects.push(connect_info.clone());
  284. }
  285. }
  286. }
  287. let is_empty = is_empty_session(&connects);
  288. // TODO: clean this up
  289. if accept_vec.is_empty() {
  290. let accept_addr = None;
  291. let session_info =
  292. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr);
  293. Ok(session_info)
  294. } else {
  295. let accept_addr = Some(accept_vec[0].clone());
  296. let session_info =
  297. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr);
  298. Ok(session_info)
  299. }
  300. }
  301. None => Err(DnetViewError::ValueIsNotObject),
  302. }
  303. }
  304. // TODO: placeholder for now
  305. async fn parse_manual(_manual: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  306. let name = "Manual".to_string();
  307. let session_type = Session::Manual;
  308. let mut connects: Vec<ConnectInfo> = Vec::new();
  309. let parent = node_id.to_string();
  310. let session_id = make_session_id(&parent, &session_type)?;
  311. let id: u64 = 0;
  312. let connect_id = make_connect_id(&id)?;
  313. let addr = "Null".to_string();
  314. let state = "Null".to_string();
  315. let msg_log = Vec::new();
  316. let is_empty = true;
  317. let msg = "Null".to_string();
  318. let status = "Null".to_string();
  319. let connect_info =
  320. ConnectInfo::new(connect_id.clone(), addr, state, parent, msg_log, is_empty, msg, status);
  321. connects.push(connect_info.clone());
  322. let parent = connect_id.clone();
  323. let is_empty = is_empty_session(&connects);
  324. let accept_addr = None;
  325. let session_info =
  326. SessionInfo::new(session_id, name, is_empty, parent, connects.clone(), accept_addr);
  327. Ok(session_info)
  328. }
  329. async fn parse_outbound(outbound: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  330. let name = "Outbound".to_string();
  331. let session_type = Session::Outbound;
  332. let parent = node_id.to_string();
  333. let id = make_session_id(&parent, &session_type)?;
  334. let mut connects: Vec<ConnectInfo> = Vec::new();
  335. let slots = &outbound["slots"];
  336. let mut slot_count = 0;
  337. match slots.as_array() {
  338. Some(slots) => {
  339. for slot in slots {
  340. slot_count += 1;
  341. match slot["channel"].is_null() {
  342. true => {
  343. // channel is empty. initialize with empty values
  344. let id = make_empty_id(&node_id, &session_type, slot_count)?;
  345. let addr = "Null".to_string();
  346. let state = &slot["state"];
  347. let state = state.as_str().unwrap().to_string();
  348. let parent = parent.clone();
  349. let msg_log = Vec::new();
  350. let is_empty = true;
  351. let last_msg = "Null".to_string();
  352. let last_status = "Null".to_string();
  353. let connect_info = ConnectInfo::new(
  354. id,
  355. addr,
  356. state,
  357. parent,
  358. msg_log,
  359. is_empty,
  360. last_msg,
  361. last_status,
  362. );
  363. connects.push(connect_info.clone());
  364. }
  365. false => {
  366. // channel is not empty. initialize with whole values
  367. let channel = &slot["channel"];
  368. let id = channel["random_id"].as_u64().unwrap();
  369. let id = make_connect_id(&id)?;
  370. let addr = &slot["addr"];
  371. let addr = addr.as_str().unwrap().to_string();
  372. let state = &slot["state"];
  373. let state = state.as_str().unwrap().to_string();
  374. let parent = parent.clone();
  375. let msg_values = channel["log"].as_array().unwrap();
  376. let mut msg_log: Vec<(Timestamp, String, String)> = Vec::new();
  377. for msg in msg_values {
  378. let msg: (Timestamp, String, String) =
  379. serde_json::from_value(msg.clone())?;
  380. msg_log.push(msg);
  381. }
  382. let is_empty = false;
  383. let last_msg = channel["last_msg"].as_str().unwrap().to_string();
  384. let last_status = channel["last_status"].as_str().unwrap().to_string();
  385. let connect_info = ConnectInfo::new(
  386. id,
  387. addr,
  388. state,
  389. parent,
  390. msg_log,
  391. is_empty,
  392. last_msg,
  393. last_status,
  394. );
  395. connects.push(connect_info.clone());
  396. }
  397. }
  398. }
  399. let is_empty = is_empty_session(&connects);
  400. let accept_addr = None;
  401. let session_info = SessionInfo::new(id, name, is_empty, parent, connects, accept_addr);
  402. Ok(session_info)
  403. }
  404. None => Err(DnetViewError::ValueIsNotObject),
  405. }
  406. }
  407. async fn render_view<B: Backend>(
  408. terminal: &mut Terminal<B>,
  409. model: Arc<Model>,
  410. ) -> DnetViewResult<()> {
  411. let mut asi = async_stdin();
  412. terminal.clear()?;
  413. let nodes = NodeInfoView::new(FxHashMap::default());
  414. let msg_log = FxHashMap::default();
  415. let active_ids = IdListView::new(FxHashSet::default());
  416. let selectables = FxHashMap::default();
  417. let mut view = View::new(nodes, msg_log, active_ids, selectables);
  418. view.active_ids.state.select(Some(0));
  419. loop {
  420. view.update(
  421. model.nodes.lock().await.clone(),
  422. model.msg_log.lock().await.clone(),
  423. model.selectables.lock().await.clone(),
  424. );
  425. let mut err: Option<DnetViewError> = None;
  426. terminal.draw(|f| match view.render(f) {
  427. Ok(()) => {}
  428. Err(e) => {
  429. err = Some(e);
  430. }
  431. })?;
  432. match err {
  433. Some(e) => return Err(e),
  434. None => {}
  435. }
  436. for k in asi.by_ref().keys() {
  437. match k.unwrap() {
  438. Key::Char('q') => {
  439. terminal.clear()?;
  440. return Ok(())
  441. }
  442. Key::Char('j') => {
  443. view.active_ids.next();
  444. }
  445. Key::Char('k') => {
  446. view.active_ids.previous();
  447. }
  448. _ => (),
  449. }
  450. }
  451. }
  452. }