Exemplo n.º 1
0
def wrap_view_handler(wrapped, priority=3):
    """
    :param wrapped:
    :param priority:
    :return:
    """
    # views handler maybe called twice on same ResolverMatch. so mark it
    if hasattr(wrapped, '_self_django_view_handler_wrapped'):
        return wrapped

    name = callable_name(wrapped)

    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        tracker.set_tracker_name(name, priority=priority)
        with FunctionTracker(tracker, name=name):
            try:
                return wrapped(*args, **kwargs)
            except:  # Catch all
                tracker.record_exception(ignore_errors=should_ignore)
                raise

    result = FunctionWrapper(wrapped, wrapper)
    result._self_django_view_handler_wrapped = True

    return result
Exemplo n.º 2
0
def mq_consume_wrapper(wrapped, instance, args, kwargs):
    """
    :return:
    """
    def parse_callback(cb, *_args, **_kwargs):
        """
        :return:
        """
        return cb, _args, _kwargs

    if 'consumer_callback' in kwargs:
        callback_class_name = getattr(getattr(kwargs['consumer_callback'], 'im_class', None), '__name__', None)
        if getattr(kwargs['consumer_callback'], '_self_is_wrapped', None) or callback_class_name == 'BlockingChannel':
            console.debug("Consumer was wrapped before.")
            return wrapped(*args, **kwargs)

        kwargs['consumer_callback'] = FunctionWrapper(kwargs['consumer_callback'], callback_wrapper)
        return wrapped(*args, **kwargs)
    else:
        cb, _args, _kwargs = parse_callback(*args, **kwargs)
        callback_class_name = getattr(getattr(cb, 'im_class', None), '__name__', None)
        if getattr(cb, '_self_is_wrapped', None) or callback_class_name == 'BlockingChannel':
            console.debug("Consumer was wrapped before.")
            return wrapped(cb, *_args, **_kwargs)

        wrapped_cb = FunctionWrapper(cb, callback_wrapper)
        wrapped_cb._self_is_wrapped = True

        return wrapped(wrapped_cb, *_args, **_kwargs)
def function_trace_wrapper(wrapped,
                           name=None,
                           group=None,
                           label=None,
                           params=None):
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        _name = name
        _params = params
        _label = label
        _group = group

        if callable(name):
            if instance is not None:
                _name = name(instance, *args, **kwargs)
            else:
                _name = name(*args, **kwargs)
        elif name is None:
            _name = callable_name(wrapped)

        if callable(group):
            if instance is not None:
                _group = group(instance, *args, **kwargs)
            else:
                _group = group(*args, **kwargs)

        with FunctionTracker(tracker, _name, _group, _label, _params) as ft:
            try:
                return wrapped(*args, **kwargs)
            except:
                ft.exception.append(tracker.record_exception(is_error=False))
                raise

    def literal_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        _name = name or callable_name(wrapped)

        with FunctionTracker(tracker, _name, group, label, params) as ft:
            try:
                return wrapped(*args, **kwargs)
            except:
                ft.exception.append(tracker.record_exception(is_error=False))
                raise

    if callable(name) or callable(group) or callable(label) or callable(
            params):
        return FunctionWrapper(wrapped, dynamic_wrapper)

    return FunctionWrapper(wrapped, literal_wrapper)
def mongo_trace_wrapper(wrapped, schema, method, server=None):
    """
    :return:
    """
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        _method = method
        if callable(method):
            if instance is not None:
                _method = method(instance, *args, **kwargs)
            else:
                _method = method(*args, **kwargs)

        if callable(server):
            host, port, schema = server(instance, *args, **kwargs)
        else:
            host, port, schema = "Unknown", "Unknown", "Unknown"

        with MongoTracker(tracker, host, port, schema, _method) as mt:
            try:
                return wrapped(*args, **kwargs)
            except:
                mt.exception = tracker.record_exception(is_error=False)
                raise

    def literal_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if callable(server):
            host, port, schema = server(instance, *args, **kwargs)
        else:
            host, port, schema = "Unknown", "Unknown", "Unknown"

        with MongoTracker(tracker, host, port, schema, method) as mt:
            try:
                return wrapped(*args, **kwargs)
            except:
                mt.exception = tracker.record_exception(is_error=False)
                raise

    if callable(method):
        return FunctionWrapper(wrapped, dynamic_wrapper)

    return FunctionWrapper(wrapped, literal_wrapper)
