From dec286460db032c0931f64fe9e7d419b8192e211 Mon Sep 17 00:00:00 2001 From: l_samenv Date: Thu, 8 Apr 2021 10:19:03 +0200 Subject: [PATCH] starting TcpServer in case of Address already in use try several times, in case this is a restart. It seems that allow_reuse_address = True is not always enough --- secop/protocol/interface/tcp.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/secop/protocol/interface/tcp.py b/secop/protocol/interface/tcp.py index 55d85a9..6048a3c 100644 --- a/secop/protocol/interface/tcp.py +++ b/secop/protocol/interface/tcp.py @@ -25,6 +25,7 @@ import socket import socketserver import sys import threading +import time from secop.datatypes import BoolType, StringType from secop.errors import SECoPError @@ -184,8 +185,19 @@ class TCPServer(socketserver.ThreadingTCPServer): port = int(options.pop('uri').split('://', 1)[-1]) self.detailed_errors = options.pop('detailed_errors', False) - self.allow_reuse_address = True self.log.info("TCPServer %s binding to port %d" % (name, port)) - socketserver.ThreadingTCPServer.__init__( - self, ('0.0.0.0', port), TCPRequestHandler, bind_and_activate=True) + for ntry in range(5): + try: + socketserver.ThreadingTCPServer.__init__( + self, ('0.0.0.0', port), TCPRequestHandler, bind_and_activate=True) + break + except OSError as e: + if e.args[0] == 98: # address already in use + # this may happen despite of allow_reuse_address + time.sleep(0.3 * (1 << ntry)) + else: + self.log.error('could not initialize TCP Server: %r' % e) + raise + if ntry: + self.log.warning('tried again %d times after "Address already in use"' % ntry) self.log.info("TCPServer initiated")