Пример #1
0
    def send_error(self,
                   exc_info,
                   template='error.html',
                   content_type='text/html',
                   status=500,
                   env=None,
                   data={}):
        try:
            if template.endswith('.html') and env:
                from trac.web.chrome import Chrome, add_stylesheet
                add_stylesheet(self, 'common/css/code.css')
                try:
                    out = Chrome(env).render_template(self, template, data)
                except Exception:
                    # second chance rendering, in "safe" mode
                    try:
                        data['trac_error_rendering'] = True
                        out = Chrome(env).render_template(self, template, data)
                    except:
                        odata = dict({
                            'trac_error_rendering': True,
                            'title': data.title,
                            'type': data.__class__.__name__,
                            'message': data.message
                        })
                        out = Chrome(env).render_template(
                            self, template, odata)
            else:
                content_type = 'text/plain'
                try:
                    out = '%s\n\n%s: %s' % (data.get('title'),
                                            data.get('type'),
                                            data.get('message'))
                except:
                    out = '%s\n\n%s: %s \n\nTraceback Follows:\n\n%s' % (
                        data.title, data.__class__.__name__, data.message,
                        get_last_traceback())
        except Exception:  # failed to render
            out = get_last_traceback()
            content_type = 'text/plain'

        if isinstance(out, unicode):
            out = out.encode('utf-8')

        self.send_response(status)
        self._outheaders = []
        self.send_header('Cache-Control', 'must-revalidate')
        self.send_header('Expires', 'Fri, 01 Jan 1999 00:00:00 GMT')
        self.send_header('Content-Type', content_type + ';charset=utf-8')
        self.send_header('Content-Length', len(out))
        self._send_cookie_headers()

        self._write = self._start_response(self._status, self._outheaders,
                                           exc_info)

        if self.method != 'HEAD':
            self.write(out)
        raise RequestDone
Пример #2
0
    def send_error(self, exc_info, template='error.cs',
                   content_type='text/html', status=500):
        if self.hdf:
            if self.args.has_key('hdfdump'):
                # FIXME: the administrator should probably be able to disable HDF
                #        dumps
                content_type = 'text/plain'
                data = str(self.hdf)
            else:
                data = self.hdf.render(template)
        else:
            content_type = 'text/plain'
            data = get_last_traceback()

        self.send_response(status)
        self._outheaders = []
        self.send_header('Cache-control', 'must-revalidate')
        self.send_header('Expires', 'Fri, 01 Jan 1999 00:00:00 GMT')
        self.send_header('Content-Type', content_type + ';charset=utf-8')
        self.send_header('Content-Length', len(data))
        self._send_cookie_headers()

        self._write = self._start_response(self._status, self._outheaders,
                                           exc_info)

        if self.method != 'HEAD':
            self.write(data)
        raise RequestDone
Пример #3
0
    def send_error(self,
                   exc_info,
                   template='error.cs',
                   content_type='text/html',
                   status=500):
        if self.hdf:
            if self.args.has_key('hdfdump'):
                # FIXME: the administrator should probably be able to disable HDF
                #        dumps
                content_type = 'text/plain'
                data = str(self.hdf)
            else:
                data = self.hdf.render(template)
        else:
            content_type = 'text/plain'
            data = get_last_traceback()

        self.send_response(status)
        self._outheaders = []
        self.send_header('Cache-control', 'must-revalidate')
        self.send_header('Expires', 'Fri, 01 Jan 1999 00:00:00 GMT')
        self.send_header('Content-Type', content_type + ';charset=utf-8')
        self.send_header('Content-Length', len(data))
        self._send_cookie_headers()

        self._write = self._start_response(self._status, self._outheaders,
                                           exc_info)

        if self.method != 'HEAD':
            self.write(data)
        raise RequestDone
Пример #4
0
def exception_to_unicode(e, traceback=False):
    message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
    if traceback:
        from trac.util import get_last_traceback
        traceback_only = get_last_traceback().split('\n')[:-2]
        message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
    return message
