-
Notifications
You must be signed in to change notification settings - Fork 4
/
otrace.py
executable file
·5813 lines (4976 loc) · 233 KB
/
otrace.py
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# otrace: An object-oriented debugger for nonlinear tracing
#
# otrace was developed as part of the Mindmeldr project.
# Documentation can be found at http://code.mindmeldr.com/otrace
#
# BSD License
#
# Copyright (c) 2012, Ramalingam Saravanan <sarava@sarava.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""An object-oriented debugger for nonlinear tracing
Installation
============
Ensure that ``otrace.py`` is in the python module load path.
(For python 2.6 or earlier, you will also need ``ordereddict.py``.)
Usage
======
*otrace* may be used as:
- a tracing tool for debugging web servers and interactive programs
- a console or dashboard for monitoring production servers
- a teaching tool for exploring the innards of a program
- a code patching tool for unit testing
*otrace* does not consume any resources until some tracing action is
initiated. So it can be included in production code without any
performance penalty.
*otrace* works well with detached server processes (*daemons*)
via the GNU `screen <http://www.gnu.org/software/screen>`_
utility that emulates a terminal.
*otrace* is meant to be used in conjunction with an *event loop*, which
is usually present in programs that interact with users such as web
servers or GUI applications. *otrace* takes control of the terminal,
and would not work very well with programs that read user input
directly from the terminal (or standard input).
To use *otrace*, simply ``import otrace`` and instantiate the class ``otrace.OShell``,
which provides a unix-like shell interface to interact with a running
program via the terminal.
Here is a simple server example::
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from otrace import OShell, traceassert
http_server = BaseHTTPServer.HTTPServer(("", 8888), SimpleHTTPRequestHandler)
oshell = OShell(locals_dict=locals(), globals_dict=globals(),
new_thread=True, allow_unsafe=True, init_file="server.trc")
try:
oshell.loop()
http_server.serve_forever() # Main event loop
except KeyboardInterrupt:
oshell.shutdown()
*Usage notes:*
- If you run in *oshell* in its own daemon thread as shown above, use
the ^C sequence to abort the main thread, and call ``OShell.shutdown``
from main thread to cleanup terminal I/O etc.
- If you run *oshell* in the main thread and the event loop in a
separate thread, ^C will abort and cleanup *oshell*. You may need to
shutdown the event loop cleanly after that.
- Install the python ``readline`` module to enable *TAB* command completion.
- To start a detached server (daemon) process, use the command:
``screen -d -m -S <screen_name> <executable> <argument1> ...``
To attach a terminal to this process, use:
``screen -r <screen_name>``
- By default, *otrace* logs to the ``logging`` module. Subclass
``TraceCallback``, overriding the methods ``callback`` and ``returnback``
to implement your own logging (see ``DefaultCallback`` for a simple example)
Synopsis
=========
*otrace* uses a *Virtual Directory Shell Interface* which maps all the
objects in a a running python program to a virtual filesystem mounted in
the directory ``/osh`` (sort of like the unix ``/proc`` filesystem, if you are
familiar with it). Each module, class, method, function, and variable in the global namespace
is mapped to a virtual file within this directory.
For example, a class ``TestClass`` in the ``globals()`` dictionary can be accessed as::
/osh/globals/TestClass
and a method ``test_method`` can be accessed as::
/osh/globals/TestClass/test_method
and so on.
*otrace* provides a unix shell-like interface, *oshell*, with commands
such as ``cd``, ``ls``, ``view``, and ``edit`` that can be used navigate, view,
and edit the virtual files. Editing a function or method
"`monkey patches <http://en.wikipedia.org/wiki/Monkey_patch>`_" it,
allowing the insertion of ``print`` statements etc. in the running program.
The ``trace`` command allows dynamic tracing of function or method invocations,
return values, and exceptions. This is accomplished by
dynamically *decorating* (or *wrapping*) the function to be traced.
When a trace condition is satisfied, the function-wrapper saves *context information*, such as
arguments and return values, in a newly created virtual directory in::
/osh/recent/*
These *trace context* directories can be navigated just like
``/osh/globals/*``. (If there are too many trace contexts, the oldest
ones are deleted, unless they have been explicitly *saved*.)
*oshell* allows standard unix shell commands to be interspersed with
*oshell*-specific commands. The path of the "current working directory"
determines which of the these two types of commands will be executed.
If the current working directory is not in ``/osh/*``, the command is
treated as a standard unix shell command (except for ``cd``, which is
always handled by *oshell*.)
Credits
========
*otrace* was developed as part of the `Mindmeldr <http://mindmeldr.com>`_ project, which is aimed at improving classroom interaction.
*otrace* was inspired by the following:
- the tracing module `echo.py <http://wordaligned.org/articles/echo>`_ written by Thomas Guest <tag@wordaligned.org>. This nifty little program uses decorators to trace function calls.
- the python ``dir()`` function, which treats objects as directories. If objects are directories, then shouldn't we be able to inspect them using the familiar ``cd`` and ``ls`` unix shell commands?
- the unix `proc <http://en.wikipedia.org/wiki/Procfs>`_ filesystem, which cleverly maps non-file data to a filesystem interface mounted at ``/proc``
- the movie `Being John Malkovich <http://en.wikipedia.org/wiki/Being_John_Malkovich>`_ (think of ``/osh`` as the portal to the "mind" of a running program)
License
=========
*otrace* is distributed as open source under the `BSD-license <http://www.opensource.org/licenses/bsd-license.php>`_.
"""
from __future__ import with_statement
import cgi
import cgitb
import codeop
import collections
import copy
import cPickle
import datetime
import functools
import hashlib
import hmac
import inspect
import logging
import logging.handlers
import os
import os.path
import pprint
import Queue
import random
import re
import select
import shlex
import sqlite3
import StringIO
import struct
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import types
import urllib
import weakref
Banner_messages = []
# Save terminal attributes before using readline
# (Need this to restore terminal attributes after abnormal exit from oshell thread)
try:
import termios
Term_attr = termios.tcgetattr(sys.stdin.fileno())
except Exception:
Term_attr = None
try:
import readline # this allows raw_input to handle line editing
if readline.__doc__ and "libedit" in readline.__doc__:
# http://stackoverflow.com/questions/7116038/python-tab-completion-mac-osx-10-7-lion
readline.parse_and_bind("bind ^I rl_complete")
except Exception:
readline = None
mod_name = "pyreadline" if sys.platform.startswith("win") else "readline"
Banner_messages.append(" Please install '%s' module for TAB completion (e.g. 'easy_install %s')" % (mod_name, mod_name))
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
try:
from collections import MutableMapping
except ImportError:
from UserDict import DictMixin as MutableMapping
OTRACE_VERSION = "0.30.9"
__all__ = ["OTrace", "OShell", "OTraceException"]
EXEC_TIMEOUT = 10 # Execution timeout (in sec)
REPEAT_COUNT = 10000 # Default repeat count
# Path separator
PATH_SEP = "/"
BACKSLASH = "\\"
ENTITY_CHAR = ":"
BASE_DIR = "osh"
BASE_OFFSET = 1
BASE1_OFFSET = 2
BASE2_OFFSET = 3
TRACE_OFFSET = 6
MAX_PICKLE_CHECK_DEPTH = 3 # Max depth to check for pickleability
MAX_PICKLE_DATA_LENGTH = 10000 # Max length for individual pickled component data length
ALL_DIR = "all"
BROWSER_DIR = "browser"
DATABASE_DIR = "db"
GLOBALS_DIR = "globals"
LOCALS_DIR = "locals"
PATCHES_DIR = "patches"
PICKLED_DIR = "pickled"
RECENT_DIR = "recent"
SAVED_DIR = "saved"
WEB_DIR = "web"
LAZY_DIRS = [DATABASE_DIR, PICKLED_DIR] # Lazy data loading directories
DIR_LIST = [ALL_DIR, BROWSER_DIR, DATABASE_DIR, GLOBALS_DIR, LOCALS_DIR, PATCHES_DIR, PICKLED_DIR, RECENT_DIR, SAVED_DIR, WEB_DIR]
OT_DIRS = set(DIR_LIST)
DIR_PREFIX = dict((dir_name, PATH_SEP + BASE_DIR + PATH_SEP + dir_name + PATH_SEP) for dir_name in DIR_LIST)
BREAK_ACTIONS = ["break", "ipdb", "pdb"]
TRACE_ACTIONS = BREAK_ACTIONS + ["hold", "tag"]
TRACE_INFO = "__trc"
DOWN_STACK = "__down"
UP_STACK = "__up"
SHOW_HIDDEN = set(["__call__", TRACE_INFO, DOWN_STACK, UP_STACK])
IGNORE_FUNCNAMES = set(["otrace_function_call", "otrace_wrapped"])
ASSIGNMENT_RE = re.compile(r"\s*[a-zA-Z][a-zA-Z0-9_\.]*\s*=[^=]")
EXEC_PREFIX = "!"
NEWCONTEXT_PREFIX = "~~"
GLOBALS_PREFIX = "~~g"
WORKDIR_PREFIX = "~~w"
TRACE_ID_PREFIX = "~"
TRACE_ID_SEP = ":"
TRACE_LABEL_PREFIX = ":"
TRACE_LOG_PREFIX = "log:"
CLEAR_SCREEN_SEQUENCE = "\x1b[H\x1b[J" # <ESC>[H<ESC>[J
ALT_SCREEN_ONSEQ = "\x1b[?1049h"
ALT_SCREEN_OFFSEQ = "\x1b[?1049l"
INAME = 0
ISUBDIR = 1
FILE_EXTENSIONS = {"css": "css", "htm": "html", "html": "html", "js": "javascript", "py": "python",
"xml": "xml"}
DOC_URL = "http://code.mindmeldr.com/otrace"
DEFAULT_BANNER = """ ***otrace object shell (v%s)*** (type 'help' for info)""" % OTRACE_VERSION
Help_params = OrderedDict()
Help_params["allow_xml"] = "Allow output markup for display in browser (if supported)"
Help_params["append_traceback"] = "Append traceback information to exceptions"
Help_params["assert_context"]= "No. of lines of context retrieved for traceassert (0 for efficiency)"
Help_params["auto_lock"] = "Automatically lock after specified idle time (in seconds), if password is set"
Help_params["deep_copy"] = "Create deep copies of arguments and local variables for 'snapshots'"
Help_params["editor"] = "Editor to use for editing patches or viewing source"
Help_params["exec_lock"] = "Execute code within re-entrant lock"
Help_params["log_format"] = "Format for log messages"
Help_params["log_level"] = "Logging level (10=>DEBUG, 20=>INFO, 30=>WARNING ...; see logging module)"
Help_params["log_remote"] = "IP address or domain (:port) for remote logging (default port: 9020)"
Help_params["log_truncate"] = "No. of characters to display for log messages (default: 72)"
Help_params["max_recent"] = "Maximum number of entries to keep in /osh/recent"
Help_params["osh_bin"] = "Path to prepend to $PATH to use custom commands"
Help_params["password"] = "Encrypted access password (use otrace.encrypt_password to create it)"
Help_params["pickle_file"] = "Name of file to save pickled trace contexts"
Help_params["pretty_print"] = "Use pprint.pformat rather than print to display expressions"
Help_params["repeat_interval"] = "Command repeat interval (sec)"
Help_params["safe_mode"] = "Safe mode (disable code modification and execution)"
Help_params["save_tags"] = "Automatically save all tag contexts"
Help_params["trace_active"] = "Activate tracing (can be used to force/suppress tracing)"
Help_params["trace_related"] = "Automatically trace calls related to tagged objects"
Help_params["unpickle_file"] = "Name of file to read pickled trace contexts from"
Set_params = {}
Set_params["allow_xml"] = True
Set_params["append_traceback"] = False
Set_params["assert_context"] = 0
Set_params["auto_lock"] = 0
Set_params["deep_copy"] = False
Set_params["editor"] = ""
Set_params["exec_lock"] = False
Set_params["log_format"] = None # placeholder
Set_params["log_level"] = None # placeholder
Set_params["log_remote"] = None # placeholder
Set_params["log_truncate"] = None # placeholder
Set_params["max_recent"] = 10
Set_params["osh_bin"] = ""
Set_params["password"] = ""
Set_params["pickle_file"] = ""
Set_params["pretty_print"] = False
Set_params["repeat_interval"] = 0.2
Set_params["safe_mode"] = True
Set_params["save_tags"] = False
Set_params["trace_active"] = None # placeholder
Set_params["trace_related"]= False
Set_params["unpickle_file"]= None # placeholder
Trace_rlock = threading.RLock()
Pickle_rlock = threading.RLock()
if sys.version_info[0] < 3:
def encode(s):
return s
def decode(s):
return s
else:
def encode(s):
return s.encode("utf-8")
def decode(s):
return s.decode("utf-8")
def encrypt_password(password, salt=None, hexdigits=16):
"""Encrypt password, returning encrypted password prefixed with salt,
which defaults to a random value
"""
if not salt:
salt = "%015d" % random.randrange(0, 10**15)
elif ":" in salt:
raise Exception("Colon not allowed in salt")
encrypted = hmac.new(encode(salt), encode(password), digestmod=hashlib.sha256).hexdigest()[:hexdigits]
return salt+":"+encrypted
def verify_password(password, encrypted_password):
salt, sep, _ = encrypted_password.partition(":")
if not salt:
raise Exception("No salt in encrypted password")
return encrypted_password == encrypt_password(password, salt=salt)
class OSDirectory(object):
def __init__(self, path=None):
self.path = path
class AltHandler(Exception):
pass
def is_absolute_path(path):
if path.startswith(PATH_SEP):
return True
if os.sep == BACKSLASH and re.match(r"[a-zA-Z]:", path):
# Windows absolute path
return True
return False
def os_path(path):
"""Convert unix-style path to OS path"""
if os.sep == BACKSLASH:
# Windows path
if path.startswith(PATH_SEP):
comps = path[1:].split(PATH_SEP)
comps[0] = "c:\\" + comps[0]
else:
comps = path.split(PATH_SEP)
path = os.path.join(*comps)
return path
def expanduser(filepath):
if filepath.startswith(GLOBALS_PREFIX):
filepath = DIR_PREFIX[GLOBALS_DIR][:-1]+filepath[len(GLOBALS_PREFIX):]
elif filepath.startswith(WORKDIR_PREFIX):
dir_path = (OShell.instance and OShell.instance.work_dir) or os.getcwd()
filepath = dir_path+filepath[len(WORKDIR_PREFIX):]
elif filepath.startswith(NEWCONTEXT_PREFIX):
# Change to top directory of newest context
return PATH_SEP + PATH_SEP.join(OTrace.recent_pathnames)
return os.path.expanduser(filepath)
def expandpath(filepath):
"""Return expanded filepath (absolute path or assumed relative to work directory)"""
return expanduser(filepath if is_absolute_path(filepath) or filepath.startswith(NEWCONTEXT_PREFIX) or filepath.startswith("~") else WORKDIR_PREFIX+PATH_SEP+filepath)
def otrace_pformat(*args, **kwargs):
if Set_params["pretty_print"]:
return "\n".join(pprint.pformat(arg, **kwargs) for arg in args)
else:
return " ".join(str(arg) for arg in args)
def de_indent(lines):
"""Remove global indentation"""
out_lines = []
indent = None
for line in lines:
temline = line.lstrip()
if indent is None and temline and not temline.startswith("#") and not temline.startswith("@"):
# First non-blank, non-comment, non-decorator line; initialize global indentation
indent = len(line) - len(temline)
if indent and len(line) - len(temline) >= indent:
# Strip global indentation from line
out_lines.append(line[indent:])
elif not temline.startswith("@"):
# Skip leading decorators (like @classmethod, @staticmethod)
# to get code for pure function
out_lines.append(line)
return out_lines
def pythonize(args):
"""Convert shell-style space-separated, unquoted arguments to
python-style comma-separated, quoted arguments"""
arg_list = []
for arg in args:
if "=" in arg:
kw, sep, arg = arg.partition("=")
prefix = kw+sep
else:
prefix = ""
if arg and (arg.isdigit() or arg[0] in "+-" and arg[1:].isdigit()):
arg_list.append(prefix+arg)
else:
arg_list.append(prefix+repr(arg))
return ", ".join(arg_list)
def strip_compare_op(prop_name):
"""Return (stripped_prop_name, compare_op) for suffixed property names of the form "arg1!=", "arg2<" etc."""
cmp_op = ""
if prop_name.endswith("="):
cmp_op = "="
prop_name = prop_name[:-1]
if prop_name[-1] in ("=", "!", "<", ">"):
cmp_op = prop_name[-1] + cmp_op
prop_name = prop_name[:-1]
if not cmp_op or cmp_op == "=":
cmp_op = "=="
return (prop_name.strip(), cmp_op)
def compare(value1, op_str, value2):
"""Return True or False for comparison using operator."""
return ( (op_str == "==" and value1 == value2) or
(op_str == "!=" and value1 != value2) or
(op_str == "<=" and value1 <= value2) or
(op_str == ">=" and value1 >= value2) or
(op_str == "<" and value1 < value2) or
(op_str == ">" and value1 > value2) )
def match_parse(match_str, delimiter=","):
"""Parse match dict components of the form: var1.comp1==value1,var2!=value2,... where values with commas/spaces must be quoted."""
match_dict = {}
invalid_tokens = []
lex = shlex.shlex(match_str, None, True)
lex.whitespace = delimiter
lex.whitespace_split = True
while True:
token = lex.get_token()
if token is None:
break
if not token:
continue
re_match = re.match(r"^([\w\.]+)(==|!=|<=|>=|<|>)(.+)$", token)
if not re_match:
invalid_tokens.append(token)
continue
value = re_match.group(3)
if value and (value[0].isdigit() or value[0] in "+-" and value[1:2].isdigit()):
try:
if "." in value:
value = float(value)
else:
value = long(value)
except Exception:
invalid_tokens.append(token)
value = None
elif value in ("True", "False"):
value = (value == "True")
elif value == "None":
value = None
match_dict[re_match.group(1)+re_match.group(2)] = value
if invalid_tokens and re.search(r"[=<>]", match_str):
raise Exception("Invalid match components: " + ",".join(invalid_tokens))
return match_dict
def get_obj_properties(value, full_path=None):
"""Return (python_mime_type, command) for object value"""
opts = ""
if full_path and OShell.instance:
if len(full_path) > BASE_OFFSET and full_path[BASE_OFFSET] in OShell.instance.lazy_dirs:
# In database
base_subdir = full_path[BASE_OFFSET]
if len(full_path) == BASE1_OFFSET+OShell.instance.lazy_dirs[base_subdir].root_depth:
# Need to "cdls" to load database entries
return ("object", "cdls")
opts += " -v"
if value is None or isinstance(value, (basestring, bool, complex, float, int, list, tuple)):
return ("value", "pr")
elif inspect.isfunction(value) or inspect.ismethod(value):
return ("function", "view -i")
else:
return ("object", "cdls"+opts)
def format_traceback(exc_info=None):
"""Return string describing exception."""
try:
etype, value, tb = exc_info if exc_info else sys.exc_info()
tblist = traceback.extract_tb(tb)
del tblist[:1] # Remove self-reference to tracing code in traceback
fmtlist = traceback.format_list(tblist)
if fmtlist:
fmtlist.insert(0, "Traceback (most recent call last):\n")
fmtlist[len(fmtlist):] = traceback.format_exception_only(etype, value)
finally:
tblist = tb = None
return "".join(fmtlist)
def get_naked_function(method):
"""Return function object associated with a method."""
if inspect.isfunction(method):
return method
return getattr(method, "__func__", None)
def ismethod_or_function(method):
return inspect.isfunction(get_naked_function(method))
def get_method_type(parent_cls, method):
"""Return 'instancemethod'/'classmethod'/'staticmethod' """
# Get class attribute directly
attr_value = parent_cls.__dict__[method.__name__]
if inspect.isfunction(attr_value):
# Undecorated function => instance method
return "instancemethod"
# Decorated function; return type
return type(attr_value).__name__
class OTraceException(Exception):
pass
class TraceDict(dict):
# Subclass dict to allow a weak reference to be created to it
# Also implements *_trc methods for trace info
def has_trc(self, trace_attr):
"""Returns True if self[TRACE_INFO] has attribute."""
return TRACE_INFO in self and trace_attr in self[TRACE_INFO]
def get_trc(self, trace_attr, default=None):
"""Return self[TRACE_INFO][trace_attr] or default."""
if TRACE_INFO in self:
return self[TRACE_INFO].get(trace_attr, default)
else:
return default
def set_trc(self, trace_attr, value):
"""Set self[TRACE_INFO][trace_attr] to value."""
if TRACE_INFO not in self:
self[TRACE_INFO] = {}
self[TRACE_INFO][trace_attr] = value
class MappingDict(MutableMapping):
pass
class ObjectDict(MappingDict):
"""Wrapper to make an object appear like a dict."""
def __init__(self, obj):
self._obj = obj
def copy(self):
return ObjectDict(self._obj)
def keys(self):
return dir(self._obj)
def __contains__(self, key):
return hasattr(self._obj, key)
def __getitem__(self, key):
if not hasattr(self._obj, key):
raise KeyError(key)
return getattr(self._obj, key)
def __iter__(self):
return self.keys().__iter__
def __len__(self):
return len(self.keys())
def __setitem__(self, key, value):
setattr(self._obj, key, value)
def __delitem__(self, key):
if not hasattr(self._obj, key):
raise KeyError(key)
delattr(self._obj, key)
class ListDict(MappingDict):
"""Wrapper to make a list/tuple appear like a dict."""
def __init__(self, lst):
self._lst = lst
def copy(self):
return ListDict(self._lst)
def keys(self):
return [str(x) for x in range(len(self._lst))]
def __contains__(self, key):
try:
key = int(key)
except Exception:
return False
return (key >= 0) and (key < len(self._lst))
def __getitem__(self, key):
if not self.__contains__(key):
raise KeyError(key)
return self._lst[int(key)]
def __iter__(self):
for x in self.keys():
yield x
def __len__(self):
return len(self._lst)
def __setitem__(self, key, value):
if not self.__contains__(key):
raise KeyError(key)
self._lst[int(key)] = value
def __delitem__(self, key):
if not self.__contains__(key):
raise KeyError(key)
del self._lst[int(key)]
class LineList(list):
def __str__(self):
s = [str(x) for x in self]
return "".join(x if x.endswith("\n") else x+"\n" for x in s)
def setTerminalEcho(enabled):
if not Term_attr:
return
fd = sys.stdin.fileno()
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(fd)
if enabled:
lflag |= termios.ECHO
else:
lflag &= ~termios.ECHO
new_attr = [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
termios.tcsetattr(fd, termios.TCSANOW, new_attr)
### http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
def getTerminalSize():
"""Return (lines:int, cols:int)"""
if not Term_attr:
return(25, 80)
def ioctl_GWINSZ(fd):
import fcntl
return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
# Try stdin, stdout, stderr
for fd in (0, 1, 2):
try:
return ioctl_GWINSZ(fd)
except Exception:
pass
# Try os.ctermid()
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
return ioctl_GWINSZ(fd)
finally:
os.close(fd)
except Exception:
pass
# Try `stty size` (commented out to avoid popen)
##try:
## return tuple(int(x) for x in os.popen("stty size", "r").read().split())
##except Exception:
## pass
#
# Try environment variables
try:
return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
except Exception:
pass
# return default.
return (25, 80)
def read_password(prompt="Password:"):
"""Read password, with no echo, from stdin"""
setTerminalEcho(False)
try:
password = raw_input(prompt)
except ValueError:
raise EOFError
sys.stdout.write("\n")
setTerminalEcho(True)
return password
def check_for_hold(self_arg):
"""Return callable function if self_arg has a hold, else return None."""
return getattr(self_arg, OTrace.hold_attr, None)
def resume_from_hold(self_arg):
# Executed in otrace thread; should insert resume callback in event loop and return immediately
if hasattr(self_arg, OTrace.resume_attr):
callback = getattr(self_arg, OTrace.resume_attr)
delattr(self_arg, OTrace.resume_attr)
if callback:
try:
callback()
return True
except Exception:
return False
return False
class TraceInterpreter(object):
"""Class to execute code interactively using argument values as the local context."""
def __init__(self):
self.compile = codeop.CommandCompiler()
def evaluate(self, expression, locals_dict={}, globals_dict={}, print_out=False):
""" Evaluate expression; return output string, if print_out is True.
Returns tuple (out_str, err_str), with err_str == "" for successful execution,
and err_str == None for incomplete expression
"""
_stdout = StringIO.StringIO()
_stderr = StringIO.StringIO()
locals_dict["_stdout"] = _stdout
locals_dict["_stderr"] = _stderr
prefix = "print >>_stdout, " if print_out else ""
result = self.exec_source(prefix+expression, locals_dict=locals_dict, globals_dict=globals_dict)
del locals_dict["_stdout"]
del locals_dict["_stderr"]
out_str = _stdout.getvalue()
err_str = _stderr.getvalue()
_stdout.close()
_stderr.close()
if result is None:
return ("<Incomplete Expression>", None)
return (out_str, err_str + result)
def exec_source(self, source, filename="<input>", symbol="single", locals_dict={}, globals_dict={}):
"""Execute source code.
Returns None if code is incomplete,
null string on successful execution of code,
or a string describing a syntax error or other exeception.
All exceptions, excepting for SystemExit, are caught.
"""
try:
# Compile code
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Syntax error
etype, value, last_traceback = sys.exc_info()
return ".".join(traceback.format_exception_only(etype, value))
if code is None:
# Incomplete code
return None
try:
if globals_dict is locals_dict:
exec code in locals_dict
else:
exec code in globals_dict, locals_dict
return "" # Successful execution
except SystemExit:
raise
except Exception:
return format_traceback() # Error in execution
class TraceConsole(object):
"""Console for trace interpreter (similar to code.interact).
Runs in separate thread (as a daemon)
"""
prompt1 = "> "
prompt2 = "... "
def __init__(self, globals_dict={}, locals_dict={}, banner=DEFAULT_BANNER,
echo_callback=None, db_interface=None, web_interface=None, no_input=False, new_thread=False,
_stdin=sys.stdin, _stdout=sys.stdout, _stderr=sys.stderr):
"""Create console instance.
If echo_callback is specified, it should be a callable,
and it will be called with stdout and stderr string data to echo output.
If new_thread, a new (daemon) thread is created for TraceConsole,
else TraceConsole runs in current thread, blocking it.
"""
self.globals_dict = globals_dict
self.locals_dict = locals_dict
self.banner = banner
self.echo_callback = echo_callback
self.lazy_dirs = {PICKLED_DIR: PickleInterface}
if db_interface:
self.lazy_dirs[DATABASE_DIR] = db_interface
self.web_interface = web_interface
self.no_input = no_input
self.thread = threading.Thread(target=self.run) if new_thread and not no_input else None
if self.thread:
self.thread.setDaemon(True)
self.queue = None
self.expect_run = False
self._stdin = _stdin
self._stdout = _stdout
self._stderr = _stderr
self.interpreter = TraceInterpreter()
self.resetbuffer()
self.feed_lines = []
self.last_input_time = 0
self.set_repeat(None)
self.repeat_alt_screen = 0
self.reading_stdin = False
self.suspend_input = False
self.shutting_down = False
def set_repeat(self, line=None):
if line and Set_params["repeat_interval"]:
self.repeat_line = line
self.repeat_count = REPEAT_COUNT
self.repeat_interval = Set_params["repeat_interval"]
else:
self.repeat_line = None
self.repeat_count = 0
self.repeat_interval = None
def has_trc(self, trace_attr):
""" Return True if self.locals_dict[TRACE_INFO] has attribute."""
return self.locals_dict and TRACE_INFO in self.locals_dict and trace_attr in self.locals_dict[TRACE_INFO]
def get_trc(self, trace_attr, default=None):
""" Return self.locals_dict[TRACE_INFO][trace_attr] or default."""
if self.locals_dict and TRACE_INFO in self.locals_dict:
return self.locals_dict[TRACE_INFO].get(trace_attr, default)
else:
return default
def set_trc(self, trace_attr, value):
""" Set self.locals_dict[TRACE_INFO][trace_attr] to value."""
if TRACE_INFO not in self.locals_dict:
self.locals_dict[TRACE_INFO] = {}
self.locals_dict[TRACE_INFO][trace_attr] = value
def loop(self, wait_to_run=False):
"""Start trace input loop.
If wait_to_run, block until run command is issued in oshell.
(wait_to_run requires new_thread or no_input)
If not no_input, block until shutdown.
"""
if wait_to_run:
assert self.thread or self.no_input
self.queue = Queue.Queue()
self.expect_run = True
if self.thread:
self.thread.start()
else:
# Blocks if not no_input
self.run()
if not wait_to_run:
return
while not self.shutting_down:
try:
run_args = self.queue.get(block=True, timeout=1)
except Queue.Empty:
run_args = None
if run_args:
self.expect_run = False
try:
retval = run_args[0](run_args[1])
run_msg = "Run completed"
except Exception, excp:
run_msg = "Error in completed run\n"+format_traceback()
finally:
self.expect_run = True
OTrace.callback_handler.logmessage(None, run_msg)
def run(self):
self.reading_stdin = (not self.no_input)
self.display_banner()
self.interact()
def display_banner(self):
banner = self.banner
for msg in Banner_messages:
banner += "\n" + msg
banner += "\n ^C to terminate program"
self.std_output("%s\n" % str(banner))
def resetbuffer(self):
self.buffer = []
@classmethod
def invoke_debugger(cls, action="pdb"):
if cls.instance:
cls.instance.suspend_input = True
if action == "ipdb":
try:
import ipdb
ipdb.set_trace()
except ImportError:
import pdb
pdb.set_trace()
else:
import pdb
pdb.set_trace()
if cls.instance:
cls.instance.suspend_input = False
def interact(self):
more = False
noprompt = False
while not self.shutting_down:
try:
if noprompt or self.repeat_interval:
prompt = ""