debug.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """The debug module contains utilities and functions for better
  2. debugging Eventlet-powered applications."""
  3. from __future__ import print_function
  4. import os
  5. import sys
  6. import linecache
  7. import re
  8. import inspect
  9. __all__ = ['spew', 'unspew', 'format_hub_listeners', 'format_hub_timers',
  10. 'hub_listener_stacks', 'hub_exceptions', 'tpool_exceptions',
  11. 'hub_prevent_multiple_readers', 'hub_timer_stacks',
  12. 'hub_blocking_detection']
  13. _token_splitter = re.compile('\W+')
  14. class Spew(object):
  15. def __init__(self, trace_names=None, show_values=True):
  16. self.trace_names = trace_names
  17. self.show_values = show_values
  18. def __call__(self, frame, event, arg):
  19. if event == 'line':
  20. lineno = frame.f_lineno
  21. if '__file__' in frame.f_globals:
  22. filename = frame.f_globals['__file__']
  23. if (filename.endswith('.pyc') or
  24. filename.endswith('.pyo')):
  25. filename = filename[:-1]
  26. name = frame.f_globals['__name__']
  27. line = linecache.getline(filename, lineno)
  28. else:
  29. name = '[unknown]'
  30. try:
  31. src = inspect.getsourcelines(frame)
  32. line = src[lineno]
  33. except IOError:
  34. line = 'Unknown code named [%s]. VM instruction #%d' % (
  35. frame.f_code.co_name, frame.f_lasti)
  36. if self.trace_names is None or name in self.trace_names:
  37. print('%s:%s: %s' % (name, lineno, line.rstrip()))
  38. if not self.show_values:
  39. return self
  40. details = []
  41. tokens = _token_splitter.split(line)
  42. for tok in tokens:
  43. if tok in frame.f_globals:
  44. details.append('%s=%r' % (tok, frame.f_globals[tok]))
  45. if tok in frame.f_locals:
  46. details.append('%s=%r' % (tok, frame.f_locals[tok]))
  47. if details:
  48. print("\t%s" % ' '.join(details))
  49. return self
  50. def spew(trace_names=None, show_values=False):
  51. """Install a trace hook which writes incredibly detailed logs
  52. about what code is being executed to stdout.
  53. """
  54. sys.settrace(Spew(trace_names, show_values))
  55. def unspew():
  56. """Remove the trace hook installed by spew.
  57. """
  58. sys.settrace(None)
  59. def format_hub_listeners():
  60. """ Returns a formatted string of the current listeners on the current
  61. hub. This can be useful in determining what's going on in the event system,
  62. especially when used in conjunction with :func:`hub_listener_stacks`.
  63. """
  64. from eventlet import hubs
  65. hub = hubs.get_hub()
  66. result = ['READERS:']
  67. for l in hub.get_readers():
  68. result.append(repr(l))
  69. result.append('WRITERS:')
  70. for l in hub.get_writers():
  71. result.append(repr(l))
  72. return os.linesep.join(result)
  73. def format_hub_timers():
  74. """ Returns a formatted string of the current timers on the current
  75. hub. This can be useful in determining what's going on in the event system,
  76. especially when used in conjunction with :func:`hub_timer_stacks`.
  77. """
  78. from eventlet import hubs
  79. hub = hubs.get_hub()
  80. result = ['TIMERS:']
  81. for l in hub.timers:
  82. result.append(repr(l))
  83. return os.linesep.join(result)
  84. def hub_listener_stacks(state=False):
  85. """Toggles whether or not the hub records the stack when clients register
  86. listeners on file descriptors. This can be useful when trying to figure
  87. out what the hub is up to at any given moment. To inspect the stacks
  88. of the current listeners, call :func:`format_hub_listeners` at critical
  89. junctures in the application logic.
  90. """
  91. from eventlet import hubs
  92. hubs.get_hub().set_debug_listeners(state)
  93. def hub_timer_stacks(state=False):
  94. """Toggles whether or not the hub records the stack when timers are set.
  95. To inspect the stacks of the current timers, call :func:`format_hub_timers`
  96. at critical junctures in the application logic.
  97. """
  98. from eventlet.hubs import timer
  99. timer._g_debug = state
  100. def hub_prevent_multiple_readers(state=True):
  101. """Toggle prevention of multiple greenlets reading from a socket
  102. When multiple greenlets read from the same socket it is often hard
  103. to predict which greenlet will receive what data. To achieve
  104. resource sharing consider using ``eventlet.pools.Pool`` instead.
  105. But if you really know what you are doing you can change the state
  106. to ``False`` to stop the hub from protecting against this mistake.
  107. """
  108. from eventlet.hubs import hub
  109. hub.g_prevent_multiple_readers = state
  110. def hub_exceptions(state=True):
  111. """Toggles whether the hub prints exceptions that are raised from its
  112. timers. This can be useful to see how greenthreads are terminating.
  113. """
  114. from eventlet import hubs
  115. hubs.get_hub().set_timer_exceptions(state)
  116. from eventlet import greenpool
  117. greenpool.DEBUG = state
  118. def tpool_exceptions(state=False):
  119. """Toggles whether tpool itself prints exceptions that are raised from
  120. functions that are executed in it, in addition to raising them like
  121. it normally does."""
  122. from eventlet import tpool
  123. tpool.QUIET = not state
  124. def hub_blocking_detection(state=False, resolution=1):
  125. """Toggles whether Eventlet makes an effort to detect blocking
  126. behavior in an application.
  127. It does this by telling the kernel to raise a SIGALARM after a
  128. short timeout, and clearing the timeout every time the hub
  129. greenlet is resumed. Therefore, any code that runs for a long
  130. time without yielding to the hub will get interrupted by the
  131. blocking detector (don't use it in production!).
  132. The *resolution* argument governs how long the SIGALARM timeout
  133. waits in seconds. The implementation uses :func:`signal.setitimer`
  134. and can be specified as a floating-point value.
  135. The shorter the resolution, the greater the chance of false
  136. positives.
  137. """
  138. from eventlet import hubs
  139. assert resolution > 0
  140. hubs.get_hub().debug_blocking = state
  141. hubs.get_hub().debug_blocking_resolution = resolution
  142. if not state:
  143. hubs.get_hub().block_detect_post()