Exemple #1
0
def noodlesapp(env, start_response):
    """

    :rtype : noodles.http.Response
    :param env:
    :param start_response:
    :return: :rtype: :raise:
    """
    # Get request object
    if get_config('ENCODE_SEMICOLON_IN_REQUEST') is True:
        env['QUERY_STRING'] = re.sub('[;]', '%3b', env['QUERY_STRING'])
    request = Request(env)

    if "HTTP_X_FORWARDED_FOR" in env:
        x_forwarded_for = env["HTTP_X_FORWARDED_FOR"].split(',')[:1]
        if x_forwarded_for:
            request.remote_addr = x_forwarded_for[0]
    #print("Try to handle url_path '%s'" % request.path)
    # Get callable object with routine method to handle request
    producer = dispatcher.get_callable(request)
    if not producer:
        # May be here an error,raise exception
        raise Exception('Can\'t find callable for this url path')

    # Callable function must return Response object
    try:
        response = middlewares.run_chain(producer, request)
        if not hasattr(response, 'is_noodles_response'):
            response = producer()
    # Capture traceback here and send it if debug mode
    except Exception as e:
        f = Formatter()
        if EXCEPTION_FLAVOR=='html':
            traceback = '<pre>%s\n\n%s</pre>' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           xml_escape(f.formatException(sys.exc_info())))
        else:
            traceback = '%s\n%s' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           f.formatException(sys.exc_info()))
        extra = {'request': request}
        log.error(format_exception(e, None), extra=extra)
        report_exception(e, extra=extra)

        if DEBUG:
            response = Error500(e, traceback)
        else:
            response = Error500()
    finally:
        middlewares.end_chain(lambda x: x, request)

    return response(env, start_response)
def noodlesapp(env, start_response):
    """

    :rtype : noodles.http.Response
    :param env:
    :param start_response:
    :return: :rtype: :raise:
    """
    # Get request object
    if get_config('ENCODE_SEMICOLON_IN_REQUEST') is True:
        env['QUERY_STRING'] = re.sub('[;]', '%3b', env['QUERY_STRING'])
    request = Request(env)

    if "HTTP_X_FORWARDED_FOR" in env:
        x_forwarded_for = env["HTTP_X_FORWARDED_FOR"].split(',')[:1]
        if x_forwarded_for:
            request.remote_addr = x_forwarded_for[0]
    #print("Try to handle url_path '%s'" % request.path)
    # Get callable object with routine method to handle request
    producer = dispatcher.get_callable(request)
    if not producer:
        # May be here an error,raise exception
        raise Exception('Can\'t find callable for this url path')

    # Callable function must return Response object
    try:
        response = middlewares.run_chain(producer, request)
        if not hasattr(response, 'is_noodles_response'):
            response = producer()
    # Capture traceback here and send it if debug mode
    except Exception as e:
        f = Formatter()
        if EXCEPTION_FLAVOR=='html':
            traceback = '<pre>%s\n\n%s</pre>' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           xml_escape(f.formatException(sys.exc_info())))
        else:
            traceback = '%s\n%s' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           f.formatException(sys.exc_info()))
        extra = {'request': request}
        log.error(format_exception(e, None), extra=extra)
        report_exception(e, extra=extra)

        if DEBUG:
            response = Error500(e, traceback)
        else:
            response = Error500()
    finally:
        middlewares.end_chain(lambda x: x, request)

    return response(env, start_response)
 def onerror(self, e):
     """Send here Exception and traceback by Error channel
     """
     f = Formatter()
     history = json.dumps(self.channel_history,
                          indent=2,
                          default=datahandler)
     data = (history, xml_escape(f.formatException(sys.exc_info())),)
     if EXCEPTION_FLAVOR == 'html':
         traceback = '<pre>%s\n\n%s</pre>' % data
     else:
         traceback = '%s\n%s' % data
     if DEBUG:
         err_message = {'channel': WS_CHANNELS['ERROR_CHID'],
                        'pkg': {'exception': repr(e), 'tb': traceback}}
     else:
         err_message = {'channel': WS_CHANNELS['ERROR_CHID'],
                        'pkg': {'exception': 'error 500',
                                'tb': 'an error occurred'}}
     log.error(format_exception(e, None), extra=self.channel_history)
     report_exception(e, extra=self.channel_history)
     if not self.ws.closed:
         try:
             self.ws.send(json.dumps(err_message, separators=(', ', ':')))
         except WebSocketError as e:
             if is_ws_error_abnormal(e):
                 log.error('WebSocket fault: %s' % e.message,
                           extra=self.channel_history)
