manual_session.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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. //! Manual connections session. Manages the creation of manual sessions.
  19. //! Used to create a manual session and to stop and start the session.
  20. //!
  21. //! A manual session is a type of outbound session in which we attempt
  22. //! connection to a predefined set of peers. Manual sessions loop forever
  23. //! continually trying to connect to a given peer, and sleep
  24. //! `outbound_connect_timeout` times between each attempt.
  25. //!
  26. //! Class consists of a weak pointer to the p2p interface and a vector of
  27. //! outbound connection slots. Using a weak pointer to p2p allows us to
  28. //! avoid circular dependencies. The vector of slots is wrapped in a mutex
  29. //! lock. This is switched on every time we instantiate a connection slot
  30. //! and insures that no other part of the program uses the slots at the
  31. //! same time.
  32. use std::sync::{Arc, Weak};
  33. use async_trait::async_trait;
  34. use futures::stream::{FuturesUnordered, StreamExt};
  35. use smol::lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
  36. use tracing::{debug, info, warn};
  37. use url::Url;
  38. use super::{
  39. super::{
  40. connector::Connector,
  41. p2p::{P2p, P2pPtr},
  42. },
  43. Session, SessionBitFlag, SESSION_MANUAL,
  44. };
  45. use crate::{
  46. net::{hosts::HostState, settings::Settings},
  47. system::{sleep, StoppableTask, StoppableTaskPtr},
  48. util::logger::verbose,
  49. Error, Result,
  50. };
  51. pub type ManualSessionPtr = Arc<ManualSession>;
  52. /// Defines manual connections session.
  53. pub struct ManualSession {
  54. pub(in crate::net) p2p: Weak<P2p>,
  55. slots: AsyncMutex<Vec<Arc<Slot>>>,
  56. }
  57. impl ManualSession {
  58. /// Create a new manual session.
  59. pub fn new(p2p: Weak<P2p>) -> ManualSessionPtr {
  60. Arc::new(Self { p2p, slots: AsyncMutex::new(Vec::new()) })
  61. }
  62. pub(crate) async fn start(self: Arc<Self>) {
  63. // Activate mutex lock on connection slots.
  64. let mut slots = self.slots.lock().await;
  65. let mut futures = FuturesUnordered::new();
  66. let self_ = Arc::downgrade(&self);
  67. // Initialize a slot for each configured peer.
  68. // Connections will be started by not yet activated.
  69. for peer in &self.p2p().settings().read().await.peers {
  70. let slot = Slot::new(self_.clone(), peer.clone(), self.p2p().settings());
  71. futures.push(slot.clone().start());
  72. slots.push(slot);
  73. }
  74. while (futures.next().await).is_some() {}
  75. }
  76. /// Stops the manual session.
  77. pub async fn stop(&self) {
  78. let slots = &*self.slots.lock().await;
  79. let mut futures = FuturesUnordered::new();
  80. for slot in slots {
  81. futures.push(slot.stop());
  82. }
  83. while (futures.next().await).is_some() {}
  84. }
  85. }
  86. #[async_trait]
  87. impl Session for ManualSession {
  88. fn p2p(&self) -> P2pPtr {
  89. self.p2p.upgrade().unwrap()
  90. }
  91. fn type_id(&self) -> SessionBitFlag {
  92. SESSION_MANUAL
  93. }
  94. async fn reload(self: Arc<Self>) {}
  95. }
  96. struct Slot {
  97. addr: Url,
  98. process: StoppableTaskPtr,
  99. session: Weak<ManualSession>,
  100. connector: Connector,
  101. }
  102. impl Slot {
  103. fn new(
  104. session: Weak<ManualSession>,
  105. addr: Url,
  106. settings: Arc<AsyncRwLock<Settings>>,
  107. ) -> Arc<Self> {
  108. Arc::new(Self {
  109. addr,
  110. process: StoppableTask::new(),
  111. session: session.clone(),
  112. connector: Connector::new(settings, session),
  113. })
  114. }
  115. async fn start(self: Arc<Self>) {
  116. let ex = self.p2p().executor();
  117. self.process.clone().start(
  118. self.run(),
  119. |res| async {
  120. match res {
  121. Ok(()) | Err(Error::NetworkServiceStopped) => {}
  122. Err(e) => verbose!("net::manual_session {e}"),
  123. }
  124. },
  125. Error::NetworkServiceStopped,
  126. ex,
  127. );
  128. }
  129. /// Attempts a connection on the associated Connector object.
  130. async fn run(self: Arc<Self>) -> Result<()> {
  131. let ex = self.p2p().executor();
  132. let mut attempts = 0;
  133. loop {
  134. attempts += 1;
  135. verbose!(
  136. target: "net::manual_session",
  137. "[P2P] Connecting to manual outbound [{}] (attempt #{})",
  138. self.addr, attempts
  139. );
  140. let settings = self.p2p().settings().read_arc().await;
  141. let seeds = settings.seeds.clone();
  142. let outbound_connect_timeout = settings.outbound_connect_timeout(self.addr.scheme());
  143. drop(settings);
  144. // Do not establish a connection to a host that is also configured as a seed.
  145. // This indicates a user misconfiguration.
  146. if seeds.contains(&self.addr) {
  147. verbose!(
  148. target: "net::manual_session",
  149. "[P2P] Suspending manual connection to seed [{}]", self.addr.clone(),
  150. );
  151. return Ok(())
  152. }
  153. if let Err(e) = self.p2p().hosts().try_register(self.addr.clone(), HostState::Connect) {
  154. debug!(target: "net::manual_session",
  155. "Cannot connect to manual={}, err={e}", &self.addr);
  156. sleep(outbound_connect_timeout).await;
  157. continue
  158. }
  159. match self.connector.connect(&self.addr).await {
  160. Ok((_, channel)) => {
  161. info!(
  162. target: "net::manual_session",
  163. "[P2P] Manual outbound connected [{}]",
  164. channel.display_address()
  165. );
  166. let stop_sub = channel.subscribe_stop().await?;
  167. // Channel is now connected but not yet setup
  168. // Register the new channel
  169. match self.session().register_channel(channel.clone(), ex.clone()).await {
  170. Ok(()) => {
  171. // Wait for channel to close
  172. stop_sub.receive().await;
  173. verbose!(
  174. target: "net::manual_session",
  175. "[P2P] Manual outbound disconnected [{}]",
  176. channel.display_address()
  177. );
  178. }
  179. Err(e) => {
  180. warn!(
  181. target: "net::manual_session",
  182. "[P2P] Unable to connect to manual outbound [{}]: {e}",
  183. channel.display_address(),
  184. );
  185. // Free up this addr for future operations.
  186. if let Err(e) = self.p2p().hosts().unregister(channel.address()) {
  187. verbose!(target: "net::manual_session", "[P2P] Error while unregistering addr={}, err={e}", channel.display_address());
  188. }
  189. }
  190. }
  191. }
  192. Err(e) => {
  193. warn!(
  194. target: "net::manual_session",
  195. "[P2P] Unable to connect to manual outbound: {e}",
  196. );
  197. // Free up this addr for future operations.
  198. if let Err(e) = self.p2p().hosts().unregister(&self.addr) {
  199. verbose!(target: "net::manual_session", "[P2P] Error while unregistering addr={}, err={e}", self.addr);
  200. }
  201. }
  202. }
  203. verbose!(
  204. target: "net::manual_session",
  205. "[P2P] Waiting {outbound_connect_timeout} seconds until next manual outbound connection attempt [{}]",
  206. self.addr,
  207. );
  208. sleep(outbound_connect_timeout).await;
  209. }
  210. }
  211. fn session(&self) -> ManualSessionPtr {
  212. self.session.upgrade().unwrap()
  213. }
  214. fn p2p(&self) -> P2pPtr {
  215. self.session().p2p()
  216. }
  217. async fn stop(&self) {
  218. self.connector.stop();
  219. self.process.stop().await;
  220. }
  221. }