-
Notifications
You must be signed in to change notification settings - Fork 172
/
tracer.py
215 lines (162 loc) · 4.61 KB
/
tracer.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
#!/usr/bin/env python
import json
import linecache
import os
import sys
import threading
import inspect
import time
import socket
state = {
'speed': 'slow'
}
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 4387))
s.setblocking(False)
def debounce(wait):
def decorator(fn):
class context:
last_call = None
def debounced(*args, **kwargs):
def call_it():
args, kwargs = context.last_call
fn(*args, **kwargs)
context.last_call = None
if context.last_call is None:
debounced.t = threading.Timer(wait, call_it)
debounced.t.start()
context.last_call = (args, kwargs)
return debounced
return decorator
def log(msg):
try:
s.send(bytes(msg+'\n', 'utf8'))
except:
s.send(msg+'\n')
@debounce(0.1)
def log_frame(frame):
log(json.dumps(generate_call_event(frame)))
starting_filename = os.path.abspath(sys.argv[1])
starting_dir = os.path.dirname(starting_filename)
os.chdir(starting_dir)
sys.path.insert(0, starting_dir)
current_filename = None
current_line = None
current_locals = {}
failed = False
def should_ignore_variable(name):
return name.startswith('__') and name.endswith('__')
def truncate_list(l):
if len(l) > 3:
ret = ', '.join(map(process_variable, l[:2]))
ret += ", ..., "
ret += process_variable(l[-1])
return ret
else:
return ', '.join(map(process_variable, l))
def format_function(f):
args = inspect.getargspec(f).args
return "function(%s)" % truncate_list(args)
def format_list(l):
return "[%s]" % truncate_list(l)
def process_variable(var):
type_name = type(var).__name__
if type_name == 'list':
return format_list(var)
elif type_name == 'module':
return "<module '%s'>" % var.__name__
else:
return str(var)
def get_module_name(full_path):
global starting_filename
return os.path.relpath(
os.path.abspath(full_path),
os.path.dirname(os.path.abspath(starting_filename))
)
def generate_call_event(frame):
frame_locals = {k:
{'value': process_variable(v), 'type': type(v).__name__}
for k, v in frame.f_locals.items() if not should_ignore_variable(k)
}
frame_globals = {k:
{'value': process_variable(v), 'type': type(v).__name__}
for k, v in frame.f_globals.items() if not should_ignore_variable(k)
}
obj = {
'type': 'call',
'frame_locals': frame_locals,
'frame_globals': frame_globals,
'filename': get_module_name(frame.f_code.co_filename),
'lineno': frame.f_lineno,
'source': ''.join(linecache.getlines(frame.f_code.co_filename))
}
return obj
def generate_exception_event(e):
return {
'type': 'exception',
'exception_type': type(e).__name__,
'exception_message': str(e),
'filename': current_filename,
'lineno': current_line,
'time': time.time()
}
def process_msg(msg):
global state
if type(msg) == bytes:
msg = msg.decode('utf8')
msg = json.loads(msg)
if msg['type'] == 'change_speed':
print('changed speed')
state['speed'] = msg['speed']
def local_trace(frame, why, arg):
try:
received_msg = s.recv(1024)
process_msg(received_msg)
except:
pass
global current_line
global current_filename
if failed:
return
if why == 'exception':
exc_type = arg[0].__name__
exc_msg = arg[1]
return
current_filename = frame.f_code.co_filename
current_line = frame.f_lineno
if not current_filename.startswith(starting_dir):
return
if 'livepython' in current_filename:
return
if 'site-packages' in current_filename:
return
if 'lib/python' in current_filename:
return
log_frame(frame)
if state['speed'] == 'slow':
time.sleep(1)
return local_trace
def global_trace(frame, why, arg):
return local_trace
with open(starting_filename, 'rb') as fp:
code = compile(fp.read(), starting_filename, 'exec')
namespace = {
'__file__': starting_filename,
'__name__': '__main__',
}
log(json.dumps({
'type': 'start',
'startmodule': starting_filename
}))
sys.settrace(global_trace)
threading.settrace(global_trace)
try:
sys.argv = sys.argv[1:]
exec(code, namespace)
log(json.dumps({'type': 'finish'}))
except Exception as err:
failed = True
log(json.dumps(generate_exception_event(err)))
finally:
sys.settrace(None)
threading.settrace(None)