main.rs 23 KB

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