Пример #5
0
    def send_error(self,
                   exc_info,
                   template='error.html',
                   content_type='text/html',
                   status=500,
                   env=None,
                   data={}):
        try:
            if template.endswith('.html'):
                if env:
                    from trac.web.chrome import Chrome, add_stylesheet
                    add_stylesheet(self, 'common/css/code.css')
                    metadata = {'content_type': 'text/html'}
                    try:
                        content = Chrome(env).render_template(
                            self, template, data, metadata)
                    except Exception:
                        # second chance rendering, in "safe" mode
                        data['trac_error_rendering'] = True
                        content = Chrome(env).render_template(
                            self, template, data, metadata)
                else:
                    content_type = 'text/plain'
                    content = '%s\n\n%s: %s' % (data.get('title'),
                                                data.get('type'),
                                                data.get('message'))
        except Exception:  # failed to render
            content = get_last_traceback()
            content_type = 'text/plain'

        if isinstance(content, unicode):
            content = content.encode('utf-8')

        self._outheaders = []
        self._send(content, content_type, status, exc_info)
Пример #6
0
def exception_to_unicode(e, traceback=False):
    message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
    if traceback:
        from trac.util import get_last_traceback
        traceback_only = get_last_traceback().split('\n')[:-2]
        message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
    return message
Пример #7
0
def _send_error(req, exc_info, template='error.html', content_type='text/html',
                status=500, env=None, data={}):
    if env:
        add_stylesheet(req, 'common/css/code.css')
        metadata = {'content_type': 'text/html', 'iterable': False}
        try:
            content = Chrome(env).render_template(req, template,
                                                  data, metadata)
        except Exception:
            # second chance rendering, in "safe" mode
            data['trac_error_rendering'] = True
            try:
                content = Chrome(env).render_template(req, template,
                                                      data, metadata)
            except Exception:
                content = get_last_traceback()
                content_type = 'text/plain'
    else:
        content_type = 'text/plain'
        content = '%s\n\n%s: %s' % (data.get('title'),
                                    data.get('type'),
                                    data.get('message'))

    if isinstance(content, unicode):
        content = content.encode('utf-8')

    try:
        req.send_error(exc_info, content, content_type, status)
    except RequestDone:
        pass
Пример #8
0
def exception_to_unicode(e, traceback=False):
    """Convert an `Exception` to an `unicode` object.

    In addition to `to_unicode`, this representation of the exception
    also contains the class name and optionally the traceback.
    """
    message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
    if traceback:
        from trac.util import get_last_traceback
        traceback_only = get_last_traceback().split('\n')[:-2]
        message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
    return message
Пример #9
0
def exception_to_unicode(e, traceback=False):
    """Convert an `Exception` to an `unicode` object.

    In addition to `to_unicode`, this representation of the exception
    also contains the class name and optionally the traceback.
    """
    message = '%s: %s' % (e.__class__.__name__, to_unicode(e))
    if traceback:
        from trac.util import get_last_traceback
        traceback_only = get_last_traceback().split('\n')[:-2]
        message = '\n%s\n%s' % (to_unicode('\n'.join(traceback_only)), message)
    return message
Пример #10
0
    def send_error(self,
                   exc_info,
                   template='error.html',
                   content_type='text/html',
                   status=500,
                   env=None,
                   data={}):
        """Render error page.

        The rendered content can also be passed to the method, when the
        method is invoked as:
        `send_error(exc_info, content, content_type='text/html', status=500)`

        :since 1.3.3: the method that renders an error page is deprecated
            in favor of the method that sends rendered content. The method
            that renders an error page will be removed in 1.5.1.
        """
        try:
            if isinstance(template, basestring) and template.endswith('.html'):
                if env:
                    from trac.web.chrome import Chrome, add_stylesheet
                    add_stylesheet(self, 'common/css/code.css')
                    metadata = {'content_type': 'text/html'}
                    try:
                        content = Chrome(env).render_template(
                            self, template, data, metadata)
                    except Exception:
                        # second chance rendering, in "safe" mode
                        data['trac_error_rendering'] = True
                        content = Chrome(env).render_template(
                            self, template, data, metadata)
                else:
                    content_type = 'text/plain'
                    content = '%s\n\n%s: %s' % (data.get('title'),
                                                data.get('type'),
                                                data.get('message'))
            else:
                # send_error(self, exc_info, content, content_type='text/html',
                #            status=500)
                content = template
        except Exception:  # failed to render
            content = get_last_traceback()
            content_type = 'text/plain'

        if isinstance(content, unicode):
            content = content.encode('utf-8')

        self._outheaders = []
        self._send(content, content_type, status, exc_info)
