Created
February 2, 2012 14:46
-
-
Save rbdcti/1723790 to your computer and use it in GitHub Desktop.
mongoengine reconnect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymongo.cursor import Cursor | |
from pymongo.connection import Connection | |
from pymongo.errors import AutoReconnect | |
import pymongo | |
import time | |
import functools | |
import logging | |
MAX_AUTO_RECONNECT_ATTEMPTS = 5 | |
def graceful_auto_reconnect(mongo_op_func): | |
"""Gracefully handle a reconnection event.""" | |
@functools.wraps(mongo_op_func) | |
def wrapper(*args, **kwargs): | |
attempt = 0 | |
print "WRAPPER ENTRY" | |
for attempt in xrange(MAX_AUTO_RECONNECT_ATTEMPTS): | |
try: | |
return mongo_op_func(*args, **kwargs) | |
except pymongo.errors.AutoReconnect as e: | |
wait_t = 0.5 * pow(2, attempt) # exponential back off | |
print "PyMongo auto-reconnecting... %s. Waiting %.1f seconds. (Attempt %i)" % (str(e), wait_t, attempt) | |
if attempt >= 5: | |
print "MAX ATTEMPTS REACHED" | |
raise | |
time.sleep(wait_t) | |
print "WRAPPER EXIT" | |
return wrapper | |
print "SETTING OVERRIDES" | |
Cursor._Cursor__send_message = graceful_auto_reconnect(Cursor._Cursor__send_message) | |
Connection._send_message = graceful_auto_reconnect(Connection._send_message) | |
Connection._send_message_with_response = graceful_auto_reconnect(Connection._send_message_with_response) | |
#Connection._Connection__find_master = reconnect(Connection._Connection__find_master) | |
print "SETTING OVERRIDES DONE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment