Source

hotdebug / utils.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ai et si ts=4 sts=4 sw=4:

import sys, threading


# thread-local storage for hotdebug
_hotdebug_tls = threading.local()


def register_exception_callback(cb):
    _hotdebug_tls.exception_callback = cb


def unregister_exception_callback():
    if getattr(_hotdebug_tls, 'exception_callback', None):
        del _hotdebug_tls.exception_callback


def _hook_excpetion():

    def _wrap_dispatch(old):
        def dispatch(self, method, auth, params):
            try:
                return old(self, method, auth, params)
            except:
                cb = getattr(_hotdebug_tls, 'exception_callback', None)
                # only process the same thread's exception
                if cb is not None:
                    cb(*sys.exc_info())
                raise
        dispatch._hooked = True
        return dispatch

    from netsvc import ExportService
    for service in ExportService._services.itervalues():
        dispatch = service.__class__.__dict__.get('dispatch', None)
        if dispatch and getattr(dispatch, '_hooked', False):
            service.__class__.dispatch = _wrap_dispatch(dispatch)


_hook_excpetion()
del _hook_excpetion