main.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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::{debug, 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::{Error, Result},
  17. rpc::{jsonrpc, jsonrpc::JsonResult},
  18. util::{
  19. async_util,
  20. cli::{log_config, spawn_config, Config},
  21. join_config_path,
  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, NodeInfoView, View},
  31. };
  32. struct DnetView {
  33. url: Url,
  34. name: String,
  35. }
  36. impl DnetView {
  37. fn new(url: Url, name: String) -> Self {
  38. Self { url, name }
  39. }
  40. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  41. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r), None).await {
  42. Ok(v) => v,
  43. Err(e) => return Err(e),
  44. };
  45. match reply {
  46. JsonResult::Resp(r) => {
  47. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  48. Ok(r.result)
  49. }
  50. JsonResult::Err(e) => {
  51. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  52. Err(Error::JsonRpcError(e.error.message.to_string()))
  53. }
  54. JsonResult::Notif(n) => {
  55. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  56. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  57. }
  58. }
  59. }
  60. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  61. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  62. async fn _ping(&self) -> Result<Value> {
  63. let req = jsonrpc::request(json!("ping"), json!([]));
  64. Ok(self.request(req).await?)
  65. }
  66. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  67. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  68. async fn get_info(&self) -> Result<Value> {
  69. let req = jsonrpc::request(json!("get_info"), json!([]));
  70. Ok(self.request(req).await?)
  71. }
  72. }
  73. #[async_std::main]
  74. async fn main() -> DnetViewResult<()> {
  75. let options = ProgramOptions::load()?;
  76. let verbosity_level = options.app.occurrences_of("verbose");
  77. let (lvl, cfg) = log_config(verbosity_level)?;
  78. let file = File::create(&*options.log_path).unwrap();
  79. WriteLogger::init(lvl, cfg, file)?;
  80. info!("Log level: {}", lvl);
  81. let config_path = join_config_path(&PathBuf::from("dnetview_config.toml"))?;
  82. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  83. let config = Config::<DnvConfig>::load(config_path)?;
  84. let stdout = io::stdout().into_raw_mode()?;
  85. let backend = TermionBackend::new(stdout);
  86. let mut terminal = Terminal::new(backend)?;
  87. terminal.clear()?;
  88. let ids = Mutex::new(FxHashSet::default());
  89. let nodes = Mutex::new(FxHashMap::default());
  90. let selectables = Mutex::new(FxHashMap::default());
  91. let msg_log = Mutex::new(FxHashMap::default());
  92. let model = Arc::new(Model::new(ids, nodes, selectables, msg_log));
  93. let nthreads = num_cpus::get();
  94. let (signal, shutdown) = async_channel::unbounded::<()>();
  95. let ex = Arc::new(Executor::new());
  96. let ex2 = ex.clone();
  97. let (_, result) = Parallel::new()
  98. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  99. .finish(|| {
  100. smol::future::block_on(async move {
  101. poll_and_update_model(&config, ex2.clone(), model.clone()).await?;
  102. render_view(&mut terminal, model.clone()).await?;
  103. drop(signal);
  104. Ok(())
  105. })
  106. });
  107. result
  108. }
  109. // create a new RPC instance for every node in the config file
  110. // spawn poll() and detach in the background
  111. async fn poll_and_update_model(
  112. config: &DnvConfig,
  113. ex: Arc<Executor<'_>>,
  114. model: Arc<Model>,
  115. ) -> DnetViewResult<()> {
  116. for node in &config.nodes {
  117. let client = DnetView::new(Url::parse(&node.rpc_url)?, node.name.clone());
  118. ex.spawn(poll(client, model.clone())).detach();
  119. }
  120. Ok(())
  121. }
  122. async fn poll(client: DnetView, model: Arc<Model>) -> DnetViewResult<()> {
  123. loop {
  124. let reply = client.get_info().await?;
  125. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  126. parse_data(reply.as_object().unwrap(), &client, model.clone()).await?;
  127. } else {
  128. return Err(DnetViewError::EmptyRpcReply)
  129. }
  130. async_util::sleep(2).await;
  131. }
  132. }
  133. async fn parse_data(
  134. reply: &serde_json::Map<String, Value>,
  135. client: &DnetView,
  136. model: Arc<Model>,
  137. ) -> DnetViewResult<()> {
  138. let addr = &reply.get("external_addr");
  139. let inbound = &reply["session_inbound"];
  140. let manual = &reply["session_manual"];
  141. let outbound = &reply["session_outbound"];
  142. let mut sessions: Vec<SessionInfo> = Vec::new();
  143. let node_name = &client.name;
  144. let node_id = make_node_id(node_name)?;
  145. //let external_addr = ext_addr.unwrap().as_str().unwrap();
  146. let ext_addr = parse_external_addr(addr).await?;
  147. let in_session = parse_inbound(inbound, &node_id).await?;
  148. let out_session = parse_outbound(outbound, &node_id).await?;
  149. let man_session = parse_manual(manual, &node_id).await?;
  150. sessions.push(in_session.clone());
  151. sessions.push(out_session.clone());
  152. sessions.push(man_session.clone());
  153. let node = NodeInfo::new(node_id.clone(), node_name.to_string(), sessions.clone(), ext_addr);
  154. update_node(model.clone(), node.clone(), node_id.clone()).await;
  155. update_selectable_and_ids(model.clone(), sessions.clone(), node.clone()).await?;
  156. update_msgs(model.clone(), sessions.clone()).await?;
  157. //debug!("IDS: {:?}", model.ids.lock().await);
  158. //debug!("INFOS: {:?}", model.infos.lock().await);
  159. Ok(())
  160. }
  161. async fn update_msgs(model: Arc<Model>, sessions: Vec<SessionInfo>) -> DnetViewResult<()> {
  162. for session in sessions {
  163. for connection in session.children {
  164. if !model.msg_log.lock().await.contains_key(&connection.id) {
  165. model.msg_log.lock().await.insert(connection.id, connection.msg_log);
  166. } else {
  167. match model.msg_log.lock().await.entry(connection.id) {
  168. Entry::Vacant(e) => {
  169. e.insert(connection.msg_log);
  170. }
  171. Entry::Occupied(mut e) => {
  172. for msg in connection.msg_log {
  173. e.get_mut().push(msg);
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. //debug!("MSGS: {:?}", model.msg_log.lock().await);
  181. Ok(())
  182. }
  183. async fn update_ids(model: Arc<Model>, id: String) {
  184. model.ids.lock().await.insert(id);
  185. }
  186. async fn update_node(model: Arc<Model>, node: NodeInfo, id: String) {
  187. model.nodes.lock().await.insert(id, node);
  188. }
  189. async fn update_selectable_and_ids(
  190. model: Arc<Model>,
  191. sessions: Vec<SessionInfo>,
  192. node: NodeInfo,
  193. ) -> DnetViewResult<()> {
  194. let node_obj = SelectableObject::Node(node.clone());
  195. model.selectables.lock().await.insert(node.id.clone(), node_obj);
  196. update_ids(model.clone(), node.id.clone()).await;
  197. for session in sessions.clone() {
  198. let session_obj = SelectableObject::Session(session.clone());
  199. model.selectables.lock().await.insert(session.clone().id, session_obj);
  200. update_ids(model.clone(), session.clone().id).await;
  201. for connect in session.children {
  202. let connect_obj = SelectableObject::Connect(connect.clone());
  203. model.selectables.lock().await.insert(connect.clone().id, connect_obj);
  204. update_ids(model.clone(), connect.clone().id).await;
  205. }
  206. }
  207. Ok(())
  208. }
  209. async fn parse_external_addr(addr: &Option<&Value>) -> DnetViewResult<String> {
  210. match addr {
  211. Some(addr) => match addr.as_str() {
  212. Some(addr) => return Ok(addr.to_string()),
  213. None => return Ok("null".to_string()),
  214. },
  215. None => Err(DnetViewError::NoExternalAddr),
  216. }
  217. }
  218. async fn parse_inbound(inbound: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  219. let name = "Inbound".to_string();
  220. let session_type = Session::Inbound;
  221. let parent = node_id.to_string();
  222. let id = make_session_id(&parent, &session_type)?;
  223. let mut connects: Vec<ConnectInfo> = Vec::new();
  224. let connections = &inbound["connected"];
  225. let mut connect_count = 0;
  226. match connections.as_object() {
  227. Some(connect) => {
  228. match connect.is_empty() {
  229. true => {
  230. connect_count += 1;
  231. // channel is empty. initialize with empty values
  232. let id = make_empty_id(&node_id, &session_type, connect_count)?;
  233. let addr = "Null".to_string();
  234. let state = "Null".to_string();
  235. let parent = parent.clone();
  236. let msg_log = Vec::new();
  237. let is_empty = true;
  238. let last_msg = "Null".to_string();
  239. let last_status = "Null".to_string();
  240. let connect_info = ConnectInfo::new(
  241. id,
  242. addr,
  243. state,
  244. parent,
  245. msg_log,
  246. is_empty,
  247. last_msg,
  248. last_status,
  249. );
  250. connects.push(connect_info.clone());
  251. }
  252. false => {
  253. // channel is not empty. initialize with whole values
  254. for k in connect.keys() {
  255. let node = connect.get(k);
  256. let addr = k.to_string();
  257. let id = node.unwrap().get("random_id").unwrap().as_u64().unwrap();
  258. let id = make_connect_id(&id)?;
  259. let state = "state".to_string();
  260. let parent = parent.clone();
  261. let msg_values = node.unwrap().get("log").unwrap().as_array().unwrap();
  262. let mut msg_log: Vec<(String, String)> = Vec::new();
  263. for msg in msg_values {
  264. let msg: (String, String) = serde_json::from_value(msg.clone())?;
  265. msg_log.push(msg);
  266. }
  267. let is_empty = false;
  268. let last_msg =
  269. node.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  270. let last_status =
  271. node.unwrap().get("last_status").unwrap().as_str().unwrap().to_string();
  272. let connect_info = ConnectInfo::new(
  273. id,
  274. addr,
  275. state,
  276. parent,
  277. msg_log,
  278. is_empty,
  279. last_msg,
  280. last_status,
  281. );
  282. connects.push(connect_info.clone());
  283. }
  284. }
  285. }
  286. let is_empty = is_empty_session(&connects);
  287. let session_info = SessionInfo::new(id, name, is_empty, parent, connects);
  288. Ok(session_info)
  289. }
  290. None => Err(DnetViewError::ValueIsNotObject),
  291. }
  292. }
  293. // TODO: placeholder for now
  294. async fn parse_manual(_manual: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  295. let name = "Manual".to_string();
  296. let session_type = Session::Manual;
  297. let mut connects: Vec<ConnectInfo> = Vec::new();
  298. let parent = node_id.to_string();
  299. let session_id = make_session_id(&parent, &session_type)?;
  300. let id: u64 = 0;
  301. let connect_id = make_connect_id(&id)?;
  302. let addr = "Null".to_string();
  303. let state = "Null".to_string();
  304. let msg_log = Vec::new();
  305. let is_empty = true;
  306. let msg = "Null".to_string();
  307. let status = "Null".to_string();
  308. let connect_info =
  309. ConnectInfo::new(connect_id.clone(), addr, state, parent, msg_log, is_empty, msg, status);
  310. connects.push(connect_info.clone());
  311. let parent = connect_id.clone();
  312. let is_empty = is_empty_session(&connects);
  313. let session_info = SessionInfo::new(session_id, name, is_empty, parent, connects.clone());
  314. Ok(session_info)
  315. }
  316. async fn parse_outbound(outbound: &Value, node_id: &String) -> DnetViewResult<SessionInfo> {
  317. let name = "Outbound".to_string();
  318. let session_type = Session::Outbound;
  319. let parent = node_id.to_string();
  320. let id = make_session_id(&parent, &session_type)?;
  321. let mut connects: Vec<ConnectInfo> = Vec::new();
  322. let slots = &outbound["slots"];
  323. let mut slot_count = 0;
  324. match slots.as_array() {
  325. Some(slots) => {
  326. for slot in slots {
  327. slot_count += 1;
  328. match slot["channel"].is_null() {
  329. true => {
  330. // channel is empty. initialize with empty values
  331. let id = make_empty_id(&node_id, &session_type, slot_count)?;
  332. let addr = "Null".to_string();
  333. let state = &slot["state"];
  334. let state = state.as_str().unwrap().to_string();
  335. let parent = parent.clone();
  336. let msg_log = Vec::new();
  337. let is_empty = true;
  338. let last_msg = "Null".to_string();
  339. let last_status = "Null".to_string();
  340. let connect_info = ConnectInfo::new(
  341. id,
  342. addr,
  343. state,
  344. parent,
  345. msg_log,
  346. is_empty,
  347. last_msg,
  348. last_status,
  349. );
  350. connects.push(connect_info.clone());
  351. }
  352. false => {
  353. // channel is not empty. initialize with whole values
  354. let channel = &slot["channel"];
  355. let id = channel["random_id"].as_u64().unwrap();
  356. let id = make_connect_id(&id)?;
  357. let addr = &slot["addr"];
  358. let addr = addr.as_str().unwrap().to_string();
  359. let state = &slot["state"];
  360. let state = state.as_str().unwrap().to_string();
  361. let parent = parent.clone();
  362. let msg_values = channel["log"].as_array().unwrap();
  363. let mut msg_log: Vec<(String, String)> = Vec::new();
  364. for msg in msg_values {
  365. let msg: (String, String) = serde_json::from_value(msg.clone())?;
  366. msg_log.push(msg);
  367. }
  368. let is_empty = false;
  369. let last_msg = channel["last_msg"].as_str().unwrap().to_string();
  370. let last_status = channel["last_status"].as_str().unwrap().to_string();
  371. let connect_info = ConnectInfo::new(
  372. id,
  373. addr,
  374. state,
  375. parent,
  376. msg_log,
  377. is_empty,
  378. last_msg,
  379. last_status,
  380. );
  381. connects.push(connect_info.clone());
  382. }
  383. }
  384. }
  385. let is_empty = is_empty_session(&connects);
  386. let session_info = SessionInfo::new(id, name, is_empty, parent, connects);
  387. Ok(session_info)
  388. }
  389. None => Err(DnetViewError::ValueIsNotObject),
  390. }
  391. }
  392. async fn render_view<B: Backend>(
  393. terminal: &mut Terminal<B>,
  394. model: Arc<Model>,
  395. ) -> DnetViewResult<()> {
  396. let mut asi = async_stdin();
  397. terminal.clear()?;
  398. let nodes = NodeInfoView::new(FxHashMap::default());
  399. let msg_log = FxHashMap::default();
  400. let active_ids = IdListView::new(FxHashSet::default());
  401. let selectables = FxHashMap::default();
  402. let mut view = View::new(nodes, msg_log, active_ids, selectables);
  403. view.active_ids.state.select(Some(0));
  404. loop {
  405. view.update(
  406. model.nodes.lock().await.clone(),
  407. model.msg_log.lock().await.clone(),
  408. model.selectables.lock().await.clone(),
  409. );
  410. let mut err: Option<DnetViewError> = None;
  411. terminal.draw(|f| match view.render(f) {
  412. Ok(()) => {}
  413. Err(e) => {
  414. err = Some(e);
  415. }
  416. })?;
  417. match err {
  418. Some(e) => return Err(e),
  419. None => {}
  420. }
  421. for k in asi.by_ref().keys() {
  422. match k.unwrap() {
  423. Key::Char('q') => {
  424. terminal.clear()?;
  425. return Ok(())
  426. }
  427. Key::Char('j') => {
  428. view.active_ids.next();
  429. }
  430. Key::Char('k') => {
  431. view.active_ids.previous();
  432. }
  433. _ => (),
  434. }
  435. }
  436. }
  437. }