main.rs 23 KB

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