main.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. use darkfi::{
  2. error::{Error, Result},
  3. rpc::{jsonrpc, jsonrpc::JsonResult},
  4. util::{
  5. async_util,
  6. cli::{log_config, spawn_config, Config},
  7. join_config_path,
  8. },
  9. };
  10. use async_std::sync::Arc;
  11. use easy_parallel::Parallel;
  12. use log::{debug, info};
  13. use serde_json::{json, Value};
  14. use simplelog::*;
  15. use smol::Executor;
  16. use std::{
  17. collections::{HashMap, HashSet},
  18. fs::File,
  19. io,
  20. io::Read,
  21. net::SocketAddr,
  22. path::PathBuf,
  23. };
  24. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  25. use tui::{
  26. backend::{Backend, TermionBackend},
  27. Terminal,
  28. };
  29. use url::Url;
  30. use dnetview::{
  31. config::{DnvConfig, CONFIG_FILE_CONTENTS},
  32. model::{Channel, IdList, InboundInfo, InfoList, ManualInfo, NodeInfo, OutboundInfo, Slot},
  33. options::ProgramOptions,
  34. ui,
  35. view::{IdListView, InfoListView},
  36. Model, View,
  37. };
  38. struct Map {
  39. url: Url,
  40. }
  41. impl Map {
  42. pub fn new(url: Url) -> Self {
  43. Self { url }
  44. }
  45. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  46. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r), None).await {
  47. Ok(v) => v,
  48. Err(e) => return Err(e),
  49. };
  50. match reply {
  51. JsonResult::Resp(r) => {
  52. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  53. Ok(r.result)
  54. }
  55. JsonResult::Err(e) => {
  56. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  57. Err(Error::JsonRpcError(e.error.message.to_string()))
  58. }
  59. JsonResult::Notif(n) => {
  60. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  61. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  62. }
  63. }
  64. }
  65. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  66. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  67. async fn _ping(&self) -> Result<Value> {
  68. let req = jsonrpc::request(json!("ping"), json!([]));
  69. Ok(self.request(req).await?)
  70. }
  71. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  72. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  73. async fn get_info(&self) -> Result<Value> {
  74. let req = jsonrpc::request(json!("get_info"), json!([]));
  75. Ok(self.request(req).await?)
  76. }
  77. }
  78. #[async_std::main]
  79. async fn main() -> Result<()> {
  80. let options = ProgramOptions::load()?;
  81. let verbosity_level = options.app.occurrences_of("verbose");
  82. let (lvl, cfg) = log_config(verbosity_level)?;
  83. let file = File::create(&*options.log_path).unwrap();
  84. WriteLogger::init(lvl, cfg, file)?;
  85. info!("Log level: {}", lvl);
  86. let config_path = join_config_path(&PathBuf::from("dnetview_config.toml"))?;
  87. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  88. let config = Config::<DnvConfig>::load(config_path)?;
  89. let stdout = io::stdout().into_raw_mode()?;
  90. let backend = TermionBackend::new(stdout);
  91. let mut terminal = Terminal::new(backend)?;
  92. terminal.clear()?;
  93. let info_list = InfoList::new();
  94. let ids = HashSet::new();
  95. let id_list = IdList::new(ids);
  96. let model = Arc::new(Model::new(id_list, info_list));
  97. let nthreads = num_cpus::get();
  98. let (signal, shutdown) = async_channel::unbounded::<()>();
  99. let ex = Arc::new(Executor::new());
  100. let ex2 = ex.clone();
  101. let (_, result) = Parallel::new()
  102. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  103. .finish(|| {
  104. smol::future::block_on(async move {
  105. run_rpc(&config, ex2.clone(), model.clone()).await?;
  106. render(&mut terminal, model.clone()).await?;
  107. drop(signal);
  108. Ok::<(), darkfi::Error>(())
  109. })
  110. });
  111. result
  112. }
  113. async fn run_rpc(config: &DnvConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  114. for node in config.nodes.clone() {
  115. let client = Map::new(Url::parse(&node.node_id)?);
  116. ex.spawn(poll(client, model.clone())).detach();
  117. }
  118. Ok(())
  119. }
  120. async fn poll(client: Map, model: Arc<Model>) -> Result<()> {
  121. debug!("Attemping to poll: {}", client.url);
  122. loop {
  123. let reply = client.get_info().await?;
  124. debug!("{:?}", reply);
  125. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  126. // TODO: clean up this section into seperate functions.
  127. // TODO: replace if/else with match where possible
  128. // TODO: test than all of these unwraps will never ever crash
  129. let ext_addr_option = reply.as_object().unwrap().get("external_addr");
  130. let inbound_obj = &reply.as_object().unwrap()["session_inbound"];
  131. let manual_obj = &reply.as_object().unwrap()["session_manual"];
  132. let outbound_obj = &reply.as_object().unwrap()["session_outbound"];
  133. let mut inconnects = Vec::new();
  134. let mut manconnects = Vec::new();
  135. let mut outconnects = Vec::new();
  136. let mut slots = Vec::new();
  137. // parse inbound connection data
  138. let inbound_connected = &inbound_obj["connected"];
  139. if !inbound_connected.as_object().unwrap().is_empty() {
  140. let inbound_connect: InboundInfo =
  141. serde_json::from_value(inbound_connected.clone())?;
  142. inconnects.push(inbound_connect);
  143. }
  144. // parse manual connection data
  145. let manual_connect: ManualInfo = serde_json::from_value(manual_obj.clone())?;
  146. manconnects.push(manual_connect);
  147. // parse outbound connection data
  148. let outbound_slots = &outbound_obj["slots"];
  149. for slot in outbound_slots.as_array().unwrap() {
  150. if slot["channel"].is_null() {
  151. // channel is empty. initialize with empty values
  152. let state = &slot["state"];
  153. let channel = Channel::new(String::new(), String::new());
  154. let new_slot =
  155. Slot::new(String::new(), channel, state.as_str().unwrap().to_string());
  156. slots.push(new_slot)
  157. } else {
  158. // channel is not empty. initialize with whole values
  159. let addr = &slot["addr"];
  160. let state = &slot["state"];
  161. let channel: Channel = serde_json::from_value(slot["channel"].clone())?;
  162. let new_slot = Slot::new(
  163. addr.as_str().unwrap().to_string(),
  164. channel,
  165. state.as_str().unwrap().to_string(),
  166. );
  167. slots.push(new_slot)
  168. }
  169. }
  170. let oconnect = OutboundInfo::new(slots);
  171. outconnects.push(oconnect);
  172. let infos =
  173. NodeInfo { outbound: outconnects, manual: manconnects, inbound: inconnects };
  174. let mut node_info = HashMap::new();
  175. // TODO: if the external_addr is empty, we set the display address as the rpc url.
  176. // however we need to add a 'name' param to the config file to display instead
  177. match ext_addr_option {
  178. Some(addr) => {
  179. debug!("{:?}", addr);
  180. let external_addr = addr.as_str().unwrap();
  181. node_info.insert(external_addr, infos);
  182. }
  183. _ => {
  184. let external_addr = &client.url;
  185. node_info.insert(external_addr.as_str(), infos);
  186. }
  187. }
  188. for (key, value) in node_info.clone() {
  189. model.id_list.node_id.lock().await.insert(key.to_string().clone());
  190. model.info_list.infos.lock().await.insert(key.to_string(), value);
  191. }
  192. } else {
  193. // TODO: error handling
  194. debug!("Reply is empty");
  195. }
  196. async_util::sleep(2).await;
  197. }
  198. }
  199. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  200. let mut asi = async_stdin();
  201. terminal.clear()?;
  202. let id_list = IdListView::new(HashSet::new());
  203. let info_list = InfoListView::new(HashMap::new());
  204. let mut view = View::new(id_list.clone(), info_list.clone());
  205. view.id_list.state.select(Some(0));
  206. view.info_list.index = 0;
  207. loop {
  208. view.update(model.info_list.infos.lock().await.clone());
  209. terminal.draw(|f| {
  210. ui::ui(f, view.clone());
  211. })?;
  212. for k in asi.by_ref().keys() {
  213. match k.unwrap() {
  214. Key::Char('q') => {
  215. terminal.clear()?;
  216. return Ok(())
  217. }
  218. Key::Char('j') => {
  219. view.id_list.next();
  220. view.info_list.next().await;
  221. }
  222. Key::Char('k') => {
  223. view.id_list.previous();
  224. view.info_list.previous().await;
  225. }
  226. _ => (),
  227. }
  228. }
  229. }
  230. }