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

random_port(): more robust version #31

Closed
HenrikBengtsson opened this issue Jan 26, 2023 · 1 comment
Closed

random_port(): more robust version #31

HenrikBengtsson opened this issue Jan 26, 2023 · 1 comment

Comments

@HenrikBengtsson
Copy link

HenrikBengtsson commented Jan 26, 2023

While I'm at it:

random_port() relies on "chance", i.e. it bets on a random port will be available:

> proffer::random_port
function (lower = 49152L, upper = 65355L) 
{
    sample(seq.int(from = lower, to = upper, by = 1L), size = 1L)
}

Suggestion

In R (>= 4.0.0) we can easily check if a port is available, e.g.

> parallelly:::canPortBeUsed
function (port) 
{
    port <- assertPort(port)
    ns <- asNamespace("parallel")
    if (!exists("serverSocket", envir = ns, mode = "function")) 
        return(NA)
    serverSocket <- get("serverSocket", envir = ns, mode = "function")
    suspendInterrupts <- get("suspendInterrupts", envir = asNamespace("base"), 
        mode = "function")
    suspendInterrupts({
        con <- tryCatch(serverSocket(port), error = identity)
    })
    free <- inherits(con, "connection")
    if (free) 
        close(con)
    free
}
<environment: namespace:parallelly>

So, you could use that technique to increase the chances for getting a port that's actually available. That's now parallelly::freePort() works.

@wlandau
Copy link
Collaborator

wlandau commented Jan 27, 2023

Thanks for such a helpful suggestion! Happy to invoke parallelly::freePort() directly on the ephemeral port range.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants