diff options
-rw-r--r-- | doc/book/reference-manual/configuration.md | 40 | ||||
-rw-r--r-- | src/garage/main.rs | 2 | ||||
-rw-r--r-- | src/net/netapp.rs | 45 | ||||
-rw-r--r-- | src/net/peering.rs | 54 | ||||
-rw-r--r-- | src/net/test.rs | 2 | ||||
-rw-r--r-- | src/rpc/system.rs | 15 | ||||
-rw-r--r-- | src/util/config.rs | 3 |
7 files changed, 105 insertions, 56 deletions
diff --git a/doc/book/reference-manual/configuration.md b/doc/book/reference-manual/configuration.md index 5e12a7da..f1474613 100644 --- a/doc/book/reference-manual/configuration.md +++ b/doc/book/reference-manual/configuration.md @@ -17,7 +17,7 @@ data_fsync = false db_engine = "lmdb" -block_size = 1048576 +block_size = "1M" sled_cache_capacity = "128MiB" sled_flush_every_ms = 2000 @@ -27,11 +27,12 @@ compression_level = 1 rpc_secret = "4425f5c26c5e11581d3223904324dcb5b5d5dfb14e5e7f35e38c595424f5f1e6" rpc_bind_addr = "[::]:3901" +rpc_bind_outgoing = false rpc_public_addr = "[fc00:1::1]:3901" bootstrap_peers = [ "563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d@[fc00:1::1]:3901", - "86f0f26ae4afbd59aaf9cfb059eefac844951efd5b8caeec0d53f4ed6c85f332[fc00:1::2]:3901", + "86f0f26ae4afbd59aaf9cfb059eefac844951efd5b8caeec0d53f4ed6c85f332@[fc00:1::2]:3901", "681456ab91350f92242e80a531a3ec9392cb7c974f72640112f90a600d7921a4@[fc00:B::1]:3901", "212fd62eeaca72c122b45a7f4fa0f55e012aa5e24ac384a72a3016413fa724ff@[fc00:F::1]:3901", ] @@ -83,7 +84,7 @@ Top-level configuration options: [`block_size`](#block_size), [`bootstrap_peers`](#bootstrap_peers), [`compression_level`](#compression_level), -[`data_dir`](#metadata_dir), +[`data_dir`](#data_dir), [`data_fsync`](#data_fsync), [`db_engine`](#db_engine), [`lmdb_map_size`](#lmdb_map_size), @@ -91,21 +92,21 @@ Top-level configuration options: [`metadata_fsync`](#metadata_fsync), [`replication_mode`](#replication_mode), [`rpc_bind_addr`](#rpc_bind_addr), +[`rpc_bind_outgoing`](#rpc_bind_outgoing), [`rpc_public_addr`](#rpc_public_addr), -[`rpc_secret`](#rpc_secret), -[`rpc_secret_file`](#rpc_secret), +[`rpc_secret`/`rpc_secret_file`](#rpc_secret), [`sled_cache_capacity`](#sled_cache_capacity), [`sled_flush_every_ms`](#sled_flush_every_ms). The `[consul_discovery]` section: [`api`](#consul_api), [`ca_cert`](#consul_ca_cert), -[`client_cert`](#consul_client_cert), -[`client_key`](#consul_client_cert), +[`client_cert`](#consul_client_cert_and_key), +[`client_key`](#consul_client_cert_and_key), [`consul_http_addr`](#consul_http_addr), -[`meta`](#consul_tags), +[`meta`](#consul_tags_and_meta), [`service_name`](#consul_service_name), -[`tags`](#consul_tags), +[`tags`](#consul_tags_and_meta), [`tls_skip_verify`](#consul_tls_skip_verify), [`token`](#consul_token). @@ -125,10 +126,8 @@ The `[s3_web]` section: The `[admin]` section: [`api_bind_addr`](#admin_api_bind_addr), -[`metrics_token`](#admin_metrics_token), -[`metrics_token_file`](#admin_metrics_token), -[`admin_token`](#admin_token), -[`admin_token_file`](#admin_token), +[`metrics_token`/`metrics_token_file`](#admin_metrics_token), +[`admin_token`/`admin_token_file`](#admin_token), [`trace_sink`](#admin_trace_sink), @@ -418,6 +417,17 @@ the node, even in the case of a NAT: the NAT should be configured to forward the port number to the same internal port nubmer. This means that if you have several nodes running behind a NAT, they should each use a different RPC port number. +#### `rpc_bind_outgoing` {#rpc_bind_outgoing} (since v0.9.2) + +If enabled, pre-bind all sockets for outgoing connections to the same IP address +used for listening (the IP address specified in `rpc_bind_addr`) before +trying to connect to remote nodes. +This can be necessary if a node has multiple IP addresses, +but only one is allowed or able to reach the other nodes, +for instance due to firewall rules or specific routing configuration. + +Disabled by default. + #### `rpc_public_addr` {#rpc_public_addr} The address and port that other nodes need to use to contact this node for @@ -474,7 +484,7 @@ the `/v1/catalog` endpoints, enabling mTLS if `client_cert` and `client_key` are `service_name` should be set to the service name under which Garage's RPC ports are announced. -#### `client_cert`, `client_key` {#consul_client_cert} +#### `client_cert`, `client_key` {#consul_client_cert_and_key} TLS client certificate and client key to use when communicating with Consul over TLS. Both are mandatory when doing so. Only available when `api = "catalog"`. @@ -508,7 +518,7 @@ node_prefix "" { } ``` -#### `tags` and `meta` {#consul_tags} +#### `tags` and `meta` {#consul_tags_and_meta} Additional list of tags and map of service meta to add during service registration. diff --git a/src/garage/main.rs b/src/garage/main.rs index 4d8dcc67..e489fff0 100644 --- a/src/garage/main.rs +++ b/src/garage/main.rs @@ -203,7 +203,7 @@ async fn cli_command(opt: Opt) -> Result<(), Error> { // Generate a temporary keypair for our RPC client let (_pk, sk) = sodiumoxide::crypto::sign::ed25519::gen_keypair(); - let netapp = NetApp::new(GARAGE_VERSION_TAG, network_key, sk); + let netapp = NetApp::new(GARAGE_VERSION_TAG, network_key, sk, None); // Find and parse the address of the target host let (id, addr, is_default_addr) = if let Some(h) = opt.rpc_host { diff --git a/src/net/netapp.rs b/src/net/netapp.rs index b1ad9db8..faa51a99 100644 --- a/src/net/netapp.rs +++ b/src/net/netapp.rs @@ -13,7 +13,7 @@ use sodiumoxide::crypto::sign::ed25519; use futures::stream::futures_unordered::FuturesUnordered; use futures::stream::StreamExt; -use tokio::net::{TcpListener, TcpStream}; +use tokio::net::{TcpListener, TcpSocket, TcpStream}; use tokio::select; use tokio::sync::{mpsc, watch}; @@ -38,6 +38,11 @@ pub(crate) type VersionTag = [u8; 16]; /// Value of the Netapp version used in the version tag pub(crate) const NETAPP_VERSION_TAG: u64 = 0x6e65746170700005; // netapp 0x0005 +/// HelloMessage is sent by the client on a Netapp connection to indicate +/// that they are also a server and ready to recieve incoming connections +/// at the specified address and port. If the client doesn't know their +/// public address, they don't need to specify it and we look at the +/// remote address of the socket is used instead. #[derive(Serialize, Deserialize, Debug)] pub(crate) struct HelloMessage { pub server_addr: Option<IpAddr>, @@ -56,10 +61,8 @@ type OnDisconnectHandler = Box<dyn Fn(NodeID, bool) + Send + Sync>; /// NetApp can be used in a stand-alone fashion or together with a peering strategy. /// If using it alone, you will want to set `on_connect` and `on_disconnect` events /// in order to manage information about the current peer list. -/// -/// It is generally not necessary to use NetApp stand-alone, as the provided full mesh -/// and RPS peering strategies take care of the most common use cases. pub struct NetApp { + bind_outgoing_to: Option<IpAddr>, listen_params: ArcSwapOption<ListenParams>, /// Version tag, 8 bytes for netapp version, 8 bytes for app version @@ -83,7 +86,7 @@ pub struct NetApp { struct ListenParams { listen_addr: SocketAddr, - public_addr: Option<IpAddr>, + public_addr: Option<SocketAddr>, } impl NetApp { @@ -92,13 +95,19 @@ impl NetApp { /// using `.listen()` /// /// Our Peer ID is the public key associated to the secret key given here. - pub fn new(app_version_tag: u64, netid: auth::Key, privkey: ed25519::SecretKey) -> Arc<Self> { + pub fn new( + app_version_tag: u64, + netid: auth::Key, + privkey: ed25519::SecretKey, + bind_outgoing_to: Option<IpAddr>, + ) -> Arc<Self> { let mut version_tag = [0u8; 16]; version_tag[0..8].copy_from_slice(&u64::to_be_bytes(NETAPP_VERSION_TAG)[..]); version_tag[8..16].copy_from_slice(&u64::to_be_bytes(app_version_tag)[..]); let id = privkey.public_key(); let netapp = Arc::new(Self { + bind_outgoing_to, listen_params: ArcSwapOption::new(None), version_tag, netid, @@ -180,7 +189,7 @@ impl NetApp { pub async fn listen( self: Arc<Self>, listen_addr: SocketAddr, - public_addr: Option<IpAddr>, + public_addr: Option<SocketAddr>, mut must_exit: watch::Receiver<bool>, ) { let listen_params = ListenParams { @@ -298,9 +307,20 @@ impl NetApp { return Ok(()); } - let socket = TcpStream::connect(ip).await?; + let stream = match self.bind_outgoing_to { + Some(addr) => { + let socket = if addr.is_ipv4() { + TcpSocket::new_v4()? + } else { + TcpSocket::new_v6()? + }; + socket.bind(SocketAddr::new(addr, 0))?; + socket.connect(ip).await? + } + None => TcpStream::connect(ip).await?, + }; info!("Connected to {}, negotiating handshake...", ip); - ClientConn::init(self, socket, id).await?; + ClientConn::init(self, stream, id).await?; Ok(()) } @@ -396,8 +416,11 @@ impl NetApp { } if let Some(lp) = self.listen_params.load_full() { - let server_addr = lp.public_addr; - let server_port = lp.listen_addr.port(); + let server_addr = lp.public_addr.map(|x| x.ip()); + let server_port = lp + .public_addr + .map(|x| x.port()) + .unwrap_or(lp.listen_addr.port()); let hello_endpoint = self.hello_endpoint.load_full().unwrap(); tokio::spawn(async move { hello_endpoint diff --git a/src/net/peering.rs b/src/net/peering.rs index 32199cf8..61882a18 100644 --- a/src/net/peering.rs +++ b/src/net/peering.rs @@ -80,6 +80,23 @@ impl PeerInfoInternal { failed_pings: 0, } } + fn add_addr(&mut self, addr: SocketAddr) -> bool { + if !self.all_addrs.contains(&addr) { + self.all_addrs.push(addr); + // If we are learning a new address for this node, + // we want to retry connecting + self.state = match self.state { + PeerConnState::Trying(_) => PeerConnState::Trying(0), + PeerConnState::Waiting(_, _) | PeerConnState::Abandonned => { + PeerConnState::Waiting(0, Instant::now()) + } + x @ (PeerConnState::Ourself | PeerConnState::Connected) => x, + }; + true + } else { + false + } + } } /// Information that the full mesh peering strategy can return about the peers it knows of @@ -147,23 +164,22 @@ struct KnownHosts { impl KnownHosts { fn new() -> Self { let list = HashMap::new(); - let hash = Self::calculate_hash(&list); + let hash = Self::calculate_hash(vec![]); Self { list, hash } } fn update_hash(&mut self) { - self.hash = Self::calculate_hash(&self.list); + self.hash = Self::calculate_hash(self.connected_peers_vec()); } - fn map_into_vec(input: &HashMap<NodeID, PeerInfoInternal>) -> Vec<(NodeID, SocketAddr)> { - let mut list = Vec::with_capacity(input.len()); - for (id, peer) in input.iter() { - if peer.state == PeerConnState::Connected || peer.state == PeerConnState::Ourself { + fn connected_peers_vec(&self) -> Vec<(NodeID, SocketAddr)> { + let mut list = Vec::with_capacity(self.list.len()); + for (id, peer) in self.list.iter() { + if peer.state.is_up() { list.push((*id, peer.addr)); } } list } - fn calculate_hash(input: &HashMap<NodeID, PeerInfoInternal>) -> hash::Digest { - let mut list = Self::map_into_vec(input); + fn calculate_hash(mut list: Vec<(NodeID, SocketAddr)>) -> hash::Digest { list.sort(); let mut hash_state = hash::State::new(); for (id, addr) in list { @@ -214,6 +230,7 @@ impl PeeringManager { netapp.id, PeerInfoInternal::new(addr, PeerConnState::Ourself), ); + known_hosts.update_hash(); } // TODO for v0.10 / v1.0 : rename the endpoint (it will break compatibility) @@ -234,13 +251,11 @@ impl PeeringManager { let strat2 = strat.clone(); netapp.on_connected(move |id: NodeID, addr: SocketAddr, is_incoming: bool| { - let strat2 = strat2.clone(); strat2.on_connected(id, addr, is_incoming); }); let strat2 = strat.clone(); netapp.on_disconnected(move |id: NodeID, is_incoming: bool| { - let strat2 = strat2.clone(); strat2.on_disconnected(id, is_incoming); }); @@ -445,7 +460,7 @@ impl PeeringManager { } async fn exchange_peers(self: Arc<Self>, id: &NodeID) { - let peer_list = KnownHosts::map_into_vec(&self.known_hosts.read().unwrap().list); + let peer_list = self.known_hosts.read().unwrap().connected_peers_vec(); let pex_message = PeerListMessage { list: peer_list }; match self .peer_list_endpoint @@ -465,8 +480,7 @@ impl PeeringManager { let mut changed = false; for (id, addr) in list.iter() { if let Some(kh) = known_hosts.list.get_mut(id) { - if !kh.all_addrs.contains(addr) { - kh.all_addrs.push(*addr); + if kh.add_addr(*addr) { changed = true; } } else { @@ -534,13 +548,11 @@ impl PeeringManager { } } - fn on_connected(self: Arc<Self>, id: NodeID, addr: SocketAddr, is_incoming: bool) { + fn on_connected(self: &Arc<Self>, id: NodeID, addr: SocketAddr, is_incoming: bool) { let mut known_hosts = self.known_hosts.write().unwrap(); if is_incoming { if let Some(host) = known_hosts.list.get_mut(&id) { - if !host.all_addrs.contains(&addr) { - host.all_addrs.push(addr); - } + host.add_addr(addr); } else { known_hosts.list.insert(id, self.new_peer(&id, addr)); } @@ -553,9 +565,7 @@ impl PeeringManager { if let Some(host) = known_hosts.list.get_mut(&id) { host.state = PeerConnState::Connected; host.addr = addr; - if !host.all_addrs.contains(&addr) { - host.all_addrs.push(addr); - } + host.add_addr(addr); } else { known_hosts .list @@ -566,7 +576,7 @@ impl PeeringManager { self.update_public_peer_list(&known_hosts); } - fn on_disconnected(self: Arc<Self>, id: NodeID, is_incoming: bool) { + fn on_disconnected(self: &Arc<Self>, id: NodeID, is_incoming: bool) { if !is_incoming { info!("Connection to {} was closed", hex::encode(&id[..8])); let mut known_hosts = self.known_hosts.write().unwrap(); @@ -608,7 +618,7 @@ impl EndpointHandler<PeerListMessage> for PeeringManager { _from: NodeID, ) -> PeerListMessage { self.handle_peer_list(&peer_list.list[..]); - let peer_list = KnownHosts::map_into_vec(&self.known_hosts.read().unwrap().list); + let peer_list = self.known_hosts.read().unwrap().connected_peers_vec(); PeerListMessage { list: peer_list } } } diff --git a/src/net/test.rs b/src/net/test.rs index c6259752..5a3f236d 100644 --- a/src/net/test.rs +++ b/src/net/test.rs @@ -102,7 +102,7 @@ fn run_netapp( Arc<NetApp>, Arc<PeeringManager>, ) { - let netapp = NetApp::new(0u64, netid, sk); + let netapp = NetApp::new(0u64, netid, sk, None); let peering = PeeringManager::new(netapp.clone(), bootstrap_peers, None); let peering2 = peering.clone(); diff --git a/src/rpc/system.rs b/src/rpc/system.rs index 14a101ca..998517de 100644 --- a/src/rpc/system.rs +++ b/src/rpc/system.rs @@ -98,7 +98,6 @@ pub struct System { system_endpoint: Arc<Endpoint<SystemRpc, System>>, rpc_listen_addr: SocketAddr, - #[cfg(any(feature = "consul-discovery", feature = "kubernetes-discovery"))] rpc_public_addr: Option<SocketAddr>, bootstrap_peers: Vec<String>, @@ -325,7 +324,10 @@ impl System { warn!("This Garage node does not know its publicly reachable RPC address, this might hamper intra-cluster communication."); } - let netapp = NetApp::new(GARAGE_VERSION_TAG, network_key, node_key); + let bind_outgoing_to = Some(config) + .filter(|x| x.rpc_bind_outgoing) + .map(|x| x.rpc_bind_addr.ip()); + let netapp = NetApp::new(GARAGE_VERSION_TAG, network_key, node_key, bind_outgoing_to); let peering = PeeringManager::new(netapp.clone(), vec![], rpc_public_addr); if let Some(ping_timeout) = config.rpc_ping_timeout_msec { peering.set_ping_timeout_millis(ping_timeout); @@ -369,7 +371,6 @@ impl System { replication_mode, replication_factor, rpc_listen_addr: config.rpc_bind_addr, - #[cfg(any(feature = "consul-discovery", feature = "kubernetes-discovery"))] rpc_public_addr, bootstrap_peers: config.bootstrap_peers.clone(), #[cfg(feature = "consul-discovery")] @@ -390,9 +391,11 @@ impl System { /// Perform bootstraping, starting the ping loop pub async fn run(self: Arc<Self>, must_exit: watch::Receiver<bool>) { join!( - self.netapp - .clone() - .listen(self.rpc_listen_addr, None, must_exit.clone()), + self.netapp.clone().listen( + self.rpc_listen_addr, + self.rpc_public_addr, + must_exit.clone() + ), self.peering.clone().run(must_exit.clone()), self.discovery_loop(must_exit.clone()), self.status_exchange_loop(must_exit.clone()), diff --git a/src/util/config.rs b/src/util/config.rs index a9a72110..056c625d 100644 --- a/src/util/config.rs +++ b/src/util/config.rs @@ -55,6 +55,9 @@ pub struct Config { pub rpc_secret_file: Option<PathBuf>, /// Address to bind for RPC pub rpc_bind_addr: SocketAddr, + /// Bind outgoing sockets to rpc_bind_addr's IP address as well + #[serde(default)] + pub rpc_bind_outgoing: bool, /// Public IP address of this node pub rpc_public_addr: Option<String>, |