patcher.py 17 KB

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