You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

565 lines
18 KiB

  1. #!/usr/bin/env python
  2. """
  3. megawarc is useful if you have .tar full of .warc.gz files and
  4. you really want one big .warc.gz. With megawarc you get your
  5. .warc.gz, but you can still restore the original .tar.
  6. The megawarc tool looks for .warc.gz in the .tar file and
  7. creates three files, the megawarc:
  8. FILE.warc.gz is the concatenated .warc.gz
  9. FILE.tar contains any non-warc files from the .tar
  10. FILE.json.gz contains metadata
  11. You need the JSON file to reconstruct the original .tar from
  12. the .warc.gz and .tar files. The JSON file has the location
  13. of every file from the original .tar file.
  14. METADATA FORMAT
  15. ---------------
  16. One line with a JSON object per file in the .tar.
  17. {
  18. "target": {
  19. "container": "warc" or "tar", (where is this file?)
  20. "offset": number, (where in the tar/warc does this
  21. file start? for files in the tar
  22. this includes the tar header,
  23. which is copied to the tar.)
  24. "size": size (where does this file end?
  25. for files in the tar, this includes
  26. the padding to 512 bytes)
  27. },
  28. "src_offsets": {
  29. "entry": number, (where is this file in the original tar?)
  30. "data": number, (where does the data start? entry+512)
  31. "next_entry": number (where does the next tar entry start)
  32. },
  33. "header_fields": {
  34. ... (parsed fields from the tar header)
  35. },
  36. "header_base64": string (the base64-encoded tar header)
  37. }
  38. In older megawarcs the header is sometimes not base64-encoded:
  39. "header_string": string (the tar header for this entry)
  40. USAGE
  41. -----
  42. megawarc convert FILE
  43. Converts the tar file (containing .warc.gz files) to a megawarc.
  44. It creates FILE.warc.gz, FILE.tar and FILE.json.gz from FILE.
  45. megawarc pack FILE INFILE_1 [[INFILE_2] ...]
  46. Creates a megawarc with basename FILE and recursively adds the
  47. given files and directories to it, as if they were in a tar file.
  48. It creates FILE.warc.gz, FILE.tar and FILE.json.gz.
  49. megawarc restore FILE
  50. Converts the megawarc back to the original tar.
  51. It reads FILE.warc.gz, FILE.tar and FILE.json.gz to make FILE.
  52. """
  53. import base64
  54. import gzip
  55. import json
  56. import os.path
  57. import re
  58. import subprocess
  59. import sys
  60. import tarfile
  61. import zlib
  62. from optparse import OptionParser
  63. try:
  64. from collections import OrderedDict
  65. except ImportError:
  66. from ordereddict import OrderedDict
  67. class ProgressInfo(object):
  68. def __init__(self, maximum):
  69. self._current = 0
  70. self._maximum = maximum
  71. self._previous_percentage = None
  72. self._active = sys.stderr.isatty()
  73. self.print_status()
  74. def update(self, new_value):
  75. self._current = new_value
  76. self.print_status()
  77. def print_status(self):
  78. if not self._active:
  79. return
  80. percentage = int(float(self._current) / float(self._maximum) * 100)
  81. if self._maximum < 0:
  82. # count down
  83. percentage = -percentage
  84. percentage = max(0, min(100, percentage))
  85. if self._previous_percentage != percentage:
  86. self._previous_percentage = percentage
  87. sys.stderr.write("\r %3d%%" % percentage)
  88. def clear(self):
  89. if self._active:
  90. sys.stderr.write("\r \r")
  91. self._active = False
  92. # open input_filename and write the data from offset to
  93. # (offset+size) to stream
  94. def copy_to_stream(stream, input_filename, offset, size, verbose=False):
  95. if verbose and size > 10 * 1024 * 1024:
  96. progress = ProgressInfo(-size)
  97. else:
  98. progress = None
  99. try:
  100. with open(input_filename, "r") as f:
  101. f.seek(offset)
  102. to_read = size
  103. while to_read > 0:
  104. buf_size = min(to_read, 4096)
  105. buf = f.read(buf_size)
  106. l = len(buf)
  107. if l < buf_size:
  108. raise Exception("End of file: %d bytes expected, but %d bytes read." % (buf_size, l))
  109. stream.write(buf)
  110. to_read -= l
  111. if progress:
  112. progress.update(-to_read)
  113. finally:
  114. if progress:
  115. progress.clear()
  116. # part of a stream as a file
  117. # (seek relative to an offset)
  118. class RangeFile(object):
  119. def __init__(self, stream, offset, size):
  120. self._stream = stream
  121. self._offset = offset
  122. self._size = size
  123. self._current_rel_offset = 0
  124. self.seek(0)
  125. def tell(self):
  126. return self._current_rel_offset
  127. def seek(self, pos, whence=os.SEEK_SET):
  128. if whence == os.SEEK_SET:
  129. self._current_rel_offset = pos
  130. elif whence == os.SEEK_CUR:
  131. self._current_rel_offset += pos
  132. elif whence == os.SEEK_END:
  133. self._current_rel_offset = self._size + pos
  134. else:
  135. raise Exception("Unknown whence: %d." % whence)
  136. if self._current_rel_offset < 0 or self._current_rel_offset > self._size:
  137. raise Exception("Seek outside file: %d." % self._current_rel_offset)
  138. self._stream.seek(self._offset + self._current_rel_offset)
  139. def read(self, size):
  140. size = min(self._size - self._current_rel_offset, size)
  141. self._current_rel_offset += size
  142. buf = self._stream.read(size)
  143. if len(buf) < size:
  144. raise Exception("Expected to read %d but received %d." % (size, len(buf)))
  145. return buf
  146. # copies while reading
  147. class CopyReader(object):
  148. def __init__(self, in_stream, out_stream):
  149. self._in_stream = in_stream
  150. self._out_stream = out_stream
  151. self._last_read = 0
  152. def tell(self):
  153. return self._in_stream.tell()
  154. def seek(self, pos, whence=os.SEEK_SET):
  155. self._in_stream.seek(pos, whence)
  156. def read(self, size):
  157. pos = self.tell()
  158. if self._last_read < pos:
  159. raise Exception("Last read: %d Current pos: %d" % (self._last_read, pos))
  160. buf = self._in_stream.read(size)
  161. read_before = self._last_read - pos
  162. if read_before == 0:
  163. new_read = buf
  164. else:
  165. new_read = buf[read_before:]
  166. l = len(new_read)
  167. if l > 0:
  168. self._last_read += l
  169. self._out_stream.write(new_read)
  170. return buf
  171. # check for gzip errors
  172. def test_gz(filename, offset, size, verbose=False, copy_to_file=None):
  173. with open(filename, "r") as f_stream:
  174. f = RangeFile(f_stream, offset, size)
  175. if verbose and size > 10 * 1024 * 1024:
  176. progress = ProgressInfo(-size)
  177. else:
  178. progress = None
  179. if copy_to_file:
  180. f = CopyReader(f, copy_to_file)
  181. start_pos = copy_to_file.tell()
  182. try:
  183. with open("/dev/null", "w") as dev_null:
  184. gz = subprocess.Popen(["gunzip", "-tv"],
  185. shell=False,
  186. stdin=subprocess.PIPE,
  187. stdout=dev_null,
  188. stderr=dev_null)
  189. while True:
  190. buf = f.read(4096)
  191. size -= len(buf)
  192. if progress:
  193. progress.update(-size)
  194. if len(buf) > 0:
  195. gz.stdin.write(buf)
  196. else:
  197. break
  198. gz.stdin.close()
  199. ret = gz.wait()
  200. if ret != 0:
  201. raise IOError("Could not decompress warc.gz. gunzip returned %d." % ret)
  202. if progress:
  203. progress.clear()
  204. except (IOError, OSError) as e:
  205. if progress:
  206. progress.clear()
  207. if verbose:
  208. print >>sys.stderr, e
  209. if copy_to_file:
  210. copy_to_file.truncate(start_pos)
  211. copy_to_file.seek(start_pos)
  212. return False
  213. return True
  214. # converting a .tar with warcs to megawarc tar+warc+json
  215. class MegawarcBuilder(object):
  216. def __init__(self, input_filename):
  217. self.verbose = False
  218. self.input_filename = input_filename
  219. self.output_warc_filename = input_filename + ".megawarc.warc.gz"
  220. self.output_tar_filename = input_filename + ".megawarc.tar"
  221. self.output_json_filename = input_filename + ".megawarc.json.gz"
  222. def process(self):
  223. with open(self.output_warc_filename, "wb") as warc_out:
  224. with open(self.output_tar_filename, "wb") as tar_out:
  225. with gzip.open(self.output_json_filename, "wb") as json_out:
  226. with tarfile.open(self.input_filename, "r") as tar:
  227. for tarinfo in tar:
  228. self.process_entry(tarinfo, warc_out, tar_out, json_out)
  229. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  230. if padding > 0:
  231. tar_out.write("\0" * padding)
  232. def process_entry(self, entry, warc_out, tar_out, json_out):
  233. with open(self.input_filename, "r") as tar:
  234. tar.seek(entry.offset)
  235. tar_header = tar.read(entry.offset_data - entry.offset)
  236. # calculate position of tar entry
  237. block_size = (len(tar_header) + # header
  238. entry.size + # data
  239. (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE)
  240. next_offset = entry.offset + block_size
  241. d_src_offsets = OrderedDict()
  242. d_src_offsets["entry"] = entry.offset
  243. d_src_offsets["data"] = entry.offset_data
  244. d_src_offsets["next_entry"] = next_offset
  245. # decide what to do with this entry
  246. valid_warc_gz = False
  247. if entry.isfile() and re.search(r"\.warc\.gz", entry.name):
  248. # this is a .warc.gz
  249. if self.verbose:
  250. print >>sys.stderr, "Checking %s" % entry.name
  251. # add to megawarc while copying to the megawarc.warc.gz
  252. warc_offset = warc_out.tell()
  253. valid_warc_gz = test_gz(self.input_filename, entry.offset_data, entry.size,
  254. copy_to_file=warc_out, verbose=self.verbose)
  255. # save in megawarc or in tar
  256. d_target = OrderedDict()
  257. if valid_warc_gz:
  258. # a warc file.gz, add to megawarc
  259. if self.verbose:
  260. print >>sys.stderr, "Copied %s to warc" % entry.name
  261. d_target["container"] = "warc"
  262. d_target["offset"] = warc_offset
  263. d_target["size"] = entry.size
  264. else:
  265. # not a warc.gz file, add to tar
  266. tar_offset = tar_out.tell()
  267. if self.verbose:
  268. print >>sys.stderr, "Copying %s to tar" % entry.name
  269. copy_to_stream(tar_out, self.input_filename, entry.offset, block_size)
  270. d_target["container"] = "tar"
  271. d_target["offset"] = tar_offset
  272. d_target["size"] = block_size
  273. # store details
  274. d = OrderedDict()
  275. d["target"] = d_target
  276. d["src_offsets"] = d_src_offsets
  277. d["header_fields"] = entry.get_info("utf-8", {})
  278. d["header_base64"] = base64.b64encode(tar_header)
  279. # store metadata
  280. json.dump(d, json_out, separators=(',', ':'))
  281. json_out.write("\n")
  282. # adding .warc.gz and other files to megawarc tar+warc+json
  283. class MegawarcPacker(object):
  284. def __init__(self, output_basename):
  285. self.verbose = False
  286. self.output_basename = output_basename
  287. self.output_warc_filename = output_basename + ".megawarc.warc.gz"
  288. self.output_tar_filename = output_basename + ".megawarc.tar"
  289. self.output_json_filename = output_basename + ".megawarc.json.gz"
  290. self.tar_pos = 0
  291. def process(self, filelist):
  292. with open(self.output_warc_filename, "wb") as warc_out:
  293. with open(self.output_tar_filename, "wb") as tar_out:
  294. with gzip.open(self.output_json_filename, "wb") as json_out:
  295. def each_file(arg, dirname, names):
  296. for n in names:
  297. n = os.path.join(dirname, n)
  298. if os.path.isfile(n):
  299. self.process_file(n, warc_out, tar_out, json_out)
  300. for filename in filelist:
  301. if os.path.isdir(filename):
  302. os.path.walk(filename, each_file, None)
  303. elif os.path.isfile(filename):
  304. self.process_file(filename, warc_out, tar_out, json_out)
  305. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  306. if padding > 0:
  307. tar_out.write("\0" * padding)
  308. def process_file(self, filename, warc_out, tar_out, json_out):
  309. # make tar header
  310. arcname = filename
  311. arcname = arcname.replace(os.sep, "/")
  312. arcname = arcname.lstrip("/")
  313. entry = tarfile.TarInfo()
  314. statres = os.stat(filename)
  315. stmd = statres.st_mode
  316. entry.name = arcname
  317. entry.mode = stmd
  318. entry.uid = statres.st_uid
  319. entry.gid = statres.st_gid
  320. entry.size = statres.st_size
  321. entry.mtime = statres.st_mtime
  322. entry.type = tarfile.REGTYPE
  323. tar_header = entry.tobuf()
  324. # find position in imaginary tar
  325. entry.offset = self.tar_pos
  326. # calculate position of tar entry
  327. tar_header_l = len(tar_header)
  328. block_size = (tar_header_l + # header
  329. entry.size + # data
  330. (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE)
  331. data_offset = entry.offset + tar_header_l
  332. next_offset = entry.offset + block_size
  333. # move to next position in imaginary tar
  334. self.tar_pos = next_offset
  335. d_src_offsets = OrderedDict()
  336. d_src_offsets["entry"] = entry.offset
  337. d_src_offsets["data"] = data_offset
  338. d_src_offsets["next_entry"] = next_offset
  339. # decide what to do with this file
  340. valid_warc_gz = False
  341. if re.search(r"\.warc\.gz", filename):
  342. if self.verbose:
  343. print >>sys.stderr, "Checking %s" % filename
  344. warc_offset = warc_out.tell()
  345. valid_warc_gz = test_gz(filename, 0, entry.size,
  346. copy_to_file=warc_out, verbose=self.verbose)
  347. # save in megawarc or in tar
  348. d_target = OrderedDict()
  349. if valid_warc_gz:
  350. # a warc file.gz, add to megawarc
  351. if self.verbose:
  352. print >>sys.stderr, "Copied %s to warc" % filename
  353. d_target["container"] = "warc"
  354. d_target["offset"] = warc_offset
  355. d_target["size"] = entry.size
  356. else:
  357. # not a warc.gz file, add to tar
  358. tar_offset = tar_out.tell()
  359. if self.verbose:
  360. print >>sys.stderr, "Copying %s to tar" % filename
  361. tar_out.write(tar_header)
  362. copy_to_stream(tar_out, filename, 0, entry.size)
  363. padding = (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE
  364. if padding > 0:
  365. tar_out.write("\0" * padding)
  366. d_target["container"] = "tar"
  367. d_target["offset"] = tar_offset
  368. d_target["size"] = block_size
  369. # store details
  370. d = OrderedDict()
  371. d["target"] = d_target
  372. d["src_offsets"] = d_src_offsets
  373. d["header_fields"] = entry.get_info("utf-8", {})
  374. d["header_base64"] = base64.b64encode(tar_header)
  375. # store metadata
  376. json.dump(d, json_out, separators=(',', ':'))
  377. json_out.write("\n")
  378. # recreate the original .tar from a megawarc tar+warc+json
  379. class MegawarcRestorer(object):
  380. def __init__(self, output_filename):
  381. self.verbose = False
  382. self.output_filename = output_filename
  383. self.input_warc_filename = output_filename + ".megawarc.warc.gz"
  384. self.input_tar_filename = output_filename + ".megawarc.tar"
  385. self.input_json_filename = output_filename + ".megawarc.json.gz"
  386. def process(self):
  387. with gzip.open(self.input_json_filename, "rb") as json_in:
  388. with open(self.output_filename, "wb") as tar_out:
  389. for line in json_in:
  390. entry = json.loads(line)
  391. self.process_entry(entry, tar_out)
  392. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  393. if padding > 0:
  394. tar_out.write("\0" * padding)
  395. def process_entry(self, entry, tar_out):
  396. if entry["target"]["container"] == "warc":
  397. if self.verbose:
  398. print >>sys.stderr, "Copying %s from warc" % entry["header_fields"]["name"]
  399. if "header_base64" in entry:
  400. tar_out.write(base64.b64decode(entry["header_base64"]))
  401. elif "header_string" in entry:
  402. tar_out.write(entry["header_string"])
  403. else:
  404. raise Exception("Missing header_string or header_base64.")
  405. copy_to_stream(tar_out, self.input_warc_filename,
  406. entry["target"]["offset"], entry["target"]["size"])
  407. padding = (tarfile.BLOCKSIZE - entry["target"]["size"]) % tarfile.BLOCKSIZE
  408. if padding > 0:
  409. tar_out.write("\0" * padding)
  410. elif entry["target"]["container"] == "tar":
  411. if self.verbose:
  412. print >>sys.stderr, "Copying %s from tar" % entry["header_fields"]["name"]
  413. copy_to_stream(tar_out, self.input_tar_filename,
  414. entry["target"]["offset"], entry["target"]["size"])
  415. padding = (tarfile.BLOCKSIZE - entry["target"]["size"]) % tarfile.BLOCKSIZE
  416. if padding > 0:
  417. tar_out.write("\0" * padding)
  418. else:
  419. raise Exception("Unkown container: %s for %s" %
  420. (entry["target"]["container"], entry["header_fields"]["name"]))
  421. def main():
  422. parser = OptionParser(
  423. usage="Usage: %prog [--verbose] convert FILE\n %prog [--verbose] pack FILE [INFILE [INFILE ...]]\n %prog [--verbose] restore FILE",
  424. description="""%prog convert FILE converts the tar file (containing .warc.gz files) to a megawarc. A megawarc has three parts: 1. a .warc.gz of the concatenated warc files; 2. a .tar with the non-warc files from the original tar; 3. a .json.gz with metadata that can be used to reconstruct the original tar.
  425. Use %prog pack FILE INFILE ... to create a megawarc containing the files.
  426. Use %prog restore FILE to reconstruct original tar.
  427. """
  428. )
  429. parser.add_option("-v", "--verbose", dest="verbose",
  430. action="store_true",
  431. help="print status messages", default=False)
  432. (options, args) = parser.parse_args()
  433. if len(args) < 2:
  434. parser.print_usage()
  435. exit(1)
  436. if args[0] == "convert":
  437. if not os.path.exists(args[1]):
  438. print >>sys.stderr, "Input file %s does not exist." % args[1]
  439. exit(1)
  440. try:
  441. mwb = MegawarcBuilder(args[1])
  442. mwb.verbose = options.verbose
  443. mwb.process()
  444. except:
  445. for ext in (".megawarc.warc.gz", ".megawarc.json.gz", ".megawarc.tar"):
  446. if os.path.exists(args[1]+ext):
  447. os.unlink(args[1]+ext)
  448. raise
  449. elif args[0] == "pack":
  450. try:
  451. mwb = MegawarcPacker(args[1])
  452. mwb.verbose = options.verbose
  453. mwb.process(args[2:])
  454. except:
  455. for ext in (".megawarc.warc.gz", ".megawarc.json.gz", ".megawarc.tar"):
  456. if os.path.exists(args[1]+ext):
  457. os.unlink(args[1]+ext)
  458. raise
  459. elif args[0] == "restore":
  460. for ext in (".megawarc.warc.gz", ".megawarc.json.gz"):
  461. if not os.path.exists(args[1]+ext):
  462. print >>sys.stderr, "Input file %s does not exist." % (args[1] + ext)
  463. exit(1)
  464. if os.path.exists(args[1]):
  465. print >>sys.stderr, "Outputfile %s already exists." % args[1]
  466. exit(1)
  467. try:
  468. mwr = MegawarcRestorer(args[1])
  469. mwr.verbose = options.verbose
  470. mwr.process()
  471. except:
  472. if os.path.exists(args[1]):
  473. os.unlink(args[1])
  474. raise
  475. else:
  476. parser.print_usage()
  477. exit(1)
  478. if __name__ == "__main__":
  479. main()