summaryrefslogtreecommitdiff
path: root/src/silx/utils/retry.py
blob: adc43bca6c1d2dffb687b28292e0fa8cf9d26f32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""
This module provides utility methods for retrying methods until they
no longer fail.
"""

__authors__ = ["W. de Nolf"]
__license__ = "MIT"
__date__ = "05/02/2020"


import time
from functools import wraps
from contextlib import contextmanager
import multiprocessing
from queue import Empty


RETRY_PERIOD = 0.01


class RetryTimeoutError(TimeoutError):
    pass


class RetryError(RuntimeError):
    pass


def _default_retry_on_error(e):
    """
    :param BaseException e:
    :returns bool:
    """
    return isinstance(e, RetryError)


@contextmanager
def _handle_exception(options):
    try:
        yield
    except BaseException as e:
        retry_on_error = options.get("retry_on_error")
        if retry_on_error is not None and retry_on_error(e):
            options["exception"] = e
        else:
            raise


def _retry_loop(retry_timeout=None, retry_period=None, retry_on_error=None):
    """Iterator which is endless or ends with an RetryTimeoutError.
    It yields a dictionary which can be used to influence the loop.

    :param num retry_timeout:
    :param num retry_period: sleep before retry
    :param callable or None retry_on_error: checks whether an exception is
                                            eligible for retry
    """
    has_timeout = retry_timeout is not None
    options = {"exception": None, "retry_on_error": retry_on_error}
    if has_timeout:
        t0 = time.time()
    while True:
        yield options
        if retry_period is not None:
            time.sleep(retry_period)
        if has_timeout and (time.time() - t0) > retry_timeout:
            raise RetryTimeoutError from options.get("exception")


def retry(
    retry_timeout=None, retry_period=None, retry_on_error=_default_retry_on_error
):
    """Decorator for a method that needs to be executed until it not longer
    fails or until `retry_on_error` returns False.

    The decorator arguments can be overriden by using them when calling the
    decorated method.

    :param num retry_timeout:
    :param num retry_period: sleep before retry
    :param callable or None retry_on_error: checks whether an exception is
                                            eligible for retry
    """

    if retry_period is None:
        retry_period = RETRY_PERIOD

    def decorator(method):
        @wraps(method)
        def wrapper(*args, **kw):
            _retry_timeout = kw.pop("retry_timeout", retry_timeout)
            _retry_period = kw.pop("retry_period", retry_period)
            _retry_on_error = kw.pop("retry_on_error", retry_on_error)
            for options in _retry_loop(
                retry_timeout=_retry_timeout,
                retry_period=_retry_period,
                retry_on_error=_retry_on_error,
            ):
                with _handle_exception(options):
                    return method(*args, **kw)

        return wrapper

    return decorator


def retry_contextmanager(
    retry_timeout=None, retry_period=None, retry_on_error=_default_retry_on_error
):
    """Decorator to make a context manager from a method that needs to be
    entered until it no longer fails or until `retry_on_error` returns False.

    The decorator arguments can be overriden by using them when calling the
    decorated method.

    :param num retry_timeout:
    :param num retry_period: sleep before retry
    :param callable or None retry_on_error: checks whether an exception is
                                            eligible for retry
    """

    if retry_period is None:
        retry_period = RETRY_PERIOD

    def decorator(method):
        @wraps(method)
        def wrapper(*args, **kw):
            _retry_timeout = kw.pop("retry_timeout", retry_timeout)
            _retry_period = kw.pop("retry_period", retry_period)
            _retry_on_error = kw.pop("retry_on_error", retry_on_error)
            for options in _retry_loop(
                retry_timeout=_retry_timeout,
                retry_period=_retry_period,
                retry_on_error=_retry_on_error,
            ):
                with _handle_exception(options):
                    gen = method(*args, **kw)
                    result = next(gen)
                    options["retry_on_error"] = None
                    yield result
                    try:
                        next(gen)
                    except StopIteration:
                        return
                    else:
                        raise RuntimeError(str(method) + " should only yield once")

        return contextmanager(wrapper)

    return decorator


def _subprocess_main(queue, method, retry_on_error, *args, **kw):
    try:
        result = method(*args, **kw)
    except BaseException as e:
        if retry_on_error(e):
            # As the traceback gets lost, make sure the top-level
            # exception is RetryError
            e = RetryError(str(e))
        queue.put(e)
    else:
        queue.put(result)


def retry_in_subprocess(
    retry_timeout=None, retry_period=None, retry_on_error=_default_retry_on_error
):
    """Same as `retry` but it also retries segmentation faults.

    As subprocesses are spawned, you cannot use this decorator with the "@" syntax
    because the decorated method needs to be an attribute of a module:

    .. code-block:: python

        def _method(*args, **kw):
            ...

        method = retry_in_subprocess()(_method)

    :param num retry_timeout:
    :param num retry_period: sleep before retry
    :param callable or None retry_on_error: checks whether an exception is
                                            eligible for retry
    """

    if retry_period is None:
        retry_period = RETRY_PERIOD

    def decorator(method):
        @wraps(method)
        def wrapper(*args, **kw):
            _retry_timeout = kw.pop("retry_timeout", retry_timeout)
            _retry_period = kw.pop("retry_period", retry_period)
            _retry_on_error = kw.pop("retry_on_error", retry_on_error)

            ctx = multiprocessing.get_context("spawn")

            def start_subprocess():
                queue = ctx.Queue(maxsize=1)
                p = ctx.Process(
                    target=_subprocess_main,
                    args=(queue, method, retry_on_error) + args,
                    kwargs=kw,
                )
                p.start()
                return p, queue

            def stop_subprocess(p):
                try:
                    p.kill()
                except AttributeError:
                    p.terminate()
                p.join()

            p, queue = start_subprocess()
            try:
                for options in _retry_loop(
                    retry_timeout=_retry_timeout, retry_on_error=_retry_on_error
                ):
                    with _handle_exception(options):
                        if not p.is_alive():
                            p, queue = start_subprocess()
                        try:
                            result = queue.get(block=True, timeout=_retry_period)
                        except Empty:
                            pass
                        except ValueError:
                            pass
                        else:
                            if isinstance(result, BaseException):
                                stop_subprocess(p)
                                raise result
                            else:
                                return result
            finally:
                stop_subprocess(p)

        return wrapper

    return decorator