outbound_session.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. use async_std::sync::{Arc, Mutex, Weak};
  2. use std::fmt;
  3. use async_executor::Executor;
  4. use async_trait::async_trait;
  5. use log::{error, info};
  6. use rand::seq::SliceRandom;
  7. use serde_json::json;
  8. use url::Url;
  9. use crate::{
  10. system::{StoppableTask, StoppableTaskPtr},
  11. Error, Result,
  12. };
  13. use super::{
  14. super::{ChannelPtr, Connector, P2p},
  15. Session, SessionBitflag, SESSION_OUTBOUND,
  16. };
  17. #[derive(Clone)]
  18. enum OutboundState {
  19. Open,
  20. Pending,
  21. Connected,
  22. }
  23. impl fmt::Display for OutboundState {
  24. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  25. write!(
  26. f,
  27. "{}",
  28. match self {
  29. Self::Open => "open",
  30. Self::Pending => "pending",
  31. Self::Connected => "connected",
  32. }
  33. )
  34. }
  35. }
  36. #[derive(Clone)]
  37. struct OutboundInfo {
  38. addr: Option<Url>,
  39. channel: Option<ChannelPtr>,
  40. state: OutboundState,
  41. }
  42. impl OutboundInfo {
  43. async fn get_info(&self) -> serde_json::Value {
  44. let addr = match self.addr.as_ref() {
  45. Some(addr) => serde_json::Value::String(addr.to_string()),
  46. None => serde_json::Value::Null,
  47. };
  48. let channel = match &self.channel {
  49. Some(channel) => channel.get_info().await,
  50. None => serde_json::Value::Null,
  51. };
  52. json!({
  53. "addr": addr,
  54. "state": self.state.to_string(),
  55. "channel": channel,
  56. })
  57. }
  58. }
  59. impl Default for OutboundInfo {
  60. fn default() -> Self {
  61. Self { addr: None, channel: None, state: OutboundState::Open }
  62. }
  63. }
  64. /// Defines outbound connections session.
  65. pub struct OutboundSession {
  66. p2p: Weak<P2p>,
  67. connect_slots: Mutex<Vec<StoppableTaskPtr>>,
  68. slot_info: Mutex<Vec<OutboundInfo>>,
  69. }
  70. impl OutboundSession {
  71. /// Create a new outbound session.
  72. pub fn new(p2p: Weak<P2p>) -> Arc<Self> {
  73. Arc::new(Self {
  74. p2p,
  75. connect_slots: Mutex::new(Vec::new()),
  76. slot_info: Mutex::new(Vec::new()),
  77. })
  78. }
  79. /// Start the outbound session. Runs the channel connect loop.
  80. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  81. let slots_count = self.p2p().settings().outbound_connections;
  82. info!(target: "net", "Starting {} outbound connection slots.", slots_count);
  83. // Activate mutex lock on connection slots.
  84. let mut connect_slots = self.connect_slots.lock().await;
  85. self.slot_info.lock().await.resize(slots_count as usize, Default::default());
  86. for i in 0..slots_count {
  87. let task = StoppableTask::new();
  88. task.clone().start(
  89. self.clone().channel_connect_loop(i, executor.clone()),
  90. // Ignore stop handler
  91. |_| async {},
  92. Error::NetworkServiceStopped,
  93. executor.clone(),
  94. );
  95. connect_slots.push(task);
  96. }
  97. Ok(())
  98. }
  99. /// Stop the outbound session.
  100. pub async fn stop(&self) {
  101. let connect_slots = &*self.connect_slots.lock().await;
  102. for slot in connect_slots {
  103. slot.stop().await;
  104. }
  105. }
  106. /// Start making outbound connections. Creates a connector object, then
  107. /// starts a connect loop. Loads a valid address then tries to connect.
  108. /// Once connected, registers the channel, removes it from the list of
  109. /// pending channels, and starts sending messages across the channel.
  110. /// Otherwise returns a network error.
  111. pub async fn channel_connect_loop(
  112. self: Arc<Self>,
  113. slot_number: u32,
  114. executor: Arc<Executor<'_>>,
  115. ) -> Result<()> {
  116. let connector = Connector::new(self.p2p().settings());
  117. loop {
  118. let addr = self.load_address(slot_number).await?;
  119. info!(target: "net", "#{} connecting to outbound [{}]", slot_number, addr);
  120. {
  121. let info = &mut self.slot_info.lock().await[slot_number as usize];
  122. info.addr = Some(addr.clone());
  123. info.state = OutboundState::Pending;
  124. }
  125. match connector.connect(addr.clone()).await {
  126. Ok(channel) => {
  127. // Blacklist goes here
  128. info!(target: "net", "#{} connected to outbound [{}]", slot_number, addr);
  129. let stop_sub = channel.subscribe_stop().await;
  130. if stop_sub.is_err() {
  131. continue
  132. }
  133. self.clone().register_channel(channel.clone(), executor.clone()).await?;
  134. // Channel is now connected but not yet setup
  135. // Remove pending lock since register_channel will add the channel to p2p
  136. self.p2p().remove_pending(&addr).await;
  137. {
  138. let info = &mut self.slot_info.lock().await[slot_number as usize];
  139. info.channel = Some(channel.clone());
  140. info.state = OutboundState::Connected;
  141. }
  142. // Wait for channel to close
  143. stop_sub.unwrap().receive().await;
  144. }
  145. Err(err) => {
  146. info!(target: "net", "Unable to connect to outbound [{}]: {}", &addr, err);
  147. {
  148. let info = &mut self.slot_info.lock().await[slot_number as usize];
  149. info.addr = None;
  150. info.channel = None;
  151. info.state = OutboundState::Open;
  152. }
  153. }
  154. }
  155. }
  156. }
  157. /// Loops through host addresses to find a outbound address that we can
  158. /// connect to. Checks whether address is valid by making sure it isn't
  159. /// our own inbound address, then checks whether it is already connected
  160. /// (exists) or connecting (pending). Keeps looping until address is
  161. /// found that passes all checks.
  162. async fn load_address(&self, slot_number: u32) -> Result<Url> {
  163. let p2p = self.p2p();
  164. let self_inbound_addr = p2p.settings().external_addr.clone();
  165. let mut addrs;
  166. {
  167. let hosts = p2p.hosts().load_all().await;
  168. addrs = hosts;
  169. }
  170. addrs.shuffle(&mut rand::thread_rng());
  171. for addr in addrs {
  172. if p2p.exists(&addr).await {
  173. continue
  174. }
  175. // Obtain a lock on this address to prevent duplicate connections
  176. if !p2p.add_pending(addr.clone()).await {
  177. continue
  178. }
  179. if Self::is_self_inbound(&addr, &self_inbound_addr) {
  180. continue
  181. }
  182. return Ok(addr)
  183. }
  184. error!(target: "net", "Hosts address pool is empty. Closing connect slot #{}", slot_number);
  185. Err(Error::NetworkServiceStopped)
  186. }
  187. /// Checks whether an address is our own inbound address to avoid connecting
  188. /// to ourselves.
  189. fn is_self_inbound(addr: &Url, inbound_addr: &Option<Url>) -> bool {
  190. match inbound_addr {
  191. Some(inbound_addr) => inbound_addr == addr,
  192. // No inbound listening address configured
  193. None => false,
  194. }
  195. }
  196. }
  197. #[async_trait]
  198. impl Session for OutboundSession {
  199. async fn get_info(&self) -> serde_json::Value {
  200. let mut slots = Vec::new();
  201. for info in &*self.slot_info.lock().await {
  202. slots.push(info.get_info().await);
  203. }
  204. json!({
  205. "slots": slots,
  206. })
  207. }
  208. fn p2p(&self) -> Arc<P2p> {
  209. self.p2p.upgrade().unwrap()
  210. }
  211. fn selector_id(&self) -> SessionBitflag {
  212. SESSION_OUTBOUND
  213. }
  214. }