contentmonster/classes/retry.py

39 lines
1.3 KiB
Python
Raw Normal View History

from paramiko.ssh_exception import SSHException, NoValidConnectionsError
from socket import timeout
2021-11-20 14:40:07 +00:00
2021-11-30 16:52:40 +00:00
from classes.logger import Logger
2021-11-20 14:40:07 +00:00
class retry:
2021-11-25 15:31:49 +00:00
"""Decorator used to automatically retry operations throwing exceptions
"""
def __init__(self, exceptions: tuple[BaseException] = None):
"""Initializing the retry decorator
Args:
exceptions (tuple, optional): A tuple containing exception classes
that should be handled by the decorator. If none, handle only
paramiko.ssh_exception.SSHException/NoValidConnectionsError and
socket.timeout/TimeoutError. Defaults to None.
2021-11-25 15:31:49 +00:00
"""
self.exceptions = exceptions or (SSHException, NoValidConnectionsError,
timeout, TimeoutError)
2021-11-30 16:52:40 +00:00
self._logger = Logger()
2021-11-20 14:40:07 +00:00
def __call__(self, f):
2021-11-25 15:31:49 +00:00
"""Return a function through the retry decorator
Args:
f (function): Function to wrap in the decorator
Returns:
function: Function wrapping the passed function
"""
def wrapped_f(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except self.exceptions as e:
2021-11-30 16:52:40 +00:00
self._logger.info("Caught expected exception: " + repr(e))
2021-11-25 15:31:49 +00:00
2021-11-20 14:40:07 +00:00
return wrapped_f