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.

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