main.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 iinfo = InboundInfo::new(connected, channel);
  144. iconnects.push(iinfo);
  145. } else {
  146. // channel is not empty. initialize with whole values
  147. let ic = i_connected.as_object().unwrap();
  148. for k in ic.keys() {
  149. let addr = k.to_string();
  150. for v in ic.values() {
  151. let msg = v.get("last_msg").unwrap().as_str().unwrap().to_string();
  152. let status = v.get("last_status").unwrap().as_str().unwrap().to_string();
  153. let channel = Channel::new(msg, status);
  154. let iinfo = InboundInfo::new(addr.clone(), channel);
  155. iconnects.push(iinfo);
  156. }
  157. }
  158. }
  159. // parse manual connection data
  160. let minfo: ManualInfo = serde_json::from_value(manual_obj.clone())?;
  161. mconnects.push(minfo);
  162. // parse outbound connection data
  163. let outbound_slots = &outbound_obj["slots"];
  164. for slot in outbound_slots.as_array().unwrap() {
  165. if slot["channel"].is_null() {
  166. // channel is empty. initialize with empty values
  167. let state = &slot["state"];
  168. let msg = "Null".to_string();
  169. let status = "Null".to_string();
  170. let channel = Channel::new(msg, status);
  171. let new_slot = Slot::new(
  172. String::from("Empty"),
  173. channel,
  174. state.as_str().unwrap().to_string(),
  175. );
  176. slots.push(new_slot.clone())
  177. } else {
  178. // channel is not empty. initialize with whole values
  179. let addr = &slot["addr"];
  180. let state = &slot["state"];
  181. let channel: Channel = serde_json::from_value(slot["channel"].clone())?;
  182. let new_slot = Slot::new(
  183. addr.as_str().unwrap().to_string(),
  184. channel,
  185. state.as_str().unwrap().to_string(),
  186. );
  187. slots.push(new_slot)
  188. }
  189. let oinfo = OutboundInfo::new(slots.clone());
  190. oconnects.push(oinfo);
  191. }
  192. let infos = NodeInfo { outbound: oconnects, manual: mconnects, inbound: iconnects };
  193. let mut node_info = HashMap::new();
  194. // TODO: here we are setting the RPC url as the node_id.
  195. // next step is to read the string variable 'name' from dnetview.toml
  196. let node_id = &client.url.as_str();
  197. node_info.insert(&node_id, infos.clone());
  198. for (key, value) in node_info.clone() {
  199. model.id_list.node_id.lock().await.insert(key.to_string().clone());
  200. model.info_list.infos.lock().await.insert(key.to_string(), value);
  201. }
  202. } else {
  203. // TODO: error handling
  204. //debug!("Reply is empty");
  205. }
  206. async_util::sleep(2).await;
  207. }
  208. }
  209. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  210. let mut asi = async_stdin();
  211. terminal.clear()?;
  212. let id_list = IdListView::new(HashSet::new());
  213. let info_list = InfoListView::new(HashMap::new());
  214. let mut view = View::new(id_list.clone(), info_list.clone());
  215. view.id_list.state.select(Some(0));
  216. view.info_list.index = 0;
  217. loop {
  218. view.update(model.info_list.infos.lock().await.clone());
  219. terminal.draw(|f| {
  220. ui::ui(f, view.clone());
  221. })?;
  222. for k in asi.by_ref().keys() {
  223. match k.unwrap() {
  224. Key::Char('q') => {
  225. terminal.clear()?;
  226. return Ok(())
  227. }
  228. Key::Char('j') => {
  229. view.id_list.next();
  230. view.info_list.next().await;
  231. }
  232. Key::Char('k') => {
  233. view.id_list.previous();
  234. view.info_list.previous().await;
  235. }
  236. _ => (),
  237. }
  238. }
  239. //async_util::sleep(3).await;
  240. }
  241. }