patcher.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import imp
  2. import sys
  3. from eventlet.support import six
  4. __all__ = ['inject', 'import_patched', 'monkey_patch', 'is_monkey_patched']
  5. __exclude = set(('__builtins__', '__file__', '__name__'))
  6. class SysModulesSaver(object):
  7. """Class that captures some subset of the current state of
  8. sys.modules. Pass in an iterator of module names to the
  9. constructor."""
  10. def __init__(self, module_names=()):
  11. self._saved = {}
  12. imp.acquire_lock()
  13. self.save(*module_names)
  14. def save(self, *module_names):
  15. """Saves the named modules to the object."""
  16. for modname in module_names:
  17. self._saved[modname] = sys.modules.get(modname, None)
  18. def restore(self):
  19. """Restores the modules that the saver knows about into
  20. sys.modules.
  21. """
  22. try:
  23. for modname, mod in six.iteritems(self._saved):
  24. if mod is not None:
  25. sys.modules[modname] = mod
  26. else:
  27. try:
  28. del sys.modules[modname]
  29. except KeyError:
  30. pass
  31. finally:
  32. imp.release_lock()
  33. def inject(module_name, new_globals, *additional_modules):
  34. """Base method for "injecting" greened modules into an imported module. It
  35. imports the module specified in *module_name*, arranging things so
  36. that the already-imported modules in *additional_modules* are used when
  37. *module_name* makes its imports.
  38. **Note:** This function does not create or change any sys.modules item, so
  39. if your greened module use code like 'sys.modules["your_module_name"]', you
  40. need to update sys.modules by yourself.
  41. *new_globals* is either None or a globals dictionary that gets populated
  42. with the contents of the *module_name* module. This is useful when creating
  43. a "green" version of some other module.
  44. *additional_modules* should be a collection of two-element tuples, of the
  45. form (<name>, <module>). If it's not specified, a default selection of
  46. name/module pairs is used, which should cover all use cases but may be
  47. slower because there are inevitably redundant or unnecessary imports.
  48. """
  49. patched_name = '__patched_module_' + module_name
  50. if patched_name in sys.modules:
  51. # returning already-patched module so as not to destroy existing
  52. # references to patched modules
  53. return sys.modules[patched_name]
  54. if not additional_modules:
  55. # supply some defaults
  56. additional_modules = (
  57. _green_os_modules() +
  58. _green_select_modules() +
  59. _green_socket_modules() +
  60. _green_thread_modules() +
  61. _green_time_modules())
  62. # _green_MySQLdb()) # enable this after a short baking-in period
  63. # after this we are gonna screw with sys.modules, so capture the
  64. # state of all the modules we're going to mess with, and lock
  65. saver = SysModulesSaver([name for name, m in additional_modules])
  66. saver.save(module_name)
  67. # Cover the target modules so that when you import the module it
  68. # sees only the patched versions
  69. for name, mod in additional_modules:
  70. sys.modules[name] = mod
  71. # Remove the old module from sys.modules and reimport it while
  72. # the specified modules are in place
  73. sys.modules.pop(module_name, None)
  74. try:
  75. module = __import__(module_name, {}, {}, module_name.split('.')[:-1])
  76. if new_globals is not None:
  77. # Update the given globals dictionary with everything from this new module
  78. for name in dir(module):
  79. if name not in __exclude:
  80. new_globals[name] = getattr(module, name)
  81. # Keep a reference to the new module to prevent it from dying
  82. sys.modules[patched_name] = module
  83. finally:
  84. saver.restore() # Put the original modules back
  85. return module
  86. def import_patched(module_name, *additional_modules, **kw_additional_modules):
  87. """Imports a module in a way that ensures that the module uses "green"
  88. versions of the standard library modules, so that everything works
  89. nonblockingly.
  90. The only required argument is the name of the module to be imported.
  91. """
  92. return inject(
  93. module_name,
  94. None,
  95. *additional_modules + tuple(kw_additional_modules.items()))
  96. def patch_function(func, *additional_modules):
  97. """Decorator that returns a version of the function that patches
  98. some modules for the duration of the function call. This is
  99. deeply gross and should only be used for functions that import
  100. network libraries within their function bodies that there is no
  101. way of getting around."""
  102. if not additional_modules:
  103. # supply some defaults
  104. additional_modules = (
  105. _green_os_modules() +
  106. _green_select_modules() +
  107. _green_socket_modules() +
  108. _green_thread_modules() +
  109. _green_time_modules())
  110. def patched(*args, **kw):
  111. saver = SysModulesSaver()
  112. for name, mod in additional_modules:
  113. saver.save(name)
  114. sys.modules[name] = mod
  115. try:
  116. return func(*args, **kw)
  117. finally:
  118. saver.restore()
  119. return patched
  120. def _original_patch_function(func, *module_names):
  121. """Kind of the contrapositive of patch_function: decorates a
  122. function such that when it's called, sys.modules is populated only
  123. with the unpatched versions of the specified modules. Unlike
  124. patch_function, only the names of the modules need be supplied,
  125. and there are no defaults. This is a gross hack; tell your kids not
  126. to import inside function bodies!"""
  127. def patched(*args, **kw):
  128. saver = SysModulesSaver(module_names)
  129. for name in module_names:
  130. sys.modules[name] = original(name)
  131. try:
  132. return func(*args, **kw)
  133. finally:
  134. saver.restore()
  135. return patched
  136. def original(modname):
  137. """ This returns an unpatched version of a module; this is useful for
  138. Eventlet itself (i.e. tpool)."""
  139. # note that it's not necessary to temporarily install unpatched
  140. # versions of all patchable modules during the import of the
  141. # module; this is because none of them import each other, except
  142. # for threading which imports thread
  143. original_name = '__original_module_' + modname
  144. if original_name in sys.modules:
  145. return sys.modules.get(original_name)
  146. # re-import the "pure" module and store it in the global _originals
  147. # dict; be sure to restore whatever module had that name already
  148. saver = SysModulesSaver((modname,))
  149. sys.modules.pop(modname, None)
  150. # some rudimentary dependency checking -- fortunately the modules
  151. # we're working on don't have many dependencies so we can just do
  152. # some special-casing here
  153. if six.PY2:
  154. deps = {'threading': 'thread', 'Queue': 'threading'}
  155. if six.PY3:
  156. deps = {'threading': '_thread', 'queue': 'threading'}
  157. if modname in deps:
  158. dependency = deps[modname]
  159. saver.save(dependency)
  160. sys.modules[dependency] = original(dependency)
  161. try:
  162. real_mod = __import__(modname, {}, {}, modname.split('.')[:-1])
  163. if modname in ('Queue', 'queue') and not hasattr(real_mod, '_threading'):
  164. # tricky hack: Queue's constructor in <2.7 imports
  165. # threading on every instantiation; therefore we wrap
  166. # it so that it always gets the original threading
  167. real_mod.Queue.__init__ = _original_patch_function(
  168. real_mod.Queue.__init__,
  169. 'threading')
  170. # save a reference to the unpatched module so it doesn't get lost
  171. sys.modules[original_name] = real_mod
  172. finally:
  173. saver.restore()
  174. return sys.modules[original_name]
  175. already_patched = {}
  176. def monkey_patch(**on):
  177. """Globally patches certain system modules to be greenthread-friendly.
  178. The keyword arguments afford some control over which modules are patched.
  179. If no keyword arguments are supplied, all possible modules are patched.
  180. If keywords are set to True, only the specified modules are patched. E.g.,
  181. ``monkey_patch(socket=True, select=True)`` patches only the select and
  182. socket modules. Most arguments patch the single module of the same name
  183. (os, time, select). The exceptions are socket, which also patches the ssl
  184. module if present; and thread, which patches thread, threading, and Queue.
  185. It's safe to call monkey_patch multiple times.
  186. """
  187. accepted_args = set(('os', 'select', 'socket',
  188. 'thread', 'time', 'psycopg', 'MySQLdb',
  189. 'builtins', 'subprocess'))
  190. # To make sure only one of them is passed here
  191. assert not ('__builtin__' in on and 'builtins' in on)
  192. try:
  193. b = on.pop('__builtin__')
  194. except KeyError:
  195. pass
  196. else:
  197. on['builtins'] = b
  198. default_on = on.pop("all", None)
  199. for k in six.iterkeys(on):
  200. if k not in accepted_args:
  201. raise TypeError("monkey_patch() got an unexpected "
  202. "keyword argument %r" % k)
  203. if default_on is None:
  204. default_on = not (True in on.values())
  205. for modname in accepted_args:
  206. if modname == 'MySQLdb':
  207. # MySQLdb is only on when explicitly patched for the moment
  208. on.setdefault(modname, False)
  209. if modname == 'builtins':
  210. on.setdefault(modname, False)
  211. on.setdefault(modname, default_on)
  212. if on['thread'] and not already_patched.get('thread'):
  213. _green_existing_locks()
  214. modules_to_patch = []
  215. for name, modules_function in [
  216. ('os', _green_os_modules),
  217. ('select', _green_select_modules),
  218. ('socket', _green_socket_modules),
  219. ('thread', _green_thread_modules),
  220. ('time', _green_time_modules),
  221. ('MySQLdb', _green_MySQLdb),
  222. ('builtins', _green_builtins),
  223. ('subprocess', _green_subprocess_modules),
  224. ]:
  225. if on[name] and not already_patched.get(name):
  226. modules_to_patch += modules_function()
  227. already_patched[name] = True
  228. if on['psycopg'] and not already_patched.get('psycopg'):
  229. try:
  230. from eventlet.support import psycopg2_patcher
  231. psycopg2_patcher.make_psycopg_green()
  232. already_patched['psycopg'] = True
  233. except ImportError:
  234. # note that if we get an importerror from trying to
  235. # monkeypatch psycopg, we will continually retry it
  236. # whenever monkey_patch is called; this should not be a
  237. # performance problem but it allows is_monkey_patched to
  238. # tell us whether or not we succeeded
  239. pass
  240. imp.acquire_lock()
  241. try:
  242. for name, mod in modules_to_patch:
  243. orig_mod = sys.modules.get(name)
  244. if orig_mod is None:
  245. orig_mod = __import__(name)
  246. for attr_name in mod.__patched__:
  247. patched_attr = getattr(mod, attr_name, None)
  248. if patched_attr is not None:
  249. setattr(orig_mod, attr_name, patched_attr)
  250. deleted = getattr(mod, '__deleted__', [])
  251. for attr_name in deleted:
  252. if hasattr(orig_mod, attr_name):
  253. delattr(orig_mod, attr_name)
  254. finally:
  255. imp.release_lock()
  256. if sys.version_info >= (3, 3):
  257. import importlib._bootstrap
  258. thread = original('_thread')
  259. # importlib must use real thread locks, not eventlet.Semaphore
  260. importlib._bootstrap._thread = thread
  261. # Issue #185: Since Python 3.3, threading.RLock is implemented in C and
  262. # so call a C function to get the thread identifier, instead of calling
  263. # threading.get_ident(). Force the Python implementation of RLock which
  264. # calls threading.get_ident() and so is compatible with eventlet.
  265. import threading
  266. threading.RLock = threading._PyRLock
  267. def is_monkey_patched(module):
  268. """Returns True if the given module is monkeypatched currently, False if
  269. not. *module* can be either the module itself or its name.
  270. Based entirely off the name of the module, so if you import a
  271. module some other way than with the import keyword (including
  272. import_patched), this might not be correct about that particular
  273. module."""
  274. return module in already_patched or \
  275. getattr(module, '__name__', None) in already_patched
  276. def _green_existing_locks():
  277. """Make locks created before monkey-patching safe.
  278. RLocks rely on a Lock and on Python 2, if an unpatched Lock blocks, it
  279. blocks the native thread. We need to replace these with green Locks.
  280. This was originally noticed in the stdlib logging module."""
  281. import gc
  282. import threading
  283. import eventlet.green.thread
  284. lock_type = type(threading.Lock())
  285. rlock_type = type(threading.RLock())
  286. if sys.version_info[0] >= 3:
  287. pyrlock_type = type(threading._PyRLock())
  288. # We're monkey-patching so there can't be any greenlets yet, ergo our thread
  289. # ID is the only valid owner possible.
  290. tid = eventlet.green.thread.get_ident()
  291. for obj in gc.get_objects():
  292. if isinstance(obj, rlock_type):
  293. if (sys.version_info[0] == 2 and
  294. isinstance(obj._RLock__block, lock_type)):
  295. _fix_py2_rlock(obj, tid)
  296. elif (sys.version_info[0] >= 3 and
  297. not isinstance(obj, pyrlock_type)):
  298. _fix_py3_rlock(obj)
  299. def _fix_py2_rlock(rlock, tid):
  300. import eventlet.green.threading
  301. old = rlock._RLock__block
  302. new = eventlet.green.threading.Lock()
  303. rlock._RLock__block = new
  304. if old.locked():
  305. new.acquire()
  306. rlock._RLock__owner = tid
  307. def _fix_py3_rlock(old):
  308. import gc
  309. import threading
  310. new = threading._PyRLock()
  311. while old._is_owned():
  312. old.release()
  313. new.acquire()
  314. if old._is_owned():
  315. new.acquire()
  316. gc.collect()
  317. for ref in gc.get_referrers(old):
  318. try:
  319. ref_vars = vars(ref)
  320. except TypeError:
  321. pass
  322. else:
  323. for k, v in ref_vars.items():
  324. if v == old:
  325. setattr(ref, k, new)
  326. def _green_os_modules():
  327. from eventlet.green import os
  328. return [('os', os)]
  329. def _green_select_modules():
  330. from eventlet.green import select
  331. modules = [('select', select)]
  332. if sys.version_info >= (3, 4):
  333. from eventlet.green import selectors
  334. modules.append(('selectors', selectors))
  335. return modules
  336. def _green_socket_modules():
  337. from eventlet.green import socket
  338. try:
  339. from eventlet.green import ssl
  340. return [('socket', socket), ('ssl', ssl)]
  341. except ImportError:
  342. return [('socket', socket)]
  343. def _green_subprocess_modules():
  344. from eventlet.green import subprocess
  345. return [('subprocess', subprocess)]
  346. def _green_thread_modules():
  347. from eventlet.green import Queue
  348. from eventlet.green import thread
  349. from eventlet.green import threading
  350. if six.PY2:
  351. return [('Queue', Queue), ('thread', thread), ('threading', threading)]
  352. if six.PY3:
  353. return [('queue', Queue), ('_thread', thread), ('threading', threading)]
  354. def _green_time_modules():
  355. from eventlet.green import time
  356. return [('time', time)]
  357. def _green_MySQLdb():
  358. try:
  359. from eventlet.green import MySQLdb
  360. return [('MySQLdb', MySQLdb)]
  361. except ImportError:
  362. return []
  363. def _green_builtins():
  364. try:
  365. from eventlet.green import builtin
  366. return [('__builtin__' if six.PY2 else 'builtins', builtin)]
  367. except ImportError:
  368. return []
  369. def slurp_properties(source, destination, ignore=[], srckeys=None):
  370. """Copy properties from *source* (assumed to be a module) to
  371. *destination* (assumed to be a dict).
  372. *ignore* lists properties that should not be thusly copied.
  373. *srckeys* is a list of keys to copy, if the source's __all__ is
  374. untrustworthy.
  375. """
  376. if srckeys is None:
  377. srckeys = source.__all__
  378. destination.update(dict([
  379. (name, getattr(source, name))
  380. for name in srckeys
  381. if not (name.startswith('__') or name in ignore)
  382. ]))
  383. if __name__ == "__main__":
  384. sys.argv.pop(0)
  385. monkey_patch()
  386. with open(sys.argv[0]) as f:
  387. code = compile(f.read(), sys.argv[0], 'exec')
  388. exec(code)