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.

571 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. stream.flush()
  114. finally:
  115. if progress:
  116. progress.clear()
  117. # part of a stream as a file
  118. # (seek relative to an offset)
  119. class RangeFile(object):
  120. def __init__(self, stream, offset, size):
  121. self._stream = stream
  122. self._offset = offset
  123. self._size = size
  124. self._current_rel_offset = 0
  125. self.seek(0)
  126. def tell(self):
  127. return self._current_rel_offset
  128. def seek(self, pos, whence=os.SEEK_SET):
  129. if whence == os.SEEK_SET:
  130. self._current_rel_offset = pos
  131. elif whence == os.SEEK_CUR:
  132. self._current_rel_offset += pos
  133. elif whence == os.SEEK_END:
  134. self._current_rel_offset = self._size + pos
  135. else:
  136. raise Exception("Unknown whence: %d." % whence)
  137. if self._current_rel_offset < 0 or self._current_rel_offset > self._size:
  138. raise Exception("Seek outside file: %d." % self._current_rel_offset)
  139. self._stream.seek(self._offset + self._current_rel_offset)
  140. def read(self, size):
  141. size = min(self._size - self._current_rel_offset, size)
  142. self._current_rel_offset += size
  143. buf = self._stream.read(size)
  144. if len(buf) < size:
  145. raise Exception("Expected to read %d but received %d." % (size, len(buf)))
  146. return buf
  147. # copies while reading
  148. class CopyReader(object):
  149. def __init__(self, in_stream, out_stream):
  150. self._in_stream = in_stream
  151. self._out_stream = out_stream
  152. self._last_read = 0
  153. def tell(self):
  154. return self._in_stream.tell()
  155. def seek(self, pos, whence=os.SEEK_SET):
  156. self._in_stream.seek(pos, whence)
  157. def read(self, size):
  158. pos = self.tell()
  159. if self._last_read < pos:
  160. raise Exception("Last read: %d Current pos: %d" % (self._last_read, pos))
  161. buf = self._in_stream.read(size)
  162. read_before = self._last_read - pos
  163. if read_before == 0:
  164. new_read = buf
  165. else:
  166. new_read = buf[read_before:]
  167. l = len(new_read)
  168. if l > 0:
  169. self._last_read += l
  170. self._out_stream.write(new_read)
  171. return buf
  172. # check for gzip errors
  173. def test_gz(filename, offset, size, verbose=False, copy_to_file=None):
  174. with open(filename, "r") as f_stream:
  175. f = RangeFile(f_stream, offset, size)
  176. if verbose and size > 10 * 1024 * 1024:
  177. progress = ProgressInfo(-size)
  178. else:
  179. progress = None
  180. if copy_to_file:
  181. f = CopyReader(f, copy_to_file)
  182. start_pos = copy_to_file.tell()
  183. try:
  184. with open("/dev/null", "w") as dev_null:
  185. gz = subprocess.Popen(["gunzip", "-tv"],
  186. shell=False,
  187. stdin=subprocess.PIPE,
  188. stdout=dev_null,
  189. stderr=dev_null)
  190. while True:
  191. buf = f.read(4096)
  192. size -= len(buf)
  193. if progress:
  194. progress.update(-size)
  195. if len(buf) > 0:
  196. gz.stdin.write(buf)
  197. else:
  198. break
  199. gz.stdin.close()
  200. ret = gz.wait()
  201. if ret != 0:
  202. raise IOError("Could not decompress warc.gz. gunzip returned %d." % ret)
  203. if progress:
  204. progress.clear()
  205. except (IOError, OSError) as e:
  206. if progress:
  207. progress.clear()
  208. if verbose:
  209. print >>sys.stderr, e
  210. if copy_to_file:
  211. copy_to_file.truncate(start_pos)
  212. copy_to_file.seek(start_pos)
  213. return False
  214. return True
  215. # converting a .tar with warcs to megawarc tar+warc+json
  216. class MegawarcBuilder(object):
  217. def __init__(self, input_filename):
  218. self.verbose = False
  219. self.input_filename = input_filename
  220. self.output_warc_filename = input_filename + ".megawarc.warc.gz"
  221. self.output_tar_filename = input_filename + ".megawarc.tar"
  222. self.output_json_filename = input_filename + ".megawarc.json.gz"
  223. def process(self):
  224. with open(self.output_warc_filename, "wb") as warc_out:
  225. with open(self.output_tar_filename, "wb") as tar_out:
  226. with gzip.open(self.output_json_filename, "wb") as json_out:
  227. with tarfile.open(self.input_filename, "r") as tar:
  228. for tarinfo in tar:
  229. self.process_entry(tarinfo, warc_out, tar_out, json_out)
  230. tar_out.flush()
  231. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  232. if padding > 0:
  233. tar_out.write("\0" * padding)
  234. def process_entry(self, entry, warc_out, tar_out, json_out):
  235. with open(self.input_filename, "r") as tar:
  236. tar.seek(entry.offset)
  237. tar_header = tar.read(entry.offset_data - entry.offset)
  238. # calculate position of tar entry
  239. block_size = (len(tar_header) + # header
  240. entry.size + # data
  241. (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE)
  242. next_offset = entry.offset + block_size
  243. d_src_offsets = OrderedDict()
  244. d_src_offsets["entry"] = entry.offset
  245. d_src_offsets["data"] = entry.offset_data
  246. d_src_offsets["next_entry"] = next_offset
  247. # decide what to do with this entry
  248. valid_warc_gz = False
  249. if entry.isfile() and re.search(r"\.warc\.gz", entry.name):
  250. # this is a .warc.gz
  251. if self.verbose:
  252. print >>sys.stderr, "Checking %s" % entry.name
  253. # add to megawarc while copying to the megawarc.warc.gz
  254. warc_offset = warc_out.tell()
  255. valid_warc_gz = test_gz(self.input_filename, entry.offset_data, entry.size,
  256. copy_to_file=warc_out, verbose=self.verbose)
  257. # save in megawarc or in tar
  258. d_target = OrderedDict()
  259. if valid_warc_gz:
  260. # a warc file.gz, add to megawarc
  261. if self.verbose:
  262. print >>sys.stderr, "Copied %s to warc" % entry.name
  263. d_target["container"] = "warc"
  264. d_target["offset"] = warc_offset
  265. d_target["size"] = entry.size
  266. else:
  267. # not a warc.gz file, add to tar
  268. tar_offset = tar_out.tell()
  269. if self.verbose:
  270. print >>sys.stderr, "Copying %s to tar" % entry.name
  271. copy_to_stream(tar_out, self.input_filename, entry.offset, block_size)
  272. d_target["container"] = "tar"
  273. d_target["offset"] = tar_offset
  274. d_target["size"] = block_size
  275. # store details
  276. d = OrderedDict()
  277. d["target"] = d_target
  278. d["src_offsets"] = d_src_offsets
  279. d["header_fields"] = entry.get_info("utf-8", {})
  280. d["header_base64"] = base64.b64encode(tar_header)
  281. # store metadata
  282. json.dump(d, json_out, separators=(',', ':'))
  283. json_out.write("\n")
  284. # adding .warc.gz and other files to megawarc tar+warc+json
  285. class MegawarcPacker(object):
  286. def __init__(self, output_basename):
  287. self.verbose = False
  288. self.output_basename = output_basename
  289. self.output_warc_filename = output_basename + ".megawarc.warc.gz"
  290. self.output_tar_filename = output_basename + ".megawarc.tar"
  291. self.output_json_filename = output_basename + ".megawarc.json.gz"
  292. self.tar_pos = 0
  293. def process(self, filelist):
  294. with open(self.output_warc_filename, "wb") as warc_out:
  295. with open(self.output_tar_filename, "wb") as tar_out:
  296. with gzip.open(self.output_json_filename, "wb") as json_out:
  297. def each_file(arg, dirname, names):
  298. for n in names:
  299. n = os.path.join(dirname, n)
  300. if os.path.isfile(n):
  301. self.process_file(n, warc_out, tar_out, json_out)
  302. for filename in filelist:
  303. if os.path.isdir(filename):
  304. os.path.walk(filename, each_file, None)
  305. elif os.path.isfile(filename):
  306. self.process_file(filename, warc_out, tar_out, json_out)
  307. tar_out.flush()
  308. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  309. if padding > 0:
  310. tar_out.write("\0" * padding)
  311. def process_file(self, filename, warc_out, tar_out, json_out):
  312. # make tar header
  313. arcname = filename
  314. arcname = arcname.replace(os.sep, "/")
  315. arcname = arcname.lstrip("/")
  316. entry = tarfile.TarInfo()
  317. statres = os.stat(filename)
  318. stmd = statres.st_mode
  319. entry.name = arcname
  320. entry.mode = stmd
  321. entry.uid = statres.st_uid
  322. entry.gid = statres.st_gid
  323. entry.size = statres.st_size
  324. entry.mtime = statres.st_mtime
  325. entry.type = tarfile.REGTYPE
  326. tar_header = entry.tobuf()
  327. # find position in imaginary tar
  328. entry.offset = self.tar_pos
  329. # calculate position of tar entry
  330. tar_header_l = len(tar_header)
  331. block_size = (tar_header_l + # header
  332. entry.size + # data
  333. (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE)
  334. data_offset = entry.offset + tar_header_l
  335. next_offset = entry.offset + block_size
  336. # move to next position in imaginary tar
  337. self.tar_pos = next_offset
  338. d_src_offsets = OrderedDict()
  339. d_src_offsets["entry"] = entry.offset
  340. d_src_offsets["data"] = data_offset
  341. d_src_offsets["next_entry"] = next_offset
  342. # decide what to do with this file
  343. valid_warc_gz = False
  344. if re.search(r"\.warc\.gz", filename):
  345. if self.verbose:
  346. print >>sys.stderr, "Checking %s" % filename
  347. warc_offset = warc_out.tell()
  348. valid_warc_gz = test_gz(filename, 0, entry.size,
  349. copy_to_file=warc_out, verbose=self.verbose)
  350. # save in megawarc or in tar
  351. d_target = OrderedDict()
  352. if valid_warc_gz:
  353. # a warc file.gz, add to megawarc
  354. if self.verbose:
  355. print >>sys.stderr, "Copied %s to warc" % filename
  356. d_target["container"] = "warc"
  357. d_target["offset"] = warc_offset
  358. d_target["size"] = entry.size
  359. else:
  360. # not a warc.gz file, add to tar
  361. tar_offset = tar_out.tell()
  362. if self.verbose:
  363. print >>sys.stderr, "Copying %s to tar" % filename
  364. tar_out.write(tar_header)
  365. copy_to_stream(tar_out, filename, 0, entry.size)
  366. padding = (tarfile.BLOCKSIZE - entry.size) % tarfile.BLOCKSIZE
  367. if padding > 0:
  368. tar_out.write("\0" * padding)
  369. tar_out.flush()
  370. d_target["container"] = "tar"
  371. d_target["offset"] = tar_offset
  372. d_target["size"] = block_size
  373. # store details
  374. d = OrderedDict()
  375. d["target"] = d_target
  376. d["src_offsets"] = d_src_offsets
  377. d["header_fields"] = entry.get_info("utf-8", {})
  378. d["header_base64"] = base64.b64encode(tar_header)
  379. # store metadata
  380. json.dump(d, json_out, separators=(',', ':'))
  381. json_out.write("\n")
  382. # recreate the original .tar from a megawarc tar+warc+json
  383. class MegawarcRestorer(object):
  384. def __init__(self, output_filename):
  385. self.verbose = False
  386. self.output_filename = output_filename
  387. self.input_warc_filename = output_filename + ".megawarc.warc.gz"
  388. self.input_tar_filename = output_filename + ".megawarc.tar"
  389. self.input_json_filename = output_filename + ".megawarc.json.gz"
  390. def process(self):
  391. with gzip.open(self.input_json_filename, "rb") as json_in:
  392. with open(self.output_filename, "wb") as tar_out:
  393. for line in json_in:
  394. entry = json.loads(line)
  395. self.process_entry(entry, tar_out)
  396. tar_out.flush()
  397. padding = (tarfile.RECORDSIZE - tar_out.tell()) % tarfile.RECORDSIZE
  398. if padding > 0:
  399. tar_out.write("\0" * padding)
  400. def process_entry(self, entry, tar_out):
  401. if entry["target"]["container"] == "warc":
  402. if self.verbose:
  403. print >>sys.stderr, "Copying %s from warc" % entry["header_fields"]["name"]
  404. if "header_base64" in entry:
  405. tar_out.write(base64.b64decode(entry["header_base64"]))
  406. elif "header_string" in entry:
  407. tar_out.write(entry["header_string"])
  408. else:
  409. raise Exception("Missing header_string or header_base64.")
  410. copy_to_stream(tar_out, self.input_warc_filename,
  411. entry["target"]["offset"], entry["target"]["size"])
  412. padding = (tarfile.BLOCKSIZE - entry["target"]["size"]) % tarfile.BLOCKSIZE
  413. if padding > 0:
  414. tar_out.write("\0" * padding)
  415. elif entry["target"]["container"] == "tar":
  416. if self.verbose:
  417. print >>sys.stderr, "Copying %s from tar" % entry["header_fields"]["name"]
  418. copy_to_stream(tar_out, self.input_tar_filename,
  419. entry["target"]["offset"], entry["target"]["size"])
  420. padding = (tarfile.BLOCKSIZE - entry["target"]["size"]) % tarfile.BLOCKSIZE
  421. if padding > 0:
  422. tar_out.write("\0" * padding)
  423. else:
  424. raise Exception("Unkown container: %s for %s" %
  425. (entry["target"]["container"], entry["header_fields"]["name"]))
  426. def main():
  427. parser = OptionParser(
  428. usage="Usage: %prog [--verbose] convert FILE\n %prog [--verbose] pack FILE [INFILE [INFILE ...]]\n %prog [--verbose] restore FILE",
  429. 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.
  430. Use %prog pack FILE INFILE ... to create a megawarc containing the files.
  431. Use %prog restore FILE to reconstruct original tar.
  432. """
  433. )
  434. parser.add_option("-v", "--verbose", dest="verbose",
  435. action="store_true",
  436. help="print status messages", default=False)
  437. (options, args) = parser.parse_args()
  438. if len(args) < 2:
  439. parser.print_usage()
  440. exit(1)
  441. if args[0] == "convert":
  442. if not os.path.exists(args[1]):
  443. print >>sys.stderr, "Input file %s does not exist." % args[1]
  444. exit(1)
  445. try:
  446. mwb = MegawarcBuilder(args[1])
  447. mwb.verbose = options.verbose
  448. mwb.process()
  449. except:
  450. for ext in (".megawarc.warc.gz", ".megawarc.json.gz", ".megawarc.tar"):
  451. if os.path.exists(args[1]+ext):
  452. os.unlink(args[1]+ext)
  453. raise
  454. elif args[0] == "pack":
  455. try:
  456. mwb = MegawarcPacker(args[1])
  457. mwb.verbose = options.verbose
  458. mwb.process(args[2:])
  459. except:
  460. for ext in (".megawarc.warc.gz", ".megawarc.json.gz", ".megawarc.tar"):
  461. if os.path.exists(args[1]+ext):
  462. os.unlink(args[1]+ext)
  463. raise
  464. elif args[0] == "restore":
  465. for ext in (".megawarc.warc.gz", ".megawarc.json.gz"):
  466. if not os.path.exists(args[1]+ext):
  467. print >>sys.stderr, "Input file %s does not exist." % (args[1] + ext)
  468. exit(1)
  469. if os.path.exists(args[1]):
  470. print >>sys.stderr, "Outputfile %s already exists." % args[1]
  471. exit(1)
  472. try:
  473. mwr = MegawarcRestorer(args[1])
  474. mwr.verbose = options.verbose
  475. mwr.process()
  476. except:
  477. if os.path.exists(args[1]):
  478. os.unlink(args[1])
  479. raise
  480. else:
  481. parser.print_usage()
  482. exit(1)
  483. if __name__ == "__main__":
  484. main()