Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Test failing CI tests due to port conflicts #4134

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions common/unused_port/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
lru_cache = { path = "../lru_cache" }
lazy_static = "1.4.0"
parking_lot = "0.12.0"
27 changes: 26 additions & 1 deletion common/unused_port/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use std::net::{TcpListener, UdpSocket};
use lazy_static::lazy_static;
use lru_cache::LRUTimeCache;
use parking_lot::Mutex;
use std::net::{SocketAddr, TcpListener, UdpSocket};
use std::time::Duration;

#[derive(Copy, Clone)]
pub enum Transport {
Expand All @@ -12,6 +16,13 @@ pub enum IpVersion {
Ipv6,
}

pub const CACHED_PORTS_TTL: Duration = Duration::from_secs(300);

lazy_static! {
static ref FOUND_PORTS_CACHE: Mutex<LRUTimeCache<u16>> =
Mutex::new(LRUTimeCache::new(CACHED_PORTS_TTL));
}

/// A convenience wrapper over [`zero_port`].
pub fn unused_tcp4_port() -> Result<u16, String> {
zero_port(Transport::Tcp, IpVersion::Ipv4)
Expand Down Expand Up @@ -48,6 +59,20 @@ pub fn zero_port(transport: Transport, ipv: IpVersion) -> Result<u16, String> {
IpVersion::Ipv6 => std::net::Ipv6Addr::LOCALHOST.into(),
};
let socket_addr = std::net::SocketAddr::new(localhost, 0);
let mut unused_port: u16;
loop {
unused_port = find_unused_port(transport, socket_addr)?;
let mut cache_lock = FOUND_PORTS_CACHE.lock();
if !cache_lock.contains(&unused_port) {
cache_lock.insert(unused_port);
break;
}
}

Ok(unused_port)
}

fn find_unused_port(transport: Transport, socket_addr: SocketAddr) -> Result<u16, String> {
let local_addr = match transport {
Transport::Tcp => {
let listener = TcpListener::bind(socket_addr).map_err(|e| {
Expand Down