main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 rand::{thread_rng, Rng};
  7. use serde_json::{json, Value};
  8. use simplelog::*;
  9. use smol::Executor;
  10. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  11. use tui::{
  12. backend::{Backend, TermionBackend},
  13. Terminal,
  14. };
  15. use url::Url;
  16. use darkfi::{
  17. error::{Error, Result},
  18. rpc::{jsonrpc, jsonrpc::JsonResult},
  19. util::{
  20. async_util,
  21. cli::{log_config, spawn_config, Config},
  22. join_config_path,
  23. },
  24. };
  25. use dnetview::{
  26. config::{DnvConfig, CONFIG_FILE_CONTENTS},
  27. model::{ConnectInfo, Model, NodeInfo, SelectableObject, SessionInfo},
  28. options::ProgramOptions,
  29. ui,
  30. view::{IdListView, InfoListView, View},
  31. };
  32. struct DNetView {
  33. url: Url,
  34. name: String,
  35. }
  36. impl DNetView {
  37. pub 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() -> Result<()> {
  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 id_set = Mutex::new(FxHashSet::default());
  89. let node_info = Mutex::new(FxHashMap::default());
  90. let session_info = Mutex::new(FxHashMap::default());
  91. let connect_info = Mutex::new(FxHashMap::default());
  92. let model = Arc::new(Model::new(id_set, node_info, session_info, connect_info));
  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. run_rpc(&config, ex2.clone(), model.clone()).await?;
  102. render(&mut terminal, model.clone()).await?;
  103. drop(signal);
  104. Ok::<(), darkfi::Error>(())
  105. })
  106. });
  107. result
  108. }
  109. async fn run_rpc(config: &DnvConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  110. for node in config.nodes.clone() {
  111. let client = DNetView::new(Url::parse(&node.rpc_url)?, node.name);
  112. ex.spawn(poll(client, model.clone())).detach();
  113. }
  114. Ok(())
  115. }
  116. async fn poll(client: DNetView, model: Arc<Model>) -> Result<()> {
  117. loop {
  118. let reply = client.get_info().await?;
  119. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  120. parse_data(reply.as_object().unwrap(), &client, model.clone()).await?;
  121. } else {
  122. // TODO: error handling
  123. //debug!("Reply is empty");
  124. }
  125. async_util::sleep(2).await;
  126. }
  127. }
  128. // TODO: split into parse maunal/ inbound/ outbound functions
  129. // make if/else into switch statements for clarity
  130. async fn parse_data(
  131. reply: &serde_json::Map<String, Value>,
  132. client: &DNetView,
  133. model: Arc<Model>,
  134. ) -> io::Result<()> {
  135. // TODO
  136. let _ext_addr = reply.get("external_addr");
  137. let inbound_obj = &reply["session_inbound"];
  138. // TODO
  139. let manual_obj = &reply["session_manual"];
  140. let outbound_obj = &reply["session_outbound"];
  141. let mut model_vec: Vec<SelectableObject> = Vec::new();
  142. let connections: Vec<ConnectInfo> = Vec::new();
  143. let sessions: Vec<SessionInfo> = Vec::new();
  144. let node_id = generate_id();
  145. let node_name = &client.name;
  146. parse_inbound(inbound_obj, connections.clone(), sessions.clone(), model_vec.clone(), node_id);
  147. parse_outbound(outbound_obj, connections.clone(), sessions.clone(), model_vec.clone(), node_id);
  148. parse_manual(manual_obj, connections.clone(), sessions.clone(), model_vec.clone(), node_id);
  149. let node_info = NodeInfo::new(node_id, node_name.to_string(), sessions);
  150. let node = SelectableObject::Node(node_info.clone());
  151. model_vec.push(node);
  152. // TODO: write data to HashMaps and HashSets
  153. Ok(())
  154. }
  155. fn parse_inbound(
  156. inbound_obj: &Value,
  157. mut connections: Vec<ConnectInfo>,
  158. mut sessions: Vec<SessionInfo>,
  159. mut model_vec: Vec<SelectableObject>,
  160. node_id: u32,
  161. ) {
  162. let i_connected = &inbound_obj["connected"];
  163. let i_session_id = generate_id();
  164. if i_connected.as_object().unwrap().is_empty() {
  165. // channel is empty. initialize with empty values
  166. let i_connect_id = generate_id();
  167. let addr = "Null".to_string();
  168. let msg = "Null".to_string();
  169. let status = "Null".to_string();
  170. let is_empty = true;
  171. let parent = i_session_id;
  172. // TODO
  173. let state = "Null".to_string();
  174. // TODO
  175. let msg_log = Vec::new();
  176. let connect_info =
  177. ConnectInfo::new(i_connect_id, addr, is_empty, msg, status, state, msg_log, parent);
  178. connections.push(connect_info.clone());
  179. let connect = SelectableObject::Connect(connect_info.clone());
  180. model_vec.push(connect);
  181. } else {
  182. // channel is not empty. initialize with whole values
  183. let i_connect_id = generate_id();
  184. let ic = i_connected.as_object().unwrap();
  185. for k in ic.keys() {
  186. let node = ic.get(k);
  187. let addr = k.to_string();
  188. let msg = node.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  189. let status = node.unwrap().get("last_status").unwrap().as_str().unwrap().to_string();
  190. let state = node.unwrap().get("state").unwrap().as_str().unwrap().to_string();
  191. let is_empty = false;
  192. let parent = i_session_id;
  193. // TODO
  194. let msg_log = Vec::new();
  195. let connect_info =
  196. ConnectInfo::new(i_connect_id, addr, is_empty, msg, status, state, msg_log, parent);
  197. connections.push(connect_info.clone());
  198. let connect = SelectableObject::Connect(connect_info.clone());
  199. model_vec.push(connect);
  200. }
  201. }
  202. let i_session_info = SessionInfo::new(i_session_id, node_id, connections.clone());
  203. sessions.push(i_session_info.clone());
  204. let session = SelectableObject::Session(i_session_info.clone());
  205. model_vec.push(session);
  206. }
  207. fn parse_manual(
  208. manual_obj: &Value,
  209. mut connections: Vec<ConnectInfo>,
  210. mut sessions: Vec<SessionInfo>,
  211. mut model_vec: Vec<SelectableObject>,
  212. node_id: u32,
  213. ) {
  214. let m_session_id = generate_id();
  215. let m_connect_id = generate_id();
  216. let addr = "Null".to_string();
  217. let msg = "Null".to_string();
  218. let status = "Null".to_string();
  219. let is_empty = true;
  220. let parent = m_session_id;
  221. // TODO
  222. let state = "Null".to_string();
  223. // TODO
  224. let msg_log = Vec::new();
  225. let m_connect_info =
  226. ConnectInfo::new(m_connect_id, addr, is_empty, msg, status, state, msg_log, parent);
  227. connections.push(m_connect_info.clone());
  228. let connect = SelectableObject::Connect(m_connect_info.clone());
  229. model_vec.push(connect);
  230. }
  231. fn parse_outbound(
  232. outbound_obj: &Value,
  233. mut connections: Vec<ConnectInfo>,
  234. mut sessions: Vec<SessionInfo>,
  235. mut model_vec: Vec<SelectableObject>,
  236. node_id: u32,
  237. ) {
  238. // parse outbound connection data
  239. let outbound_slots = &outbound_obj["slots"];
  240. let o_session_id = generate_id();
  241. for slot in outbound_slots.as_array().unwrap() {
  242. let o_connect_id = generate_id();
  243. if slot["channel"].is_null() {
  244. // channel is empty. initialize with empty values
  245. let is_empty = true;
  246. let addr = "Null".to_string();
  247. let state = &slot["state"];
  248. let msg = "Null".to_string();
  249. let status = "Null".to_string();
  250. // placeholder for now
  251. let msg_log = Vec::new();
  252. let parent = o_session_id;
  253. let connect_info = ConnectInfo::new(
  254. o_connect_id,
  255. addr,
  256. is_empty,
  257. msg,
  258. status,
  259. state.as_str().unwrap().to_string(),
  260. msg_log,
  261. parent,
  262. );
  263. connections.push(connect_info.clone());
  264. let connect = SelectableObject::Connect(connect_info.clone());
  265. model_vec.push(connect);
  266. } else {
  267. // TODO: cleanup/ make style consistent
  268. // channel is not empty. initialize with whole values
  269. let is_empty = false;
  270. let addr = &slot["addr"];
  271. let state = &slot["state"];
  272. let msg = &slot["last_msg"];
  273. let status = &slot["last_status"];
  274. let parent = o_session_id;
  275. // TODO
  276. let msg_log = Vec::new();
  277. let connect_info = ConnectInfo::new(
  278. o_connect_id,
  279. addr.as_str().unwrap().to_string(),
  280. is_empty,
  281. msg.as_str().unwrap().to_string(),
  282. status.as_str().unwrap().to_string(),
  283. state.as_str().unwrap().to_string(),
  284. msg_log,
  285. parent,
  286. );
  287. connections.push(connect_info.clone());
  288. let connect = SelectableObject::Connect(connect_info.clone());
  289. model_vec.push(connect);
  290. }
  291. }
  292. let o_session_info = SessionInfo::new(o_session_id, node_id, connections.clone());
  293. sessions.push(o_session_info.clone());
  294. let session = SelectableObject::Session(o_session_info.clone());
  295. model_vec.push(session);
  296. }
  297. fn generate_id() -> u32 {
  298. let mut rng = thread_rng();
  299. let id: u32 = rng.gen();
  300. id
  301. }
  302. //fn is_empty_outbound(slots: Vec<Slot>) -> bool {
  303. // return slots.iter().all(|slot| slot.is_empty);
  304. //}
  305. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  306. let mut asi = async_stdin();
  307. terminal.clear()?;
  308. let id_list = IdListView::new(FxHashSet::default());
  309. let info_list = InfoListView::new(FxHashMap::default());
  310. let mut view = View::new(id_list.clone(), info_list.clone());
  311. view.id_list.state.select(Some(0));
  312. view.info_list.index = 0;
  313. loop {
  314. //view.update(model.info_list.infos.lock().await.clone());
  315. terminal.draw(|f| {
  316. ui::ui(f, view.clone());
  317. })?;
  318. for k in asi.by_ref().keys() {
  319. match k.unwrap() {
  320. Key::Char('q') => {
  321. terminal.clear()?;
  322. return Ok(())
  323. }
  324. Key::Char('j') => {
  325. view.id_list.next();
  326. }
  327. Key::Char('k') => {
  328. view.id_list.previous();
  329. }
  330. _ => (),
  331. }
  332. }
  333. }
  334. }