debug.py 5.43 KB
Newer Older
1
"""Example of script starting a debugger on RTMIN+3 signal
2 3 4 5 6 7 8 9 10 11

The pdb is launched in a separate thread in order not to trigger timeouts.
The prompt is accessible through network in case that the process is daemonized:
  $ socat READLINE TCP:127.0.0.1:54930
  > neo/debug.py(63)pdb()
  -> app # this is Application instance
  (Pdb) app
  <neo.master.app.Application object at 0x1fc9750>
"""

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
import sys

def app_set():
    try:
        return sys.modules['neo.lib.threaded_app'].app_set
    except KeyError:
        f = sys._getframe(4)
        try:
            while f.f_code.co_name != 'run' or \
                  f.f_locals.get('self').__class__.__name__ != 'Application':
                f = f.f_back
            return f.f_locals['self'],
        except AttributeError:
            return ()

def defer(task):
    def wrapper():
        from traceback import print_exc
        try:
            task(app)
        except:
            print_exc()
    for app in app_set():
        app.em.wakeup(wrapper)
        break

38 39
IF = 'pdb'
if IF == 'pdb':
40 41 42 43 44 45 46 47
    # List of (module, callables) to break at.
    # If empty, a thread is started with a breakpoint.
    # All breakpoints are automatically removed on the first break,
    # or when this module is reloaded.
    BP = (#('ZODB.Connection', 'Connection.setstate'),
          #('ZPublisher.Publish', 'publish_module_standard'),
         )

48
    import errno, socket, threading, weakref
49 50 51
    # Unfortunately, IPython does not always print to given stdout.
    #from neo.lib.debug import getPdb
    from pdb import Pdb as getPdb
52 53 54 55

    class Socket(object):

        def __init__(self, socket):
56 57
            # In case that the default timeout is not None.
            socket.settimeout(None)
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            self._socket = socket
            self._buf = ''

        def write(self, data):
            self._socket.send(data)

        def readline(self):
            recv = self._socket.recv
            data = self._buf
            while True:
                i = 1 + data.find('\n')
                if i:
                    self._buf = data[i:]
                    return data[:i]
                d = recv(4096)
                data += d
                if not d:
                    self._buf = ''
                    return data

        def flush(self):
            pass

        def closed(self):
            self._socket.setblocking(0)
            try:
                self._socket.recv(0)
                return True
            except socket.error, (err, _):
                if err != errno.EAGAIN:
                    raise
                self._socket.setblocking(1)
            return False

92
    def pdb():
93 94
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
95 96
            # For better security, maybe we should use a unix socket.
            s.settimeout(60)
97 98 99
            s.bind(('127.0.0.1', 0))
            s.listen(0)
            print 'Listening to %u' % s.getsockname()[1]
100
            sys.stdout.flush() # BBB: On Python 3, print() takes a 'flush' arg.
101 102 103
            _socket = Socket(s.accept()[0])
        finally:
            s.close()
104 105 106 107
        try:
            app, = app_set
        except ValueError:
            app = None
108
        getPdb(stdin=_socket, stdout=_socket).set_trace()
109
        app # this is Application instance (see 'app_set' if there are several)
110

111
    app_set = app_set()
112 113 114 115 116 117

    class setupBreakPoints(list):

        def __init__(self, bp_list):
            self._lock = threading.Lock()
            for o, name in bp_list:
118
                o = __import__(o, fromlist=('*',), level=0)
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
                x = name.split('.')
                name = x.pop()
                for x in x:
                    o = getattr(o, x)
                orig = getattr(o, name)
                if orig.__module__ == __name__:
                    orig.__closure__[1].cell_contents._revert()
                    orig = getattr(o, name)
                    assert orig.__module__ != __name__, (o, name)
                orig = getattr(orig, '__func__', orig)
                self.append((o, name, orig))
                setattr(o, name, self._wrap(orig))
                print 'BP set on', orig
            sys.stdout.flush()
            self._hold = weakref.ref(pdb, self._revert)

        def _revert(self, *_):
            for x in self:
                setattr(*x)
                print 'BP removed on', x[2]
            sys.stdout.flush()
            del self[:]

        def _wrap(self, orig):
            return lambda *args, **kw: self(orig, *args, **kw)

        def __call__(self, orig, *args, **kw):
            stop = False
            with self._lock:
                if self:
                    stop = True
                    self._revert()
            if stop:
                pdb()
            return orig(*args, **kw)

    if BP:
        setupBreakPoints(BP)
    else:
        threading.Thread(target=pdb).start()
159 160

elif IF == 'frames':
161
    import traceback
162 163 164 165 166
    write = sys.stderr.write
    for thread_id, frame in sys._current_frames().iteritems():
        write("Thread %s:\n" % thread_id)
        traceback.print_stack(frame)
    write("End of dump\n")
167 168 169 170 171 172 173 174 175 176 177 178 179 180

elif IF == 'profile':
    DURATION = 60
    def stop(prof, path):
        prof.disable()
        prof.dump_stats(path)
    @defer
    def profile(app):
        import cProfile, threading, time
        from .lib.protocol import uuid_str
        path = 'neo-%s-%s.prof' % (uuid_str(app.uuid), time.time())
        prof = cProfile.Profile()
        threading.Timer(DURATION, stop, (prof, path)).start()
        prof.enable()