main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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, serial,
  23. },
  24. };
  25. use dnetview::{
  26. config::{DnvConfig, CONFIG_FILE_CONTENTS},
  27. model::{ConnectInfo, Model, NodeInfo, SelectableObject, Session, 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. ) -> 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. // first check if we have this node
  137. let node_name = &client.name;
  138. let node_id = make_node_id(node_name)?;
  139. let in_session = parse_inbound(inbound, node_id.clone()).await?;
  140. let out_session = parse_outbound(outbound, node_id.clone()).await?;
  141. let man_session = parse_manual(manual, node_id.clone()).await?;
  142. sessions.push(in_session);
  143. sessions.push(out_session);
  144. sessions.push(man_session);
  145. let node_info = NodeInfo::new(node_id.clone(), node_name.to_string(), sessions);
  146. let node = SelectableObject::Node(node_info.clone());
  147. model.ids.lock().await.insert(node_id.clone());
  148. model.infos.lock().await.insert(node_id.clone(), node);
  149. debug!("IDS: {:?}", model.ids.lock().await);
  150. debug!("INFOS: {:?}", model.infos.lock().await);
  151. Ok(())
  152. }
  153. async fn parse_inbound(inbound: &Value, node_id: String) -> Result<SessionInfo> {
  154. let session_type = Session::Inbound;
  155. let session_id = make_session_id(node_id.clone(), &session_type)?;
  156. let mut connects: Vec<ConnectInfo> = Vec::new();
  157. let connections = &inbound["connected"];
  158. match connections.as_object() {
  159. Some(connect) => {
  160. match connect.is_empty() {
  161. true => {
  162. // channel is empty. initialize with empty values
  163. // TODO: fix this
  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.clone();
  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. for k in connect.keys() {
  180. let node = connect.get(k);
  181. let addr = k.to_string();
  182. let msg =
  183. node.unwrap().get("last_msg").unwrap().as_str().unwrap().to_string();
  184. let status =
  185. node.unwrap().get("last_status").unwrap().as_str().unwrap().to_string();
  186. // TODO: state, msg log
  187. let id = node.unwrap().get("random_id").unwrap().as_u64().unwrap();
  188. let connect_id = make_connect_id(id)?;
  189. let state = "state".to_string();
  190. let is_empty = false;
  191. let parent = session_id.clone();
  192. let msg_log = Vec::new();
  193. let connect_info = ConnectInfo::new(
  194. connect_id, addr, is_empty, msg, status, state, msg_log, parent,
  195. );
  196. connects.push(connect_info.clone());
  197. }
  198. }
  199. }
  200. let session_info =
  201. SessionInfo::new(session_id.clone(), node_id.clone(), connects.clone());
  202. Ok(session_info)
  203. }
  204. None => Err(Error::ValueIsNotObject),
  205. }
  206. }
  207. // TODO: placeholder for now
  208. async fn parse_manual(_manual: &Value, node_id: String) -> Result<SessionInfo> {
  209. let session_type = Session::Manual;
  210. let mut connects: Vec<ConnectInfo> = Vec::new();
  211. let session_id = make_session_id(node_id.clone(), &session_type)?;
  212. let id: u64 = 0;
  213. let connect_id = make_connect_id(id)?;
  214. let addr = "Null".to_string();
  215. let msg = "Null".to_string();
  216. let status = "Null".to_string();
  217. let is_empty = true;
  218. let parent = session_id.clone();
  219. let state = "Null".to_string();
  220. let msg_log = Vec::new();
  221. let connect_info =
  222. ConnectInfo::new(connect_id, addr, is_empty, msg, status, state, msg_log, parent);
  223. connects.push(connect_info.clone());
  224. let session_info = SessionInfo::new(session_id, node_id, connects.clone());
  225. Ok(session_info)
  226. }
  227. async fn parse_outbound(outbound: &Value, node_id: String) -> Result<SessionInfo> {
  228. let session_type = Session::Outbound;
  229. let mut connects: Vec<ConnectInfo> = Vec::new();
  230. let slots = &outbound["slots"];
  231. let session_id = make_session_id(node_id.clone(), &session_type)?;
  232. match slots.as_array() {
  233. Some(slots) => {
  234. for slot in slots {
  235. match slot["channel"].is_null() {
  236. true => {
  237. // channel is empty. initialize with empty values
  238. // TODO: fix this
  239. let connect_id = generate_id()?;
  240. let is_empty = true;
  241. let addr = "Null".to_string();
  242. let state = &slot["state"];
  243. let msg = "Null".to_string();
  244. let status = "Null".to_string();
  245. // TODO: msg log
  246. let msg_log = Vec::new();
  247. let parent = session_id.clone();
  248. let connect_info = ConnectInfo::new(
  249. connect_id,
  250. addr,
  251. is_empty,
  252. msg,
  253. status,
  254. state.as_str().unwrap().to_string(),
  255. msg_log,
  256. parent,
  257. );
  258. connects.push(connect_info.clone());
  259. }
  260. false => {
  261. // channel is not empty. initialize with whole values
  262. let channel = &slot["channel"];
  263. let last_msg = channel["last_msg"].as_str().unwrap().to_string();
  264. let last_status = channel["last_status"].as_str().unwrap().to_string();
  265. let id = channel["random_id"].as_u64().unwrap();
  266. let connect_id = make_connect_id(id)?;
  267. let is_empty = false;
  268. let addr = &slot["addr"];
  269. let state = &slot["state"];
  270. let parent = session_id.clone();
  271. // TODO: deserialize msg_log
  272. let _msg_log = channel["log"].as_array().unwrap();
  273. let msg_log = Vec::new();
  274. let connect_info = ConnectInfo::new(
  275. connect_id,
  276. addr.as_str().unwrap().to_string(),
  277. is_empty,
  278. last_msg,
  279. last_status,
  280. state.as_str().unwrap().to_string(),
  281. msg_log,
  282. parent,
  283. );
  284. connects.push(connect_info.clone());
  285. }
  286. }
  287. }
  288. let session_info = SessionInfo::new(session_id, node_id, connects.clone());
  289. Ok(session_info)
  290. }
  291. None => Err(Error::ValueIsNotObject),
  292. }
  293. }
  294. fn make_node_id(node_name: &String) -> Result<String> {
  295. Ok(serial::serialize_hex(node_name))
  296. }
  297. pub fn make_session_id(node_id: String, session: &Session) -> Result<String> {
  298. let mut num = 0_u64;
  299. match session {
  300. Session::Inbound => {
  301. for i in ['i', 'n'] {
  302. num += i as u64;
  303. }
  304. }
  305. Session::Outbound => {
  306. for i in ['o', 'u', 't'] {
  307. num += i as u64;
  308. }
  309. }
  310. Session::Manual => {
  311. for i in ['m', 'a', 'n'] {
  312. num += i as u64;
  313. }
  314. }
  315. }
  316. for i in node_id.chars() {
  317. num += i as u64
  318. }
  319. Ok(serial::serialize_hex(&num))
  320. }
  321. pub fn make_connect_id(id: u64) -> Result<String> {
  322. Ok(serial::serialize_hex(&id))
  323. }
  324. // we use a random id for empty connections
  325. fn generate_id() -> Result<String> {
  326. let mut rng = thread_rng();
  327. let id: u32 = rng.gen();
  328. Ok(serial::serialize_hex(&id))
  329. }
  330. //fn is_empty_outbound(slots: Vec<Slot>) -> bool {
  331. // return slots.iter().all(|slot| slot.is_empty);
  332. //}
  333. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> Result<()> {
  334. let mut asi = async_stdin();
  335. terminal.clear()?;
  336. let id_list = IdListView::new(FxHashSet::default());
  337. let info_list = InfoListView::new(FxHashMap::default());
  338. let mut view = View::new(id_list.clone(), info_list.clone());
  339. view.id_list.state.select(Some(0));
  340. view.info_list.index = 0;
  341. loop {
  342. //view.update(model.info_list.infos.lock().await.clone());
  343. terminal.draw(|f| {
  344. ui::ui(f, view.clone());
  345. })?;
  346. for k in asi.by_ref().keys() {
  347. match k.unwrap() {
  348. Key::Char('q') => {
  349. terminal.clear()?;
  350. return Ok(())
  351. }
  352. Key::Char('j') => {
  353. view.id_list.next();
  354. }
  355. Key::Char('k') => {
  356. view.id_list.previous();
  357. }
  358. _ => (),
  359. }
  360. }
  361. }
  362. }