parser.rs 23 KB

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