rdb.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. default_port = 6899
  35. CELERY_RDB_HOST = os.environ.get('CELERY_RDB_HOST') or '127.0.0.1'
  36. CELERY_RDB_PORT = int(os.environ.get('CELERY_RDB_PORT') or default_port)
  37. #: Holds the currently active debugger.
  38. _current = [None]
  39. _frame = getattr(sys, '_getframe')
  40. NO_AVAILABLE_PORT = """\
  41. {self.ident}: Couldn't find an available port.
  42. Please specify one using the CELERY_RDB_PORT environment variable.
  43. """
  44. BANNER = """\
  45. {self.ident}: Please telnet into {self.host} {self.port}.
  46. Type `exit` in session to continue.
  47. {self.ident}: Waiting for client...
  48. """
  49. SESSION_STARTED = '{self.ident}: Now in session with {self.remote_addr}.'
  50. SESSION_ENDED = '{self.ident}: Session with {self.remote_addr} ended.'
  51. class Rdb(Pdb):
  52. me = 'Remote Debugger'
  53. _prev_outs = None
  54. _sock = None
  55. def __init__(self, host=CELERY_RDB_HOST, port=CELERY_RDB_PORT,
  56. port_search_limit=100, port_skew=+0, out=sys.stdout):
  57. self.active = True
  58. self.out = out
  59. self._prev_handles = sys.stdin, sys.stdout
  60. self._sock, this_port = self.get_avail_port(
  61. host, port, port_search_limit, port_skew,
  62. )
  63. self._sock.setblocking(1)
  64. self._sock.listen(1)
  65. self.ident = '{0}:{1}'.format(self.me, this_port)
  66. self.host = host
  67. self.port = this_port
  68. self.say(BANNER.format(self=self))
  69. self._client, address = self._sock.accept()
  70. self._client.setblocking(1)
  71. self.remote_addr = ':'.join(str(v) for v in address)
  72. self.say(SESSION_STARTED.format(self=self))
  73. self._handle = sys.stdin = sys.stdout = self._client.makefile('rw')
  74. Pdb.__init__(self, completekey='tab',
  75. stdin=self._handle, stdout=self._handle)
  76. def get_avail_port(self, host, port, search_limit=100, skew=+0):
  77. try:
  78. _, skew = current_process().name.split('-')
  79. skew = int(skew)
  80. except ValueError:
  81. pass
  82. this_port = None
  83. for i in range(search_limit):
  84. _sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  85. this_port = port + skew + i
  86. try:
  87. _sock.bind((host, this_port))
  88. except socket.error as exc:
  89. if exc.errno in [errno.EADDRINUSE, errno.EINVAL]:
  90. continue
  91. raise
  92. else:
  93. return _sock, this_port
  94. else:
  95. raise Exception(NO_AVAILABLE_PORT.format(self=self))
  96. def say(self, m):
  97. print(m, file=self.out)
  98. def _close_session(self):
  99. self.stdin, self.stdout = sys.stdin, sys.stdout = self._prev_handles
  100. self._handle.close()
  101. self._client.close()
  102. self._sock.close()
  103. self.active = False
  104. self.say(SESSION_ENDED.format(self=self))
  105. def do_continue(self, arg):
  106. self._close_session()
  107. self.set_continue()
  108. return 1
  109. do_c = do_cont = do_continue
  110. def do_quit(self, arg):
  111. self._close_session()
  112. self.set_quit()
  113. return 1
  114. do_q = do_exit = do_quit
  115. def set_trace(self, frame=None):
  116. if frame is None:
  117. frame = _frame().f_back
  118. with ignore_errno(errno.ECONNRESET):
  119. Pdb.set_trace(self, frame)
  120. def set_quit(self):
  121. # this raises a BdbQuit exception that we are unable to catch.
  122. sys.settrace(None)
  123. def debugger():
  124. """Returns the current debugger instance (if any),
  125. or creates a new one."""
  126. rdb = _current[0]
  127. if rdb is None or not rdb.active:
  128. rdb = _current[0] = Rdb()
  129. return rdb
  130. def set_trace(frame=None):
  131. """Set breakpoint at current location, or a specified frame"""
  132. if frame is None:
  133. frame = _frame().f_back
  134. return debugger().set_trace(frame)