serialization.py 5.0 KB

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