Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

Commit

Permalink
fix: add delay to make sure we drop the socket
Browse files Browse the repository at this point in the history
  • Loading branch information
RolandSherwin committed Jan 23, 2024
1 parent c3f9c00 commit 69c8652
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ pub enum SubCmd {
},
}

#[tokio::main]
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
color_eyre::install()?;
let args = Cmd::parse();
Expand Down
12 changes: 10 additions & 2 deletions src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ use service_manager::{
ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStopCtx,
ServiceUninstallCtx,
};
use std::ffi::OsString;
use std::net::SocketAddr;
#[cfg(feature = "tcp")]
use std::net::TcpListener as SocketBinder;
#[cfg(not(feature = "tcp"))]
use std::net::UdpSocket as SocketBinder;
use std::time::Duration;
use std::{ffi::OsString, thread::sleep};

use std::path::PathBuf;
use sysinfo::{Pid, System, SystemExt};
Expand Down Expand Up @@ -163,7 +164,14 @@ impl ServiceControl for NodeServiceManager {
fn get_available_port(&self) -> Result<u16> {
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

Ok(SocketBinder::bind(addr)?.local_addr()?.port())
let socket = SocketBinder::bind(addr)?;
let port = socket.local_addr()?.port();
drop(socket);
// Sleep a little while to make sure that we've dropped the socket.
// Without the delay, we may face 'Port already in use' error, when trying to re-use this port.
sleep(Duration::from_secs(1));

Ok(port)
}

fn install(&self, config: ServiceConfig) -> Result<()> {
Expand Down

0 comments on commit 69c8652

Please sign in to comment.