Пример #11
0
    def send_error(self, exc_info, template='error.html',
                   content_type='text/html', status=500, env=None, data={}):
        try:
            if template.endswith('.cs') and self.hdf: # FIXME: remove this
                if self.args.has_key('hdfdump'):
                    self.perm.require('TRAC_ADMIN')
                    content_type = 'text/plain'
                    data = str(self.hdf)
                else:
                    data = self.hdf.render(template)

            if template.endswith('.html'):
                if env:
                    from trac.web.chrome import Chrome
                    try:
                        data = Chrome(env).render_template(self, template,
                                                           data, 'text/html')
                    except Exception:
                        # second chance rendering, in "safe" mode
                        data['trac_error_rendering'] = True
                        data = Chrome(env).render_template(self, template,
                                                           data, 'text/html')
                else:
                    content_type = 'text/plain'
                    data = '%s\n\n%s: %s' % (data.get('title'),
                                             data.get('type'),
                                             data.get('message'))
        except: # failed to render
            data = get_last_traceback()
            content_type = 'text/plain'

        if isinstance(data, unicode):
            data = data.encode('utf-8')

        self.send_response(status)
        self._outheaders = []
        self.send_header('Cache-Control', 'must-revalidate')
        self.send_header('Expires', 'Fri, 01 Jan 1999 00:00:00 GMT')
        self.send_header('Content-Type', content_type + ';charset=utf-8')
        self.send_header('Content-Length', len(data))
        self._send_cookie_headers()

        self._write = self._start_response(self._status, self._outheaders,
                                           exc_info)

        if self.method != 'HEAD':
            self.write(data)
        raise RequestDone
Пример #12
0
def send_internal_error(env, req, exc_info):
    if env:
        env.log.error("Internal Server Error: %s",
                      exception_to_unicode(exc_info[1], traceback=True))
    message = exception_to_unicode(exc_info[1])
    traceback = get_last_traceback()

    frames, plugins, faulty_plugins = [], [], []
    th = 'http://trac-hacks.org'
    has_admin = False
    try:
        has_admin = 'TRAC_ADMIN' in req.perm
    except Exception:
        pass

    tracker = default_tracker
    tracker_args = {}
    if has_admin and not isinstance(exc_info[1], MemoryError):
        # Collect frame and plugin information
        frames = get_frame_info(exc_info[2])
        if env:
            plugins = [p for p in get_plugin_info(env)
                       if any(c['enabled']
                              for m in p['modules'].itervalues()
                              for c in m['components'].itervalues())]
            match_plugins_to_frames(plugins, frames)

            # Identify the tracker where the bug should be reported
            faulty_plugins = [p for p in plugins if 'frame_idx' in p]
            faulty_plugins.sort(key=lambda p: p['frame_idx'])
            if faulty_plugins:
                info = faulty_plugins[0]['info']
                if 'trac' in info:
                    tracker = info['trac']
                elif info.get('home_page', '').startswith(th):
                    tracker = th
                    plugin_name = info.get('home_page', '').rstrip('/') \
                                                           .split('/')[-1]
                    tracker_args = {'component': plugin_name}

    def get_description(_):
        if env and has_admin:
            sys_info = "".join("|| '''`%s`''' || `%s` ||\n"
                               % (k, v.replace('\n', '` [[br]] `'))
                               for k, v in env.get_systeminfo())
            sys_info += "|| '''`jQuery`''' || `#JQUERY#` ||\n" \
                        "|| '''`jQuery UI`''' || `#JQUERYUI#` ||\n" \
                        "|| '''`jQuery Timepicker`''' || `#JQUERYTP#` ||\n"
            enabled_plugins = "".join("|| '''`%s`''' || `%s` ||\n"
                                      % (p['name'], p['version'] or _('N/A'))
                                      for p in plugins)
        else:
            sys_info = _("''System information not available''\n")
            enabled_plugins = _("''Plugin information not available''\n")
        return _("""\
==== How to Reproduce ====

While doing a %(method)s operation on `%(path_info)s`, Trac issued an internal error.

''(please provide additional details here)''

Request parameters:
{{{
%(req_args)s
}}}

User agent: `#USER_AGENT#`

==== System Information ====
%(sys_info)s
==== Enabled Plugins ====
%(enabled_plugins)s
==== Python Traceback ====
{{{
%(traceback)s}}}""",
            method=req.method, path_info=req.path_info,
            req_args=pformat(req.args), sys_info=sys_info,
            enabled_plugins=enabled_plugins, traceback=to_unicode(traceback))

    # Generate the description once in English, once in the current locale
    description_en = get_description(lambda s, **kw: safefmt(s, kw))
    try:
        description = get_description(_)
    except Exception:
        description = description_en

    data = {'title': 'Internal Error',
            'type': 'internal', 'message': message,
            'traceback': traceback, 'frames': frames,
            'shorten_line': shorten_line, 'repr': safe_repr,
            'plugins': plugins, 'faulty_plugins': faulty_plugins,
            'tracker': tracker, 'tracker_args': tracker_args,
            'description': description, 'description_en': description_en}

    Chrome(env).add_jquery_ui(req)
    try:
        req.send_error(exc_info, status=500, env=env, data=data)
    except RequestDone:
        pass
