main.rs 21 KB

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