Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

486 Zeilen
17KB

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