main.rs 22 KB

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