Exemple #4
0
 def emit(self, record):
     if record.exc_info:
         # The log formatter will use the cached exc_text in place of the
         # exc_info Traceback object; since Traceback objects can't be
         # pickled, use this to pass over the formatted exception text
         # instead.
         fmt = Formatter()
         record.exc_info = fmt.formatException(record.exc_info)
     self.queue.put(record)
Exemple #5
0
 def emit(self, record):
     if record.exc_info:
         # The log formatter will use the cached exc_text in place of the
         # exc_info Traceback object; since Traceback objects can't be
         # pickled, use this to pass over the formatted exception text
         # instead.
         fmt = Formatter()
         record.exc_info = fmt.formatException(record.exc_info)
     self.queue.put(record)
def get_exc_info(record: logging.LogRecord,
                 formatter: logging.Formatter) -> typing.Union[str, None]:
    if record.exc_text:
        val = record.exc_text
    elif record.exc_info:
        val = formatter.formatException(record.exc_info)
        record.exc_text = val
    else:
        val = None  # type: ignore

    return val
Exemple #7
0
    def formatException(self, ei):
        ''' Format the stack of the exception only
            if the log level is INFO or below (eg DEBUG).

            Otherwise, format only the message of the exception
            hidding the stack and the exception class.

            In this case let the user know that if he/she wants
            to see the traceback he/she can see it enabling a
            more verbose log level.
            '''
        if self._cur_logger.isEnabledFor(INFO):
            return Formatter.formatException(self, ei)
        else:
            return '%s\n\n%s' % (str(
                ei[1]), "Rerun with -vvv to get a full stack trace.")
 def onerror(self, e):
     """Send here Exception and traceback by Error channel
     """
     f = Formatter()
     history = json.dumps(self.channel_history,
                          indent=2,
                          default=datahandler)
     data = (
         history,
         xml_escape(f.formatException(sys.exc_info())),
     )
     if EXCEPTION_FLAVOR == 'html':
         traceback = '<pre>%s\n\n%s</pre>' % data
     else:
         traceback = '%s\n%s' % data
     if DEBUG:
         err_message = {
             'channel': WS_CHANNELS['ERROR_CHID'],
             'pkg': {
                 'exception': repr(e),
                 'tb': traceback
             }
         }
     else:
         err_message = {
             'channel': WS_CHANNELS['ERROR_CHID'],
             'pkg': {
                 'exception': 'error 500',
                 'tb': 'an error occurred'
             }
         }
     log.error(format_exception(e, None), extra=self.channel_history)
     report_exception(e, extra=self.channel_history)
     if not self.ws.closed:
         try:
             self.ws.send(json.dumps(err_message, separators=(', ', ':')))
         except WebSocketError as e:
             if is_ws_error_abnormal(e):
                 log.error('WebSocket fault: %s' % e.message,
                           extra=self.channel_history)
    def __call__(self, env, start_response):
        websocket = env.get('wsgi.websocket')
        if not websocket:
            self.bad_request()
        self.ws = websocket
        # Endless event loop
        while 1:
            try:
                data = self.ws.receive()
                self.clear_test_data()
            except WebSocketError as e:
                if is_ws_error_abnormal(e):
                    log.error('WebSocket fault: %s' % e.message,
                              extra=self.channel_history)
                break
            except Exception:
                f = Formatter()
                traceback = f.formatException(sys.exc_info())
                log.error('Servlet fault: \n%s' % traceback,
                          extra=self.channel_history)
                break

            if data:
                jd = json.loads(data)
                if jd.get('pkg') \
                        and jd['pkg'].get('data') \
                        and isinstance(jd['pkg']['data'], dict)\
                        and jd['pkg']['data'].get('testData'):
                    self.write_test_data(jd['pkg']['data']['testData'])
                    del jd['pkg']['data']['testData']
                self.channel_history['messages'].append(jd)
                if hasattr(self.session, 'sess') and self.session.sess:
                    self.channel_history['session_id'] = self.session.sess.id
                    self.channel_history['user_id'] = self.session.sess.user_id
                if not jd.get('channel') and jd.get('pkg'):
                    act = jd['pkg'].get('action')
                    assert not act.startswith('_'), "security violation"
                    try:
                        handler = getattr(self, act)
                    except WebSocketError as e:
                        if is_ws_error_abnormal(e):
                            f = Formatter()
                            traceback = f.formatException(sys.exc_info())
                            log.error('Global channel action error: \n%s' %
                                      traceback,
                                      extra=self.channel_history)
                        break
                    assert handler.__name__ == "action_wrapper", \
                        "%s is not allowed to be executed externally." % act
                    handler(jd['pkg']['data'])
                    continue
                if self.check_permissions \
                        and not self.validate_send(jd.get('channel')):
                    jd['result'] = 403
                    if not self.ws.closed:
                        try:
                            self.ws.send(json.dumps(jd))
                        except WebSocketError as e:
                            if is_ws_error_abnormal(e):
                                log.error('WebSocket fault: %s' % e.message,
                                          extra=self.channel_history)
                    continue
                else:
                    self.run_callback('message', ApiSocketMessage(data))
            else:
                log.debug('Web Socket is disconnected')
                self.close_event.set()
            if self.close_event.is_set():
                break
        self.run_callback('close')
    def __call__(self, env, start_response):
        websocket = env.get('wsgi.websocket')
        if not websocket:
            self.bad_request()
        self.ws = websocket
        # Endless event loop
        while 1:
            try:
                data = self.ws.receive()
                self.clear_test_data()
            except WebSocketError as e:
                if is_ws_error_abnormal(e):
                    log.error('WebSocket fault: %s' % e.message,
                              extra=self.channel_history)
                break
            except Exception:
                f = Formatter()
                traceback = f.formatException(sys.exc_info())
                log.error('Servlet fault: \n%s' % traceback,
                          extra=self.channel_history)
                break

            if data:
                jd = json.loads(data)
                if jd.get('pkg') \
                        and jd['pkg'].get('data') \
                        and isinstance(jd['pkg']['data'], dict)\
                        and jd['pkg']['data'].get('testData'):
                    self.write_test_data(jd['pkg']['data']['testData'])
                    del jd['pkg']['data']['testData']
                self.channel_history['messages'].append(jd)
                if hasattr(self.session, 'sess') and self.session.sess:
                    self.channel_history['session_id'] = self.session.sess.id
                    self.channel_history['user_id'] = self.session.sess.user_id
                if not jd.get('channel') and jd.get('pkg'):
                    act = jd['pkg'].get('action')
                    assert not act.startswith('_'), "security violation"
                    try:
                        handler = getattr(self, act)
                    except WebSocketError as e:
                        if is_ws_error_abnormal(e):
                            f = Formatter()
                            traceback = f.formatException(sys.exc_info())
                            log.error('Global channel action error: \n%s'
                                      % traceback, extra=self.channel_history)
                        break
                    assert handler.__name__ == "action_wrapper", \
                        "%s is not allowed to be executed externally." % act
                    handler(jd['pkg']['data'])
                    continue
                if self.check_permissions \
                        and not self.validate_send(jd.get('channel')):
                    jd['result'] = 403
                    if not self.ws.closed:
                        try:
                            self.ws.send(json.dumps(jd))
                        except WebSocketError as e:
                            if is_ws_error_abnormal(e):
                                log.error('WebSocket fault: %s' % e.message,
                                          extra=self.channel_history)
                    continue
                else:
                    self.run_callback('message', ApiSocketMessage(data))
            else:
                log.debug('Web Socket is disconnected')
                self.close_event.set()
            if self.close_event.is_set():
                break
        self.run_callback('close')