Created
April 6, 2012 11:34
-
-
Save jrydberg/2319050 to your computer and use it in GitHub Desktop.
watchdog for gevent greenlets
This file contains hidden or 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
# Small snippet that shows how to put a watchdog around a greenlet. | |
# When the watchdog is triggered, a stacktrace of the greenlet is | |
# printed. | |
import gevent | |
import traceback | |
import sys | |
def a(a=10): | |
c = 20 | |
gevent.sleep(5) | |
def b(d): | |
x = d + 10 | |
a(x) | |
def c(): | |
b(20) | |
def dogslow(g, timeout=1): | |
try: | |
return g.get(True, timeout=timeout) | |
except gevent.Timeout: | |
print >>sys.stderr, "Watchdog triggered:" | |
sys.stderr.write(''.join(traceback.format_stack(g.gr_frame))) | |
dogslow(gevent.spawn(c)) |
This file contains hidden or 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
def monitor(g, timeout=1): | |
"""Puts a watchdog around greenlet `g`. If the greenlet | |
has not finished within `timeout` seconds, take a traceback | |
and wait for the greenlet to finish. | |
""" | |
t0 = time.time() | |
try: | |
return g.get(True, timeout=timeout) | |
except gevent.Timeout: | |
tb = traceback.format_stack(g.gr_frame) | |
try: | |
return g.get(True) | |
finally: | |
print >>sys.stderr, "Operation took %.3f seconds, expected max %.3f" % ( | |
time.time() - t0, timeout) | |
print >>sys.stderr, "Traceback at %.3f into the operation:" % (timeout,) | |
sys.stderr.write(''.join(tb)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment