serialization.py 4.6 KB

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