Exemplo n.º 5
0
def uncaught_exception_wrapper(wrapped):
    """
    :param wrapped:
    :return:
    """
    def wrapper(wrapped, instance, args, kwargs):
        name = callable_name(wrapped)
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        def _wrapped(request, resolver, exc_info):
            tracker.set_tracker_name(name, priority=1)
            tracker.record_exception(*exc_info)

            try:
                return wrapped(request, resolver, exc_info)
            except:  # Catch all
                tracker.record_exception(*sys.exc_info())
                raise

        with FunctionTracker(tracker, name=name):
            return _wrapped(*args, **kwargs)

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 6
0
def app_delegate_wrapper(wrapped):
    """
    :param wrapped:
    :return:
    """
    def wrapper(wrapped, instance, args, kwargs):
        f, fvars, fargs = args
        tracker = current_tracker()
        if not tracker:
            return wrapped(f, fvars, fargs)

        if isinstance(f, six.string_types):
            name = f
        else:
            name = callable_name(f)

        tracker.set_tracker_name(name, 2)
        with FunctionTracker(tracker, name):
            try:
                return wrapped(*args, **kwargs)
            except Exception:
                tracker.record_exception(*sys.exc_info())
                raise

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 7
0
def uncaught_exception_wrapper(wrapped):
    """
    :param wrapped:
    :return:
    """
    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        def _wrapper(request, response, session):
            """
            """
            name = '%s.%s.%s.%s' % (request.application, request.controller,
                                    request.function, request.extension)
            tracker.set_tracker_name(name=name, group='web2py')
            wrapped(request, response, session)

        if tracker is None:
            return wrapped(*args, **kwargs)

        HTTP = import_module('gluon.http').HTTP
        try:
            return _wrapper(*args, **kwargs)
        except HTTP:
            raise
        except:
            tracker.record_exception(*sys.exc_info())
            raise

    return FunctionWrapper(wrapped, wrapper)
def redis_trace_wrapper(wrapped, command, server=None):
    """
    :return:
    """
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if instance:
            _command = command(instance, *args, **kwargs)
        else:
            _command = command(*args, **kwargs)

        if callable(server) and instance:
            host, port, db = server(instance, *args, **kwargs)
        else:
            host, port, db = "Unknown", 0, 0

        with RedisTrace(tracker, host, port, db, _command) as rt:
            try:
                return wrapped(*args, **kwargs)
            except:
                rt.exception = tracker.record_exception(is_error=False)
                raise

    def literal_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if callable(server) and instance:
            host, port, db = server(instance, *args, **kwargs)
        else:
            host, port, db = "Unknown", 0, 0

        with RedisTrace(tracker, host, port, db, command) as rt:
            try:
                return wrapped(*args, **kwargs)
            except:
                rt.exception = tracker.record_exception(is_error=False)
                raise

    if callable(command):
        return FunctionWrapper(wrapped, dynamic_wrapper)

    return FunctionWrapper(wrapped, literal_wrapper)
def memcached_trace_wrapper(wrapped, server, command):
    """
    :return:
    """
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if callable(server):
            host, port = server(instance, *args, **kwargs)
        else:
            host, port = "Unknown", 0

        if instance is not None:
            _command = command(instance, *args, **kwargs)
        else:
            _command = command(*args, **kwargs)

        with MemcacheTrace(tracker, host, port, _command) as mt:
            try:
                return wrapped(*args, **kwargs)
            except:
                mt.exception = tracker.record_exception(is_error=False)
                raise

    def literal_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if callable(server):
            host, port = server(instance, *args, **kwargs)
        else:
            host, port = "Unknown", 0

        with MemcacheTrace(tracker, host, port, command) as mt:
            try:
                return wrapped(*args, **kwargs)
            except:
                mt.exception = tracker.record_exception(is_error=False)
                raise

    if callable(command):
        return FunctionWrapper(wrapped, dynamic_wrapper)

    return FunctionWrapper(wrapped, literal_wrapper)
