main.rs 10.0 KB

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