serialization.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils.serialization
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Utilities for safely pickling exceptions.
  6. """
  7. from __future__ import absolute_import
  8. from inspect import getmro
  9. from itertools import takewhile
  10. try:
  11. import cPickle as pickle
  12. except ImportError:
  13. import pickle # noqa
  14. from .encoding import safe_repr
  15. __all__ = ['UnpickleableExceptionWrapper', 'subclass_exception',
  16. 'find_pickleable_exception', 'create_exception_cls',
  17. 'get_pickleable_exception', 'get_pickleable_etype',
  18. 'get_pickled_exception']
  19. #: List of base classes we probably don't want to reduce to.
  20. try:
  21. unwanted_base_classes = (StandardError, Exception, BaseException, object)
  22. except NameError: # pragma: no cover
  23. unwanted_base_classes = (Exception, BaseException, object) # py3k
  24. def subclass_exception(name, parent, module): # noqa
  25. return type(name, (parent, ), {'__module__': module})
  26. def find_pickleable_exception(exc, loads=pickle.loads,
  27. dumps=pickle.dumps):
  28. """With an exception instance, iterate over its super classes (by mro)
  29. and find the first super exception that is pickleable. It does
  30. not go below :exc:`Exception` (i.e. it skips :exc:`Exception`,
  31. :class:`BaseException` and :class:`object`). If that happens
  32. you should use :exc:`UnpickleableException` instead.
  33. :param exc: An exception instance.
  34. Will return the nearest pickleable parent exception class
  35. (except :exc:`Exception` and parents), or if the exception is
  36. pickleable it will return :const:`None`.
  37. :rtype :exc:`Exception`:
  38. """
  39. exc_args = getattr(exc, 'args', [])
  40. for supercls in itermro(exc.__class__, unwanted_base_classes):
  41. try:
  42. superexc = supercls(*exc_args)
  43. loads(dumps(superexc))
  44. except:
  45. pass
  46. else:
  47. return superexc
  48. find_nearest_pickleable_exception = find_pickleable_exception # XXX compat
  49. def itermro(cls, stop):
  50. return takewhile(lambda sup: sup not in stop, getmro(cls))
  51. def create_exception_cls(name, module, parent=None):
  52. """Dynamically create an exception class."""
  53. if not parent:
  54. parent = Exception
  55. return subclass_exception(name, parent, module)
  56. class UnpickleableExceptionWrapper(Exception):
  57. """Wraps unpickleable exceptions.
  58. :param exc_module: see :attr:`exc_module`.
  59. :param exc_cls_name: see :attr:`exc_cls_name`.
  60. :param exc_args: see :attr:`exc_args`
  61. **Example**
  62. .. code-block:: python
  63. >>> def pickle_it(raising_function):
  64. ... try:
  65. ... raising_function()
  66. ... except Exception as e:
  67. ... exc = UnpickleableExceptionWrapper(
  68. ... e.__class__.__module__,
  69. ... e.__class__.__name__,
  70. ... e.args,
  71. ... )
  72. ... pickle.dumps(exc) # Works fine.
  73. """
  74. #: The module of the original exception.
  75. exc_module = None
  76. #: The name of the original exception class.
  77. exc_cls_name = None
  78. #: The arguments for the original exception.
  79. exc_args = None
  80. def __init__(self, exc_module, exc_cls_name, exc_args, text=None):
  81. safe_exc_args = []
  82. for arg in exc_args:
  83. try:
  84. pickle.dumps(arg)
  85. safe_exc_args.append(arg)
  86. except Exception:
  87. safe_exc_args.append(safe_repr(arg))
  88. self.exc_module = exc_module
  89. self.exc_cls_name = exc_cls_name
  90. self.exc_args = safe_exc_args
  91. self.text = text
  92. Exception.__init__(self, exc_module, exc_cls_name, safe_exc_args, text)
  93. def restore(self):
  94. return create_exception_cls(self.exc_cls_name,
  95. self.exc_module)(*self.exc_args)
  96. def __str__(self):
  97. return self.text
  98. @classmethod
  99. def from_exception(cls, exc):
  100. return cls(exc.__class__.__module__,
  101. exc.__class__.__name__,
  102. getattr(exc, 'args', []),
  103. safe_repr(exc))
  104. def get_pickleable_exception(exc):
  105. """Make sure exception is pickleable."""
  106. try:
  107. pickle.loads(pickle.dumps(exc))
  108. except Exception:
  109. pass
  110. else:
  111. return exc
  112. nearest = find_pickleable_exception(exc)
  113. if nearest:
  114. return nearest
  115. return UnpickleableExceptionWrapper.from_exception(exc)
  116. def get_pickleable_etype(cls, loads=pickle.loads, dumps=pickle.dumps):
  117. try:
  118. loads(dumps(cls))
  119. except:
  120. return Exception
  121. else:
  122. return cls
  123. def get_pickled_exception(exc):
  124. """Get original exception from exception pickled using
  125. :meth:`get_pickleable_exception`."""
  126. if isinstance(exc, UnpickleableExceptionWrapper):
  127. return exc.restore()
  128. return exc