compressor.py 19 KB

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