Exemplo n.º 10
0
def trace_wsgi_app_entrance(wrapped):
    """flowing situations maybe faced.

        1. the tornado application transferred to run with WSGI server
        2. WSGI application run in tornado server.
        3. tornado application run in tornado server.
    """
    def parse_param(request, *args, **kwargs):
        return request, args, kwargs

    def trace_app_without_body(wrapped, instance, request, args, kwargs):
        """
        :return:
        """
        tracker = generate_tracer(request)
        if not tracker:
            return wrapped(*args, **kwargs)

        try:
            # we should use `FunctionWrapper` at here.because the Connection._on_finished will be executed in the
            # wrapped func. use `FunctionWrapper` will cause errors.
            ret = wrapped(*args, **kwargs)
        except:
            stop_request_tracer(request,
                                *sys.exc_info(),
                                segment="App.__call__.exception")
            raise
        else:
            if request._self_request_finished:
                return ret

            request._self_request_finished = True
            stop_request_tracer(request, segment='finish-app-call')
            return ret

    def wrapper(wrapped, instance, args, kwargs):
        """tracker will be put into the thread for other plugins trace in user code. such as mysql/memcached etc.
        :return:
        """
        request, _args, _kwargs = parse_param(*args, **kwargs)
        async_tracker = getattr(request, '_self_tracer', None)
        thread_tracker = current_tracker()

        # situation 1 & 2. just do nothing because the entrance of the wsgi app was detected.
        if not async_tracker and thread_tracker:
            # console.info("has not self tracer.%s, thread tracer %s", async_tracker, thread_tracker)
            return wrapped(*args, **kwargs)

        # situation 3. but no request body send by the client, at this case, the tracker was not set into the request
        # in HTTPConnection._on_headers
        if not async_tracker:
            return trace_app_without_body(wrapped, instance, request, args,
                                          kwargs)

        # situation 3. client send the header & body content to server for requesting data.
        return wrapped(*args, **kwargs)

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 11
0
def wsgi_wrapper_inline(wrapped,
                        framework="Python",
                        version=None,
                        target=TARGET_WEB_APP):
    """ wrap the uwsgi application entrance
    :param wrapped: the method need to be wrapped
    :param framework: framework of current used web framework
    :param version: version of current used web framework
    :return:
    """
    console.info("wrap the wsgi entrance with framework(%s), version(%s)",
                 framework, version)

    def wrapper(wrapped, instance, args, kwargs):
        """More detail about the argument, read the wrapper doc
        """
        tracker = current_tracker()
        if tracker:
            return wrapped(*args, **kwargs)

        environ, start_response = parse_wsgi_protocol(target, *args, **kwargs)
        disable_agent = environ.get(AGENT_REQUEST_SWITCH, None)
        if disable_agent:
            console.debug(
                "Current trace is disabled with http request environment. %s",
                environ)
            return wrapped(*args, **kwargs)

        tracker = Tracer(proxy_instance(), environ, framework)
        tracker.start_work()

        # respect the wsgi protocol
        def _start_response(status, response_headers, *args):
            # deal the response header/data
            process_header(tracker, response_headers)
            tracker.deal_response(status, response_headers, *args)
            _write = start_response(status, response_headers, *args)

            return _write

        result = []
        try:
            tracker.set_tracker_name(callable_name(wrapped), priority=1)
            application = function_trace_wrapper(wrapped)
            with FunctionTracker(tracker,
                                 name='Application',
                                 group='Python.WSGI'):
                result = TingYunWSGIBrowserRumMiddleware(
                    tracker, application, _start_response, environ)()
                # result = application(environ, start_response)
        except:
            tracker.finish_work(*sys.exc_info())
            raise

        return WSGIApplicationResponse(tracker, result)

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 12
0
def mq_common_callback_wrapper(wrapped, instance, args, kwargs):
    """
    :return:
    """
    def parse_callback(callback, *_args, **_kwargs):
        """
        :return:
        """
        return callback, _args, _kwargs

    cb, _args, _kwargs = parse_callback(*args, **kwargs)
    if getattr(cb, '_self_is_wrapped', None):
        console.debug("Consumer was wrapped before.")
        return wrapped(cb, *_args, **_kwargs)

    wrapped_cb = FunctionWrapper(cb, _do_comon_callback_wrap)
    wrapped_cb._self_is_wrapped = True

    return wrapped(wrapped_cb, *_args, **_kwargs)
