zerotier: fix: find free port without collissions
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
import contextlib
|
||||||
import json
|
import json
|
||||||
import socket
|
import socket
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -33,11 +34,11 @@ def try_connect_port(port: int) -> bool:
|
|||||||
return result == 0
|
return result == 0
|
||||||
|
|
||||||
|
|
||||||
def find_free_port(port_range: range) -> Optional[int]:
|
def find_free_port() -> Optional[int]:
|
||||||
for port in port_range:
|
"""Find an unused localhost port from 1024-65535 and return it."""
|
||||||
if try_bind_port(port):
|
with contextlib.closing(socket.socket(type=socket.SOCK_STREAM)) as sock:
|
||||||
return port
|
sock.bind(("127.0.0.1", 0))
|
||||||
return None
|
return sock.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
class ZerotierController:
|
class ZerotierController:
|
||||||
@@ -82,7 +83,7 @@ class ZerotierController:
|
|||||||
@contextmanager
|
@contextmanager
|
||||||
def zerotier_controller() -> Iterator[ZerotierController]:
|
def zerotier_controller() -> Iterator[ZerotierController]:
|
||||||
# This check could be racy but it's unlikely in practice
|
# This check could be racy but it's unlikely in practice
|
||||||
controller_port = find_free_port(range(10000, 65535))
|
controller_port = find_free_port()
|
||||||
if controller_port is None:
|
if controller_port is None:
|
||||||
raise ClanError("cannot find a free port for zerotier controller")
|
raise ClanError("cannot find a free port for zerotier controller")
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,6 @@ def generate_secrets(machine: Machine) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if proc.returncode != 0:
|
if proc.returncode != 0:
|
||||||
log.error("stdout: %s", proc.stdout)
|
|
||||||
log.error("stderr: %s", proc.stderr)
|
|
||||||
raise ClanError("failed to generate secrets")
|
raise ClanError("failed to generate secrets")
|
||||||
else:
|
else:
|
||||||
print("successfully generated secrets")
|
print("successfully generated secrets")
|
||||||
|
|||||||
Reference in New Issue
Block a user