Пример #13
0
                  '<a href="%(href)s">do so</a> now.',
                  href=req.href.login())))
        try:
            req.send_error(sys.exc_info(), status=e.code, env=env, data=data)
        except RequestDone:
            pass

    except Exception, e:
        if env:
            env.log.error("Internal Server Error: %s", 
                          exception_to_unicode(e, traceback=True))

        exc_info = sys.exc_info()
        try:
            message = "%s: %s" % (e.__class__.__name__, to_unicode(e))
            traceback = get_last_traceback()

            frames = []
            has_admin = False
            try:
                has_admin = 'TRAC_ADMIN' in req.perm
            except Exception, e:
                pass
            if has_admin and not isinstance(e, MemoryError):
                tb = exc_info[2]
                while tb:
                    tb_hide = tb.tb_frame.f_locals.get('__traceback_hide__')
                    if tb_hide in ('before', 'before_and_this'):
                        del frames[:]
                        tb_hide = tb_hide[6:]
                    if not tb_hide:
Пример #14
0
                'message': e.message
            }
        try:
            req.send_error(sys.exc_info(), status=e.code)
        except RequestDone:
            return []

    except Exception, e:
        env.log.exception(e)

        if req.hdf:
            req.hdf['title'] = to_unicode(e) or u'Erreur'
            req.hdf['error'] = {
                'title': to_unicode(e) or u'Erreur',
                'type': 'internal',
                'traceback': get_last_traceback()
            }
        try:
            req.send_error(sys.exc_info(), status=500)
        except RequestDone:
            return []

def send_project_index(environ, start_response, parent_dir=None,
                       env_paths=None):
    from trac.config import default_dir

    req = Request(environ, start_response)

    loadpaths = [default_dir('templates')]
    if req.environ.get('trac.env_index_template'):
        tmpl_path, template = os.path.split(req.environ['trac.env_index_template'])
Пример #15
0
                'message': e.message
            }
        try:
            req.send_error(sys.exc_info(), status=e.code)
        except RequestDone:
            return []

    except Exception, e:
        env.log.exception(e)

        if req.hdf:
            req.hdf['title'] = to_unicode(e) or 'Error'
            req.hdf['error'] = {
                'title': to_unicode(e) or 'Error',
                'type': 'internal',
                'traceback': get_last_traceback()
            }
        try:
            req.send_error(sys.exc_info(), status=500)
        except RequestDone:
            return []


def send_project_index(environ,
                       start_response,
                       parent_dir=None,
                       env_paths=None):
    from trac.config import default_dir

    req = Request(environ, start_response)
