-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmonkeypatch.py
More file actions
334 lines (294 loc) · 9.82 KB
/
monkeypatch.py
File metadata and controls
334 lines (294 loc) · 9.82 KB
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
#monkeypatch.py
#
import sys
import threading as real_threading
import contextlib
from . import main
from .replacements import thread, threading, popen
from .app import sleep as app_sleep
from .threadpool import call_on_thread
# Use stacklessio if available
try:
import stacklessio
except ImportError:
stacklessio = False
# First of all, a set of helper functions to do monkey patching
@contextlib.contextmanager
def stored_modules(modules):
"""
A context manager that stores the appropriate values of sys.modules
and restores them afterwards
"""
stored = []
sentinel = object()
for m in modules:
mod = sys.modules.get(m, sentinel)
stored.append((m, mod))
try:
yield
finally:
for m, mod in stored:
if mod is not sentinel:
sys.modules[m] = mod
else:
try:
del sys.modules[m]
except KeyError:
pass
@contextlib.contextmanager
def cleared_modules(modules):
"""
A context manager which clears the specified modules, i.e. removes them from sys.modules,
for the duration, and then restores them to the previous state. Useful to force the load
of a particular module.
"""
with stored_modules(modules):
for m in modules:
del sys.modules[m]
yield
@contextlib.contextmanager
def patched(targetname, value, up=0):
"""
Patch an attribute of a named object. The object is found in the locals or globals
and its attributes descended as appropriate.
"""
frame = sys._getframe(up+1)
parts = targetname.rsplit(".", 1)
if len(parts) == 2:
# at least one dot. Copmute head . [mid] . attr
path, attr = parts
parts = path.split(".")
head = parts[0]
mid = pargs[1:]
# find the root object
where, obj = find_name(frame, head)
# descend to the final part
for s in mid:
obj = getattr(obj, s)
with patched_attribute(obj, attr) as old:
yield old
else:
# only a single object named
where, obj = find_name(frame, targetname)
with patched_dict(where, targetname, object) as old:
yield old
def find_name(frame, name):
"""
find 'name' in a frame's locals or globals and return the corresponding
dict along with its object
"""
if name in frame.f_locals:
return f_locals, f_locals[name]
elif name in frame.f_globals:
return f_globals, f_globals[name]
raise NameError("name %r is not found" % name)
@contextlib.contextmanager
def patched_dictitem(d, name, object):
"""
Patch an item in a dict
"""
try:
old = d[name]
except KeyError:
d[name] = object
try:
yield
finally:
del d[name]
else:
d[name] = object
try:
yield old
finally:
d[name] = old
@contextlib.contextmanager
def patched_attribute(object, attribute, new_object):
"""
Patch an named attribute of a given object with a target object for the duration
"""
try:
old = getattr(object, attribute)
except AttributeError:
setattr(object, attribute, new_object)
try:
yield
finally:
delattr(object, attribute)
else:
setattr(object, attribute, new_object)
try:
yield old
finally:
setattr(object, attribute, old)
@contextlib.contextmanager
def patched_module(name, module, soft=False):
"""
Patch a named module with an alternative module. If the target
module already exists, its dict is updated. This is to sneak
the new module into places where import has already been performed.
"""
old = sys.modules.get(name, None)
if not old or soft:
sys.modules[name] = module
try:
yield old
finally:
if old:
sys.modules[name] = old
else:
del sys.modules[name]
else:
# hard monkeypatching, trampling over old instance
olddict = dict(old.__dict__)
old.__dict__.clear()
old.__dict__.update(module.__dict__)
try:
yield old
finally:
old.__dict__.clear()
old.__dict__.update(olddict)
# helper functions to disentangle a context manager, e.g. for
# unittests
def cm_start(contextmanager):
"""
Enter a context manager. The result of this function should be passed
to ``cm_stop()`` to exit the context manager.
"""
contextmanager.__enter__()
return contextmanager
def cm_stop(ctxt):
"""
Leave a context manager. Call with the return value of ``cm_start()``
"""
ctxt.__exit__(None, None, None)
def patch_all():
patch_misc()
patch_thread()
patch_threading()
patch_select()
patch_socket()
patch_ssl()
def patch_misc():
# Fudge time.sleep.
import time
sleep_orig = time.sleep
time.sleep = main.sleep
if not hasattr(time, "real_sleep"):
time.real_sleep = sleep_orig
# Fudge popen4 (if it exists).
import os
if hasattr(os, "popen4"):
real_popen4 = os.popen4
os.popen4 = popen.popen4
if not hasattr(os, "real_popen4"):
os.real_popen4 = real_popen4
def patch_thread():
import thread as real_thread
if not hasattr(thread, "real_thread"):
thread.real_thread = real_thread
sys.modules["thread"] = thread
def patch_threading():
if not hasattr(threading, "real_threading"):
threading.real_threading = real_threading
sys.modules["threading"] = threading
def patch_select():
""" Selectively choose to monkey-patch the 'select' module. """
if stacklessio:
from stacklessio import select
else:
from stacklesslib.replacements import select
import select as real_select
if not hasattr(select, "real_select"):
select.real_select = real_select
sys.modules["select"] = select
def patch_socket(will_be_pumped=True):
"""
Selectively choose to monkey-patch the 'socket' module.
If 'will_be_pumped' is set to False, the patched socket module will take
care of polling networking events in a scheduled tasklet. Otherwise, the
controlling application is responsible for pumping these events.
"""
if stacklessio:
from stacklessio import _socket
sys.modules["_socket"] = _socket
else:
# Fallback on the generic 'stacklesssocket' module.
from stacklesslib.replacements import socket
socket._sleep_func = app_sleep
socket._schedule_func = lambda: app_sleep(0)
if will_be_pumped:
#We will pump it somehow. Tell the mainloop to pump it too.
socket.stacklesssocket_manager(None)
socket.StopManager()
def pump():
with Unpatched():
socket.pump()
main.mainloop.add_pump(pump)
socket.install()
def patch_ssl():
"""
Patch using a modified _ssl module which allows wrapping any
Python object, not just sockets.
"""
try:
import _ssl
import socket
import errno
from cStringIO import StringIO
except ImportError:
return
from . import util
class SocketBio(object):
"""This PyBio for the builtin SSL module implements receive buffering
for performance"""
default_bufsize = 8192 #read buffer size
def __init__(self, sock, rbufsize=-1):
self.sock = sock
self.bufsize = self.default_bufsize if rbufsize < 0 else rbufsize
if self.bufsize:
self.buf = StringIO()
def write(self, data):
return self.wrap_errors("write", self.sock.send, (data,))
def read(self, want):
if self.bufsize:
data = self.buf.read(want)
if not data:
buf = self.wrap_errors("read", self.sock.recv, (self.bufsize,))
self.buf = StringIO(buf)
data = self.buf.read(want)
else:
data = self.wrap_errors("read", self.sock.recv, (want,))
return data
def wrap_errors(self, name, call, args):
try:
return call(*args)
except socket.timeout:
if self.sock.gettimeout() == 0.0:
return None if name=="read" else 0 #signal EWOULDBLOCK
#create the exact same error as the _ssl module would
raise _ssl.SSLError("The %s operation timed out" % (name,))
except socket.error as e:
#signal EWOULDBLOCK
if e.errno == errno.EWOULDBLOCK:
return None if name=="read" else 0
raise
#pass on stuff to the internal sock object, so that
#unwrapping works
def __getattr__(self, attr):
return getattr(self.sock, attr)
realwrap = _ssl.sslwrap
def wrapbio(sock, *args, **kwds):
bio = SocketBio(sock)
return call_on_thread(realwrap, (bio,)+args, kwds)
_ssl.sslwrap = wrapbio
@contextlib.contextmanager
def Unpatched():
""" A context manager that temporarily un-monkeypatches sleep and select """
import time, select
old = time.sleep, select.select
new = getattr(time, "real_sleep", time.sleep), getattr(select, "real_select", select).select
time.sleep, select.select = new
try:
yield
finally:
time.sleep, select.select = old