diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index d91e42d5516..3b633de5030 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -8,8 +8,11 @@ - Add support for IPv6. To enable set the multicast address in `MdnsConfig` to `IPV6_MDNS_MULTICAST_ADDRESS`. See [PR 2161] for details. - + +- Prevent timers from firing at the same time. See [PR 2212] for details. + [PR 2161]: https://github.com/libp2p/rust-libp2p/pull/2161/ +[PR 2212]: https://github.com/libp2p/rust-libp2p/pull/2212/ # 0.31.0 [2021-07-12] diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index 215a00be21b..a3c90aeb1f6 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -153,6 +153,13 @@ impl Mdns { Async::new(socket)? }; let if_watch = if_watch::IfWatcher::new().await?; + // randomize timer to prevent all converging and firing at the same time. + let query_interval = { + use rand::Rng; + let mut rng = rand::thread_rng(); + let jitter = rng.gen_range(0..100); + config.query_interval + Duration::from_millis(jitter) + }; Ok(Self { recv_socket, send_socket, @@ -162,9 +169,9 @@ impl Mdns { discovered_nodes: SmallVec::new(), closest_expiration: None, events: Default::default(), - query_interval: config.query_interval, + query_interval, ttl: config.ttl, - timeout: Timer::interval(config.query_interval), + timeout: Timer::interval(query_interval), multicast_addr: config.multicast_addr, }) } @@ -179,10 +186,19 @@ impl Mdns { self.discovered_nodes.iter().map(|(p, _, _)| p) } + fn reset_timer(&mut self) { + self.timeout.set_interval(self.query_interval); + } + + fn fire_timer(&mut self) { + self.timeout + .set_interval_at(Instant::now(), self.query_interval); + } + fn inject_mdns_packet(&mut self, packet: MdnsPacket, params: &impl PollParameters) { match packet { MdnsPacket::Query(query) => { - self.timeout.set_interval(self.query_interval); + self.reset_timer(); log::trace!("sending response"); for packet in build_query_response( query.query_id(), @@ -279,8 +295,7 @@ impl NetworkBehaviour for Mdns { } fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { - self.timeout - .set_interval_at(Instant::now(), self.query_interval); + self.fire_timer(); } fn poll( @@ -302,8 +317,7 @@ impl NetworkBehaviour for Mdns { if let Err(err) = socket.join_multicast_v4(&multicast, &addr) { log::error!("join multicast failed: {}", err); } else { - self.timeout - .set_interval_at(Instant::now(), self.query_interval); + self.fire_timer(); } } } @@ -313,8 +327,7 @@ impl NetworkBehaviour for Mdns { if let Err(err) = socket.join_multicast_v6(&multicast, 0) { log::error!("join multicast failed: {}", err); } else { - self.timeout - .set_interval_at(Instant::now(), self.query_interval); + self.fire_timer(); } } }