serialization.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. """
  2. celery.utils.serialization
  3. ==========================
  4. Serialization utilities for safely pickling exceptions.
  5. """
  6. from __future__ import absolute_import
  7. import inspect
  8. import sys
  9. import types
  10. from copy import deepcopy
  11. import pickle as pypickle
  12. try:
  13. import cPickle as cpickle
  14. except ImportError:
  15. cpickle = None # noqa
  16. from .encoding import safe_repr
  17. if sys.version_info < (2, 6): # pragma: no cover
  18. # cPickle is broken in Python <= 2.6.
  19. # It unsafely and incorrectly uses relative instead of absolute imports,
  20. # so e.g.:
  21. # exceptions.KeyError
  22. # becomes:
  23. # celery.exceptions.KeyError
  24. #
  25. # Your best choice is to upgrade to Python 2.6,
  26. # as while the pure pickle version has worse performance,
  27. # it is the only safe option for older Python versions.
  28. pickle = pypickle
  29. else:
  30. pickle = cpickle or pypickle
  31. #: List of base classes we probably don't want to reduce to.
  32. unwanted_base_classes = (StandardError, Exception, BaseException, object)
  33. __all__ = ["subclass_exception", "find_nearest_pickleable_exception",
  34. "create_exception_cls", "UnpickleableExceptionWrapper",
  35. "get_pickleable_exception", "get_pickled_exception"]
  36. if sys.version_info < (2, 5): # pragma: no cover
  37. # Prior to Python 2.5, Exception was an old-style class
  38. def subclass_exception(name, parent, unused):
  39. return types.ClassType(name, (parent,), {})
  40. else:
  41. def subclass_exception(name, parent, module): # noqa
  42. return type(name, (parent,), {'__module__': module})
  43. def find_nearest_pickleable_exception(exc):
  44. """With an exception instance, iterate over its super classes (by mro)
  45. and find the first super exception that is pickleable. It does
  46. not go below :exc:`Exception` (i.e. it skips :exc:`Exception`,
  47. :class:`BaseException` and :class:`object`). If that happens
  48. you should use :exc:`UnpickleableException` instead.
  49. :param exc: An exception instance.
  50. :returns: the nearest exception if it's not :exc:`Exception` or below,
  51. if it is it returns :const:`None`.
  52. :rtype :exc:`Exception`:
  53. """
  54. cls = exc.__class__
  55. getmro_ = getattr(cls, "mro", None)
  56. # old-style classes doesn't have mro()
  57. if not getmro_:
  58. # all Py2.4 exceptions has a baseclass.
  59. if not getattr(cls, "__bases__", ()):
  60. return
  61. # Use inspect.getmro() to traverse bases instead.
  62. getmro_ = lambda: inspect.getmro(cls)
  63. for supercls in getmro_():
  64. if supercls in unwanted_base_classes:
  65. # only BaseException and object, from here on down,
  66. # we don't care about these.
  67. return
  68. try:
  69. exc_args = getattr(exc, "args", [])
  70. superexc = supercls(*exc_args)
  71. pickle.dumps(superexc)
  72. except:
  73. pass
  74. else:
  75. return superexc
  76. def create_exception_cls(name, module, parent=None):
  77. """Dynamically create an exception class."""
  78. if not parent:
  79. parent = Exception
  80. return subclass_exception(name, parent, module)
  81. class UnpickleableExceptionWrapper(Exception):
  82. """Wraps unpickleable exceptions.
  83. :param exc_module: see :attr:`exc_module`.
  84. :param exc_cls_name: see :attr:`exc_cls_name`.
  85. :param exc_args: see :attr:`exc_args`
  86. **Example**
  87. .. code-block:: python
  88. >>> try:
  89. ... something_raising_unpickleable_exc()
  90. >>> except Exception, e:
  91. ... exc = UnpickleableException(e.__class__.__module__,
  92. ... e.__class__.__name__,
  93. ... e.args)
  94. ... pickle.dumps(exc) # Works fine.
  95. """
  96. #: The module of the original exception.
  97. exc_module = None
  98. #: The name of the original exception class.
  99. exc_cls_name = None
  100. #: The arguments for the original exception.
  101. exc_args = None
  102. def __init__(self, exc_module, exc_cls_name, exc_args, text=None):
  103. self.exc_module = exc_module
  104. self.exc_cls_name = exc_cls_name
  105. self.exc_args = exc_args
  106. self.text = text
  107. Exception.__init__(self, exc_module, exc_cls_name, exc_args, text)
  108. def restore(self):
  109. return create_exception_cls(self.exc_cls_name,
  110. self.exc_module)(*self.exc_args)
  111. def __str__(self):
  112. return self.text
  113. @classmethod
  114. def from_exception(cls, exc):
  115. return cls(exc.__class__.__module__,
  116. exc.__class__.__name__,
  117. getattr(exc, "args", []),
  118. safe_repr(exc))
  119. def get_pickleable_exception(exc):
  120. """Make sure exception is pickleable."""
  121. nearest = find_nearest_pickleable_exception(exc)
  122. if nearest:
  123. return nearest
  124. try:
  125. pickle.dumps(deepcopy(exc))
  126. except Exception:
  127. return UnpickleableExceptionWrapper.from_exception(exc)
  128. return exc
  129. def get_pickled_exception(exc):
  130. """Get original exception from exception pickled using
  131. :meth:`get_pickleable_exception`."""
  132. if isinstance(exc, UnpickleableExceptionWrapper):
  133. return exc.restore()
  134. return exc