Skip to content

Commit d351cc8

Browse files
committed
Test failing CI tests due to port conflicts (#4134)
## Issue Addressed #4127. PR to test port conflicts in CI tests . ## Proposed Changes See issue for more details, potential solution could be adding a cache bound by time to the `unused_port` function.
1 parent 036b797 commit d351cc8

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

Cargo.lock

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

common/unused_port/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,6 @@ edition = "2021"
66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
77

88
[dependencies]
9+
lru_cache = { path = "../lru_cache" }
10+
lazy_static = "1.4.0"
11+
parking_lot = "0.12.0"

common/unused_port/src/lib.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
use std::net::{TcpListener, UdpSocket};
1+
use lazy_static::lazy_static;
2+
use lru_cache::LRUTimeCache;
3+
use parking_lot::Mutex;
4+
use std::net::{SocketAddr, TcpListener, UdpSocket};
5+
use std::time::Duration;
26

37
#[derive(Copy, Clone)]
48
pub enum Transport {
@@ -12,6 +16,13 @@ pub enum IpVersion {
1216
Ipv6,
1317
}
1418

19+
pub const CACHED_PORTS_TTL: Duration = Duration::from_secs(300);
20+
21+
lazy_static! {
22+
static ref FOUND_PORTS_CACHE: Mutex<LRUTimeCache<u16>> =
23+
Mutex::new(LRUTimeCache::new(CACHED_PORTS_TTL));
24+
}
25+
1526
/// A convenience wrapper over [`zero_port`].
1627
pub fn unused_tcp4_port() -> Result<u16, String> {
1728
zero_port(Transport::Tcp, IpVersion::Ipv4)
@@ -48,6 +59,20 @@ pub fn zero_port(transport: Transport, ipv: IpVersion) -> Result<u16, String> {
4859
IpVersion::Ipv6 => std::net::Ipv6Addr::LOCALHOST.into(),
4960
};
5061
let socket_addr = std::net::SocketAddr::new(localhost, 0);
62+
let mut unused_port: u16;
63+
loop {
64+
unused_port = find_unused_port(transport, socket_addr)?;
65+
let mut cache_lock = FOUND_PORTS_CACHE.lock();
66+
if !cache_lock.contains(&unused_port) {
67+
cache_lock.insert(unused_port);
68+
break;
69+
}
70+
}
71+
72+
Ok(unused_port)
73+
}
74+
75+
fn find_unused_port(transport: Transport, socket_addr: SocketAddr) -> Result<u16, String> {
5176
let local_addr = match transport {
5277
Transport::Tcp => {
5378
let listener = TcpListener::bind(socket_addr).map_err(|e| {

0 commit comments

Comments
 (0)