summaryrefslogtreecommitdiffstats
path: root/src/Hooks/abrt_exception_handler.py.in
blob: 8ac7aa2328d9b485c653b63fadb4430b6a9ac322 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# -*- coding: utf-8 -*-
## Copyright (C) 2001-2005 Red Hat, Inc.
## Copyright (C) 2001-2005 Harald Hoyer <harald@redhat.com>
## Copyright (C) 2009 Jiri Moskovcak <jmoskovc@redhat.com>

## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

"""
Module for a userfriendly exception handling

Example code:

import sys

from exception import action, error, exitcode, installExceptionHandler

installExceptionHandler("test", "1.0", gui=0, debug=0)

def exception_function():
    action("Trying to divide by zero")

    try:
        local_var_1 = 1
        local_var_2 = 0
        # test exception raised to show the effect
        local_var_3 = local_var_1 / local_var_2
    except:
        error("Does not seem to work!? :-)")
        exitcode(15)
        raise

"""
import sys
import os
import syslog
# abrt lib for saving debugdumps
import ABRTUtils


__DUMPHASH = {}
# FIXME: do length limits on obj dumps.
def __dump_class(instance, fd, level=0):
    "dumps all classes"
    import types
    # protect from loops
    if not __DUMPHASH.has_key(instance):
        __DUMPHASH[instance] = True
    else:
        fd.write("Already dumped\n")
        return
    if (instance.__class__.__dict__.has_key("__str__") or
        instance.__class__.__dict__.has_key("__repr__")):
        fd.write("%s\n" % (instance,))
        return
    fd.write("%s instance, containing members:\n" %
             (instance.__class__.__name__))
    pad = ' ' * ((level) * 2)
    for key, value in instance.__dict__.items():
        if type(value) == types.ListType:
            fd.write("%s%s: [" % (pad, key))
            first = 1
            for item in value:
                if not first:
                    fd.write(", ")
                else:
                    first = 0
                if type(item) == types.InstanceType:
                    __dump_class(item, fd, level + 1)
                else:
                    fd.write("%s" % (item,))
            fd.write("]\n")
        elif type(value) == types.DictType:
            fd.write("%s%s: {" % (pad, key))
            first = 1
            for k, v in value.items():
                if not first:
                    fd.write(", ")
                else:
                    first = 0
                if type(k) == types.StringType:
                    fd.write("'%s': " % (k,))
                else:
                    fd.write("%s: " % (k,))
                if type(v) == types.InstanceType:
                    __dump_class(v, fd, level + 1)
                else:
                    fd.write("%s" % (v,))
            fd.write("}\n")
        elif type(value) == types.InstanceType:
            fd.write("%s%s: " % (pad, key))
            __dump_class(value, fd, level + 1)
        else:
            fd.write("%s%s: %s\n" % (pad, key, value))

def write_dump(pid, tb_uuid, tb):
    import time
    ttime = int(time.time())
    # localstatedir
    dir_name = "@DEBUG_DUMP_DIR@/pyhook-%s-%s" % (ttime, pid)
    dd = ABRTUtils.CDebugDump()
    try:
        #os.mkdir(dir_name)
        dd.Create(dir_name, os.getuid())
    except Exception, e:
        syslog.syslog("abrt: Cannot create dir %s %s" % (dir_name, e))
        return
    # save executable
    fexecutable = open("%s/executable" % dir_name, "w")
    if sys.argv[0]:
        fexecutable.write(os.path.abspath(sys.argv[0]))
    else:
        fexecutable.write("Exception raised from python shell")
    fexecutable.close()
    # save coredump
    coredump = open("%s/backtrace" % dir_name, "w")
    coredump.write(tb)
    coredump.close()
    # save uuid
    uuid = open("%s/uuid" % dir_name, "w")
    uuid.write(tb_uuid)
    uuid.close()
    # save cmdline
    cmdline = open("%s/cmdline" % dir_name, "w")
    cmdline.write(open("/proc/%s/cmdline" % pid).read().replace('\x00',' '))
    cmdline.close()
    # save uid
    uid = open("%s/uid" % dir_name, "w")
    uid.write(open("/proc/%s/loginuid" % pid).readlines()[0])
    uid.close()
    # save analyzer
    analyzer = open("%s/analyzer" % dir_name, "w")
    analyzer.write("Python")
    analyzer.close()
    dd.Close()

def __dump_exception(out, text, tracebk):
    'write a traceback to "out"'

    out.write(text)

    trace = tracebk
    while trace.tb_next:
        trace = trace.tb_next
    frame = trace.tb_frame
    out.write ("\nLocal variables in innermost frame:\n")
    try:
        for (key, value) in frame.f_locals.items():
            out.write ("%s: %s\n" % (key, value))
    except:
        pass


def __exception_window(title, text, component_name):
    pass

__ACTION_STR = ""
def action(what):
    """Describe what you want to do actually.
    what - string
    """
    global __ACTION_STR # pylint: disable-msg=W0603
    __ACTION_STR = what

__ERROR_STR = ""
def error(what):
    """Describe what went wrong with a userfriendly text.
    what - string
    """
    global __ERROR_STR # pylint: disable-msg=W0603
    __ERROR_STR = what

__EXITCODE = 10
def exitcode(num):
    """The exitcode, with which the exception handling routine should call
    sys.exit().
    num - int(exitcode)
    """
    global __EXITCODE # pylint: disable-msg=W0603
    __EXITCODE = int(num)

#
# handleMyException function
#
def handleMyException((etype, value, tb)):
    """
    The exception handling function.

    progname - the name of the application
    version  - the version of the application
    """

    # restore original exception handler
    sys.excepthook = sys.__excepthook__  # pylint: disable-msg=E1101
    # ignore uncaught ctrl-c
    if etype == KeyboardInterrupt:
        return sys.__excepthook__(etype, value, tb)

    import os.path
    from hashlib import md5
    import traceback

    syslog.syslog("abrt: Pyhook: Detected unhandled exception in %s " % sys.argv[0])
    elist = traceback.format_exception (etype, value, tb)
    tblast = traceback.extract_tb(tb, limit=None)
    if len(tblast):
        tblast = tblast[len(tblast)-1]
    extxt = traceback.format_exception_only(etype, value)
    text = ""
    text = text + "Summary: TB"
    if tblast and len(tblast) > 3:
        ll = []
        ll.extend(tblast[:3])
        ll[0] = os.path.basename(tblast[0])
        tblast = ll

    m = md5()
    ntext = ""
    for t in tblast:
        ntext += str(t) + ":"
        m.update(str(t))

    tb_uuid = str(m.hexdigest())[:8]
    text += tb_uuid + " " + ntext

    text += extxt[0]
    text += "\n"
    text += "".join(elist)

    trace = tb
    while trace.tb_next:
        trace = trace.tb_next
    frame = trace.tb_frame
    text += ("\nLocal variables in innermost frame:\n")
    try:
        for (key, val) in frame.f_locals.items():
            text += "%s: %s\n" % (key, val)
    except:
        pass

    # add coredump saving
    write_dump(os.getpid(), tb_uuid, text)
    return sys.__excepthook__(etype, value, tb)

def installExceptionHandler(debug = 1):
    """
    Install the exception handling function.

    progname - the name of the application
    version  - the version of the application
    debug    - show the full traceback (with "Save to file" in GUI)
    """
    sys.excepthook = lambda etype, value, tb: \
        handleMyException((etype, value, tb))

if __name__ == '__main__':
    def _exception_function():
        action("Trying to divide by zero")

        try:
            local_var_1 = 1
            local_var_2 = 0
            # test exception raised to show the effect
            local_var_3 = local_var_1 / local_var_2 # pylint: disable-msg=W0612
        except:
            error("Does not seem to work!? :-)")
            exitcode(15)
            raise

    def _usage():
        print """%s [-dgh] [--debug] [--gui] [--help]
    -d, --debug
        Show the whole backtrace

    -h, --help
        Display this message""" % (sys.argv[0])

    import getopt
    __debug = 1

    installExceptionHandler(__debug)

    __debug = 0

    class BadUsage(Exception):
        "exception for a bad command line usage"

    try:
        __opts, __args = getopt.getopt(sys.argv[1:], "dgh",
                                   [
                                    "debug",
                                    "help",
                                    "gui",
                                    ])

        for __opt, __val in __opts:
            if __opt == '-d' or __opt == '--debug':
                __debug = 1
                continue

            if __opt == '-g' or __opt == '--gui':
                __gui = 1
                continue

            if __opt == '-h' or __opt == '--help':
                _usage()
                sys.exit(0)

    except (getopt.error, BadUsage):
        _usage()
        sys.exit(1)

    installExceptionHandler(__debug)

    _exception_function()
    sys.exit(0)


__author__ = "Harald Hoyer <harald@redhat.com>"