serialization.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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
  10. if sys.version_info < (2, 6):
  11. # cPickle is broken in Python <= 2.5.
  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. # BaseException was introduced in Python 2.5.
  25. try:
  26. _error_bases = (BaseException, )
  27. except NameError:
  28. _error_bases = (SystemExit, KeyboardInterrupt)
  29. unwanted_base_classes = (StandardError, Exception) + _error_bases + (object, )
  30. if sys.version_info < (2, 5):
  31. # Prior to Python 2.5, Exception was an old-style class
  32. def subclass_exception(name, parent, unused):
  33. return types.ClassType(name, (parent,), {})
  34. else:
  35. def subclass_exception(name, parent, module):
  36. return type(name, (parent,), {'__module__': module})
  37. def find_nearest_pickleable_exception(exc):
  38. """With an exception instance, iterate over its super classes (by mro)
  39. and find the first super exception that is pickleable. It does
  40. not go below :exc:`Exception` (i.e. it skips :exc:`Exception`,
  41. :class:`BaseException` and :class:`object`). If that happens
  42. you should use :exc:`UnpickleableException` instead.
  43. :param exc: An exception instance.
  44. :returns: the nearest exception if it's not :exc:`Exception` or below,
  45. if it is it returns ``None``.
  46. :rtype: :exc:`Exception`
  47. """
  48. cls = exc.__class__
  49. getmro_ = getattr(cls, "mro", None)
  50. # old-style classes doesn't have mro()
  51. if not getmro_:
  52. # all Py2.4 exceptions has a baseclass.
  53. if not getattr(cls, "__bases__", ()):
  54. return
  55. # Use inspect.getmro() to traverse bases instead.
  56. getmro_ = lambda: inspect.getmro(cls)
  57. for supercls in getmro_():
  58. if supercls in unwanted_base_classes:
  59. # only BaseException and object, from here on down,
  60. # we don't care about these.
  61. return
  62. try:
  63. exc_args = getattr(exc, "args", [])
  64. superexc = supercls(*exc_args)
  65. pickle.dumps(superexc)
  66. except:
  67. pass
  68. else:
  69. return superexc
  70. return
  71. def create_exception_cls(name, module, parent=None):
  72. """Dynamically create an exception class."""
  73. if not parent:
  74. parent = Exception
  75. return subclass_exception(name, parent, module)
  76. class UnpickleableExceptionWrapper(Exception):
  77. """Wraps unpickleable exceptions.
  78. :param exc_module: see :attr:`exc_module`.
  79. :param exc_cls_name: see :attr:`exc_cls_name`.
  80. :param exc_args: see :attr:`exc_args`
  81. .. attribute:: exc_module
  82. The module of the original exception.
  83. .. attribute:: exc_cls_name
  84. The name of the original exception class.
  85. .. attribute:: exc_args
  86. The arguments for the original exception.
  87. Example
  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. def __init__(self, exc_module, exc_cls_name, exc_args):
  97. self.exc_module = exc_module
  98. self.exc_cls_name = exc_cls_name
  99. self.exc_args = exc_args
  100. Exception.__init__(self, exc_module, exc_cls_name, exc_args)
  101. @classmethod
  102. def from_exception(cls, exc):
  103. return cls(exc.__class__.__module__,
  104. exc.__class__.__name__,
  105. getattr(exc, "args", []))
  106. def restore(self):
  107. return create_exception_cls(self.exc_cls_name,
  108. self.exc_module)(*self.exc_args)
  109. def get_pickleable_exception(exc):
  110. """Make sure exception is pickleable."""
  111. nearest = find_nearest_pickleable_exception(exc)
  112. if nearest:
  113. return nearest
  114. try:
  115. pickle.dumps(deepcopy(exc))
  116. except Exception:
  117. return UnpickleableExceptionWrapper.from_exception(exc)
  118. return exc
  119. def get_pickled_exception(exc):
  120. """Get original exception from exception pickled using
  121. :meth:`get_pickleable_exception`."""
  122. if isinstance(exc, UnpickleableExceptionWrapper):
  123. return exc.restore()
  124. return exc