main.rs 20 KB

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