A framework for quick web archiving
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.

233 lines
8.3 KiB

  1. import fcntl
  2. import gzip
  3. import io
  4. import itertools
  5. import json
  6. import logging
  7. import os
  8. import qwarc.utils
  9. import tempfile
  10. import time
  11. import warcio
  12. class WARC:
  13. def __init__(self, prefix, maxFileSize, dedupe, command, specFile, specDependencies, logFilename):
  14. '''
  15. Initialise the WARC writer
  16. prefix: str, path prefix for WARCs; a dash, a five-digit number, and ".warc.gz" will be appended.
  17. maxFileSize: int, maximum size of an individual WARC. Use 0 to disable splitting.
  18. dedupe: bool, whether to enable record deduplication
  19. command: list, the command line call for qwarc
  20. specFile: str, path to the spec file
  21. specDependencies: qwarc.utils.SpecDependencies
  22. logFilename: str, name of the log file written by this process
  23. '''
  24. self._prefix = prefix
  25. self._counter = 0
  26. self._maxFileSize = maxFileSize
  27. self._closed = True
  28. self._file = None
  29. self._warcWriter = None
  30. self._dedupe = dedupe
  31. self._dedupeMap = {}
  32. self._command = command
  33. self._specFile = specFile
  34. self._specDependencies = specDependencies
  35. self._logFile = None
  36. self._logHandler = None
  37. self._setup_logger()
  38. self._logFilename = logFilename
  39. self._metaWarcinfoRecordID = None
  40. self._write_meta_warc(self._write_initial_meta_records)
  41. def _setup_logger(self):
  42. rootLogger = logging.getLogger()
  43. formatter = qwarc.utils.LogFormatter()
  44. self._logFile = tempfile.NamedTemporaryFile(prefix = 'qwarc-warc-', suffix = '.log.gz', delete = False)
  45. self._logHandler = logging.StreamHandler(io.TextIOWrapper(gzip.GzipFile(filename = self._logFile.name, mode = 'wb'), encoding = 'utf-8'))
  46. self._logHandler.setFormatter(formatter)
  47. rootLogger.addHandler(self._logHandler)
  48. self._logHandler.setLevel(logging.INFO)
  49. def _ensure_opened(self):
  50. '''Open the next file that doesn't exist yet if there is currently no file opened'''
  51. if not self._closed:
  52. return
  53. while True:
  54. filename = f'{self._prefix}-{self._counter:05d}.warc.gz'
  55. try:
  56. # Try to open the file for writing, requiring that it does not exist yet, and attempt to get an exclusive, non-blocking lock on it
  57. self._file = open(filename, 'xb')
  58. fcntl.flock(self._file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  59. except FileExistsError:
  60. logging.info(f'{filename} already exists, skipping')
  61. self._counter += 1
  62. else:
  63. break
  64. logging.info(f'Opened {filename}')
  65. self._warcWriter = warcio.warcwriter.WARCWriter(self._file, gzip = True, warc_version = '1.1')
  66. self._closed = False
  67. self._counter += 1
  68. def _write_warcinfo_record(self):
  69. data = {
  70. 'software': qwarc.utils.get_software_info(self._specFile, self._specDependencies),
  71. 'command': self._command,
  72. 'files': {
  73. 'spec': self._specFile,
  74. 'spec-dependencies': self._specDependencies.files
  75. },
  76. 'extra': self._specDependencies.extra,
  77. }
  78. payload = io.BytesIO(json.dumps(data, indent = 2).encode('utf-8'))
  79. digester = warcio.utils.Digester('sha1')
  80. digester.update(payload.getvalue())
  81. record = self._warcWriter.create_warc_record(
  82. None,
  83. 'warcinfo',
  84. payload = payload,
  85. warc_headers_dict = {'Content-Type': 'application/json; charset=utf-8', 'WARC-Block-Digest': str(digester)},
  86. length = len(payload.getvalue()),
  87. )
  88. self._warcWriter.write_record(record)
  89. return record.rec_headers.get_header('WARC-Record-ID')
  90. def write_client_response(self, response):
  91. '''
  92. Write the requests and responses stored in a ClientResponse instance to the currently opened WARC.
  93. A new WARC will be started automatically if the size of the current file exceeds the limit after writing all requests and responses from this `response` to the current WARC.
  94. '''
  95. self._ensure_opened()
  96. for r in response.iter_all():
  97. usec = f'{(r.rawRequestTimestamp - int(r.rawRequestTimestamp)):.6f}'[2:]
  98. requestDate = time.strftime(f'%Y-%m-%dT%H:%M:%S.{usec}Z', time.gmtime(r.rawRequestTimestamp))
  99. requestRecord = self._warcWriter.create_warc_record(
  100. str(r.url),
  101. 'request',
  102. payload = io.BytesIO(r.rawRequestData),
  103. warc_headers_dict = {
  104. 'WARC-Date': requestDate,
  105. 'WARC-IP-Address': r.remoteAddress[0],
  106. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  107. }
  108. )
  109. requestRecordID = requestRecord.rec_headers.get_header('WARC-Record-ID')
  110. responseRecord = self._warcWriter.create_warc_record(
  111. str(r.url),
  112. 'response',
  113. payload = io.BytesIO(r.rawResponseData),
  114. warc_headers_dict = {
  115. 'WARC-Date': requestDate,
  116. 'WARC-IP-Address': r.remoteAddress[0],
  117. 'WARC-Concurrent-To': requestRecordID,
  118. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  119. }
  120. )
  121. payloadDigest = responseRecord.rec_headers.get_header('WARC-Payload-Digest')
  122. assert payloadDigest is not None
  123. if self._dedupe and responseRecord.payload_length > 0: # Don't "deduplicate" empty responses
  124. if payloadDigest in self._dedupeMap:
  125. refersToRecordId, refersToUri, refersToDate = self._dedupeMap[payloadDigest]
  126. responseHttpHeaders = responseRecord.http_headers
  127. responseRecord = self._warcWriter.create_revisit_record(
  128. str(r.url),
  129. digest = payloadDigest,
  130. refers_to_uri = refersToUri,
  131. refers_to_date = refersToDate,
  132. http_headers = responseHttpHeaders,
  133. warc_headers_dict = {
  134. 'WARC-Date': requestDate,
  135. 'WARC-IP-Address': r.remoteAddress[0],
  136. 'WARC-Concurrent-To': requestRecordID,
  137. 'WARC-Refers-To': refersToRecordId,
  138. 'WARC-Truncated': 'length',
  139. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  140. }
  141. )
  142. # Workaround for https://github.com/webrecorder/warcio/issues/94
  143. responseRecord.rec_headers.replace_header('WARC-Profile', 'http://netpreserve.org/warc/1.1/revisit/identical-payload-digest')
  144. else:
  145. self._dedupeMap[payloadDigest] = (responseRecord.rec_headers.get_header('WARC-Record-ID'), str(r.url), requestDate)
  146. self._warcWriter.write_record(requestRecord)
  147. self._warcWriter.write_record(responseRecord)
  148. if self._maxFileSize and self._file.tell() > self._maxFileSize:
  149. self._close_file()
  150. def _write_resource_records(self):
  151. '''Write spec file and dependencies'''
  152. assert self._metaWarcinfoRecordID is not None, 'write_warcinfo_record must be called first'
  153. for type_, contentType, fn in itertools.chain((('specfile', 'application/x-python', self._specFile),), map(lambda x: ('spec-dependency-file', 'application/octet-stream', x), self._specDependencies.files)):
  154. with open(fn, 'rb') as f:
  155. record = self._warcWriter.create_warc_record(
  156. f'file://{fn}',
  157. 'resource',
  158. payload = f,
  159. warc_headers_dict = {'X-QWARC-Type': type_, 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID, 'Content-Type': contentType},
  160. )
  161. self._warcWriter.write_record(record)
  162. def _write_initial_meta_records(self):
  163. self._metaWarcinfoRecordID = self._write_warcinfo_record()
  164. self._write_resource_records()
  165. def _write_log_record(self):
  166. assert self._metaWarcinfoRecordID is not None, 'write_warcinfo_record must be called first'
  167. self._logHandler.flush()
  168. self._logHandler.stream.close()
  169. record = self._warcWriter.create_warc_record(
  170. f'file://{self._logFilename}',
  171. 'resource',
  172. payload = gzip.GzipFile(self._logFile.name),
  173. warc_headers_dict = {'X-QWARC-Type': 'log', 'Content-Type': 'text/plain; charset=utf-8', 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID},
  174. )
  175. self._warcWriter.write_record(record)
  176. def _close_file(self):
  177. '''Close the currently opened WARC'''
  178. if not self._closed:
  179. self._file.close()
  180. self._warcWriter = None
  181. self._file = None
  182. self._closed = True
  183. def _write_meta_warc(self, callback):
  184. filename = f'{self._prefix}-meta.warc.gz'
  185. #TODO: Handle OSError on fcntl.flock and retry
  186. self._file = open(filename, 'ab')
  187. try:
  188. fcntl.flock(self._file.fileno(), fcntl.LOCK_EX)
  189. logging.info(f'Opened {filename}')
  190. self._warcWriter = warcio.warcwriter.WARCWriter(self._file, gzip = True, warc_version = '1.1')
  191. self._closed = False
  192. callback()
  193. finally:
  194. self._close_file()
  195. def close(self):
  196. '''Clean up everything.'''
  197. self._close_file()
  198. logging.getLogger().removeHandler(self._logHandler)
  199. self._write_meta_warc(self._write_log_record)
  200. try:
  201. os.remove(self._logFile.name)
  202. except OSError:
  203. logging.error('Could not remove temporary log file')
  204. self._logFile = None
  205. self._logHandler.close()
  206. self._logHandler = None