30
30
from .checkerservice import CHECKER_METHODS , init_service
31
31
from .logging import ELKFormatter
32
32
from .nosqldict import NoSqlDict
33
- from .results import CheckerResult , EnoException , Result
33
+ from .results import CheckerResult , EnoException , OfflineException , Result
34
34
from .storeddict import DB_DEFAULT_DIR , DB_GLOBAL_CACHE_SETTING , StoredDict
35
35
from .useragents import random_useragent
36
36
from .utils import SimpleSocket , snake_caseify
@@ -739,6 +739,7 @@ def connect(
739
739
host : Optional [str ] = None ,
740
740
port : Optional [int ] = None ,
741
741
timeout : Optional [int ] = None ,
742
+ retries : int = 3 ,
742
743
) -> SimpleSocket :
743
744
"""
744
745
Open a socket/telnet connection to the remote host.
@@ -750,22 +751,51 @@ def connect(
750
751
:param timeout: timeout on connection (defaults to self.timeout)
751
752
:return: A connected Telnet instance
752
753
"""
754
+
753
755
if timeout :
754
- timeout_fun : Callable [[], int ] = lambda : cast (int , timeout )
756
+
757
+ def timeout_fun () -> int :
758
+ return cast (int , timeout )
759
+
755
760
else :
756
- timeout = self .time_remaining // 2
757
- timeout_fun = lambda : self .time_remaining // 2
761
+
762
+ def timeout_fun () -> int :
763
+ return self .time_remaining // 2
758
764
759
765
if port is None :
760
766
port = self .port
761
767
if host is None :
762
768
host = self .address
763
- self .debug (
764
- "Opening socket to {}:{} (timeout {} secs)." .format (host , port , timeout )
765
- )
766
- return SimpleSocket (
767
- host , port , timeout = timeout , logger = self .logger , timeout_fun = timeout_fun
768
- )
769
+
770
+ if retries < 0 :
771
+ raise ValueError ("Number of retries must be greater than zero." )
772
+
773
+ for i in range (0 , retries + 1 ): # + 1 for the initial try
774
+ try :
775
+
776
+ timeout = timeout_fun ()
777
+ self .debug (
778
+ "Opening socket to {}:{} (timeout {} secs)." .format (
779
+ host , port , timeout
780
+ )
781
+ )
782
+ return SimpleSocket (
783
+ host ,
784
+ port ,
785
+ timeout = timeout ,
786
+ logger = self .logger ,
787
+ timeout_fun = timeout_fun ,
788
+ )
789
+
790
+ except Exception as e :
791
+ self .warning (
792
+ f"Failed to establish connection to { host } :{ port } , Try #{ i + 1 } of { retries + 1 } " ,
793
+ exc_info = e ,
794
+ )
795
+ continue
796
+
797
+ self .error (f"Failed to establish connection to { host } :{ port } " )
798
+ raise OfflineException ("Failed establishing connection to service." )
769
799
770
800
@property
771
801
def http_useragent (self ) -> str :
0 commit comments