/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/crash.py

  • Committer: Martin Pool
  • Date: 2010-01-31 16:32:34 UTC
  • mto: (4999.3.1 apport)
  • mto: This revision was merged to the branch mainline in revision 5002.
  • Revision ID: mbp@sourcefrog.net-20100131163234-k62100thmvkfjxad
Add sample apport integration glue

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009, 2010 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Handling and reporting crashes.
 
19
"""
 
20
 
 
21
# for interactive testing, try the 'bzr assert-fail' command 
 
22
# or see http://code.launchpad.net/~mbp/bzr/bzr-fail
 
23
#
 
24
# to test with apport it's useful to set
 
25
# export APPORT_IGNORE_OBSOLETE_PACKAGES=1
 
26
 
 
27
import os
 
28
import platform
 
29
import pprint
 
30
import sys
 
31
import time
 
32
from StringIO import StringIO
 
33
 
 
34
import bzrlib
 
35
from bzrlib import (
 
36
    config,
 
37
    debug,
 
38
    osutils,
 
39
    plugin,
 
40
    trace,
 
41
    )
 
42
 
 
43
 
 
44
def report_bug(exc_info, stderr):
 
45
    if 'no_apport' not in debug.debug_flags:
 
46
        try:
 
47
            report_bug_to_apport(exc_info, stderr)
 
48
            return
 
49
        except ImportError, e:
 
50
            trace.mutter("couldn't find apport bug-reporting library: %s" % e)
 
51
            pass
 
52
        except Exception, e:
 
53
            # this should only happen if apport is installed but it didn't
 
54
            # work, eg because of an io error writing the crash file
 
55
            sys.stderr.write("bzr: failed to report crash using apport:\n "
 
56
                "    %r\n" % e)
 
57
            pass
 
58
    report_bug_legacy(exc_info, stderr)
 
59
 
 
60
 
 
61
def report_bug_legacy(exc_info, err_file):
 
62
    """Report a bug by just printing a message to the user."""
 
63
    trace.print_exception(exc_info, err_file)
 
64
    err_file.write('\n')
 
65
    err_file.write('bzr %s on python %s (%s)\n' % \
 
66
                       (bzrlib.__version__,
 
67
                        bzrlib._format_version_tuple(sys.version_info),
 
68
                        platform.platform(aliased=1)))
 
69
    err_file.write('arguments: %r\n' % sys.argv)
 
70
    err_file.write(
 
71
        'encoding: %r, fsenc: %r, lang: %r\n' % (
 
72
            osutils.get_user_encoding(), sys.getfilesystemencoding(),
 
73
            os.environ.get('LANG')))
 
74
    err_file.write("plugins:\n")
 
75
    err_file.write(_format_plugin_list())
 
76
    err_file.write(
 
77
        "\n\n"
 
78
        "*** Bazaar has encountered an internal error.  This probably indicates a\n"
 
79
        "    bug in Bazaar.  You can help us fix it by filing a bug report at\n"
 
80
        "        https://bugs.launchpad.net/bzr/+filebug\n"
 
81
        "    including this traceback and a description of the problem.\n"
 
82
        )
 
83
 
 
84
 
 
85
def report_bug_to_apport(exc_info, stderr):
 
86
    """Report a bug to apport for optional automatic filing.
 
