main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 ids = Mutex::new(FxHashSet::default());
  89. let infos = Mutex::new(FxHashMap::default());
  90. let model = Arc::new(Model::new(ids, infos));
  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. ) -> io::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 connects: Vec<ConnectInfo> = Vec::new();
  136. let sessions: Vec<SessionInfo> = Vec::new();
  137. let node_id = generate_id();
  138. let node_name = &client.name;
  139. parse_inbound(inbound, connects.clone(), sessions.clone(), node_id, model.clone()).await;
  140. parse_outbound(outbound, connects.clone(), sessions.clone(), node_id, model.clone()).await;
  141. parse_manual(manual, connects.clone(), node_id, model.clone()).await;
  142. let node_info = NodeInfo::new(node_id, node_name.to_string(), sessions);
  143. let node = SelectableObject::Node(node_info.clone());
  144. model.ids.lock().await.insert(node_id);
  145. model.infos.lock().await.insert(node_id, node);
  146. //debug!("IDS: {:?}", model.ids.lock().await);
  147. //debug!("INFOS: {:?}", model.infos.lock().await);
  148. Ok(())
  149. }
  150. async fn parse_inbound(
  151. inbound: &Value,
  152. mut connects: Vec<ConnectInfo>,
  153. mut sessions: Vec<SessionInfo>,
  154. node_id: u32,
  155. model: Arc<Model>,
  156. ) {
  157. let connections = &inbound["connected"];
  158. let session_id = generate_id();
  159. match connections.as_object() {
  160. Some(connect) => {
  161. match connect.is_empty() {
  162. true => {
  163. // channel is empty. initialize with empty values
  164. let connect_id = generate_id();
  165. let addr = "Null".to_string();
  166. let msg = "Null".to_string();
  167. let status = "Null".to_string();
  168. let is_empty = true;
  169. let parent = session_id;
  170. let state = "Null".to_string();
  171. let msg_log = Vec::new();
  172. let connect_info = ConnectInfo::new(
  173. connect_id, addr, is_empty, msg, status, state, msg_log, parent,
  174. );
  175. connects.push(connect_info.clone());
  176. }
  177. false => {
  178. // channel is not empty. initialize with whole values
  179. let connect_id = generate_id();
  180. for k in connect.keys() {
  181. let node = connect.get(k);
  182. let addr = k.to_string();
  183. let msg =
  184. node.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  185. let status =
  186. node.unwrap().get("last_status").unwrap().as_str().unwrap().to_string();
  187. // TODO: state, msg log
  188. let state = "state".to_string();
  189. let is_empty = false;
  190. let parent = session_id;
  191. let msg_log = Vec::new();
  192. let connect_info = ConnectInfo::new(
  193. connect_id, addr, is_empty, msg, status, state, msg_log, parent,
  194. );
  195. connects.push(connect_info.clone());
  196. }
  197. }
  198. }
  199. let session_info = SessionInfo::new(session_id, node_id, connects.clone());
  200. sessions.push(session_info.clone());
  201. let session = SelectableObject::Session(session_info.clone());
  202. model.ids.lock().await.insert(session_id);
  203. model.infos.lock().await.insert(session_id, session);
  204. }
  205. None => {
  206. // TODO
  207. }
  208. }
  209. }
  210. // TODO: placeholder for now
  211. async fn parse_manual(
  212. _manual_obj: &Value,
  213. mut connections: Vec<ConnectInfo>,
  214. _node_id: u32,
  215. model: Arc<Model>,
  216. ) {
  217. let m_session_id = generate_id();
  218. let m_connect_id = generate_id();
  219. let addr = "Null".to_string();
  220. let msg = "Null".to_string();
  221. let status = "Null".to_string();
  222. let is_empty = true;
  223. let parent = m_session_id;
  224. let state = "Null".to_string();
  225. let msg_log = Vec::new();
  226. let m_connect_info =
  227. ConnectInfo::new(m_connect_id, addr, is_empty, msg, status, state, msg_log, parent);
  228. connections.push(m_connect_info.clone());
  229. let connect = SelectableObject::Connect(m_connect_info.clone());
  230. model.ids.lock().await.insert(m_session_id);
  231. model.infos.lock().await.insert(m_session_id, connect);
  232. }
  233. async fn parse_outbound(
  234. outbound: &Value,
  235. mut connects: Vec<ConnectInfo>,
  236. mut sessions: Vec<SessionInfo>,
  237. node_id: u32,
  238. model: Arc<Model>,
  239. ) {
  240. // parse outbound connection data
  241. let slots = &outbound["slots"];
  242. let session_id = generate_id();
  243. match slots.as_array() {
  244. Some(slots) => {
  245. for slot in slots {
  246. match slot["channel"].is_null() {
  247. true => {
  248. // channel is empty. initialize with empty values
  249. let connect_id = generate_id();
  250. let is_empty = true;
  251. let addr = "Null".to_string();
  252. let state = &slot["state"];
  253. let msg = "Null".to_string();
  254. let status = "Null".to_string();
  255. // TODO: msg log
  256. let msg_log = Vec::new();
  257. let parent = session_id;
  258. let connect_info = ConnectInfo::new(
  259. connect_id,
  260. addr,
  261. is_empty,
  262. msg,
  263. status,
  264. state.as_str().unwrap().to_string(),
  265. msg_log,
  266. parent,
  267. );
  268. connects.push(connect_info.clone());
  269. }
  270. false => {
  271. // channel is not empty. initialize with whole values
  272. let connect_id = generate_id();
  273. let is_empty = false;
  274. let addr = &slot["addr"];
  275. let state = &slot["state"];
  276. // TODO: msg and status
  277. let msg = "msg";
  278. let status = &slot["last_status"];
  279. let parent = session_id;
  280. // TODO
  281. let msg_log = Vec::new();
  282. let connect_info = ConnectInfo::new(
  283. connect_id,
  284. addr.as_str().unwrap().to_string(),
  285. is_empty,
  286. msg.to_string(),
  287. status.as_str().unwrap().to_string(),
  288. state.as_str().unwrap().to_string(),
  289. msg_log,
  290. parent,
  291. );
  292. connects.push(connect_info.clone());
  293. }
  294. }
  295. }
  296. let session_info = SessionInfo::new(session_id, node_id, connects.clone());
  297. sessions.push(session_info.clone());
  298. let session = SelectableObject::Session(session_info.clone());
  299. model.ids.lock().await.insert(session_id);
  300. model.infos.lock().await.insert(session_id, session);
  301. }
  302. None => {
  303. // TODO
  304. }
  305. }
  306. }
  307. fn generate_id() -> u32 {
  308. let mut rng = thread_rng();
  309. let id: u32 = rng.gen();
  310. id
  311. }
  312. //fn is_empty_outbound(slots: Vec<Slot>) -> bool {
  313. // return slots.iter().all(|slot| slot.is_empty);
  314. //}
  315. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  316. let mut asi = async_stdin();
  317. terminal.clear()?;
  318. let id_list = IdListView::new(FxHashSet::default());
  319. let info_list = InfoListView::new(FxHashMap::default());
  320. let mut view = View::new(id_list.clone(), info_list.clone());
  321. view.id_list.state.select(Some(0));
  322. view.info_list.index = 0;
  323. loop {
  324. //view.update(model.info_list.infos.lock().await.clone());
  325. terminal.draw(|f| {
  326. ui::ui(f, view.clone());
  327. })?;
  328. for k in asi.by_ref().keys() {
  329. match k.unwrap() {
  330. Key::Char('q') => {
  331. terminal.clear()?;
  332. return Ok(())
  333. }
  334. Key::Char('j') => {
  335. view.id_list.next();
  336. }
  337. Key::Char('k') => {
  338. view.id_list.previous();
  339. }
  340. _ => (),
  341. }
  342. }
  343. }
  344. }