From b875130724828056fd26d33c8aa6de0c6848558e Mon Sep 17 00:00:00 2001 From: Jorrit Schaap <schaap@astron.nl> Date: Tue, 4 Feb 2020 12:43:41 +0100 Subject: [PATCH] TMSS-139: use a preferred port if available, otherwise a random free port --- LCS/PyCommon/util.py | 13 ++++++++++--- SAS/TMSS/test/test_utils.py | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/LCS/PyCommon/util.py b/LCS/PyCommon/util.py index cef4cda88c4..8ddd6531dac 100644 --- a/LCS/PyCommon/util.py +++ b/LCS/PyCommon/util.py @@ -194,12 +194,19 @@ def single_line_with_single_spaces(lines: str) -> str: return line length = new_length -def find_free_port(): - '''find and return a random free network port''' +def find_free_port(preferred_port: int=0): + '''find and return a random free network port, preferably the given <preferred_port>''' import socket from contextlib import closing with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: - s.bind(('', 0)) + try: + s.bind(('', preferred_port)) + except OSError as e: + if e.errno==98: # OSError: [Errno 98] Address already in use + s.bind(('', 0)) + else: + raise + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()[1] diff --git a/SAS/TMSS/test/test_utils.py b/SAS/TMSS/test/test_utils.py index 79cf57cfcce..d64d416d258 100644 --- a/SAS/TMSS/test/test_utils.py +++ b/SAS/TMSS/test/test_utils.py @@ -233,7 +233,7 @@ class TMSSTestEnvironment: self.database = TMSSTestDatabaseInstance() self.django_server = TMSSDjangoServerInstance(db_dbcreds_id=self.database.dbcreds_id, ldap_dbcreds_id=self.ldap_server.dbcreds_id, - port=find_free_port()) + port=find_free_port(8000)) def start(self): self.ldap_server.start() -- GitLab