From 1e599c950666bce097549130bcf5e4a4f3a138d2 Mon Sep 17 00:00:00 2001 From: Riley Jones Date: Mon, 28 Aug 2023 19:30:42 +0000 Subject: [PATCH 1/2] fix the port scanning logic --- tensorboard/program.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tensorboard/program.py b/tensorboard/program.py index 762adc32b4d..9f24b0f2e63 100644 --- a/tensorboard/program.py +++ b/tensorboard/program.py @@ -205,7 +205,7 @@ def configure(self, argv=("",), **kwargs): # any positional arguments to `serve`. serve_parser = serve_subparser - for (name, subcommand) in self.subcommands.items(): + for name, subcommand in self.subcommands.items(): subparser = subparsers.add_parser( name, help=subcommand.help(), @@ -647,9 +647,15 @@ def init(wsgi_app, flags): max_attempts = 100 if should_scan else 1 base_port = min(base_port + max_attempts, 0x10000) - max_attempts + def is_port_in_use(port): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(("localhost", port)) == 0 + for port in range(base_port, base_port + max_attempts): subflags = argparse.Namespace(**vars(flags)) subflags.port = port + if is_port_in_use(port): + continue try: return cls(wsgi_app=wsgi_app, flags=subflags) except TensorBoardPortInUseError: From c1c6ba51b1190b5c37e218dc64f47745b965365c Mon Sep 17 00:00:00 2001 From: Riley Jones Date: Tue, 29 Aug 2023 01:02:41 +0000 Subject: [PATCH 2/2] change where the error is thrown --- tensorboard/program.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/tensorboard/program.py b/tensorboard/program.py index 9f24b0f2e63..02cd660980b 100644 --- a/tensorboard/program.py +++ b/tensorboard/program.py @@ -647,15 +647,9 @@ def init(wsgi_app, flags): max_attempts = 100 if should_scan else 1 base_port = min(base_port + max_attempts, 0x10000) - max_attempts - def is_port_in_use(port): - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - return s.connect_ex(("localhost", port)) == 0 - for port in range(base_port, base_port + max_attempts): subflags = argparse.Namespace(**vars(flags)) subflags.port = port - if is_port_in_use(port): - continue try: return cls(wsgi_app=wsgi_app, flags=subflags) except TensorBoardPortInUseError: @@ -704,7 +698,17 @@ def __init__(self, wsgi_app, flags): self._url = None # Will be set by get_url() below self._fix_werkzeug_logging() + + def is_port_in_use(port): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(("localhost", port)) == 0 + try: + if is_port_in_use(port): + raise TensorBoardPortInUseError( + "TensorBoard could not bind to port %d, it was already in use" + % port + ) super().__init__(host, port, wsgi_app, _WSGIRequestHandler) except socket.error as e: if hasattr(errno, "EACCES") and e.errno == errno.EACCES: