main.rs 15 KB

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