| 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 |
from time import sleep as _sleep |
| 28 |
|
| 29 |
import sys |
| 30 |
absolute_import = (sys.version_info[0] >= 3) |
| 31 |
if absolute_import : |
| 32 |
|
| 33 |
exec("from . import db") |
| 34 |
else : |
| 35 |
import db |
| 36 |
|
| 37 |
|
| 38 |
_deadlock_MinSleepTime = 1.0/128 |
| 39 |
|
| 40 |
_deadlock_MaxSleepTime = 3.14159 |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
_deadlock_VerboseFile = None |
| 45 |
|
| 46 |
|
| 47 |
def DeadlockWrap(function, *_args, **_kwargs): |
| 48 |
"""DeadlockWrap(function, *_args, **_kwargs) - automatically retries |
| 49 |
function in case of a database deadlock. |
| 50 |
|
| 51 |
This is a function intended to be used to wrap database calls such |
| 52 |
that they perform retrys with exponentially backing off sleeps in |
| 53 |
between when a DBLockDeadlockError exception is raised. |
| 54 |
|
| 55 |
A 'max_retries' parameter may optionally be passed to prevent it |
| 56 |
from retrying forever (in which case the exception will be reraised). |
| 57 |
|
| 58 |
d = DB(...) |
| 59 |
d.open(...) |
| 60 |
DeadlockWrap(d.put, "foo", data="bar") # set key "foo" to "bar" |
| 61 |
""" |
| 62 |
sleeptime = _deadlock_MinSleepTime |
| 63 |
max_retries = _kwargs.get('max_retries', -1) |
| 64 |
if 'max_retries' in _kwargs: |
| 65 |
del _kwargs['max_retries'] |
| 66 |
while True: |
| 67 |
try: |
| 68 |
return function(*_args, **_kwargs) |
| 69 |
except db.DBLockDeadlockError: |
| 70 |
if _deadlock_VerboseFile: |
| 71 |
_deadlock_VerboseFile.write( |
| 72 |
'dbutils.DeadlockWrap: sleeping %1.3f\n' % sleeptime) |
| 73 |
_sleep(sleeptime) |
| 74 |
|
| 75 |
sleeptime *= 2 |
| 76 |
if sleeptime > _deadlock_MaxSleepTime: |
| 77 |
sleeptime = _deadlock_MaxSleepTime |
| 78 |
max_retries -= 1 |
| 79 |
if max_retries == -1: |
| 80 |
raise |
| 81 |
|
| 82 |
|
| 83 |
|