87
    """
 
88
    # this function is based on apport_package_hook.py, but omitting some of the
 
89
    # Ubuntu-specific policy about what to report and when
 
90
 
 
91
    # if the import fails, the exception will be caught at a higher level and
 
92
    # we'll report the error by other means
 
93
    import apport
 
94
 
 
95
    crash_filename = _write_apport_report_to_file(exc_info)
 
96
 
 
97
    trace.print_exception(exc_info, stderr)
 
98
    if crash_filename is None:
 
99
        stderr.write("\n"
 
100
            "apport is set to ignore crashes in this version of bzr.\n"
 
101
            )
 
102
    else:
 
103
        stderr.write("\n"
 
104
            "You can report this problem to Bazaar's developers by running\n"
 
105
            "    apport-bug %s\n"
 
106
            "if a bug-reporting window does not automatically appear.\n"
 
107
            % (crash_filename))
 
108
        # XXX: on Windows, Mac, and other platforms where we might have the
 
109
        # apport libraries but not have an apport always running, we could
 
110
        # synchronously file now
 
111
 
 
112
 
 
113
def _write_apport_report_to_file(exc_info):
 
114
    import traceback
 
115
    from apport.report import Report
 
116
 
 
117
    exc_type, exc_object, exc_tb = exc_info
 
118
 
 
119
    pr = Report()
 
120
    # add_proc_info gets the executable and interpreter path, which is needed,
 
121
    # plus some less useful stuff like the memory map
 
122
    pr.add_proc_info()
 
123
    pr.add_user_info()
 
124
 
 
125
    # Package and SourcePackage are needed so that apport will report about even
 
126
    # non-packaged versions of bzr; also this reports on their packaged
 
127
    # dependencies which is useful.
 
128
    pr['SourcePackage'] = 'bzr'
 
129
    pr['Package'] = 'bzr'
 
130
 
 
131
    pr['CommandLine'] = pprint.pformat(sys.argv)
 
132
    pr['BzrVersion'] = bzrlib.__version__
 
133
    pr['PythonVersion'] = bzrlib._format_version_tuple(sys.version_info)
 
134
    pr['Platform'] = platform.platform(aliased=1)
 
135
    pr['UserEncoding'] = osutils.get_user_encoding()
 
136
    pr['FileSystemEncoding'] = sys.getfilesystemencoding()
 
137
    pr['Locale'] = os.environ.get('LANG')
 
138
    pr['BzrPlugins'] = _format_plugin_list()
 
139
    pr['PythonLoadedModules'] = _format_module_list()
 
140
    pr['BzrDebugFlags'] = pprint.pformat(debug.debug_flags)
 
141
 
 
142
    tb_file = StringIO()
 
143
    traceback.print_exception(exc_type, exc_object, exc_tb, file=tb_file)
 
144
    pr['Traceback'] = tb_file.getvalue()
 
145
 
 
146
    _attach_log_tail(pr)
 
147
 
 
148
    # We want to use the 'bzr' crashdb so that it gets sent directly upstream,
 
149
    # which is a reasonable default for most internal errors.  However, if we
 
150
    # set it here then apport will crash later if it doesn't know about that
 
151
    # crashdb.  Instead, we rely on the bzr package installing both a
 
152
    # source hook telling crashes to go to this crashdb, and a crashdb
 
153
    # configuration describing it.
 
154
 
 
155
    # these may contain some sensitive info (smtp_passwords)
 
156
    # TODO: strip that out and attach the rest
 
157
    #
 
158
    #attach_file_if_exists(report,
 
159
    #   os.path.join(dot_bzr, 'bazaar.conf', 'BzrConfig')
 
160
    #attach_file_if_exists(report,
 
161
    #   os.path.join(dot_bzr, 'locations.conf', 'BzrLocations')
 
162
    
 
163
    # strip username, hostname, etc
 
164
    pr.anonymize()
 
165
 
 
166
    if pr.check_ignored():
 
167
        # eg configured off in ~/.apport-ignore.xml
 
168
        return None
 
169
    else:
 
170
        crash_file = _open_crash_file()
 
171
        pr.write(crash_file)
 
172
        crash_file.close()
 
173
        return crash_file.name
 
174
 
 
175
 
 
176
def _attach_log_tail(pr):
 
177
    try:
 
178
        bzr_log = open(trace._get_bzr_log_filename(), 'rt')
 
179
        lines = bzr_log.readlines()
 
180
        pr['BzrLogTail'] = ''.join(lines[-40:])
 
181
    finally:
 
182
        bzr_log.close()
 
183
 
 
184
 
 
185
def _open_crash_file():
 
186
    crash_dir = config.crash_dir()
 
187
    if not osutils.isdir(crash_dir):
 
188
        # on unix this should be /var/crash and should already exist; on
 
189
        # Windows or if it's manually configured it might need to be created,
 
190
        # and then it should be private
 
191
        os.makedirs(crash_dir, mode=0600)
 
192
    date_string = time.strftime('%Y-%m-%dT%H:%M', time.gmtime())
 
193
    filename = 'bzr.%d.%s.crash' % (
 
194
        os.getuid(),
 
195
        date_string)
 
196
    return open(osutils.pathjoin(crash_dir, filename), 'wt')
 
197
 
 
198
 
 
199
def _format_plugin_list():
 
200
    plugin_lines = []
 
201
    for name, a_plugin in sorted(plugin.plugins().items()):
 
202
        plugin_lines.append("  %-20s %s [%s]" %
 
203
            (name, a_plugin.path(), a_plugin.__version__))
 
204
    return '\n'.join(plugin_lines)
 
205
 
 
206
 
 
207
def _format_module_list():
 
208
    return pprint.pformat(sys.modules)