parser.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. use async_std::sync::Arc;
  2. use std::collections::hash_map::Entry;
  3. use log::{debug, error, info};
  4. use serde_json::Value;
  5. use smol::Executor;
  6. use url::Url;
  7. use darkfi::util::NanoTimestamp;
  8. use crate::{
  9. config::{DnvConfig, Node, NodeType},
  10. error::{DnetViewError, DnetViewResult},
  11. model::{
  12. ConnectInfo, LilithInfo, Model, NetworkInfo, NodeInfo, SelectableObject, Session,
  13. SessionInfo,
  14. },
  15. rpc::RpcConnect,
  16. util::{is_empty_session, make_connect_id, make_empty_id, make_node_id, make_session_id},
  17. };
  18. pub struct DataParser {
  19. model: Arc<Model>,
  20. config: DnvConfig,
  21. }
  22. impl DataParser {
  23. pub fn new(model: Arc<Model>, config: DnvConfig) -> Arc<Self> {
  24. Arc::new(Self { model, config })
  25. }
  26. pub async fn start_connect_slots(self: Arc<Self>, ex: Arc<Executor<'_>>) -> DnetViewResult<()> {
  27. debug!(target: "dnetview", "start_connect_slots() START");
  28. for node in &self.config.nodes {
  29. debug!(target: "dnetview", "attempting to spawn...");
  30. ex.clone().spawn(self.clone().try_connect(node.clone())).detach();
  31. }
  32. Ok(())
  33. }
  34. async fn try_connect(self: Arc<Self>, node: Node) -> DnetViewResult<()> {
  35. debug!(target: "dnetview", "try_connect() START");
  36. loop {
  37. info!("Attempting to poll {}, RPC URL: {}", node.name, node.rpc_url);
  38. // Parse node config and execute poll.
  39. // On any failure, sleep and retry.
  40. match RpcConnect::new(Url::parse(&node.rpc_url)?, node.name.clone()).await {
  41. Ok(client) => {
  42. if let Err(e) = self.poll(&node, client).await {
  43. error!("Poll execution error: {:?}", e);
  44. }
  45. }
  46. Err(e) => {
  47. error!("RPC client creation error: {:?}", e);
  48. }
  49. }
  50. self.parse_offline(node.name.clone()).await?;
  51. crate::util::sleep(2000).await;
  52. }
  53. }
  54. async fn poll(&self, node: &Node, client: RpcConnect) -> DnetViewResult<()> {
  55. loop {
  56. // Ping the node to verify if its online.
  57. if let Err(e) = client.ping().await {
  58. return Err(DnetViewError::Darkfi(e))
  59. }
  60. // Retrieve node info, based on its type
  61. let response = match &node.node_type {
  62. NodeType::LILITH => client.lilith_spawns().await,
  63. NodeType::NORMAL => client.get_info().await,
  64. };
  65. // Parse response
  66. match response {
  67. Ok(reply) => {
  68. if reply.as_object().is_none() || reply.as_object().unwrap().is_empty() {
  69. return Err(DnetViewError::EmptyRpcReply)
  70. }
  71. match &node.node_type {
  72. NodeType::LILITH => {
  73. self.parse_lilith_data(
  74. reply.as_object().unwrap().clone(),
  75. node.name.clone(),
  76. )
  77. .await?
  78. }
  79. NodeType::NORMAL => {
  80. self.parse_data(reply.as_object().unwrap(), node.name.clone()).await?
  81. }
  82. };
  83. }
  84. Err(e) => return Err(e),
  85. }
  86. // Sleep until next poll
  87. crate::util::sleep(2000).await;
  88. }
  89. }
  90. async fn parse_offline(&self, node_name: String) -> DnetViewResult<()> {
  91. let name = "Offline".to_string();
  92. let session_type = Session::Offline;
  93. let node_id = make_node_id(&node_name)?;
  94. let session_id = make_session_id(&node_id, &session_type)?;
  95. let mut connects: Vec<ConnectInfo> = Vec::new();
  96. let mut sessions: Vec<SessionInfo> = Vec::new();
  97. // initialize with empty values
  98. let id = make_empty_id(&node_id, &session_type, 0)?;
  99. let addr = "Null".to_string();
  100. let state = "Null".to_string();
  101. let parent = node_id.clone();
  102. let msg_log = Vec::new();
  103. let is_empty = true;
  104. let last_msg = "Null".to_string();
  105. let last_status = "Null".to_string();
  106. let remote_node_id = "Null".to_string();
  107. let connect_info = ConnectInfo::new(
  108. id,
  109. addr,
  110. state.clone(),
  111. parent.clone(),
  112. msg_log,
  113. is_empty,
  114. last_msg,
  115. last_status,
  116. remote_node_id,
  117. );
  118. connects.push(connect_info.clone());
  119. let accept_addr = None;
  120. let session_info =
  121. SessionInfo::new(session_id, name, is_empty, parent, connects, accept_addr, None);
  122. sessions.push(session_info);
  123. let node = NodeInfo::new(node_id, node_name, state, sessions.clone(), None, true);
  124. self.update_selectables(sessions, node).await?;
  125. Ok(())
  126. }
  127. async fn parse_data(
  128. &self,
  129. reply: &serde_json::Map<String, Value>,
  130. node_name: String,
  131. ) -> DnetViewResult<()> {
  132. let addr = &reply.get("external_addr");
  133. let inbound = &reply["session_inbound"];
  134. let _manual = &reply["session_manual"];
  135. let outbound = &reply["session_outbound"];
  136. let state = &reply["state"];
  137. let mut sessions: Vec<SessionInfo> = Vec::new();
  138. let node_id = make_node_id(&node_name)?;
  139. let ext_addr = self.parse_external_addr(addr).await?;
  140. let in_session = self.parse_inbound(inbound, &node_id).await?;
  141. let out_session = self.parse_outbound(outbound, &node_id).await?;
  142. //let man_session = self.parse_manual(manual, &node_id).await?;
  143. sessions.push(in_session.clone());
  144. sessions.push(out_session.clone());
  145. //sessions.push(man_session.clone());
  146. let node = NodeInfo::new(
  147. node_id,
  148. node_name,
  149. state.as_str().unwrap().to_string(),
  150. sessions.clone(),
  151. ext_addr,
  152. false,
  153. );
  154. self.update_selectables(sessions.clone(), node).await?;
  155. self.update_msgs(sessions).await?;
  156. //debug!("IDS: {:?}", self.model.ids.lock().await);
  157. //debug!("INFOS: {:?}", self.model.nodes.lock().await);
  158. Ok(())
  159. }
  160. async fn parse_lilith_data(
  161. &self,
  162. reply: serde_json::Map<String, Value>,
  163. name: String,
  164. ) -> DnetViewResult<()> {
  165. let urls: Vec<String> = serde_json::from_value(reply.get("urls").unwrap().clone()).unwrap();
  166. let spawns: Vec<serde_json::Map<String, Value>> =
  167. serde_json::from_value(reply.get("spawns").unwrap().clone()).unwrap();
  168. let mut networks = vec![];
  169. for spawn in spawns {
  170. let name = spawn.get("name").unwrap().as_str().unwrap().to_string();
  171. let id = make_node_id(&name)?;
  172. let urls: Vec<String> =
  173. serde_json::from_value(spawn.get("urls").unwrap().clone()).unwrap();
  174. let nodes: Vec<String> =
  175. serde_json::from_value(spawn.get("hosts").unwrap().clone()).unwrap();
  176. let network = NetworkInfo::new(id, name, urls, nodes);
  177. networks.push(network);
  178. }
  179. let id = make_node_id(&name)?;
  180. let lilith = LilithInfo::new(id.clone(), name, urls, networks);
  181. let lilith_obj = SelectableObject::Lilith(lilith.clone());
  182. self.model.selectables.lock().await.insert(id, lilith_obj);
  183. for network in lilith.networks {
  184. let network_obj = SelectableObject::Network(network.clone());
  185. self.model.selectables.lock().await.insert(network.id, network_obj);
  186. }
  187. Ok(())
  188. }
  189. async fn update_msgs(&self, sessions: Vec<SessionInfo>) -> DnetViewResult<()> {
  190. for session in sessions {
  191. for connection in session.children {
  192. if !self.model.msg_map.lock().await.contains_key(&connection.id) {
  193. // we don't have this ID: it is a new node
  194. self.model
  195. .msg_map
  196. .lock()
  197. .await
  198. .insert(connection.id, connection.msg_log.clone());
  199. } else {
  200. // we have this id: append the msg values
  201. match self.model.msg_map.lock().await.entry(connection.id) {
  202. Entry::Vacant(e) => {
  203. e.insert(connection.msg_log);
  204. }
  205. Entry::Occupied(mut e) => {
  206. for msg in connection.msg_log {
  207. e.get_mut().push(msg);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. Ok(())
  215. }
  216. async fn update_selectables(
  217. &self,
  218. sessions: Vec<SessionInfo>,
  219. node: NodeInfo,
  220. ) -> DnetViewResult<()> {
  221. if node.is_offline {
  222. let node_obj = SelectableObject::Node(node.clone());
  223. self.model.selectables.lock().await.insert(node.id.clone(), node_obj.clone());
  224. } else {
  225. let node_obj = SelectableObject::Node(node.clone());
  226. self.model.selectables.lock().await.insert(node.id.clone(), node_obj.clone());
  227. for session in sessions {
  228. if !session.is_empty {
  229. let session_obj = SelectableObject::Session(session.clone());
  230. self.model
  231. .selectables
  232. .lock()
  233. .await
  234. .insert(session.clone().id, session_obj.clone());
  235. for connect in session.children {
  236. let connect_obj = SelectableObject::Connect(connect.clone());
  237. self.model
  238. .selectables
  239. .lock()
  240. .await
  241. .insert(connect.clone().id, connect_obj.clone());
  242. }
  243. }
  244. }
  245. }
  246. Ok(())
  247. }
  248. async fn parse_external_addr(&self, addr: &Option<&Value>) -> DnetViewResult<Option<String>> {
  249. match addr {
  250. Some(addr) => match addr.as_str() {
  251. Some(addr) => Ok(Some(addr.to_string())),
  252. None => Ok(None),
  253. },
  254. None => Err(DnetViewError::NoExternalAddr),
  255. }
  256. }
  257. async fn parse_inbound(
  258. &self,
  259. inbound: &Value,
  260. node_id: &String,
  261. ) -> DnetViewResult<SessionInfo> {
  262. let name = "Inbound".to_string();
  263. let session_type = Session::Inbound;
  264. let parent = node_id.to_string();
  265. let id = make_session_id(&parent, &session_type)?;
  266. let mut connects: Vec<ConnectInfo> = Vec::new();
  267. let connections = &inbound["connected"];
  268. let mut connect_count = 0;
  269. let mut accept_vec = Vec::new();
  270. match connections.as_object() {
  271. Some(connect) => {
  272. match connect.is_empty() {
  273. true => {
  274. connect_count += 1;
  275. // channel is empty. initialize with empty values
  276. let id = make_empty_id(node_id, &session_type, connect_count)?;
  277. let addr = "Null".to_string();
  278. let state = "Null".to_string();
  279. let parent = parent.clone();
  280. let msg_log = Vec::new();
  281. let is_empty = true;
  282. let last_msg = "Null".to_string();
  283. let last_status = "Null".to_string();
  284. let remote_node_id = "Null".to_string();
  285. let connect_info = ConnectInfo::new(
  286. id,
  287. addr,
  288. state,
  289. parent,
  290. msg_log,
  291. is_empty,
  292. last_msg,
  293. last_status,
  294. remote_node_id,
  295. );
  296. connects.push(connect_info);
  297. }
  298. false => {
  299. // channel is not empty. initialize with whole values
  300. for k in connect.keys() {
  301. let node = connect.get(k);
  302. let addr = k.to_string();
  303. let info = node.unwrap().as_array();
  304. // get the accept address
  305. let accept_addr = info.unwrap().get(0);
  306. let acc_addr = accept_addr
  307. .unwrap()
  308. .get("accept_addr")
  309. .unwrap()
  310. .as_str()
  311. .unwrap()
  312. .to_string();
  313. accept_vec.push(acc_addr);
  314. let info2 = info.unwrap().get(1);
  315. let id = info2.unwrap().get("random_id").unwrap().as_u64().unwrap();
  316. let id = make_connect_id(&id)?;
  317. let state = "state".to_string();
  318. let parent = parent.clone();
  319. let msg_values = info2.unwrap().get("log").unwrap().as_array().unwrap();
  320. let mut msg_log: Vec<(NanoTimestamp, String, String)> = Vec::new();
  321. for msg in msg_values {
  322. let msg: (NanoTimestamp, String, String) =
  323. serde_json::from_value(msg.clone())?;
  324. msg_log.push(msg);
  325. }
  326. let is_empty = false;
  327. let last_msg = info2
  328. .unwrap()
  329. .get("last_msg")
  330. .unwrap()
  331. .as_str()
  332. .unwrap()
  333. .to_string();
  334. let last_status = info2
  335. .unwrap()
  336. .get("last_status")
  337. .unwrap()
  338. .as_str()
  339. .unwrap()
  340. .to_string();
  341. let remote_node_id = info2
  342. .unwrap()
  343. .get("remote_node_id")
  344. .unwrap()
  345. .as_str()
  346. .unwrap()
  347. .to_string();
  348. let r_node_id: String = match remote_node_id.is_empty() {
  349. true => "no remote id".to_string(),
  350. false => remote_node_id,
  351. };
  352. let connect_info = ConnectInfo::new(
  353. id,
  354. addr,
  355. state,
  356. parent,
  357. msg_log,
  358. is_empty,
  359. last_msg,
  360. last_status,
  361. r_node_id,
  362. );
  363. connects.push(connect_info.clone());
  364. }
  365. }
  366. }
  367. let is_empty = is_empty_session(&connects);
  368. // TODO: clean this up
  369. if accept_vec.is_empty() {
  370. let accept_addr = None;
  371. let session_info =
  372. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr, None);
  373. Ok(session_info)
  374. } else {
  375. let accept_addr = Some(accept_vec[0].clone());
  376. let session_info =
  377. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr, None);
  378. Ok(session_info)
  379. }
  380. }
  381. None => Err(DnetViewError::ValueIsNotObject),
  382. }
  383. }
  384. // TODO: placeholder for now
  385. async fn _parse_manual(
  386. &self,
  387. _manual: &Value,
  388. node_id: &String,
  389. ) -> DnetViewResult<SessionInfo> {
  390. let name = "Manual".to_string();
  391. let session_type = Session::Manual;
  392. let mut connects: Vec<ConnectInfo> = Vec::new();
  393. let parent = node_id.to_string();
  394. let session_id = make_session_id(&parent, &session_type)?;
  395. //let id: u64 = 0;
  396. let connect_id = make_empty_id(node_id, &session_type, 0)?;
  397. //let connect_id = make_connect_id(&id)?;
  398. let addr = "Null".to_string();
  399. let state = "Null".to_string();
  400. let msg_log = Vec::new();
  401. let is_empty = true;
  402. let msg = "Null".to_string();
  403. let status = "Null".to_string();
  404. let remote_node_id = "Null".to_string();
  405. let connect_info = ConnectInfo::new(
  406. connect_id.clone(),
  407. addr,
  408. state,
  409. parent,
  410. msg_log,
  411. is_empty,
  412. msg,
  413. status,
  414. remote_node_id,
  415. );
  416. connects.push(connect_info);
  417. let parent = connect_id;
  418. let is_empty = is_empty_session(&connects);
  419. let accept_addr = None;
  420. let session_info = SessionInfo::new(
  421. session_id,
  422. name,
  423. is_empty,
  424. parent,
  425. connects.clone(),
  426. accept_addr,
  427. None,
  428. );
  429. Ok(session_info)
  430. }
  431. async fn parse_outbound(
  432. &self,
  433. outbound: &Value,
  434. node_id: &String,
  435. ) -> DnetViewResult<SessionInfo> {
  436. let name = "Outbound".to_string();
  437. let session_type = Session::Outbound;
  438. let parent = node_id.to_string();
  439. let id = make_session_id(&parent, &session_type)?;
  440. let mut connects: Vec<ConnectInfo> = Vec::new();
  441. let slots = &outbound["slots"];
  442. let mut slot_count = 0;
  443. let hosts = &outbound["hosts"];
  444. match slots.as_array() {
  445. Some(slots) => {
  446. for slot in slots {
  447. slot_count += 1;
  448. match slot["channel"].is_null() {
  449. true => {
  450. // TODO: this is not actually empty
  451. let id = make_empty_id(node_id, &session_type, slot_count)?;
  452. let addr = "Null".to_string();
  453. let state = &slot["state"];
  454. let state = state.as_str().unwrap().to_string();
  455. let parent = parent.clone();
  456. let msg_log = Vec::new();
  457. let is_empty = false;
  458. let last_msg = "Null".to_string();
  459. let last_status = "Null".to_string();
  460. let remote_node_id = "Null".to_string();
  461. let connect_info = ConnectInfo::new(
  462. id,
  463. addr,
  464. state,
  465. parent,
  466. msg_log,
  467. is_empty,
  468. last_msg,
  469. last_status,
  470. remote_node_id,
  471. );
  472. connects.push(connect_info.clone());
  473. }
  474. false => {
  475. // channel is not empty. initialize with whole values
  476. let channel = &slot["channel"];
  477. let id = channel["random_id"].as_u64().unwrap();
  478. let id = make_connect_id(&id)?;
  479. let addr = &slot["addr"];
  480. let addr = addr.as_str().unwrap().to_string();
  481. let state = &slot["state"];
  482. let state = state.as_str().unwrap().to_string();
  483. let parent = parent.clone();
  484. let msg_values = channel["log"].as_array().unwrap();
  485. let mut msg_log: Vec<(NanoTimestamp, String, String)> = Vec::new();
  486. for msg in msg_values {
  487. let msg: (NanoTimestamp, String, String) =
  488. serde_json::from_value(msg.clone())?;
  489. msg_log.push(msg);
  490. }
  491. let is_empty = false;
  492. let last_msg = channel["last_msg"].as_str().unwrap().to_string();
  493. let last_status = channel["last_status"].as_str().unwrap().to_string();
  494. let remote_node_id =
  495. channel["remote_node_id"].as_str().unwrap().to_string();
  496. let r_node_id: String = match remote_node_id.is_empty() {
  497. true => "no remote id".to_string(),
  498. false => remote_node_id,
  499. };
  500. let connect_info = ConnectInfo::new(
  501. id,
  502. addr,
  503. state,
  504. parent,
  505. msg_log,
  506. is_empty,
  507. last_msg,
  508. last_status,
  509. r_node_id,
  510. );
  511. connects.push(connect_info.clone());
  512. }
  513. }
  514. }
  515. let is_empty = is_empty_session(&connects);
  516. let accept_addr = None;
  517. match hosts.as_array() {
  518. Some(hosts) => {
  519. let hosts: Vec<String> =
  520. hosts.iter().map(|addr| addr.as_str().unwrap().to_string()).collect();
  521. let session_info = SessionInfo::new(
  522. id,
  523. name,
  524. is_empty,
  525. parent,
  526. connects,
  527. accept_addr,
  528. Some(hosts),
  529. );
  530. Ok(session_info)
  531. }
  532. None => Err(DnetViewError::ValueIsNotObject),
  533. }
  534. }
  535. None => Err(DnetViewError::ValueIsNotObject),
  536. }
  537. }
  538. }