Пример #16
0
def send_internal_error(env, req, exc_info):
    if env:
        env.log.error("Internal Server Error: %r, referrer %r%s", req,
                      req.environ.get('HTTP_REFERER'),
                      exception_to_unicode(exc_info[1], traceback=True))
    message = exception_to_unicode(exc_info[1])
    traceback = get_last_traceback()

    frames, plugins, faulty_plugins, interface_custom = [], [], [], []
    th = 'http://trac-hacks.org'
    has_admin = False
    try:
        has_admin = 'TRAC_ADMIN' in req.perm
    except Exception:
        pass

    tracker = default_tracker
    tracker_args = {}
    if has_admin and not isinstance(exc_info[1], MemoryError):
        # Collect frame and plugin information
        frames = get_frame_info(exc_info[2])
        if env:
            plugins = [
                p for p in get_plugin_info(env)
                if any(c['enabled'] for m in p['modules'].itervalues()
                       for c in m['components'].itervalues())
            ]
            match_plugins_to_frames(plugins, frames)

            # Identify the tracker where the bug should be reported
            faulty_plugins = [p for p in plugins if 'frame_idx' in p]
            faulty_plugins.sort(key=lambda p: p['frame_idx'])
            if faulty_plugins:
                info = faulty_plugins[0]['info']
                if 'trac' in info:
                    tracker = info['trac']
                elif info.get('home_page', '').startswith(th):
                    tracker = th
                    plugin_name = info.get('home_page', '').rstrip('/') \
                                                           .split('/')[-1]
                    tracker_args = {'component': plugin_name}
        interface_custom = Chrome(env).get_interface_customization_files()

    def get_description(_):
        if env and has_admin:
            sys_info = "".join("|| '''`%s`''' || `%s` ||\n" %
                               (k, v.replace('\n', '` [[br]] `'))
                               for k, v in env.get_systeminfo())
            sys_info += "|| '''`jQuery`''' || `#JQUERY#` ||\n" \
                        "|| '''`jQuery UI`''' || `#JQUERYUI#` ||\n" \
                        "|| '''`jQuery Timepicker`''' || `#JQUERYTP#` ||\n"
            enabled_plugins = "".join("|| '''`%s`''' || `%s` ||\n" %
                                      (p['name'], p['version'] or _('N/A'))
                                      for p in plugins)
            files = Chrome(env).get_interface_customization_files().items()
            interface_files = "".join("|| **%s** || %s ||\n" %
                                      (k, ", ".join("`%s`" % f for f in v))
                                      for k, v in sorted(files))
        else:
            sys_info = _("''System information not available''\n")
            enabled_plugins = _("''Plugin information not available''\n")
            interface_files = _("''Interface customization information not "
                                "available''\n")
        return _("""\
==== How to Reproduce ====

While doing a %(method)s operation on `%(path_info)s`, Trac issued an internal error.

''(please provide additional details here)''

Request parameters:
{{{
%(req_args)s
}}}

User agent: `#USER_AGENT#`

==== System Information ====
%(sys_info)s
==== Enabled Plugins ====
%(enabled_plugins)s
==== Interface Customization ====
%(interface_customization)s
==== Python Traceback ====
{{{
%(traceback)s}}}""",
                 method=req.method,
                 path_info=req.path_info,
                 req_args=pformat(req.args),
                 sys_info=sys_info,
                 enabled_plugins=enabled_plugins,
                 interface_customization=interface_files,
                 traceback=to_unicode(traceback))

    # Generate the description once in English, once in the current locale
    description_en = get_description(lambda s, **kw: safefmt(s, kw))
    try:
        description = get_description(_)
    except Exception:
        description = description_en

    data = {
        'title': 'Internal Error',
        'type': 'internal',
        'message': message,
        'traceback': traceback,
        'frames': frames,
        'shorten_line': shorten_line,
        'repr': safe_repr,
        'plugins': plugins,
        'faulty_plugins': faulty_plugins,
        'interface': interface_custom,
        'tracker': tracker,
        'tracker_args': tracker_args,
        'description': description,
        'description_en': description_en
    }

    Chrome(env).add_jquery_ui(req)
    try:
        req.send_error(exc_info, status=500, env=env, data=data)
    except RequestDone:
        pass
Пример #17
0
                        '<a href="%(href)s">do so</a> now.',
                        href=req.href.login())))
        try:
            req.send_error(sys.exc_info(), status=e.code, env=env, data=data)
        except RequestDone:
            pass

    except Exception, e:
        if env:
            env.log.error("Internal Server Error: %s",
                          exception_to_unicode(e, traceback=True))

        exc_info = sys.exc_info()
        try:
            message = "%s: %s" % (e.__class__.__name__, to_unicode(e))
            traceback = get_last_traceback()

            frames = []
            has_admin = False
            try:
                has_admin = 'TRAC_ADMIN' in req.perm
            except Exception, e:
                pass
            if has_admin and not isinstance(e, MemoryError):
                tb = exc_info[2]
                while tb:
                    tb_hide = tb.tb_frame.f_locals.get('__traceback_hide__')
                    if tb_hide in ('before', 'before_and_this'):
                        del frames[:]
                        tb_hide = tb_hide[6:]
                    if not tb_hide: