Source

hotdebug / debugger.py

Full commit
jayven 1c87e5f 


jayven 717f8d6 
jayven d369510 
jayven e726dd0 
jayven 77ea0c7 
jayven 717f8d6 
jayven 546f016 
jayven d2b3ab4 

jayven 44b7919 
jayven 635c8f2 
jayven 1c87e5f 
jayven 635c8f2 



jayven d2b3ab4 
jayven 1c87e5f 


jayven d369510 
jayven 1c87e5f 


jayven d369510 

jayven 1c87e5f 
jayven d369510 



























jayven 1c87e5f 


jayven d369510 




jayven 1c87e5f 
jayven 635c8f2 

jayven 1c87e5f 












jayven e726dd0 
jayven ae3e056 
jayven d2b3ab4 











jayven ae3e056 

jayven d2b3ab4 
jayven f2f81fd 
jayven 49c40f2 

jayven d2b3ab4 



jayven bc44a1a 
jayven 5236b15 
jayven e726dd0 
jayven d2b3ab4 

jayven e726dd0 
jayven 49c40f2 
jayven e726dd0 
jayven d2b3ab4 
jayven 49c40f2 
jayven e726dd0 



jayven 44b7919 
jayven 72f6a11 
jayven 44b7919 

jayven 72f6a11 

jayven 1b787fa 




jayven 44b7919 
jayven d2b3ab4 
jayven 546f016 
jayven e726dd0 
jayven bd85dce 
jayven e726dd0 

jayven 546f016 

jayven e726dd0 
jayven 546f016 
jayven 44b7919 
jayven 546f016 
jayven 658f6a1 
jayven ae3e056 

jayven d2b3ab4 

jayven 49c40f2 
jayven ae3e056 










jayven 1c87e5f 

jayven f2f81fd 
jayven 1c87e5f 

jayven 49d6e89 


jayven 49c40f2 

jayven d2b3ab4 
jayven ae3e056 
jayven 49c40f2 



jayven 49d6e89 
jayven 49c40f2 
jayven d2b3ab4 








jayven 49c40f2 
jayven e726dd0 
jayven 49d6e89 
jayven e726dd0 




jayven 49c40f2 




jayven d2b3ab4 


jayven 15904e2 
jayven 49c40f2 

jayven d2b3ab4 
jayven bd46d96 
jayven 418071c 
jayven d2b3ab4 






















jayven 635c8f2 
jayven d2b3ab4 
jayven 635c8f2 
jayven d2b3ab4 
jayven 2e22b03 
jayven d2b3ab4 
jayven 635c8f2 

























jayven 717f8d6 
























jayven 77ea0c7 
jayven 717f8d6 

































jayven 77ea0c7 



jayven d2b3ab4 
jayven e726dd0 
jayven 1c87e5f 
jayven 49c40f2 

jayven 1c87e5f 


jayven 418071c 
jayven e726dd0 
jayven bd85dce 






jayven e726dd0 
jayven d2b3ab4 



jayven 635c8f2 






jayven 1c87e5f 


jayven ae3e056 
jayven 49c40f2 

jayven d2b3ab4 

jayven 635c8f2 






jayven 1c87e5f 


jayven e726dd0 
jayven 49d6e89 
jayven e726dd0 
jayven 49c40f2 






























jayven ae3e056 
jayven 49c40f2 





jayven e726dd0 
jayven bd85dce 








jayven e726dd0 
jayven 546f016 
jayven e726dd0 
jayven 546f016 


jayven e726dd0 
jayven 692ec59 
jayven e726dd0 
jayven 692ec59 

jayven bd85dce 
jayven ad10471 
jayven bd85dce 

jayven e726dd0 






jayven eeea826 
jayven 3af78ad 
jayven eeea826 









jayven e726dd0 




jayven eeea826 



jayven e726dd0 


jayven 717f8d6 




















jayven 77ea0c7 
jayven 717f8d6 

















  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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# -*- coding: utf-8 -*-
# vim: set ai et si ts=4 sts=4 sw=4:

import sys, json
import pooler
import linecache
import base64
from datetime import datetime
from pprint import pformat
from osv import osv, fields

import codebase
import hook
from bgconsole import BGConsole
try:
    import pstats
except ImportError:
    pstats = None


help_text = """
Usage:

    Enter python src in Cmd then press 'Save' (or Ctrl+S) to send
    it to the console. Both single line and multi-lines are supported.
    But note that since Openerp will strip the head/tail whitespaces(space,
    tab,newline) in text field, you need some tricks for input, 
    for example:

    ----------------------------------------------

    input:
        def f():
    output:
        >>> def f():
        ...

    ----------------------------------------------

    input:
        #
          pass

        #
    output:
        >>> def f():
        ... #
        ...   pass
        ...   
        >>> #

    ----------------------------------------------

    The reason for the two '#' in the second input is to prevent
    openerp client from striping the indent spaces before 'pass' and the
    newline after 'pass'
    

Python environ:
    The console is a code.InteractiveConsole instance.
    locals:
        uid: the uid that open the console
        dbname: the name of db currently working on
        cr: the cursor
        pool: the object pool

For complete usage, goto: https://bitbucket.org/jayven/hotdebug

"""

def norm_select(select):
    """
    basicly from openerp-server/osv/orm.py
    """
    if isinstance(select, (int, long)):
        return [select,]
    elif isinstance(select, list):
        return select
    return []


class DebugConsole(osv.osv_memory):

    @property
    def tb_obj(self):
        return self.pool.get('hotdebug.tb')

    @property
    def tb_locals_obj(self):
        return self.pool.get('hotdebug.tb.locals')

    @property
    def bgconsole_obj(self):
        return self.pool.get('hotdebug.console.bgconsole')

    def _get_console(self, cr, uid, id, context):
        bgconsole_id = self.browse(cr, uid, id, context=context).bgconsole.id
        return self.bgconsole_obj._get_console(cr, uid, bgconsole_id, context)
    
    def _clear_exc(self, cr, uid, id, context):
        rec = self.browse(cr, uid, id, context=context)
        self.tb_locals_obj.unlink(cr, uid, [l.id 
            for tb in rec.last_traceback for l in tb.locals], context=context)
        self.tb_obj.unlink(cr, uid, [tb.id for tb in rec.last_traceback],
                context=context)
        self.write(cr, uid, [rec.id,], {'last_type': '', 'last_value': ''},
                context=context)
    
    def _set_exc(self, cr, uid, id, last_type, last_value, last_traceback,
            context):
        # first clear the previous exc
        self._clear_exc(cr, uid, id, context)

        # write last_type and last_value
        self.write(cr, uid, [id,], {'last_type': str(last_type),
            'last_value': str(last_value)}, context=context)

        # now add tracebacks
        lines_around = context.get('lines_around', 5)

        for depth, filename, where, lineno, lines, local in \
                codebase.iter_tracback(tb, lines_around):

            line = dict(lines)[lineno]

            if lines:
                w = len(str(lines[-1][0]))
                lines = ''.join(("%*d. %s" % (w, ln) for ln, l in lines))
            else:
                lines = ''

            tb_id = self.tb_obj.create(cr, uid, {'console': id,
                'depth': depth,
                'filename': filename,
                'where': where,
                'lineno': lineno,
                'line': line,
                'lines': lines,
                'locals': [(0, 0, {
                    'name': n,
                    'value': pformat(v, indent=4),
                }) for n, v in local.iteritems()],
            }, context=context)
            
    def create(self, cr, uid, vals, context=None):
        # create the associated bgconsole and create the record
        bgconsole_id = self.bgconsole_obj.create(cr, uid, {}, context=context)
        output = self.bgconsole_obj._get_console(cr, uid, bgconsole_id,
                context).output
        ret = super(DebugConsole, self).create(cr, uid, {
            'bgconsole': bgconsole_id,
            'output': output,
        }, context=context)

        # if there is some input
        if vals.get('cmd', None):
            self._cmd_set(cr, uid, [ret], 'cmd', vals['cmd'], None,
                    context=context)
        
        return ret

    def _cmd_get(self, cr, uid, ids, field_name, arg, context=None):
        return dict(((id, '') for id in norm_select(ids)))

    def _cmd_set(self, cr, uid, ids, field_name, field_val, arg, context=None):
        if context is None:
            context = {}

        ids = norm_select(ids)
        for id in ids:
            rec = self.browse(cr, uid, id, context=context)
            console = self._get_console(cr, uid, id, context)
            console.push_cmd(field_val)
            if console.dead:
                raise osv.except_osv('Info!',
                        "The console has exited, try restart")

            self.write(cr, uid, [id], {'output': console.output})
            if console.got_exception and rec.catch_console_exception:
                # should be set by InteractiveInterpreter.showtraceback at 
                # code.py
                last_type = getattr(sys, 'last_type', None)
                last_value = getattr(sys, 'last_value', None)
                last_traceback = getattr(sys, 'last_traceback', None)
                assert last_type and last_value and last_traceback
                self._set_exc(cr, uid, id, last_type, last_value,
                        last_traceback, context)

        return True

    def restart_console(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        ids = norm_select(ids)
        for rec in self.browse(cr, uid, ids, context=context):
            # clear exception
            self._clear_exc(cr, uid, rec.id, context)
            # create new console and set
            old_id = rec.bgconsole.id
            new_id = self.bgconsole_obj.create(cr, uid, {}, context=context)
            output = self.bgconsole_obj._get_console(cr, uid, new_id,
                    context).output
            self.write(cr, uid, [rec.id], {'bgconsole': new_id, 'output': output},
                    context=context)
            # unlink the old one
            self.bgconsole_obj.unlink(cr, uid, [old_id], context=context)
        return True

    def set_catch_console_exception(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        return self.write(cr, uid, ids, {
            'catch_console_exception': context.get('catch_console_exception',
                False),
        }, context=context)

    def set_catch_server_exception(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        catch_server_exception = context.get('catch_server_exception', False)
        id = ids[0]
        dbname = cr.dbname
        if catch_server_exception:
            def cb(last_type, last_value, last_traceback):
                # need to open a new cursor here
                try:
                    cr = pooler.get_db_only(dbname).cursor()
                    self._set_exc(cr, uid, id, last_type, last_value,
                            last_traceback, context)
                finally:
                    cr.close()
            hook.register_exception_callback(id, cb)
        else:
            hook.unregister_exception_callback(id)
        return self.write(cr, uid, ids, {
            'catch_server_exception': catch_server_exception,
        }, context=context)

    def set_profile(self, cr, uid, ids, context=None):
        if pstats is None:
            raise osv.except_osv('Error', 'Package \'pstats\' is not '\
                    'installed, please install it first')

        if context is None:
            context = {}
        profile_server = context.get('profile_server', False)
        id = ids[0]
        rec = self.browse(cr, uid, id, context=context)
        dbname = cr.dbname
        if profile_server:
            started = hook.start_profile(id)
            if not started:
                raise osv.except_osv('Error', 'Another application may be '\
                        'already profiling, please wait until it is stopped')
            profile_result = False
        else:
            profile_result = hook.stop_profile(id, rec.profile_sort)
            if profile_result is None:
                raise osv.except_osv('Error', 'Missing profile')
        return self.write(cr, uid, ids, {
            'profile_server': profile_server,
            'profile_result': profile_result,
        }, context=context)

    def export_tb(self, cr, uid, ids, context=None):
        rec = self.browse(cr, uid, ids[0], context=context)
        res = {
            'last_type': rec.last_type,
            'last_value': rec.last_value,
            'last_traceback': [],
        }
        for tb in rec.last_traceback:
            t = {
                'depth': tb.depth,
                'filename': tb.filename,
                'where': tb.where,
                'lineno': tb.lineno,
                'line': tb.line,
                'lines': tb.lines,
                'locals': [],
            }
            for loc in tb.locals:
                l = {
                    'name': loc.name,
                    'value': loc.value,
                }
                t['locals'].append((0, 0, l))
            res['last_traceback'].append((0, 0, t))
        res = base64.b64encode(json.dumps(res, separators=(',', ':')))
        res_id = self.pool.get('hotdebug.tb.export').create(cr, uid, {
            'file': res,
            'filename': datetime.now().strftime(
                'TracebackExport-%Y%m%d%H%M%S'),
        }, context=context)
        return {
            'name': 'Export Traceback',
            'view_mode': 'form',
            'view_id': False,
            'view_type': 'form',
            'res_id': res_id,
            'res_model': 'hotdebug.tb.export',
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'new',
            'context': context,
        }

    def import_tb(self, cr, uid, ids, context=None):
        res_id = self.pool.get('hotdebug.tb.import').create(cr, uid, {
            'console': ids[0],
        }, context=context)
        return {
            'name': 'Import Traceback',
            'view_mode': 'form',
            'view_id': False,
            'view_type': 'form',
            'res_id': res_id,
            'res_model': 'hotdebug.tb.import',
            'type': 'ir.actions.act_window',
            'nodestroy': True,
            'target': 'new',
            'context': context,
        }

    def clear_tb(self, cr, uid, ids, context=None):
        self._clear_exc(cr, uid, ids[0], context)
        return True
        
    _name = 'hotdebug.console'
    _columns = {
        'bgconsole': fields.many2one('hotdebug.console.bgconsole',
            'BGConsole Object'),
        'output': fields.text('Output', readonly=True),
        'cmd': fields.function(_cmd_get, fnct_inv=_cmd_set, type='text',
            method=True,
            string='Cmd',),
        'last_type': fields.char('Last exception type',
            size=256,
            readonly=True),
        'last_value': fields.char('Last exception value',
            size=256,
            readonly=True),
        'last_traceback': fields.one2many('hotdebug.tb',
            'console',
            'Last exception traceback'),
        'catch_console_exception': fields.boolean('Catch console exception?',
            readonly=True),
        'catch_server_exception': fields.boolean('Catch server exception?',
            readonly=True),
        'profile_server': fields.boolean('Profile server activity', readonly=True),
        'profile_sort': fields.selection([
            ('time', 'internal time'),
            ('cumulative', 'cumulative time'),
            ('calls', 'call count'),
        ], 'Profile result order by'),
        'profile_result': fields.text('Profile result', readonly=True),
        'help': fields.text('Help', readonly=True),
    }
    _defaults = {
        'output': BGConsole.banner(),
        'last_type': '',
        'last_value': '',
        'catch_console_exception': True,
        'catch_server_exception': False,
        'profile_server': False,
        'profile_sort': 'time',
        'profile_result': (pstats is None) and """
            Profile feature disabled since: 
                Package 'pstats' is not installed. Please install it first 
                (e.g. apt-get install python-profiler)
        """ or "",
        'help': help_text,
    }

DebugConsole()


class BGConsoleObj(osv.osv_memory):
    _name = 'hotdebug.console.bgconsole'
    _columns = {
        'py_id': fields.integer('BGConsole Object id'),
    }
    # py_id->obj
    _consoles = {}

    def default_get(self, cr, uid, fields, context=None):
        ret = super(BGConsoleObj, self).default_get(cr, uid, fields,
                context=context)

        # create the console object
        loc = {'uid': uid, 'dbname': cr.dbname}
        # cr will be closed, so create one
        db, pool = pooler.get_db_and_pool(cr.dbname)
        loc['cr'] = db.cursor()
        loc['pool'] = pool
        console = BGConsole(loc, max_line=35)

        # store
        ret['py_id'] = id(console)
        self._consoles[id(console)] = console
        return ret

    # override unlink to dettach consoles
    def unlink(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids, context=context):
            self._consoles.pop(rec.py_id, None)
        return super(BGConsoleObj, self).unlink(cr, uid, ids, context=context)

    def _get_console(self, cr, uid, id, context):
        rec = self.browse(cr, uid, id, context=context)
        return self._consoles[rec.py_id]

BGConsoleObj()


class Traceback(osv.osv_memory):

    def _name_get(self, cr, uid, ids, field_name, arg, context=None):
        ret = {}
        for tb in self.browse(cr, uid, ids, context=context):
            ret[tb.id] = 'File "%s", line %d, in %s' % (tb.filename,
                    tb.lineno,
                    tb.where)
        return ret

    _name = 'hotdebug.tb'
    _order = 'depth'
    _columns = {
        'console': fields.many2one('hotdebug.console', 'Console',
            readonly=True),
        'depth': fields.integer('Traceback frame depth', readonly=True),
        'filename': fields.char('Filename', size=256, readonly=True),
        'where': fields.char('Where', size=256, readonly=True),
        'lineno': fields.integer('Lineno', readonly=True),
        'line': fields.text('Source code', readonly=True),
        'lines': fields.text('Source code', readonly=True),
        'name': fields.function(_name_get, type='char',
            size=512,
            method=True,
            string='Tracebacks'),
        'locals': fields.one2many('hotdebug.tb.locals', 'tb', 'Locals'),
    }

Traceback()


class TracebackLocals(osv.osv_memory):

    value_short_limit = 64

    def _value_short_get(self, cr, uid, ids, field_name, arg, context=None):
        ret = {}
        for loc in self.browse(cr, uid, ids, context=context):
            if len(loc.value) < self.value_short_limit:
                ret[loc.id] = loc.value
            else:
                ret[loc.id] = loc.value[:self.value_short_limit - 3] + '...'
        return ret

    _name = 'hotdebug.tb.locals'
    _columns = {
        'tb': fields.many2one('hotdebug.tb', 'Traceback'),
        'name': fields.char('Name', size=256, readonly=True),
        'value': fields.text('Value', readonly=True),
        'value_short': fields.function(_value_short_get, type='char',
            size=value_short_limit,
            method=True,
            string='Value'),
    }

TracebackLocals()


class TracebackExport(osv.osv_memory):

    _name = 'hotdebug.tb.export'
    _columns = {
        'filename': fields.char('Export File Name', size=128),
        'file': fields.binary('Export File'),
    }


TracebackExport()


class TracebackImport(osv.osv_memory):

    def import_tb(self, cr, uid, ids, context=None):
        rec = self.browse(cr, uid, ids[0], context=context)
        if not rec.file:
            raise osv.except_osv('Error', 'Please select import file')
        try:
            value = json.loads(base64.b64decode(rec.file))
        except ValueError:
            raise osv.except_osv('Error', 'Bad content')
        # TODO: more check for value
        console_obj = self.pool.get('hotdebug.console')
        console_id = rec.console.id
        console_obj._clear_exc(cr, uid, console_id, context)
        console_obj.write(cr, uid, [console_id,], value, context=context)
        return {'type': 'ir.actions.act_window_close'}

    _name = 'hotdebug.tb.import'
    _columns = {
        'console': fields.many2one('hotdebug.console', 'Console',
            readonly=True),
        'filename': fields.char('Import File Name', size=128),
        'file': fields.binary('Import File'),
    }


TracebackImport()