compressor.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. """Classes and functions for managing compressors."""
  2. import io
  3. import zlib
  4. from distutils.version import LooseVersion
  5. try:
  6. from threading import RLock
  7. except ImportError:
  8. from dummy_threading import RLock
  9. try:
  10. import bz2
  11. except ImportError:
  12. bz2 = None
  13. try:
  14. import lz4
  15. from lz4.frame import LZ4FrameFile
  16. except ImportError:
  17. lz4 = None
  18. try:
  19. import lzma
  20. except ImportError:
  21. lzma = None
  22. LZ4_NOT_INSTALLED_ERROR = ('LZ4 is not installed. Install it with pip: '
  23. 'https://python-lz4.readthedocs.io/')
  24. # Registered compressors
  25. _COMPRESSORS = {}
  26. # Magic numbers of supported compression file formats.
  27. _ZFILE_PREFIX = b'ZF' # used with pickle files created before 0.9.3.
  28. _ZLIB_PREFIX = b'\x78'
  29. _GZIP_PREFIX = b'\x1f\x8b'
  30. _BZ2_PREFIX = b'BZ'
  31. _XZ_PREFIX = b'\xfd\x37\x7a\x58\x5a'
  32. _LZMA_PREFIX = b'\x5d\x00'
  33. _LZ4_PREFIX = b'\x04\x22\x4D\x18'
  34. def register_compressor(compressor_name, compressor,
  35. force=False):
  36. """Register a new compressor.
  37. Parameters
  38. -----------
  39. compressor_name: str.
  40. The name of the compressor.
  41. compressor: CompressorWrapper
  42. An instance of a 'CompressorWrapper'.
  43. """
  44. global _COMPRESSORS
  45. if not isinstance(compressor_name, str):
  46. raise ValueError("Compressor name should be a string, "
  47. "'{}' given.".format(compressor_name))
  48. if not isinstance(compressor, CompressorWrapper):
  49. raise ValueError("Compressor should implement the CompressorWrapper "
  50. "interface, '{}' given.".format(compressor))
  51. if (compressor.fileobj_factory is not None and
  52. (not hasattr(compressor.fileobj_factory, 'read') or
  53. not hasattr(compressor.fileobj_factory, 'write') or
  54. not hasattr(compressor.fileobj_factory, 'seek') or
  55. not hasattr(compressor.fileobj_factory, 'tell'))):
  56. raise ValueError("Compressor 'fileobj_factory' attribute should "
  57. "implement the file object interface, '{}' given."
  58. .format(compressor.fileobj_factory))
  59. if compressor_name in _COMPRESSORS and not force:
  60. raise ValueError("Compressor '{}' already registered."
  61. .format(compressor_name))
  62. _COMPRESSORS[compressor_name] = compressor
  63. class CompressorWrapper():
  64. """A wrapper around a compressor file object.
  65. Attributes
  66. ----------
  67. obj: a file-like object
  68. The object must implement the buffer interface and will be used
  69. internally to compress/decompress the data.
  70. prefix: bytestring
  71. A bytestring corresponding to the magic number that identifies the
  72. file format associated to the compressor.
  73. extention: str
  74. The file extension used to automatically select this compressor during
  75. a dump to a file.
  76. """
  77. def __init__(self, obj, prefix=b'', extension=''):
  78. self.fileobj_factory = obj
  79. self.prefix = prefix
  80. self.extension = extension
  81. def compressor_file(self, fileobj, compresslevel=None):
  82. """Returns an instance of a compressor file object."""
  83. if compresslevel is None:
  84. return self.fileobj_factory(fileobj, 'wb')
  85. else:
  86. return self.fileobj_factory(fileobj, 'wb',
  87. compresslevel=compresslevel)
  88. def decompressor_file(self, fileobj):
  89. """Returns an instance of a decompressor file object."""
  90. return self.fileobj_factory(fileobj, 'rb')
  91. class BZ2CompressorWrapper(CompressorWrapper):
  92. prefix = _BZ2_PREFIX
  93. extension = '.bz2'
  94. def __init__(self):
  95. if bz2 is not None:
  96. self.fileobj_factory = bz2.BZ2File
  97. else:
  98. self.fileobj_factory = None
  99. def _check_versions(self):
  100. if bz2 is None:
  101. raise ValueError('bz2 module is not compiled on your python '
  102. 'standard library.')
  103. def compressor_file(self, fileobj, compresslevel=None):
  104. """Returns an instance of a compressor file object."""
  105. self._check_versions()
  106. if compresslevel is None:
  107. return self.fileobj_factory(fileobj, 'wb')
  108. else:
  109. return self.fileobj_factory(fileobj, 'wb',
  110. compresslevel=compresslevel)
  111. def decompressor_file(self, fileobj):
  112. """Returns an instance of a decompressor file object."""
  113. self._check_versions()
  114. fileobj = self.fileobj_factory(fileobj, 'rb')
  115. return fileobj
  116. class LZMACompressorWrapper(CompressorWrapper):
  117. prefix = _LZMA_PREFIX
  118. extension = '.lzma'
  119. _lzma_format_name = 'FORMAT_ALONE'
  120. def __init__(self):
  121. if lzma is not None:
  122. self.fileobj_factory = lzma.LZMAFile
  123. self._lzma_format = getattr(lzma, self._lzma_format_name)
  124. else:
  125. self.fileobj_factory = None
  126. def _check_versions(self):
  127. if lzma is None:
  128. raise ValueError('lzma module is not compiled on your python '
  129. 'standard library.')
  130. def compressor_file(self, fileobj, compresslevel=None):
  131. """Returns an instance of a compressor file object."""
  132. if compresslevel is None:
  133. return self.fileobj_factory(fileobj, 'wb',
  134. format=self._lzma_format)
  135. else:
  136. return self.fileobj_factory(fileobj, 'wb',
  137. format=self._lzma_format,
  138. preset=compresslevel)
  139. def decompressor_file(self, fileobj):
  140. """Returns an instance of a decompressor file object."""
  141. return lzma.LZMAFile(fileobj, 'rb')
  142. class XZCompressorWrapper(LZMACompressorWrapper):
  143. prefix = _XZ_PREFIX
  144. extension = '.xz'
  145. _lzma_format_name = 'FORMAT_XZ'
  146. class LZ4CompressorWrapper(CompressorWrapper):
  147. prefix = _LZ4_PREFIX
  148. extension = '.lz4'
  149. def __init__(self):
  150. if lz4 is not None:
  151. self.fileobj_factory = LZ4FrameFile
  152. else:
  153. self.fileobj_factory = None
  154. def _check_versions(self):
  155. if lz4 is None:
  156. raise ValueError(LZ4_NOT_INSTALLED_ERROR)
  157. lz4_version = lz4.__version__
  158. if lz4_version.startswith("v"):
  159. lz4_version = lz4_version[1:]
  160. if LooseVersion(lz4_version) < LooseVersion('0.19'):
  161. raise ValueError(LZ4_NOT_INSTALLED_ERROR)
  162. def compressor_file(self, fileobj, compresslevel=None):
  163. """Returns an instance of a compressor file object."""
  164. self._check_versions()
  165. if compresslevel is None:
  166. return self.fileobj_factory(fileobj, 'wb')
  167. else:
  168. return self.fileobj_factory(fileobj, 'wb',
  169. compression_level=compresslevel)
  170. def decompressor_file(self, fileobj):
  171. """Returns an instance of a decompressor file object."""
  172. self._check_versions()
  173. return self.fileobj_factory(fileobj, 'rb')
  174. ###############################################################################
  175. # base file compression/decompression object definition
  176. _MODE_CLOSED = 0
  177. _MODE_READ = 1
  178. _MODE_READ_EOF = 2
  179. _MODE_WRITE = 3
  180. _BUFFER_SIZE = 8192
  181. class BinaryZlibFile(io.BufferedIOBase):
  182. """A file object providing transparent zlib (de)compression.
  183. TODO python2_drop: is it still needed since we dropped Python 2 support A
  184. BinaryZlibFile can act as a wrapper for an existing file object, or refer
  185. directly to a named file on disk.
  186. Note that BinaryZlibFile provides only a *binary* file interface: data read
  187. is returned as bytes, and data to be written should be given as bytes.
  188. This object is an adaptation of the BZ2File object and is compatible with
  189. versions of python >= 2.7.
  190. If filename is a str or bytes object, it gives the name
  191. of the file to be opened. Otherwise, it should be a file object,
  192. which will be used to read or write the compressed data.
  193. mode can be 'rb' for reading (default) or 'wb' for (over)writing
  194. If mode is 'wb', compresslevel can be a number between 1
  195. and 9 specifying the level of compression: 1 produces the least
  196. compression, and 9 produces the most compression. 3 is the default.
  197. """
  198. wbits = zlib.MAX_WBITS
  199. def __init__(self, filename, mode="rb", compresslevel=3):
  200. # This lock must be recursive, so that BufferedIOBase's
  201. # readline(), readlines() and writelines() don't deadlock.
  202. self._lock = RLock()
  203. self._fp = None
  204. self._closefp = False
  205. self._mode = _MODE_CLOSED
  206. self._pos = 0
  207. self._size = -1
  208. self.compresslevel = compresslevel
  209. if not isinstance(compresslevel, int) or not (1 <= compresslevel <= 9):
  210. raise ValueError("'compresslevel' must be an integer "
  211. "between 1 and 9. You provided 'compresslevel={}'"
  212. .format(compresslevel))
  213. if mode == "rb":
  214. self._mode = _MODE_READ
  215. self._decompressor = zlib.decompressobj(self.wbits)
  216. self._buffer = b""
  217. self._buffer_offset = 0
  218. elif mode == "wb":
  219. self._mode = _MODE_WRITE
  220. self._compressor = zlib.compressobj(self.compresslevel,
  221. zlib.DEFLATED, self.wbits,
  222. zlib.DEF_MEM_LEVEL, 0)
  223. else:
  224. raise ValueError("Invalid mode: %r" % (mode,))
  225. if isinstance(filename, str):
  226. self._fp = io.open(filename, mode)
  227. self._closefp = True
  228. elif hasattr(filename, "read") or hasattr(filename, "write"):
  229. self._fp = filename
  230. else:
  231. raise TypeError("filename must be a str or bytes object, "
  232. "or a file")
  233. def close(self):
  234. """Flush and close the file.
  235. May be called more than once without error. Once the file is
  236. closed, any other operation on it will raise a ValueError.
  237. """
  238. with self._lock:
  239. if self._mode == _MODE_CLOSED:
  240. return
  241. try:
  242. if self._mode in (_MODE_READ, _MODE_READ_EOF):
  243. self._decompressor = None
  244. elif self._mode == _MODE_WRITE:
  245. self._fp.write(self._compressor.flush())
  246. self._compressor = None
  247. finally:
  248. try:
  249. if self._closefp:
  250. self._fp.close()
  251. finally:
  252. self._fp = None
  253. self._closefp = False
  254. self._mode = _MODE_CLOSED
  255. self._buffer = b""
  256. self._buffer_offset = 0
  257. @property
  258. def closed(self):
  259. """True if this file is closed."""
  260. return self._mode == _MODE_CLOSED
  261. def fileno(self):
  262. """Return the file descriptor for the underlying file."""
  263. self._check_not_closed()
  264. return self._fp.fileno()
  265. def seekable(self):
  266. """Return whether the file supports seeking."""
  267. return self.readable() and self._fp.seekable()
  268. def readable(self):
  269. """Return whether the file was opened for reading."""
  270. self._check_not_closed()
  271. return self._mode in (_MODE_READ, _MODE_READ_EOF)
  272. def writable(self):
  273. """Return whether the file was opened for writing."""
  274. self._check_not_closed()
  275. return self._mode == _MODE_WRITE
  276. # Mode-checking helper functions.
  277. def _check_not_closed(self):
  278. if self.closed:
  279. fname = getattr(self._fp, 'name', None)
  280. msg = "I/O operation on closed file"
  281. if fname is not None:
  282. msg += " {}".format(fname)
  283. msg += "."
  284. raise ValueError(msg)
  285. def _check_can_read(self):
  286. if self._mode not in (_MODE_READ, _MODE_READ_EOF):
  287. self._check_not_closed()
  288. raise io.UnsupportedOperation("File not open for reading")
  289. def _check_can_write(self):
  290. if self._mode != _MODE_WRITE:
  291. self._check_not_closed()
  292. raise io.UnsupportedOperation("File not open for writing")
  293. def _check_can_seek(self):
  294. if self._mode not in (_MODE_READ, _MODE_READ_EOF):
  295. self._check_not_closed()
  296. raise io.UnsupportedOperation("Seeking is only supported "
  297. "on files open for reading")
  298. if not self._fp.seekable():
  299. raise io.UnsupportedOperation("The underlying file object "
  300. "does not support seeking")
  301. # Fill the readahead buffer if it is empty. Returns False on EOF.
  302. def _fill_buffer(self):
  303. if self._mode == _MODE_READ_EOF:
  304. return False
  305. # Depending on the input data, our call to the decompressor may not
  306. # return any data. In this case, try again after reading another block.
  307. while self._buffer_offset == len(self._buffer):
  308. try:
  309. rawblock = (self._decompressor.unused_data or
  310. self._fp.read(_BUFFER_SIZE))
  311. if not rawblock:
  312. raise EOFError
  313. except EOFError:
  314. # End-of-stream marker and end of file. We're good.
  315. self._mode = _MODE_READ_EOF
  316. self._size = self._pos
  317. return False
  318. else:
  319. self._buffer = self._decompressor.decompress(rawblock)
  320. self._buffer_offset = 0
  321. return True
  322. # Read data until EOF.
  323. # If return_data is false, consume the data without returning it.
  324. def _read_all(self, return_data=True):
  325. # The loop assumes that _buffer_offset is 0. Ensure that this is true.
  326. self._buffer = self._buffer[self._buffer_offset:]
  327. self._buffer_offset = 0
  328. blocks = []
  329. while self._fill_buffer():
  330. if return_data:
  331. blocks.append(self._buffer)
  332. self._pos += len(self._buffer)
  333. self._buffer = b""
  334. if return_data:
  335. return b"".join(blocks)
  336. # Read a block of up to n bytes.
  337. # If return_data is false, consume the data without returning it.
  338. def _read_block(self, n_bytes, return_data=True):
  339. # If we have enough data buffered, return immediately.
  340. end = self._buffer_offset + n_bytes
  341. if end <= len(self._buffer):
  342. data = self._buffer[self._buffer_offset: end]
  343. self._buffer_offset = end
  344. self._pos += len(data)
  345. return data if return_data else None
  346. # The loop assumes that _buffer_offset is 0. Ensure that this is true.
  347. self._buffer = self._buffer[self._buffer_offset:]
  348. self._buffer_offset = 0
  349. blocks = []
  350. while n_bytes > 0 and self._fill_buffer():
  351. if n_bytes < len(self._buffer):
  352. data = self._buffer[:n_bytes]
  353. self._buffer_offset = n_bytes
  354. else:
  355. data = self._buffer
  356. self._buffer = b""
  357. if return_data:
  358. blocks.append(data)
  359. self._pos += len(data)
  360. n_bytes -= len(data)
  361. if return_data:
  362. return b"".join(blocks)
  363. def read(self, size=-1):
  364. """Read up to size uncompressed bytes from the file.
  365. If size is negative or omitted, read until EOF is reached.
  366. Returns b'' if the file is already at EOF.
  367. """
  368. with self._lock:
  369. self._check_can_read()
  370. if size == 0:
  371. return b""
  372. elif size < 0:
  373. return self._read_all()
  374. else:
  375. return self._read_block(size)
  376. def readinto(self, b):
  377. """Read up to len(b) bytes into b.
  378. Returns the number of bytes read (0 for EOF).
  379. """
  380. with self._lock:
  381. return io.BufferedIOBase.readinto(self, b)
  382. def write(self, data):
  383. """Write a byte string to the file.
  384. Returns the number of uncompressed bytes written, which is
  385. always len(data). Note that due to buffering, the file on disk
  386. may not reflect the data written until close() is called.
  387. """
  388. with self._lock:
  389. self._check_can_write()
  390. # Convert data type if called by io.BufferedWriter.
  391. if isinstance(data, memoryview):
  392. data = data.tobytes()
  393. compressed = self._compressor.compress(data)
  394. self._fp.write(compressed)
  395. self._pos += len(data)
  396. return len(data)
  397. # Rewind the file to the beginning of the data stream.
  398. def _rewind(self):
  399. self._fp.seek(0, 0)
  400. self._mode = _MODE_READ
  401. self._pos = 0
  402. self._decompressor = zlib.decompressobj(self.wbits)
  403. self._buffer = b""
  404. self._buffer_offset = 0
  405. def seek(self, offset, whence=0):
  406. """Change the file position.
  407. The new position is specified by offset, relative to the
  408. position indicated by whence. Values for whence are:
  409. 0: start of stream (default); offset must not be negative
  410. 1: current stream position
  411. 2: end of stream; offset must not be positive
  412. Returns the new file position.
  413. Note that seeking is emulated, so depending on the parameters,
  414. this operation may be extremely slow.
  415. """
  416. with self._lock:
  417. self._check_can_seek()
  418. # Recalculate offset as an absolute file position.
  419. if whence == 0:
  420. pass
  421. elif whence == 1:
  422. offset = self._pos + offset
  423. elif whence == 2:
  424. # Seeking relative to EOF - we need to know the file's size.
  425. if self._size < 0:
  426. self._read_all(return_data=False)
  427. offset = self._size + offset
  428. else:
  429. raise ValueError("Invalid value for whence: %s" % (whence,))
  430. # Make it so that offset is the number of bytes to skip forward.
  431. if offset < self._pos:
  432. self._rewind()
  433. else:
  434. offset -= self._pos
  435. # Read and discard data until we reach the desired position.
  436. self._read_block(offset, return_data=False)
  437. return self._pos
  438. def tell(self):
  439. """Return the current file position."""
  440. with self._lock:
  441. self._check_not_closed()
  442. return self._pos
  443. class ZlibCompressorWrapper(CompressorWrapper):
  444. def __init__(self):
  445. CompressorWrapper.__init__(self, obj=BinaryZlibFile,
  446. prefix=_ZLIB_PREFIX, extension='.z')
  447. class BinaryGzipFile(BinaryZlibFile):
  448. """A file object providing transparent gzip (de)compression.
  449. If filename is a str or bytes object, it gives the name
  450. of the file to be opened. Otherwise, it should be a file object,
  451. which will be used to read or write the compressed data.
  452. mode can be 'rb' for reading (default) or 'wb' for (over)writing
  453. If mode is 'wb', compresslevel can be a number between 1
  454. and 9 specifying the level of compression: 1 produces the least
  455. compression, and 9 produces the most compression. 3 is the default.
  456. """
  457. wbits = 31 # zlib compressor/decompressor wbits value for gzip format.
  458. class GzipCompressorWrapper(CompressorWrapper):
  459. def __init__(self):
  460. CompressorWrapper.__init__(self, obj=BinaryGzipFile,
  461. prefix=_GZIP_PREFIX, extension='.gz')