Exemplo n.º 13
0
def error_trace_wrapper(wrapped, ignore_errors=None):
    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        with ErrorTrace(tracker, ignore_errors):
            return wrapped(*args, **kwargs)

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 14
0
def mq_produce_trace_wrapper(wrapped):
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        vendor = 'RabbitMQ'
        name_type = 'Exchange'
        publish_headers = {}
        role = 'Produce'

        if not tracker:
            return wrapped(*args, **kwargs)

        def parse_server(instance, exchange, routing_key, body, properties=None, *_args, **_kwargs):
            """ 获取publish的一些必要信息,优先获取exchange作为metric名字
            :return:
            """
            global publish_headers
            host, port, byte, name = "Unknown", 0, 0, "Unknown"

            try:
                # blocking  和 其他异步生产者,
                connection = getattr(instance, 'connection', None) or getattr(instance, '_connection', None)
                impl = getattr(connection, '_impl', None) or connection
                host = impl.params.host
                port = impl.params.port

                publish_headers = getattr(properties, "headers", {}) or {}
                ty_headers, _external_id = process_cross_trace(None, msg_type='TingyunID')
                if ty_headers:
                    from pika.spec import BasicProperties

                    if not properties:
                        properties = BasicProperties(headers=ty_headers)
                    else:
                        if not getattr(properties, "headers", None):
                            setattr(properties, "headers", ty_headers)
                        elif isinstance(properties.headers, dict):
                            properties.headers.update(ty_headers)

            except Exception as err:
                console.info("Parse RabbitMQ host & port with error %s", err)
                _external_id = None

            _server = (host, port, sys.getsizeof(body), exchange or routing_key, _external_id)
            return _server, exchange, routing_key, body, properties, _args, _kwargs

        server, exchange, routing_key, body, properties, _args, _kwargs = parse_server(instance, *args, **kwargs)
        host, port, byte, name, external_id = server
        name_type = 'Queue' if not exchange else name_type

        with MQTrace(tracker, vendor, name_type, host, port, byte, name, publish_headers, role,
                     ('BlockingChannel', 'publish'), external_id):
            return wrapped(exchange, routing_key, body, properties, *_args, **_kwargs)

    return FunctionWrapper(wrapped, dynamic_wrapper)
Exemplo n.º 15
0
def redis_trace_wrapper(wrapped, command, server=None):
    """
    :return:
    """
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if instance is not None:
            _command = command(instance, *args, **kwargs)
        else:
            _command = command(*args, **kwargs)

        if callable(server):
            host, port, db = server(instance, *args, **kwargs)
        else:
            host, port, db = "Unknown", 0, 0

        with RedisTrace(tracker, host, port, db, _command):
            return wrapped(*args, **kwargs)

    def literal_wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if tracker is None:
            return wrapped(*args, **kwargs)

        if callable(server):
            host, port, db = server(instance, *args, **kwargs)
        else:
            host, port, db = "Unknown", 0, 0

        with RedisTrace(tracker, host, port, db, command):
            return wrapped(*args, **kwargs)

    if callable(command):
        return FunctionWrapper(wrapped, dynamic_wrapper)

    return FunctionWrapper(wrapped, literal_wrapper)
Exemplo n.º 16
0
def wrap_template_filter(wrapped, instance, args, kwargs):
    """
    :param wrapped:
    :param instance:
    :param args:
    :param kwargs:
    :return:
    """
    def parse_func_params(name, *args, **kwargs):
        return name, args, kwargs

    name, _args, _kwargs = parse_func_params(*args, **kwargs)
    return FunctionWrapper(wrapped(name, *_args, **_kwargs), _wrapper_deco())
Exemplo n.º 17
0
def wrap_func_with_request(wrapped, instance, args, kwargs):
    """
    :param wrapped:
    :param instance:
    :param args:
    :param kwargs:
    :return:
    """
    def parse_func_params(f, *args, **kwargs):
        return f, args, kwargs

    f, _args, _kwargs = parse_func_params(*args, **kwargs)
    return wrapped(FunctionWrapper(f, _wrapper_deco()), *_args, **_kwargs)
Exemplo n.º 18
0
def add_url_rule_wrapper(wrapped, instance, args, kwargs):
    """used to trace the views metric
    :param wrapped:
    :param instance:
    :return:
    """
    def parse_view_func(rule, endpoint=None, view_func=None, **options):
        return rule, endpoint, view_func, options

    rule, endpoint, view_func, options = parse_view_func(*args, **kwargs)

    return wrapped(rule, endpoint,
                   FunctionWrapper(view_func, _wrapper_deco(4)), **options)
