Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

signal.alarm() -> threading.Timer() #11

Merged
merged 5 commits into from
Jul 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import functools
import itertools
import logging
import signal
import os
from select import poll, POLLIN
from threading import Timer
import time

from decorator import decorator
Expand All @@ -20,10 +22,9 @@ class MaximumTimeoutExceeded(Exception):
pass


def _timeout(msg):
def __internal_timeout(signum, frame):
raise MaximumTimeoutExceeded(msg)
return __internal_timeout
def _timeout(pipe_w):
with os.fdopen(pipe_w, 'w') as p:
p.write('stop')


def retry(
Expand Down Expand Up @@ -73,22 +74,26 @@ def foo(bar):

@decorator
def wrapper(func, *args, **kwargs):
signal.signal(
signal.SIGALRM, _timeout(
_timeout_error_msg.format(timeout, func.__name__)))
run_func = functools.partial(func, *args, **kwargs)
logger = logging.getLogger(func.__module__)
if max_retries < 0:
iterator = itertools.count()
else:
iterator = range(max_retries)
timer = None
if timeout > 0:
signal.alarm(timeout)
r, w = os.pipe()
timer = Timer(timeout, _timeout, [w])
timer.start()
p = poll()
p.register(r, POLLIN)

for num, _ in enumerate(iterator, 1):
try:
result = run_func()
if success is None or success(result):
signal.alarm(0)
if timer:
timer.cancel()
return result
except exceptions:
logger.exception(
Expand All @@ -99,7 +104,14 @@ def wrapper(func, *args, **kwargs):
logger.warning(
'Retrying {} in {}s...'.format(
func.__name__, interval))
time.sleep(interval)
if timer:
r_state = p.poll(interval * 1000)
if r_state and r_state[0][1] & POLLIN:
raise MaximumTimeoutExceeded(
_timeout_error_msg.format(timeout, func.__name__)
)
else:
time.sleep(interval)
else:
raise MaximumRetriesExceeded(
_retries_error_msg.format(
Expand Down
37 changes: 37 additions & 0 deletions test_retry.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
from threading import Thread
from time import sleep

import pytest
Expand Down Expand Up @@ -84,3 +85,39 @@ def test_disarm_signal_on_success():
_test_func = retry.retry(success=lambda x: True, timeout=1, interval=0.5)(foo)
_test_func(1)
sleep(1.2)


def test_successful_thread():
"""Success with function as thread"""
retryed = []

@retry.retry(timeout=1, success=lambda x: len(x) == 3)
def f(retryed):
retryed.append(0)
return retryed

t = Thread(target=f, args=[retryed])
t.start()
t.join()
assert 3 == len(retryed)


def test_unsuccessful_thread():
"""Unsuccessful with function as thread, timed out"""
retryed = []

def foo(retryed):
@retry.retry(timeout=1, success=lambda x: False)
def bar(retryed):
sleep(0.2)
retryed.append(0)

with pytest.raises(retry.MaximumTimeoutExceeded):
bar(retryed)

t = Thread(target=foo, args=[retryed])
t.start()
t.join()
assert 3 <= len(retryed) <= 5