manual_session.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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.
  23. //!
  24. //! Class consists of a weak pointer to the p2p interface and a vector of
  25. //! outbound connection slots. Using a weak pointer to p2p allows us to
  26. //! avoid circular dependencies. The vector of slots is wrapped in a mutex
  27. //! lock. This is switched on every time we instantiate a connection slot
  28. //! and insures that no other part of the program uses the slots at the
  29. //! same time.
  30. use std::{sync::Arc, time::UNIX_EPOCH};
  31. use async_trait::async_trait;
  32. use log::{debug, error, info, warn};
  33. use smol::lock::Mutex;
  34. use url::Url;
  35. use super::{
  36. super::{
  37. connector::Connector,
  38. p2p::{P2p, P2pPtr},
  39. },
  40. Session, SessionBitFlag, SESSION_MANUAL,
  41. };
  42. use crate::{
  43. net::hosts::store::{HostColor, HostState},
  44. system::{sleep, LazyWeak, StoppableTask, StoppableTaskPtr},
  45. Error, Result,
  46. };
  47. pub type ManualSessionPtr = Arc<ManualSession>;
  48. /// Defines manual connections session.
  49. pub struct ManualSession {
  50. pub(in crate::net) p2p: LazyWeak<P2p>,
  51. connect_slots: Mutex<Vec<StoppableTaskPtr>>,
  52. }
  53. impl ManualSession {
  54. /// Create a new manual session.
  55. pub fn new() -> ManualSessionPtr {
  56. Arc::new(Self { p2p: LazyWeak::new(), connect_slots: Mutex::new(Vec::new()) })
  57. }
  58. /// Stops the manual session.
  59. pub async fn stop(&self) {
  60. let connect_slots = &*self.connect_slots.lock().await;
  61. for slot in connect_slots {
  62. slot.stop().await;
  63. }
  64. }
  65. /// Connect the manual session to the given address
  66. pub async fn connect(self: Arc<Self>, addr: Url) {
  67. let ex = self.p2p().executor();
  68. let task = StoppableTask::new();
  69. self.connect_slots.lock().await.push(task.clone());
  70. task.start(
  71. self.clone().channel_connect_loop(addr),
  72. // Ignore stop handler
  73. |_| async {},
  74. Error::NetworkServiceStopped,
  75. ex,
  76. );
  77. }
  78. /// Creates a connector object and tries to connect using it
  79. pub async fn channel_connect_loop(self: Arc<Self>, addr: Url) -> Result<()> {
  80. let ex = self.p2p().executor();
  81. let parent = Arc::downgrade(&self);
  82. let settings = self.p2p().settings();
  83. let connector = Connector::new(settings.clone(), parent);
  84. let attempts = settings.manual_attempt_limit;
  85. let mut remaining = attempts;
  86. // Loop forever if attempts==0, otherwise loop attempts number of times.
  87. let mut tried_attempts = 0;
  88. loop {
  89. tried_attempts += 1;
  90. info!(
  91. target: "net::manual_session",
  92. "[P2P] Connecting to manual outbound [{}] (attempt #{})",
  93. addr, tried_attempts,
  94. );
  95. // Do not establish a connection to a host that is also configured as a seed.
  96. // This indicates a user misconfiguration.
  97. if settings.seeds.contains(&addr) {
  98. error!(target: "net::manual_session",
  99. "[P2P] Suspending manual connection to seed [{}]", addr.clone());
  100. return Ok(())
  101. }
  102. match self.p2p().hosts().try_register(addr.clone(), HostState::Connect).await {
  103. Ok(_) => {
  104. match connector.connect(&addr).await {
  105. Ok((url, channel)) => {
  106. info!(
  107. target: "net::manual_session",
  108. "[P2P] Manual outbound connected [{}]", url,
  109. );
  110. let stop_sub = channel
  111. .subscribe_stop()
  112. .await
  113. .expect("Channel should not be stopped");
  114. // Channel is now connected but not yet setup
  115. // Register the new channel
  116. self.register_channel(channel.clone(), ex.clone()).await?;
  117. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  118. // Add this connection to the anchorlist
  119. self.p2p()
  120. .hosts()
  121. .move_host(&addr, last_seen, HostColor::Gold, Some(channel.clone()))
  122. .await?;
  123. // Wait for channel to close
  124. stop_sub.receive().await;
  125. info!(
  126. target: "net::manual_session",
  127. "[P2P] Manual outbound disconnected [{}]", url,
  128. );
  129. // DEV NOTE: Here we can choose to attempt reconnection again
  130. return Ok(())
  131. }
  132. Err(e) => {
  133. warn!(
  134. target: "net::manual_session",
  135. "[P2P] Unable to connect to manual outbound [{}]: {}",
  136. addr, e,
  137. );
  138. // Stop tracking this peer, to avoid it getting stuck in the Connect
  139. // state.
  140. self.p2p().hosts().unregister(&addr).await;
  141. }
  142. }
  143. }
  144. // This address is currently unavailable.
  145. Err(e) => {
  146. debug!(target: "net::manual_session", "[P2P] Unable to connect to manual
  147. outbound [{}]: {}", addr.clone(), e);
  148. }
  149. }
  150. // Wait and try again.
  151. // TODO: Should we notify about the failure now, or after all attempts
  152. // have failed?
  153. self.p2p().hosts().channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  154. remaining = if attempts == 0 { 1 } else { remaining - 1 };
  155. if remaining == 0 {
  156. break
  157. }
  158. info!(
  159. target: "net::manual_session",
  160. "[P2P] Waiting {} seconds until next manual outbound connection attempt [{}]",
  161. settings.outbound_connect_timeout, addr,
  162. );
  163. sleep(settings.outbound_connect_timeout).await;
  164. }
  165. warn!(
  166. target: "net::manual_session",
  167. "[P2P] Suspending manual connection to {} after {} failed attempts",
  168. addr, attempts,
  169. );
  170. Ok(())
  171. }
  172. }
  173. #[async_trait]
  174. impl Session for ManualSession {
  175. fn p2p(&self) -> P2pPtr {
  176. self.p2p.upgrade()
  177. }
  178. fn type_id(&self) -> SessionBitFlag {
  179. SESSION_MANUAL
  180. }
  181. }