Exemplo n.º 19
0
def wrap_register_error(wrapped, instance, args, kwargs):
    """
    :param module:
    :return:
    """
    def parse_func_params(key, code_or_exception, f, *args, **kwargs):
        return key, code_or_exception, f, args, kwargs

    key, code_or_exception, f, _args, _kwargs = parse_func_params(
        *args, **kwargs)

    return wrapped(key, code_or_exception, FunctionWrapper(f, _wrapper_deco()),
                   *_args, **_kwargs)
Exemplo n.º 20
0
    def trace_user_func(wrapped):
        """
        """
        def user_func_wrapper(wrapped, instance, args, kwargs):
            tracer = getattr(instance.request, "_self_tracer", None)
            if not tracer:
                # console.info("ignore trace func %s", callable_name(wrapped))
                return wrapped(*args, **kwargs)

            with FunctionTracker(tracer, callable_name(wrapped)):
                # console.info("---------------trace func %s", callable_name(wrapped))
                return wrapped(*args, **kwargs)

        return FunctionWrapper(wrapped, user_func_wrapper)
Exemplo n.º 21
0
def trace_fetch_impl(wrapped, instance, args, kwargs):
    """
    :return:
    """
    def parse_callback_func(request, callback, *args, **kwargs):
        """
        :return:
        """
        return request, callback, args, kwargs

    request, callback_func, _args, _kwargs = parse_callback_func(
        *args, **kwargs)

    return wrapped(request,
                   FunctionWrapper(callback_func, trace_http_fetch_callback),
                   *_args, **_kwargs)
Exemplo n.º 22
0
def middleware_wrapper(wrapped, wrapper_function):
    """
    :return:
    """
    def dynamic_wrapper(wrapped, instance, args, kwargs):
        """
        """
        result = wrapped(*args, **kwargs)

        if instance is not None:
            wrapper_function(instance, *args, **kwargs)
        else:
            wrapper_function(*args, **kwargs)
        return result

    return FunctionWrapper(wrapped, dynamic_wrapper)
Exemplo n.º 23
0
    def wrapper(wrapped):
        name = callable_name(wrapped)

        def wrapper(wrapped, instance, args, kwargs):
            tracker = current_tracker()
            if tracker is None:
                return wrapped(*args, **kwargs)

            before_name = "%s.%s" % (tracker.name, tracker.group)
            with FunctionTracker(tracker, name=name):
                try:
                    return wrapped(*args, **kwargs)
                finally:
                    after_name = "%s.%s" % (tracker.name, tracker.group)
                    if before_name == after_name and detect_name:
                        tracker.set_tracker_name(name, priority=2)

        return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 24
