rdb.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # -*- coding: utf-8 -*-
  2. """Remote Debugger.
  3. Introduction
  4. ============
  5. This is a remote debugger for Celery tasks running in multiprocessing
  6. pool workers. Inspired by http://snippets.dzone.com/posts/show/7248
  7. Usage
  8. -----
  9. .. code-block:: python
  10. from celery.contrib import rdb
  11. from celery import task
  12. @task()
  13. def add(x, y):
  14. result = x + y
  15. rdb.set_trace()
  16. return result
  17. Environment Variables
  18. =====================
  19. .. envvar:: CELERY_RDB_HOST
  20. ``CELERY_RDB_HOST``
  21. -------------------
  22. Hostname to bind to. Default is '127.0.01', which means the socket
  23. will only be accessible from the local host.
  24. .. envvar:: CELERY_RDB_PORT
  25. ``CELERY_RDB_PORT``
  26. -------------------
  27. Base port to bind to. Default is 6899.
  28. The debugger will try to find an available port starting from the
  29. base port. The selected port will be logged by the worker.
  30. """
  31. import errno
  32. import os
  33. import socket
  34. import sys
  35. from pdb import Pdb
  36. from billiard.process import current_process
  37. __all__ = [
  38. 'CELERY_RDB_HOST', 'CELERY_RDB_PORT', 'DEFAULT_PORT',
  39. 'Rdb', 'debugger', 'set_trace',
  40. ]
  41. DEFAULT_PORT = 6899
  42. CELERY_RDB_HOST = os.environ.get('CELERY_RDB_HOST') or '127.0.0.1'
  43. CELERY_RDB_PORT = int(os.environ.get('CELERY_RDB_PORT') or DEFAULT_PORT)
  44. #: Holds the currently active debugger.
  45. _current = [None]
  46. _frame = getattr(sys, '_getframe')
  47. NO_AVAILABLE_PORT = """\
  48. {self.ident}: Couldn't find an available port.
  49. Please specify one using the CELERY_RDB_PORT environment variable.
  50. """
  51. BANNER = """\
  52. {self.ident}: Ready to connect: telnet {self.host} {self.port}
  53. Type `exit` in session to continue.
  54. {self.ident}: Waiting for client...
  55. """
  56. SESSION_STARTED = '{self.ident}: Now in session with {self.remote_addr}.'
  57. SESSION_ENDED = '{self.ident}: Session with {self.remote_addr} ended.'
  58. class Rdb(Pdb):
  59. me = 'Remote Debugger'
  60. _prev_outs = None
  61. _sock = None
  62. def __init__(self, host=CELERY_RDB_HOST, port=CELERY_RDB_PORT,
  63. port_search_limit=100, port_skew=+0, out=sys.stdout):
  64. self.active = True
  65. self.out = out
  66. self._prev_handles = sys.stdin, sys.stdout
  67. self._sock, this_port = self.get_avail_port(
  68. host, port, port_search_limit, port_skew,
  69. )
  70. self._sock.setblocking(1)
  71. self._sock.listen(1)
  72. self.ident = '{0}:{1}'.format(self.me, this_port)
  73. self.host = host
  74. self.port = this_port
  75. self.say(BANNER.format(self=self))
  76. self._client, address = self._sock.accept()
  77. self._client.setblocking(1)
  78. self.remote_addr = ':'.join(str(v) for v in address)
  79. self.say(SESSION_STARTED.format(self=self))
  80. self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
  81. Pdb.__init__(self, completekey='tab',
  82. stdin=self._handle, stdout=self._handle)
  83. def get_avail_port(self, host, port, search_limit=100, skew=+0):
  84. try:
  85. _, skew = current_process().name.split('-')
  86. skew = int(skew)
  87. except ValueError:
  88. pass
  89. this_port = None
  90. for i in range(search_limit):
  91. _sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  92. this_port = port + skew + i
  93. try:
  94. _sock.bind((host, this_port))
  95. except socket.error as exc:
  96. if exc.errno in [errno.EADDRINUSE, errno.EINVAL]:
  97. continue
  98. raise
  99. else:
  100. return _sock, this_port
  101. else:
  102. raise Exception(NO_AVAILABLE_PORT.format(self=self))
  103. def say(self, m):
  104. print(m, file=self.out)
  105. def __enter__(self):
  106. return self
  107. def __exit__(self, *exc_info):
  108. self._close_session()
  109. def _close_session(self):
  110. self.stdin, self.stdout = sys.stdin, sys.stdout = self._prev_handles
  111. if self.active:
  112. if self._handle is not None:
  113. self._handle.close()
  114. if self._client is not None:
  115. self._client.close()
  116. if self._sock is not None:
  117. self._sock.close()
  118. self.active = False
  119. self.say(SESSION_ENDED.format(self=self))
  120. def do_continue(self, arg):
  121. self._close_session()
  122. self.set_continue()
  123. return 1
  124. do_c = do_cont = do_continue
  125. def do_quit(self, arg):
  126. self._close_session()
  127. self.set_quit()
  128. return 1
  129. do_q = do_exit = do_quit
  130. def set_quit(self):
  131. # this raises a BdbQuit exception that we are unable to catch.
  132. sys.settrace(None)
  133. def debugger():
  134. """Return the current debugger instance (if any),
  135. or creates a new one."""
  136. rdb = _current[0]
  137. if rdb is None or not rdb.active:
  138. rdb = _current[0] = Rdb()
  139. return rdb
  140. def set_trace(frame=None):
  141. """Set break-point at current location, or a specified frame."""
  142. if frame is None:
  143. frame = _frame().f_back
  144. return debugger().set_trace(frame)