main.rs 24 KB

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