rdb.py 4.8 KB

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