0
def trace_request_exception(wrapped):
    """
    :param wrapped:
    :return:
    """
    def wrapper(wrapped, instance, args, kwargs):
        def parse_args(e, *args, **kwargs):
            return e

        tracer = getattr(instance.request, "_self_tracer", None)
        if tracer:
            e = parse_args(*args, **kwargs)
            tracer.http_status = getattr(e, 'status_code', 500)
            tracer.record_exception(*sys.exc_info())

        return wrapped(*args, **kwargs)

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 25
0
def route_callback_wrapper(wrapped):
    """wrap the route callback for trace the `route` performance
    :return:
    """
    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()
        if not tracker:
            return wrapped(*args, **kwargs)

        tracker.set_tracker_name(callable_name(wrapped), priority=3)
        with FunctionTracker(tracker, callable_name(wrapped)):
            try:
                return wrapped(*args, **kwargs)
            except Exception as _:
                tracker.record_exception()
                raise

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 26
0
def connection_finish_request_wrapper(wrapped):
    """the wrapped function maybe called more than once.
    """
    def wrapper(wrapped, adapter, args, kwargs):
        """
        """
        # in tornado 4.x.x
        if hasattr(adapter, "connection"):
            request = adapter.request
        else:
            request = adapter._request

        tracer = getattr(request, "_self_tracer", None)

        if not tracer:
            # console.debug("tracer is not found maybe finished before.")
            return wrapped(*args, **kwargs)

        if request._self_request_finished:
            # console.debug("tracer for current request is finished")
            return wrapped(*args, **kwargs)

        tracer = finish_async_func_trace(request, "request-finish-in")
        if not tracer:
            # console.debug("resumed a none tracer....")
            return wrapped(*args, **kwargs)

        try:
            # console.info("execute connect finish finished....")
            ret = wrapped(*args, **kwargs)
        except Exception as _:
            stop_request_tracer(
                request,
                *(sys.exc_info() + ("connect-finished-with-exceptiono", )))
            raise
        else:
            # in tornado 4.x.x, the application.__call__ will not be called directly. but call the `execute` to call
            # the RequestHandler. so we should finish our tracker at there.
            if hasattr(adapter, "connection"):
                stop_request_tracer(request, segment='finish-app-call')

        return ret

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 27
0
def trace_urlresolvers_resolve_xxx(wrapped, priority):
    """
    :param wrapped:
    :param priority:
    :return:
    """
    name = callable_name(wrapped)

    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        with FunctionTracker(tracker, name=name):
            callback, param_dict = wrapped(*args, **kwargs)
            return wrap_view_handler(callback, priority=priority), param_dict

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 28
0
def trace_request_execute(wrapped):
    """
    """
    def wrapper(wrapped, instance, args, kwargs):
        """
        """
        request = instance.request
        tracer = getattr(request, "_self_tracer", None)
        if not tracer:
            return wrapped(*args, **kwargs)

        name = callable_name(getattr(instance,
                                     instance.request.method.lower()))
        tracer.set_tracker_name(name, priority=3)

        with FunctionTracker(tracer, callable_name(wrapped)):
            thread_tracer = current_tracker()
            if thread_tracer:
                console.info(
                    "Ignore user code metric trace for current request, this will maybe cause lack of some "
                    "metric data. if this continues, please report to us, thank u."
                )
                return wrapped(*args, **kwargs)

            # at here, we get the user code. we just put the tracer to the thread for non-framework plugin use.after
            # this, we drop it again. and ignore all of the errors occurred.
            try:
                tracer.save_tracker()
            except Exception as _:
                console.error(
                    "Errors, when the tracer put into the thread, this should not occurred, if this "
                    "continues, please report to us, thank u")
            ret = wrapped(*args, **kwargs)
            try:
                tracer.drop_tracker()
            except Exception as _:
                console.error(
                    "Errors, when the tracer dropped from the thread, this should not occurred, if this "
                    "continues, please report to us, thank u")

            return ret

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 29
0
def connect_on_request_body_wrapper(wrapped):
    """
    """
    def wrapper(wrapped, adapter, args, kwargs):
        """
        """
        # in tornado 4.x.x
        if hasattr(adapter, "connection"):
            request = adapter.request
        else:
            request = adapter._request

        tracer = finish_async_func_trace(request, group='request-body-in')
        if not tracer:
            # console.info("body do not get the tracer...")
            return wrapped(*args, **kwargs)

        try:
            # console.info("execute request body...")
            ret = wrapped(*args, **kwargs)
        except Exception as err:
            console.exception(
                "Tornado raise error in HTTPConnection on_request_body. %s",
                err)
            stop_request_tracer(
                request, *(sys.exc_info() + ("request-body-exception", )))
            raise
        else:
            if request._self_request_finished:
                return ret

            if not request.connection.stream.writing():
                stop_request_tracer(request, segment='stream-not-writing')
                return ret

            setup_func_for_async_trace(request,
                                       name="connection.body-to-finish")

        return ret

    return FunctionWrapper(wrapped, wrapper)
Exemplo n.º 30
0
def trace_django_urlresolvers(wrapped):
    """
    :param wrapped:
    :return:
    """
    name = callable_name(wrapped)

    def wrapper(wrapped, instance, args, kwargs):
        tracker = current_tracker()

        if tracker is None:
            return wrapped(*args, **kwargs)

        if hasattr(tracker, '_self_django_url_resolver_wrapped'):
            return wrapped(*args, **kwargs)

        # mark the top level(views maybe has inline local url resolver operate) url resolver. and use it as the
        tracker._self_django_url_resolver_wrapped = True

        def _wrapped(path):
            with FunctionTracker(tracker, name=name, label=path):
                result = wrapped(path)

                if isinstance(type(result), tuple):
                    callback, callback_args, callback_kwargs = result
                    result = (wrap_view_handler(callback, priority=4),
                              callback_args, callback_kwargs)
                else:
                    result.func = wrap_view_handler(result.func, priority=4)

                return result

        try:
            return _wrapped(*args, **kwargs)
        finally:
            del tracker._self_django_url_resolver_wrapped

    return FunctionWrapper(wrapped, wrapper)