ioutils.py (2597B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\packages\brennivin\ioutils.py 2 import threading as _threading 3 import time as _time 4 import socket as _socket 5 EPHEMERAL_PORT_RANGE = (49152, 65535) 6 7 class Timeout(_socket.timeout, Exception): 8 pass 9 10 11 class retry(object): 12 13 def __init__(self, attempts = 2, excfilter = (Exception,), wait = 0, backoff = 1, sleepfunc = None): 14 if attempts < 1: 15 raise ValueError('attempts must be greater than or equal to 1.') 16 if wait < 0: 17 raise ValueError('wait must be greater than or equal to 0.') 18 if backoff < 1: 19 raise ValueError('backoff must be greater than or equal to 1.') 20 self.attempts = attempts 21 self.excFilter = excfilter 22 self.wait = wait 23 self.backoff = backoff 24 self.sleep = sleepfunc or _time.sleep 25 26 def __call__(self, func): 27 attemptsLeft = [self.attempts] 28 currDelay = [self.wait] 29 30 def inner(*args, **kwargs): 31 while True: 32 if attemptsLeft[0] == 1: 33 return func(*args, **kwargs) 34 attemptsLeft[0] -= 1 35 try: 36 return func(*args, **kwargs) 37 except self.excFilter: 38 if currDelay[0]: 39 self.sleep(currDelay[0]) 40 currDelay[0] *= self.backoff 41 return inner(*args, **kwargs) 42 43 return inner 44 45 46 class timeout(object): 47 48 @classmethod 49 def start_thread(cls, target): 50 t = _threading.Thread(target=target) 51 t.start() 52 return t 53 54 def __init__(self, timeoutSecs = 5): 55 self.timeoutSecs = timeoutSecs 56 57 def __call__(self, func): 58 59 def wrapped(*args, **kwargs): 60 innerResult = [] 61 innerExcRaised = [] 62 63 def inner(): 64 try: 65 result = func(*args, **kwargs) 66 innerResult.append(result) 67 except Exception as exc: 68 innerExcRaised.append(exc) 69 70 t = type(self).start_thread(inner) 71 t.join(timeout=self.timeoutSecs) 72 if innerResult: 73 return innerResult[0] 74 if innerExcRaised: 75 raise innerExcRaised[0] 76 raise Timeout 77 78 return wrapped 79 80 81 def is_local_port_open(port): 82 sock = _socket.socket() 83 isBound = False 84 try: 85 sock.bind(('127.0.0.1', port)) 86 except _socket.error: 87 isBound = True 88 finally: 89 sock.close() 90 91 return not isBound