main.rs 20 KB

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