# HG changeset patch # User RhodeCode Admin # Date 2023-01-20 11:44:26 # Node ID 2a635a31237f46624bd0a8d28183ec1faf30492a # Parent a2853d3d6ca185099ca88f37072130009a6423b1 hooks: generate bind port before init of TcpServer for better logging. diff --git a/rhodecode/lib/hooks_daemon.py b/rhodecode/lib/hooks_daemon.py --- a/rhodecode/lib/hooks_daemon.py +++ b/rhodecode/lib/hooks_daemon.py @@ -24,6 +24,7 @@ import logging import tempfile import traceback import threading +import socket from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import TCPServer @@ -152,20 +153,34 @@ class HttpHooksCallbackDaemon(ThreadedHo # request and wastes cpu at all other times. POLL_INTERVAL = 0.01 + def get_available_port(): + family = socket.AF_INET + socktype = socket.SOCK_STREAM + host = '127.0.0.1' + + mysocket = socket.socket(family, socktype) + mysocket.bind((host, 0)) + port = mysocket.getsockname()[1] + mysocket.close() + del mysocket + return port + def _prepare(self, txn_id=None, host=None, port=None): host = host or '127.0.0.1' - self._done = False + port = port or self.get_available_port() + server_address = (host, port) self.hooks_uri = '{}:{}'.format(host, port) self.txn_id = txn_id + self._done = False + + log.debug( + "Preparing HTTP callback daemon at `%s` and registering hook object: %s", + self.hooks_uri, HooksHttpHandler) + + self._daemon = TCPServer(server_address, HooksHttpHandler) # inject transaction_id for later verification self._daemon.txn_id = self.txn_id - log.debug( - "Preparing HTTP callback daemon at `%s` and registering hook object", - self.hooks_uri) - - self._daemon = TCPServer((host, port or 0), HooksHttpHandler) - _, port = self._daemon.server_address def _run(self): log.debug("Running event loop of callback daemon in background thread")