registry.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. # (c) 2005 Ben Bangert
  2. # This module is part of the Python Paste Project and is released under
  3. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  4. """Registry for handling request-local module globals sanely
  5. Dealing with module globals in a thread-safe way is good if your
  6. application is the sole responder in a thread, however that approach fails
  7. to properly account for various scenarios that occur with WSGI applications
  8. and middleware.
  9. What is actually needed in the case where a module global is desired that
  10. is always set properly depending on the current request, is a stacked
  11. thread-local object. Such an object is popped or pushed during the request
  12. cycle so that it properly represents the object that should be active for
  13. the current request.
  14. To make it easy to deal with such variables, this module provides a special
  15. StackedObjectProxy class which you can instantiate and attach to your
  16. module where you'd like others to access it. The object you'd like this to
  17. actually "be" during the request is then registered with the
  18. RegistryManager middleware, which ensures that for the scope of the current
  19. WSGI application everything will work properly.
  20. Example:
  21. .. code-block:: python
  22. #yourpackage/__init__.py
  23. from paste.registry import RegistryManager, StackedObjectProxy
  24. myglobal = StackedObjectProxy()
  25. #wsgi app stack
  26. app = RegistryManager(yourapp)
  27. #inside your wsgi app
  28. class yourapp(object):
  29. def __call__(self, environ, start_response):
  30. obj = someobject # The request-local object you want to access
  31. # via yourpackage.myglobal
  32. if environ.has_key('paste.registry'):
  33. environ['paste.registry'].register(myglobal, obj)
  34. You will then be able to import yourpackage anywhere in your WSGI app or in
  35. the calling stack below it and be assured that it is using the object you
  36. registered with Registry.
  37. RegistryManager can be in the WSGI stack multiple times, each time it
  38. appears it registers a new request context.
  39. Performance
  40. ===========
  41. The overhead of the proxy object is very minimal, however if you are using
  42. proxy objects extensively (Thousands of accesses per request or more), there
  43. are some ways to avoid them. A proxy object runs approximately 3-20x slower
  44. than direct access to the object, this is rarely your performance bottleneck
  45. when developing web applications.
  46. Should you be developing a system which may be accessing the proxy object
  47. thousands of times per request, the performance of the proxy will start to
  48. become more noticeable. In that circumstance, the problem can be avoided by
  49. getting at the actual object via the proxy with the ``_current_obj`` function:
  50. .. code-block:: python
  51. #sessions.py
  52. Session = StackedObjectProxy()
  53. # ... initialization code, etc.
  54. # somemodule.py
  55. import sessions
  56. def somefunc():
  57. session = sessions.Session._current_obj()
  58. # ... tons of session access
  59. This way the proxy is used only once to retrieve the object for the current
  60. context and the overhead is minimized while still making it easy to access
  61. the underlying object. The ``_current_obj`` function is preceded by an
  62. underscore to more likely avoid clashing with the contained object's
  63. attributes.
  64. **NOTE:** This is *highly* unlikely to be an issue in the vast majority of
  65. cases, and requires incredibly large amounts of proxy object access before
  66. one should consider the proxy object to be causing slow-downs. This section
  67. is provided solely in the extremely rare case that it is an issue so that a
  68. quick way to work around it is documented.
  69. """
  70. import sys
  71. import paste.util.threadinglocal as threadinglocal
  72. __all__ = ['StackedObjectProxy', 'RegistryManager', 'StackedObjectRestorer',
  73. 'restorer']
  74. class NoDefault(object): pass
  75. class StackedObjectProxy(object):
  76. """Track an object instance internally using a stack
  77. The StackedObjectProxy proxies access to an object internally using a
  78. stacked thread-local. This makes it safe for complex WSGI environments
  79. where access to the object may be desired in multiple places without
  80. having to pass the actual object around.
  81. New objects are added to the top of the stack with _push_object while
  82. objects can be removed with _pop_object.
  83. """
  84. def __init__(self, default=NoDefault, name="Default"):
  85. """Create a new StackedObjectProxy
  86. If a default is given, its used in every thread if no other object
  87. has been pushed on.
  88. """
  89. self.__dict__['____name__'] = name
  90. self.__dict__['____local__'] = threadinglocal.local()
  91. if default is not NoDefault:
  92. self.__dict__['____default_object__'] = default
  93. def __dir__(self):
  94. """Return a list of the StackedObjectProxy's and proxied
  95. object's (if one exists) names.
  96. """
  97. dir_list = dir(self.__class__) + self.__dict__.keys()
  98. try:
  99. dir_list.extend(dir(self._current_obj()))
  100. except TypeError:
  101. pass
  102. dir_list.sort()
  103. return dir_list
  104. def __getattr__(self, attr):
  105. return getattr(self._current_obj(), attr)
  106. def __setattr__(self, attr, value):
  107. setattr(self._current_obj(), attr, value)
  108. def __delattr__(self, name):
  109. delattr(self._current_obj(), name)
  110. def __getitem__(self, key):
  111. return self._current_obj()[key]
  112. def __setitem__(self, key, value):
  113. self._current_obj()[key] = value
  114. def __delitem__(self, key):
  115. del self._current_obj()[key]
  116. def __call__(self, *args, **kw):
  117. return self._current_obj()(*args, **kw)
  118. def __repr__(self):
  119. try:
  120. return repr(self._current_obj())
  121. except (TypeError, AttributeError):
  122. return '<%s.%s object at 0x%x>' % (self.__class__.__module__,
  123. self.__class__.__name__,
  124. id(self))
  125. def __iter__(self):
  126. return iter(self._current_obj())
  127. def __len__(self):
  128. return len(self._current_obj())
  129. def __contains__(self, key):
  130. return key in self._current_obj()
  131. def __nonzero__(self):
  132. return bool(self._current_obj())
  133. def _current_obj(self):
  134. """Returns the current active object being proxied to
  135. In the event that no object was pushed, the default object if
  136. provided will be used. Otherwise, a TypeError will be raised.
  137. """
  138. objects = getattr(self.____local__, 'objects', None)
  139. if objects:
  140. return objects[-1]
  141. else:
  142. obj = self.__dict__.get('____default_object__', NoDefault)
  143. if obj is not NoDefault:
  144. return obj
  145. else:
  146. raise TypeError(
  147. 'No object (name: %s) has been registered for this '
  148. 'thread' % self.____name__)
  149. def _push_object(self, obj):
  150. """Make ``obj`` the active object for this thread-local.
  151. This should be used like:
  152. .. code-block:: python
  153. obj = yourobject()
  154. module.glob = StackedObjectProxy()
  155. module.glob._push_object(obj)
  156. try:
  157. ... do stuff ...
  158. finally:
  159. module.glob._pop_object(conf)
  160. """
  161. if not hasattr(self.____local__, 'objects'):
  162. self.____local__.objects = []
  163. self.____local__.objects.append(obj)
  164. def _pop_object(self, obj=None):
  165. """Remove a thread-local object.
  166. If ``obj`` is given, it is checked against the popped object and an
  167. error is emitted if they don't match.
  168. """
  169. if not hasattr(self.____local__, 'objects'):
  170. raise AssertionError('No object has been registered for this thread')
  171. popped = self.____local__.objects.pop()
  172. if obj:
  173. if popped is not obj:
  174. raise AssertionError(
  175. 'The object popped (%s) is not the same as the object '
  176. 'expected (%s)' % (popped, obj))
  177. def _object_stack(self):
  178. """Returns all of the objects stacked in this container
  179. (Might return [] if there are none)
  180. """
  181. try:
  182. return self.____local__.objects[:]
  183. except AssertionError:
  184. return []
  185. # The following methods will be swapped for their original versions by
  186. # StackedObjectRestorer when restoration is enabled. The original
  187. # functions (e.g. _current_obj) will be available at _current_obj_orig
  188. def _current_obj_restoration(self):
  189. request_id = restorer.in_restoration()
  190. if request_id:
  191. return restorer.get_saved_proxied_obj(self, request_id)
  192. return self._current_obj_orig()
  193. _current_obj_restoration.__doc__ = \
  194. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  195. _current_obj.__doc__)
  196. def _push_object_restoration(self, obj):
  197. if not restorer.in_restoration():
  198. self._push_object_orig(obj)
  199. _push_object_restoration.__doc__ = \
  200. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  201. _push_object.__doc__)
  202. def _pop_object_restoration(self, obj=None):
  203. if not restorer.in_restoration():
  204. self._pop_object_orig(obj)
  205. _pop_object_restoration.__doc__ = \
  206. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  207. _pop_object.__doc__)
  208. class Registry(object):
  209. """Track objects and stacked object proxies for removal
  210. The Registry object is instantiated a single time for the request no
  211. matter how many times the RegistryManager is used in a WSGI stack. Each
  212. RegistryManager must call ``prepare`` before continuing the call to
  213. start a new context for object registering.
  214. Each context is tracked with a dict inside a list. The last list
  215. element is the currently executing context. Each context dict is keyed
  216. by the id of the StackedObjectProxy instance being proxied, the value
  217. is a tuple of the StackedObjectProxy instance and the object being
  218. tracked.
  219. """
  220. def __init__(self):
  221. """Create a new Registry object
  222. ``prepare`` must still be called before this Registry object can be
  223. used to register objects.
  224. """
  225. self.reglist = []
  226. def prepare(self):
  227. """Used to create a new registry context
  228. Anytime a new RegistryManager is called, ``prepare`` needs to be
  229. called on the existing Registry object. This sets up a new context
  230. for registering objects.
  231. """
  232. self.reglist.append({})
  233. def register(self, stacked, obj):
  234. """Register an object with a StackedObjectProxy"""
  235. myreglist = self.reglist[-1]
  236. stacked_id = id(stacked)
  237. if stacked_id in myreglist:
  238. stacked._pop_object(myreglist[stacked_id][1])
  239. del myreglist[stacked_id]
  240. stacked._push_object(obj)
  241. myreglist[stacked_id] = (stacked, obj)
  242. # Replace now does the same thing as register
  243. replace = register
  244. def cleanup(self):
  245. """Remove all objects from all StackedObjectProxy instances that
  246. were tracked at this Registry context"""
  247. for stacked, obj in self.reglist[-1].itervalues():
  248. stacked._pop_object(obj)
  249. self.reglist.pop()
  250. class RegistryManager(object):
  251. """Creates and maintains a Registry context
  252. RegistryManager creates a new registry context for the registration of
  253. StackedObjectProxy instances. Multiple RegistryManager's can be in a
  254. WSGI stack and will manage the context so that the StackedObjectProxies
  255. always proxy to the proper object.
  256. The object being registered can be any object sub-class, list, or dict.
  257. Registering objects is done inside a WSGI application under the
  258. RegistryManager instance, using the ``environ['paste.registry']``
  259. object which is a Registry instance.
  260. """
  261. def __init__(self, application, streaming=False):
  262. self.application = application
  263. self.streaming = streaming
  264. def __call__(self, environ, start_response):
  265. app_iter = None
  266. reg = environ.setdefault('paste.registry', Registry())
  267. reg.prepare()
  268. if self.streaming:
  269. return self.streaming_iter(reg, environ, start_response)
  270. try:
  271. app_iter = self.application(environ, start_response)
  272. except Exception, e:
  273. # Regardless of if the content is an iterable, generator, list
  274. # or tuple, we clean-up right now. If its an iterable/generator
  275. # care should be used to ensure the generator has its own ref
  276. # to the actual object
  277. if environ.get('paste.evalexception'):
  278. # EvalException is present in the WSGI stack
  279. expected = False
  280. for expect in environ.get('paste.expected_exceptions', []):
  281. if isinstance(e, expect):
  282. expected = True
  283. if not expected:
  284. # An unexpected exception: save state for EvalException
  285. restorer.save_registry_state(environ)
  286. reg.cleanup()
  287. raise
  288. except:
  289. # Save state for EvalException if it's present
  290. if environ.get('paste.evalexception'):
  291. restorer.save_registry_state(environ)
  292. reg.cleanup()
  293. raise
  294. else:
  295. reg.cleanup()
  296. return app_iter
  297. def streaming_iter(self, reg, environ, start_response):
  298. try:
  299. for item in self.application(environ, start_response):
  300. yield item
  301. except Exception, e:
  302. # Regardless of if the content is an iterable, generator, list
  303. # or tuple, we clean-up right now. If its an iterable/generator
  304. # care should be used to ensure the generator has its own ref
  305. # to the actual object
  306. if environ.get('paste.evalexception'):
  307. # EvalException is present in the WSGI stack
  308. expected = False
  309. for expect in environ.get('paste.expected_exceptions', []):
  310. if isinstance(e, expect):
  311. expected = True
  312. if not expected:
  313. # An unexpected exception: save state for EvalException
  314. restorer.save_registry_state(environ)
  315. reg.cleanup()
  316. raise
  317. except:
  318. # Save state for EvalException if it's present
  319. if environ.get('paste.evalexception'):
  320. restorer.save_registry_state(environ)
  321. reg.cleanup()
  322. raise
  323. else:
  324. reg.cleanup()
  325. class StackedObjectRestorer(object):
  326. """Track StackedObjectProxies and their proxied objects for automatic
  327. restoration within EvalException's interactive debugger.
  328. An instance of this class tracks all StackedObjectProxy state in existence
  329. when unexpected exceptions are raised by WSGI applications housed by
  330. EvalException and RegistryManager. Like EvalException, this information is
  331. stored for the life of the process.
  332. When an unexpected exception occurs and EvalException is present in the
  333. WSGI stack, save_registry_state is intended to be called to store the
  334. Registry state and enable automatic restoration on all currently registered
  335. StackedObjectProxies.
  336. With restoration enabled, those StackedObjectProxies' _current_obj
  337. (overwritten by _current_obj_restoration) method's strategy is modified:
  338. it will return its appropriate proxied object from the restorer when
  339. a restoration context is active in the current thread.
  340. The StackedObjectProxies' _push/pop_object methods strategies are also
  341. changed: they no-op when a restoration context is active in the current
  342. thread (because the pushing/popping work is all handled by the
  343. Registry/restorer).
  344. The request's Registry objects' reglists are restored from the restorer
  345. when a restoration context begins, enabling the Registry methods to work
  346. while their changes are tracked by the restorer.
  347. The overhead of enabling restoration is negligible (another threadlocal
  348. access for the changed StackedObjectProxy methods) for normal use outside
  349. of a restoration context, but worth mentioning when combined with
  350. StackedObjectProxies normal overhead. Once enabled it does not turn off,
  351. however:
  352. o Enabling restoration only occurs after an unexpected exception is
  353. detected. The server is likely to be restarted shortly after the exception
  354. is raised to fix the cause
  355. o StackedObjectRestorer is only enabled when EvalException is enabled (not
  356. on a production server) and RegistryManager exists in the middleware
  357. stack"""
  358. def __init__(self):
  359. # Registries and their saved reglists by request_id
  360. self.saved_registry_states = {}
  361. self.restoration_context_id = threadinglocal.local()
  362. def save_registry_state(self, environ):
  363. """Save the state of this request's Registry (if it hasn't already been
  364. saved) to the saved_registry_states dict, keyed by the request's unique
  365. identifier"""
  366. registry = environ.get('paste.registry')
  367. if not registry or not len(registry.reglist) or \
  368. self.get_request_id(environ) in self.saved_registry_states:
  369. # No Registry, no state to save, or this request's state has
  370. # already been saved
  371. return
  372. self.saved_registry_states[self.get_request_id(environ)] = \
  373. (registry, registry.reglist[:])
  374. # Tweak the StackedObjectProxies we want to save state for -- change
  375. # their methods to act differently when a restoration context is active
  376. # in the current thread
  377. for reglist in registry.reglist:
  378. for stacked, obj in reglist.itervalues():
  379. self.enable_restoration(stacked)
  380. def get_saved_proxied_obj(self, stacked, request_id):
  381. """Retrieve the saved object proxied by the specified
  382. StackedObjectProxy for the request identified by request_id"""
  383. # All state for the request identified by request_id
  384. reglist = self.saved_registry_states[request_id][1]
  385. # The top of the stack was current when the exception occurred
  386. stack_level = len(reglist) - 1
  387. stacked_id = id(stacked)
  388. while True:
  389. if stack_level < 0:
  390. # Nothing registered: Call _current_obj_orig to raise a
  391. # TypeError
  392. return stacked._current_obj_orig()
  393. context = reglist[stack_level]
  394. if stacked_id in context:
  395. break
  396. # This StackedObjectProxy may not have been registered by the
  397. # RegistryManager that was active when the exception was raised --
  398. # continue searching down the stack until it's found
  399. stack_level -= 1
  400. return context[stacked_id][1]
  401. def enable_restoration(self, stacked):
  402. """Replace the specified StackedObjectProxy's methods with their
  403. respective restoration versions.
  404. _current_obj_restoration forces recovery of the saved proxied object
  405. when a restoration context is active in the current thread.
  406. _push/pop_object_restoration avoid pushing/popping data
  407. (pushing/popping is only done at the Registry level) when a restoration
  408. context is active in the current thread"""
  409. if '_current_obj_orig' in stacked.__dict__:
  410. # Restoration already enabled
  411. return
  412. for func_name in ('_current_obj', '_push_object', '_pop_object'):
  413. orig_func = getattr(stacked, func_name)
  414. restoration_func = getattr(stacked, func_name + '_restoration')
  415. stacked.__dict__[func_name + '_orig'] = orig_func
  416. stacked.__dict__[func_name] = restoration_func
  417. def get_request_id(self, environ):
  418. """Return a unique identifier for the current request"""
  419. from paste.evalexception.middleware import get_debug_count
  420. return get_debug_count(environ)
  421. def restoration_begin(self, request_id):
  422. """Enable a restoration context in the current thread for the specified
  423. request_id"""
  424. if request_id in self.saved_registry_states:
  425. # Restore the old Registry object's state
  426. registry, reglist = self.saved_registry_states[request_id]
  427. registry.reglist = reglist
  428. self.restoration_context_id.request_id = request_id
  429. def restoration_end(self):
  430. """Register a restoration context as finished, if one exists"""
  431. try:
  432. del self.restoration_context_id.request_id
  433. except AttributeError:
  434. pass
  435. def in_restoration(self):
  436. """Determine if a restoration context is active for the current thread.
  437. Returns the request_id it's active for if so, otherwise False"""
  438. return getattr(self.restoration_context_id, 'request_id', False)
  439. restorer = StackedObjectRestorer()
  440. # Paste Deploy entry point
  441. def make_registry_manager(app, global_conf):
  442. return RegistryManager(app)
  443. make_registry_manager.__doc__ = RegistryManager.__doc__