registry.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 six
  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. try:
  139. objects = self.____local__.objects
  140. except AttributeError:
  141. objects = None
  142. if objects:
  143. return objects[-1]
  144. else:
  145. obj = self.__dict__.get('____default_object__', NoDefault)
  146. if obj is not NoDefault:
  147. return obj
  148. else:
  149. raise TypeError(
  150. 'No object (name: %s) has been registered for this '
  151. 'thread' % self.____name__)
  152. def _push_object(self, obj):
  153. """Make ``obj`` the active object for this thread-local.
  154. This should be used like:
  155. .. code-block:: python
  156. obj = yourobject()
  157. module.glob = StackedObjectProxy()
  158. module.glob._push_object(obj)
  159. try:
  160. ... do stuff ...
  161. finally:
  162. module.glob._pop_object(conf)
  163. """
  164. try:
  165. self.____local__.objects.append(obj)
  166. except AttributeError:
  167. self.____local__.objects = []
  168. self.____local__.objects.append(obj)
  169. def _pop_object(self, obj=None):
  170. """Remove a thread-local object.
  171. If ``obj`` is given, it is checked against the popped object and an
  172. error is emitted if they don't match.
  173. """
  174. try:
  175. popped = self.____local__.objects.pop()
  176. if obj and popped is not obj:
  177. raise AssertionError(
  178. 'The object popped (%s) is not the same as the object '
  179. 'expected (%s)' % (popped, obj))
  180. except AttributeError:
  181. raise AssertionError('No object has been registered for this thread')
  182. def _object_stack(self):
  183. """Returns all of the objects stacked in this container
  184. (Might return [] if there are none)
  185. """
  186. try:
  187. try:
  188. objs = self.____local__.objects
  189. except AttributeError:
  190. return []
  191. return objs[:]
  192. except AssertionError:
  193. return []
  194. # The following methods will be swapped for their original versions by
  195. # StackedObjectRestorer when restoration is enabled. The original
  196. # functions (e.g. _current_obj) will be available at _current_obj_orig
  197. def _current_obj_restoration(self):
  198. request_id = restorer.in_restoration()
  199. if request_id:
  200. return restorer.get_saved_proxied_obj(self, request_id)
  201. return self._current_obj_orig()
  202. _current_obj_restoration.__doc__ = \
  203. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  204. _current_obj.__doc__)
  205. def _push_object_restoration(self, obj):
  206. if not restorer.in_restoration():
  207. self._push_object_orig(obj)
  208. _push_object_restoration.__doc__ = \
  209. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  210. _push_object.__doc__)
  211. def _pop_object_restoration(self, obj=None):
  212. if not restorer.in_restoration():
  213. self._pop_object_orig(obj)
  214. _pop_object_restoration.__doc__ = \
  215. ('%s\n(StackedObjectRestorer restoration enabled)' % \
  216. _pop_object.__doc__)
  217. class Registry(object):
  218. """Track objects and stacked object proxies for removal
  219. The Registry object is instantiated a single time for the request no
  220. matter how many times the RegistryManager is used in a WSGI stack. Each
  221. RegistryManager must call ``prepare`` before continuing the call to
  222. start a new context for object registering.
  223. Each context is tracked with a dict inside a list. The last list
  224. element is the currently executing context. Each context dict is keyed
  225. by the id of the StackedObjectProxy instance being proxied, the value
  226. is a tuple of the StackedObjectProxy instance and the object being
  227. tracked.
  228. """
  229. def __init__(self):
  230. """Create a new Registry object
  231. ``prepare`` must still be called before this Registry object can be
  232. used to register objects.
  233. """
  234. self.reglist = []
  235. def prepare(self):
  236. """Used to create a new registry context
  237. Anytime a new RegistryManager is called, ``prepare`` needs to be
  238. called on the existing Registry object. This sets up a new context
  239. for registering objects.
  240. """
  241. self.reglist.append({})
  242. def register(self, stacked, obj):
  243. """Register an object with a StackedObjectProxy"""
  244. myreglist = self.reglist[-1]
  245. stacked_id = id(stacked)
  246. if stacked_id in myreglist:
  247. stacked._pop_object(myreglist[stacked_id][1])
  248. del myreglist[stacked_id]
  249. stacked._push_object(obj)
  250. myreglist[stacked_id] = (stacked, obj)
  251. def multiregister(self, stacklist):
  252. """Register a list of tuples
  253. Similar call semantics as register, except this registers
  254. multiple objects at once.
  255. Example::
  256. registry.multiregister([(sop, obj), (anothersop, anotherobj)])
  257. """
  258. myreglist = self.reglist[-1]
  259. for stacked, obj in stacklist:
  260. stacked_id = id(stacked)
  261. if stacked_id in myreglist:
  262. stacked._pop_object(myreglist[stacked_id][1])
  263. del myreglist[stacked_id]
  264. stacked._push_object(obj)
  265. myreglist[stacked_id] = (stacked, obj)
  266. # Replace now does the same thing as register
  267. replace = register
  268. def cleanup(self):
  269. """Remove all objects from all StackedObjectProxy instances that
  270. were tracked at this Registry context"""
  271. for stacked, obj in six.itervalues(self.reglist[-1]):
  272. stacked._pop_object(obj)
  273. self.reglist.pop()
  274. class RegistryManager(object):
  275. """Creates and maintains a Registry context
  276. RegistryManager creates a new registry context for the registration of
  277. StackedObjectProxy instances. Multiple RegistryManager's can be in a
  278. WSGI stack and will manage the context so that the StackedObjectProxies
  279. always proxy to the proper object.
  280. The object being registered can be any object sub-class, list, or dict.
  281. Registering objects is done inside a WSGI application under the
  282. RegistryManager instance, using the ``environ['paste.registry']``
  283. object which is a Registry instance.
  284. """
  285. def __init__(self, application, streaming=False):
  286. self.application = application
  287. self.streaming = streaming
  288. def __call__(self, environ, start_response):
  289. app_iter = None
  290. reg = environ.setdefault('paste.registry', Registry())
  291. reg.prepare()
  292. if self.streaming:
  293. return self.streaming_iter(reg, environ, start_response)
  294. try:
  295. app_iter = self.application(environ, start_response)
  296. except Exception as e:
  297. # Regardless of if the content is an iterable, generator, list
  298. # or tuple, we clean-up right now. If its an iterable/generator
  299. # care should be used to ensure the generator has its own ref
  300. # to the actual object
  301. if environ.get('paste.evalexception'):
  302. # EvalException is present in the WSGI stack
  303. expected = False
  304. for expect in environ.get('paste.expected_exceptions', []):
  305. if isinstance(e, expect):
  306. expected = True
  307. if not expected:
  308. # An unexpected exception: save state for EvalException
  309. restorer.save_registry_state(environ)
  310. reg.cleanup()
  311. raise
  312. except:
  313. # Save state for EvalException if it's present
  314. if environ.get('paste.evalexception'):
  315. restorer.save_registry_state(environ)
  316. reg.cleanup()
  317. raise
  318. else:
  319. reg.cleanup()
  320. return app_iter
  321. def streaming_iter(self, reg, environ, start_response):
  322. try:
  323. for item in self.application(environ, start_response):
  324. yield item
  325. except Exception as e:
  326. # Regardless of if the content is an iterable, generator, list
  327. # or tuple, we clean-up right now. If its an iterable/generator
  328. # care should be used to ensure the generator has its own ref
  329. # to the actual object
  330. if environ.get('paste.evalexception'):
  331. # EvalException is present in the WSGI stack
  332. expected = False
  333. for expect in environ.get('paste.expected_exceptions', []):
  334. if isinstance(e, expect):
  335. expected = True
  336. if not expected:
  337. # An unexpected exception: save state for EvalException
  338. restorer.save_registry_state(environ)
  339. reg.cleanup()
  340. raise
  341. except:
  342. # Save state for EvalException if it's present
  343. if environ.get('paste.evalexception'):
  344. restorer.save_registry_state(environ)
  345. reg.cleanup()
  346. raise
  347. else:
  348. reg.cleanup()
  349. class StackedObjectRestorer(object):
  350. """Track StackedObjectProxies and their proxied objects for automatic
  351. restoration within EvalException's interactive debugger.
  352. An instance of this class tracks all StackedObjectProxy state in existence
  353. when unexpected exceptions are raised by WSGI applications housed by
  354. EvalException and RegistryManager. Like EvalException, this information is
  355. stored for the life of the process.
  356. When an unexpected exception occurs and EvalException is present in the
  357. WSGI stack, save_registry_state is intended to be called to store the
  358. Registry state and enable automatic restoration on all currently registered
  359. StackedObjectProxies.
  360. With restoration enabled, those StackedObjectProxies' _current_obj
  361. (overwritten by _current_obj_restoration) method's strategy is modified:
  362. it will return its appropriate proxied object from the restorer when
  363. a restoration context is active in the current thread.
  364. The StackedObjectProxies' _push/pop_object methods strategies are also
  365. changed: they no-op when a restoration context is active in the current
  366. thread (because the pushing/popping work is all handled by the
  367. Registry/restorer).
  368. The request's Registry objects' reglists are restored from the restorer
  369. when a restoration context begins, enabling the Registry methods to work
  370. while their changes are tracked by the restorer.
  371. The overhead of enabling restoration is negligible (another threadlocal
  372. access for the changed StackedObjectProxy methods) for normal use outside
  373. of a restoration context, but worth mentioning when combined with
  374. StackedObjectProxies normal overhead. Once enabled it does not turn off,
  375. however:
  376. o Enabling restoration only occurs after an unexpected exception is
  377. detected. The server is likely to be restarted shortly after the exception
  378. is raised to fix the cause
  379. o StackedObjectRestorer is only enabled when EvalException is enabled (not
  380. on a production server) and RegistryManager exists in the middleware
  381. stack"""
  382. def __init__(self):
  383. # Registries and their saved reglists by request_id
  384. self.saved_registry_states = {}
  385. self.restoration_context_id = threadinglocal.local()
  386. def save_registry_state(self, environ):
  387. """Save the state of this request's Registry (if it hasn't already been
  388. saved) to the saved_registry_states dict, keyed by the request's unique
  389. identifier"""
  390. registry = environ.get('paste.registry')
  391. if not registry or not len(registry.reglist) or \
  392. self.get_request_id(environ) in self.saved_registry_states:
  393. # No Registry, no state to save, or this request's state has
  394. # already been saved
  395. return
  396. self.saved_registry_states[self.get_request_id(environ)] = \
  397. (registry, registry.reglist[:])
  398. # Tweak the StackedObjectProxies we want to save state for -- change
  399. # their methods to act differently when a restoration context is active
  400. # in the current thread
  401. for reglist in registry.reglist:
  402. for stacked, obj in six.itervalues(reglist):
  403. self.enable_restoration(stacked)
  404. def get_saved_proxied_obj(self, stacked, request_id):
  405. """Retrieve the saved object proxied by the specified
  406. StackedObjectProxy for the request identified by request_id"""
  407. # All state for the request identified by request_id
  408. reglist = self.saved_registry_states[request_id][1]
  409. # The top of the stack was current when the exception occurred
  410. stack_level = len(reglist) - 1
  411. stacked_id = id(stacked)
  412. while True:
  413. if stack_level < 0:
  414. # Nothing registered: Call _current_obj_orig to raise a
  415. # TypeError
  416. return stacked._current_obj_orig()
  417. context = reglist[stack_level]
  418. if stacked_id in context:
  419. break
  420. # This StackedObjectProxy may not have been registered by the
  421. # RegistryManager that was active when the exception was raised --
  422. # continue searching down the stack until it's found
  423. stack_level -= 1
  424. return context[stacked_id][1]
  425. def enable_restoration(self, stacked):
  426. """Replace the specified StackedObjectProxy's methods with their
  427. respective restoration versions.
  428. _current_obj_restoration forces recovery of the saved proxied object
  429. when a restoration context is active in the current thread.
  430. _push/pop_object_restoration avoid pushing/popping data
  431. (pushing/popping is only done at the Registry level) when a restoration
  432. context is active in the current thread"""
  433. if '_current_obj_orig' in stacked.__dict__:
  434. # Restoration already enabled
  435. return
  436. for func_name in ('_current_obj', '_push_object', '_pop_object'):
  437. orig_func = getattr(stacked, func_name)
  438. restoration_func = getattr(stacked, func_name + '_restoration')
  439. stacked.__dict__[func_name + '_orig'] = orig_func
  440. stacked.__dict__[func_name] = restoration_func
  441. def get_request_id(self, environ):
  442. """Return a unique identifier for the current request"""
  443. from paste.evalexception.middleware import get_debug_count
  444. return get_debug_count(environ)
  445. def restoration_begin(self, request_id):
  446. """Enable a restoration context in the current thread for the specified
  447. request_id"""
  448. if request_id in self.saved_registry_states:
  449. # Restore the old Registry object's state
  450. registry, reglist = self.saved_registry_states[request_id]
  451. registry.reglist = reglist
  452. self.restoration_context_id.request_id = request_id
  453. def restoration_end(self):
  454. """Register a restoration context as finished, if one exists"""
  455. try:
  456. del self.restoration_context_id.request_id
  457. except AttributeError:
  458. pass
  459. def in_restoration(self):
  460. """Determine if a restoration context is active for the current thread.
  461. Returns the request_id it's active for if so, otherwise False"""
  462. return getattr(self.restoration_context_id, 'request_id', False)
  463. restorer = StackedObjectRestorer()
  464. # Paste Deploy entry point
  465. def make_registry_manager(app, global_conf):
  466. return RegistryManager(app)
  467. make_registry_manager.__doc__ = RegistryManager.__doc__