parser.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 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. };
  82. // Parse response
  83. match response {
  84. Ok(reply) => {
  85. if reply.as_object().is_none() || reply.as_object().unwrap().is_empty() {
  86. return Err(DnetViewError::EmptyRpcReply)
  87. }
  88. match &node.node_type {
  89. NodeType::LILITH => {
  90. self.parse_lilith_data(
  91. reply.as_object().unwrap().clone(),
  92. node.name.clone(),
  93. )
  94. .await?
  95. }
  96. NodeType::NORMAL => {
  97. self.parse_data(reply.as_object().unwrap(), node.name.clone()).await?
  98. }
  99. };
  100. }
  101. Err(e) => return Err(e),
  102. }
  103. // Sleep until next poll
  104. async_util::sleep(2000).await;
  105. }
  106. }
  107. async fn parse_offline(&self, node_name: String) -> DnetViewResult<()> {
  108. let name = "Offline".to_string();
  109. let session_type = Session::Offline;
  110. let node_id = make_node_id(&node_name)?;
  111. let session_id = make_session_id(&node_id, &session_type)?;
  112. let mut connects: Vec<ConnectInfo> = Vec::new();
  113. let mut sessions: Vec<SessionInfo> = Vec::new();
  114. // initialize with empty values
  115. let id = make_empty_id(&node_id, &session_type, 0)?;
  116. let addr = "Null".to_string();
  117. let state = "Null".to_string();
  118. let parent = node_id.clone();
  119. let msg_log = Vec::new();
  120. let is_empty = true;
  121. let last_msg = "Null".to_string();
  122. let last_status = "Null".to_string();
  123. let remote_node_id = "Null".to_string();
  124. let connect_info = ConnectInfo::new(
  125. id,
  126. addr,
  127. state.clone(),
  128. parent.clone(),
  129. msg_log,
  130. is_empty,
  131. last_msg,
  132. last_status,
  133. remote_node_id,
  134. );
  135. connects.push(connect_info.clone());
  136. let accept_addr = None;
  137. let session_info =
  138. SessionInfo::new(session_id, name, is_empty, parent, connects, accept_addr, None);
  139. sessions.push(session_info);
  140. let node = NodeInfo::new(node_id, node_name, state, sessions.clone(), None, true);
  141. self.update_selectables(sessions, node).await?;
  142. Ok(())
  143. }
  144. async fn parse_data(
  145. &self,
  146. reply: &serde_json::Map<String, Value>,
  147. node_name: String,
  148. ) -> DnetViewResult<()> {
  149. let addr = &reply.get("external_addr");
  150. let inbound = &reply["session_inbound"];
  151. let _manual = &reply["session_manual"];
  152. let outbound = &reply["session_outbound"];
  153. let state = &reply["state"];
  154. let mut sessions: Vec<SessionInfo> = Vec::new();
  155. let node_id = make_node_id(&node_name)?;
  156. let ext_addr = self.parse_external_addr(addr).await?;
  157. let in_session = self.parse_inbound(inbound, &node_id).await?;
  158. let out_session = self.parse_outbound(outbound, &node_id).await?;
  159. //let man_session = self.parse_manual(manual, &node_id).await?;
  160. sessions.push(in_session.clone());
  161. sessions.push(out_session.clone());
  162. //sessions.push(man_session.clone());
  163. let node = NodeInfo::new(
  164. node_id,
  165. node_name,
  166. state.as_str().unwrap().to_string(),
  167. sessions.clone(),
  168. ext_addr,
  169. false,
  170. );
  171. self.update_selectables(sessions.clone(), node).await?;
  172. self.update_msgs(sessions).await?;
  173. //debug!("IDS: {:?}", self.model.ids.lock().await);
  174. //debug!("INFOS: {:?}", self.model.nodes.lock().await);
  175. Ok(())
  176. }
  177. async fn parse_lilith_data(
  178. &self,
  179. reply: serde_json::Map<String, Value>,
  180. name: String,
  181. ) -> DnetViewResult<()> {
  182. let urls: Vec<String> = serde_json::from_value(reply.get("urls").unwrap().clone()).unwrap();
  183. let spawns: Vec<serde_json::Map<String, Value>> =
  184. serde_json::from_value(reply.get("spawns").unwrap().clone()).unwrap();
  185. let mut networks = vec![];
  186. for spawn in spawns {
  187. let name = spawn.get("name").unwrap().as_str().unwrap().to_string();
  188. let id = make_node_id(&name)?;
  189. let urls: Vec<String> =
  190. serde_json::from_value(spawn.get("urls").unwrap().clone()).unwrap();
  191. let nodes: Vec<String> =
  192. serde_json::from_value(spawn.get("hosts").unwrap().clone()).unwrap();
  193. let network = NetworkInfo::new(id, name, urls, nodes);
  194. networks.push(network);
  195. }
  196. let id = make_node_id(&name)?;
  197. let lilith = LilithInfo::new(id.clone(), name, urls, networks);
  198. let lilith_obj = SelectableObject::Lilith(lilith.clone());
  199. self.model.selectables.lock().await.insert(id, lilith_obj);
  200. for network in lilith.networks {
  201. let network_obj = SelectableObject::Network(network.clone());
  202. self.model.selectables.lock().await.insert(network.id, network_obj);
  203. }
  204. Ok(())
  205. }
  206. async fn update_msgs(&self, sessions: Vec<SessionInfo>) -> DnetViewResult<()> {
  207. for session in sessions {
  208. for connection in session.children {
  209. if !self.model.msg_map.lock().await.contains_key(&connection.id) {
  210. // we don't have this ID: it is a new node
  211. self.model
  212. .msg_map
  213. .lock()
  214. .await
  215. .insert(connection.id, connection.msg_log.clone());
  216. } else {
  217. // we have this id: append the msg values
  218. match self.model.msg_map.lock().await.entry(connection.id) {
  219. Entry::Vacant(e) => {
  220. e.insert(connection.msg_log);
  221. }
  222. Entry::Occupied(mut e) => {
  223. for msg in connection.msg_log {
  224. e.get_mut().push(msg);
  225. }
  226. }
  227. }
  228. }
  229. }
  230. }
  231. Ok(())
  232. }
  233. async fn update_selectables(
  234. &self,
  235. sessions: Vec<SessionInfo>,
  236. node: NodeInfo,
  237. ) -> DnetViewResult<()> {
  238. if node.is_offline {
  239. let node_obj = SelectableObject::Node(node.clone());
  240. self.model.selectables.lock().await.insert(node.id.clone(), node_obj.clone());
  241. } else {
  242. let node_obj = SelectableObject::Node(node.clone());
  243. self.model.selectables.lock().await.insert(node.id.clone(), node_obj.clone());
  244. for session in sessions {
  245. if !session.is_empty {
  246. let session_obj = SelectableObject::Session(session.clone());
  247. self.model
  248. .selectables
  249. .lock()
  250. .await
  251. .insert(session.clone().id, session_obj.clone());
  252. for connect in session.children {
  253. let connect_obj = SelectableObject::Connect(connect.clone());
  254. self.model
  255. .selectables
  256. .lock()
  257. .await
  258. .insert(connect.clone().id, connect_obj.clone());
  259. }
  260. }
  261. }
  262. }
  263. Ok(())
  264. }
  265. async fn parse_external_addr(&self, addr: &Option<&Value>) -> DnetViewResult<Option<String>> {
  266. match addr {
  267. Some(addr) => match addr.as_str() {
  268. Some(addr) => Ok(Some(addr.to_string())),
  269. None => Ok(None),
  270. },
  271. None => Err(DnetViewError::NoExternalAddr),
  272. }
  273. }
  274. async fn parse_inbound(
  275. &self,
  276. inbound: &Value,
  277. node_id: &String,
  278. ) -> DnetViewResult<SessionInfo> {
  279. let name = "Inbound".to_string();
  280. let session_type = Session::Inbound;
  281. let parent = node_id.to_string();
  282. let id = make_session_id(&parent, &session_type)?;
  283. let mut connects: Vec<ConnectInfo> = Vec::new();
  284. let connections = &inbound["connected"];
  285. let mut connect_count = 0;
  286. let mut accept_vec = Vec::new();
  287. match connections.as_object() {
  288. Some(connect) => {
  289. match connect.is_empty() {
  290. true => {
  291. connect_count += 1;
  292. // channel is empty. initialize with empty values
  293. let id = make_empty_id(node_id, &session_type, connect_count)?;
  294. let addr = "Null".to_string();
  295. let state = "Null".to_string();
  296. let parent = parent.clone();
  297. let msg_log = Vec::new();
  298. let is_empty = true;
  299. let last_msg = "Null".to_string();
  300. let last_status = "Null".to_string();
  301. let remote_node_id = "Null".to_string();
  302. let connect_info = ConnectInfo::new(
  303. id,
  304. addr,
  305. state,
  306. parent,
  307. msg_log,
  308. is_empty,
  309. last_msg,
  310. last_status,
  311. remote_node_id,
  312. );
  313. connects.push(connect_info);
  314. }
  315. false => {
  316. // channel is not empty. initialize with whole values
  317. for k in connect.keys() {
  318. let node = connect.get(k);
  319. let addr = k.to_string();
  320. let info = node.unwrap().as_array();
  321. // get the accept address
  322. let accept_addr = info.unwrap().get(0);
  323. let acc_addr = accept_addr
  324. .unwrap()
  325. .get("accept_addr")
  326. .unwrap()
  327. .as_str()
  328. .unwrap()
  329. .to_string();
  330. accept_vec.push(acc_addr);
  331. let info2 = info.unwrap().get(1);
  332. let id = info2.unwrap().get("random_id").unwrap().as_u64().unwrap();
  333. let id = make_connect_id(&id)?;
  334. let state = "state".to_string();
  335. let parent = parent.clone();
  336. let msg_values = info2.unwrap().get("log").unwrap().as_array().unwrap();
  337. let mut msg_log: Vec<(NanoTimestamp, String, String)> = Vec::new();
  338. for msg in msg_values {
  339. let msg: (NanoTimestamp, String, String) =
  340. serde_json::from_value(msg.clone())?;
  341. msg_log.push(msg);
  342. }
  343. let is_empty = false;
  344. let last_msg = info2
  345. .unwrap()
  346. .get("last_msg")
  347. .unwrap()
  348. .as_str()
  349. .unwrap()
  350. .to_string();
  351. let last_status = info2
  352. .unwrap()
  353. .get("last_status")
  354. .unwrap()
  355. .as_str()
  356. .unwrap()
  357. .to_string();
  358. let remote_node_id = info2
  359. .unwrap()
  360. .get("remote_node_id")
  361. .unwrap()
  362. .as_str()
  363. .unwrap()
  364. .to_string();
  365. let r_node_id: String = match remote_node_id.is_empty() {
  366. true => "no remote id".to_string(),
  367. false => remote_node_id,
  368. };
  369. let connect_info = ConnectInfo::new(
  370. id,
  371. addr,
  372. state,
  373. parent,
  374. msg_log,
  375. is_empty,
  376. last_msg,
  377. last_status,
  378. r_node_id,
  379. );
  380. connects.push(connect_info.clone());
  381. }
  382. }
  383. }
  384. let is_empty = is_empty_session(&connects);
  385. // TODO: clean this up
  386. if accept_vec.is_empty() {
  387. let accept_addr = None;
  388. let session_info =
  389. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr, None);
  390. Ok(session_info)
  391. } else {
  392. let accept_addr = Some(accept_vec[0].clone());
  393. let session_info =
  394. SessionInfo::new(id, name, is_empty, parent, connects, accept_addr, None);
  395. Ok(session_info)
  396. }
  397. }
  398. None => Err(DnetViewError::ValueIsNotObject),
  399. }
  400. }
  401. // TODO: placeholder for now
  402. async fn _parse_manual(
  403. &self,
  404. _manual: &Value,
  405. node_id: &String,
  406. ) -> DnetViewResult<SessionInfo> {
  407. let name = "Manual".to_string();
  408. let session_type = Session::Manual;
  409. let mut connects: Vec<ConnectInfo> = Vec::new();
  410. let parent = node_id.to_string();
  411. let session_id = make_session_id(&parent, &session_type)?;
  412. //let id: u64 = 0;
  413. let connect_id = make_empty_id(node_id, &session_type, 0)?;
  414. //let connect_id = make_connect_id(&id)?;
  415. let addr = "Null".to_string();
  416. let state = "Null".to_string();
  417. let msg_log = Vec::new();
  418. let is_empty = true;
  419. let msg = "Null".to_string();
  420. let status = "Null".to_string();
  421. let remote_node_id = "Null".to_string();
  422. let connect_info = ConnectInfo::new(
  423. connect_id.clone(),
  424. addr,
  425. state,
  426. parent,
  427. msg_log,
  428. is_empty,
  429. msg,
  430. status,
  431. remote_node_id,
  432. );
  433. connects.push(connect_info);
  434. let parent = connect_id;
  435. let is_empty = is_empty_session(&connects);
  436. let accept_addr = None;
  437. let session_info = SessionInfo::new(
  438. session_id,
  439. name,
  440. is_empty,
  441. parent,
  442. connects.clone(),
  443. accept_addr,
  444. None,
  445. );
  446. Ok(session_info)
  447. }
  448. async fn parse_outbound(
  449. &self,
  450. outbound: &Value,
  451. node_id: &String,
  452. ) -> DnetViewResult<SessionInfo> {
  453. let name = "Outbound".to_string();
  454. let session_type = Session::Outbound;
  455. let parent = node_id.to_string();
  456. let id = make_session_id(&parent, &session_type)?;
  457. let mut connects: Vec<ConnectInfo> = Vec::new();
  458. let slots = &outbound["slots"];
  459. let mut slot_count = 0;
  460. let hosts = &outbound["hosts"];
  461. match slots.as_array() {
  462. Some(slots) => {
  463. for slot in slots {
  464. slot_count += 1;
  465. match slot["channel"].is_null() {
  466. true => {
  467. // TODO: this is not actually empty
  468. let id = make_empty_id(node_id, &session_type, slot_count)?;
  469. let addr = "Null".to_string();
  470. let state = &slot["state"];
  471. let state = state.as_str().unwrap().to_string();
  472. let parent = parent.clone();
  473. let msg_log = Vec::new();
  474. let is_empty = false;
  475. let last_msg = "Null".to_string();
  476. let last_status = "Null".to_string();
  477. let remote_node_id = "Null".to_string();
  478. let connect_info = ConnectInfo::new(
  479. id,
  480. addr,
  481. state,
  482. parent,
  483. msg_log,
  484. is_empty,
  485. last_msg,
  486. last_status,
  487. remote_node_id,
  488. );
  489. connects.push(connect_info.clone());
  490. }
  491. false => {
  492. // channel is not empty. initialize with whole values
  493. let channel = &slot["channel"];
  494. let id = channel["random_id"].as_u64().unwrap();
  495. let id = make_connect_id(&id)?;
  496. let addr = &slot["addr"];
  497. let addr = addr.as_str().unwrap().to_string();
  498. let state = &slot["state"];
  499. let state = state.as_str().unwrap().to_string();
  500. let parent = parent.clone();
  501. let msg_values = channel["log"].as_array().unwrap();
  502. let mut msg_log: Vec<(NanoTimestamp, String, String)> = Vec::new();
  503. for msg in msg_values {
  504. let msg: (NanoTimestamp, String, String) =
  505. serde_json::from_value(msg.clone())?;
  506. msg_log.push(msg);
  507. }
  508. let is_empty = false;
  509. let last_msg = channel["last_msg"].as_str().unwrap().to_string();
  510. let last_status = channel["last_status"].as_str().unwrap().to_string();
  511. let remote_node_id =
  512. channel["remote_node_id"].as_str().unwrap().to_string();
  513. let r_node_id: String = match remote_node_id.is_empty() {
  514. true => "no remote id".to_string(),
  515. false => remote_node_id,
  516. };
  517. let connect_info = ConnectInfo::new(
  518. id,
  519. addr,
  520. state,
  521. parent,
  522. msg_log,
  523. is_empty,
  524. last_msg,
  525. last_status,
  526. r_node_id,
  527. );
  528. connects.push(connect_info.clone());
  529. }
  530. }
  531. }
  532. let is_empty = is_empty_session(&connects);
  533. let accept_addr = None;
  534. match hosts.as_array() {
  535. Some(hosts) => {
  536. let hosts: Vec<String> =
  537. hosts.iter().map(|addr| addr.as_str().unwrap().to_string()).collect();
  538. let session_info = SessionInfo::new(
  539. id,
  540. name,
  541. is_empty,
  542. parent,
  543. connects,
  544. accept_addr,
  545. Some(hosts),
  546. );
  547. Ok(session_info)
  548. }
  549. None => Err(DnetViewError::ValueIsNotObject),
  550. }
  551. }
  552. None => Err(DnetViewError::ValueIsNotObject),
  553. }
  554. }
  555. }