A framework for quick web archiving
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

232 wiersze
8.2 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._logFilename = logFilename
  36. self._metaWarcinfoRecordID = None
  37. self._write_meta_warc(self._write_initial_meta_records)
  38. def _ensure_opened(self):
  39. '''Open the next file that doesn't exist yet if there is currently no file opened'''
  40. if not self._closed:
  41. return
  42. while True:
  43. filename = f'{self._prefix}-{self._counter:05d}.warc.gz'
  44. try:
  45. # 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
  46. self._file = open(filename, 'xb')
  47. fcntl.flock(self._file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  48. except FileExistsError:
  49. logging.info(f'{filename} already exists, skipping')
  50. self._counter += 1
  51. else:
  52. break
  53. logging.info(f'Opened {filename}')
  54. self._warcWriter = warcio.warcwriter.WARCWriter(self._file, gzip = True, warc_version = '1.1')
  55. self._closed = False
  56. self._counter += 1
  57. def _write_warcinfo_record(self):
  58. data = {
  59. 'software': qwarc.utils.get_software_info(self._specFile, self._specDependencies),
  60. 'command': self._command,
  61. 'files': {
  62. 'spec': self._specFile,
  63. 'spec-dependencies': self._specDependencies.files
  64. },
  65. 'extra': self._specDependencies.extra,
  66. }
  67. payload = io.BytesIO(json.dumps(data, indent = 2).encode('utf-8'))
  68. # Workaround for https://github.com/webrecorder/warcio/issues/87
  69. digester = warcio.utils.Digester('sha1')
  70. digester.update(payload.getvalue())
  71. record = self._warcWriter.create_warc_record(
  72. None,
  73. 'warcinfo',
  74. payload = payload,
  75. warc_headers_dict = {'Content-Type': 'application/json; charset=utf-8', 'WARC-Block-Digest': str(digester)},
  76. length = len(payload.getvalue()),
  77. )
  78. self._warcWriter.write_record(record)
  79. return record.rec_headers.get_header('WARC-Record-ID')
  80. def write_client_response(self, response):
  81. '''
  82. Write the requests and responses stored in a ClientResponse instance to the currently opened WARC.
  83. 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.
  84. '''
  85. self._ensure_opened()
  86. for r in response.iter_all():
  87. usec = f'{(r.rawRequestTimestamp - int(r.rawRequestTimestamp)):.6f}'[2:]
  88. requestDate = time.strftime(f'%Y-%m-%dT%H:%M:%S.{usec}Z', time.gmtime(r.rawRequestTimestamp))
  89. r.rawRequestData.seek(0, io.SEEK_END)
  90. length = r.rawRequestData.tell()
  91. r.rawRequestData.seek(0)
  92. requestRecord = self._warcWriter.create_warc_record(
  93. str(r.url),
  94. 'request',
  95. payload = r.rawRequestData,
  96. length = length,
  97. warc_headers_dict = {
  98. 'WARC-Date': requestDate,
  99. 'WARC-IP-Address': r.remoteAddress[0],
  100. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  101. }
  102. )
  103. requestRecordID = requestRecord.rec_headers.get_header('WARC-Record-ID')
  104. r.rawResponseData.seek(0, io.SEEK_END)
  105. length = r.rawResponseData.tell()
  106. r.rawResponseData.seek(0)
  107. responseRecord = self._warcWriter.create_warc_record(
  108. str(r.url),
  109. 'response',
  110. payload = r.rawResponseData,
  111. length = length,
  112. warc_headers_dict = {
  113. 'WARC-Date': requestDate,
  114. 'WARC-IP-Address': r.remoteAddress[0],
  115. 'WARC-Concurrent-To': requestRecordID,
  116. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  117. }
  118. )
  119. payloadDigest = responseRecord.rec_headers.get_header('WARC-Payload-Digest')
  120. assert payloadDigest is not None
  121. if self._dedupe and responseRecord.payload_length > 100: # Don't deduplicate small responses; the additional headers are typically larger than the payload dedupe savings...
  122. if payloadDigest in self._dedupeMap:
  123. refersToRecordId, refersToUri, refersToDate = self._dedupeMap[payloadDigest]
  124. responseHttpHeaders = responseRecord.http_headers
  125. responseRecord = self._warcWriter.create_revisit_record(
  126. str(r.url),
  127. digest = payloadDigest,
  128. refers_to_uri = refersToUri,
  129. refers_to_date = refersToDate,
  130. http_headers = responseHttpHeaders,
  131. warc_headers_dict = {
  132. 'WARC-Date': requestDate,
  133. 'WARC-IP-Address': r.remoteAddress[0],
  134. 'WARC-Concurrent-To': requestRecordID,
  135. 'WARC-Refers-To': refersToRecordId,
  136. 'WARC-Truncated': 'length',
  137. 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID,
  138. }
  139. )
  140. # Workaround for https://github.com/webrecorder/warcio/issues/94
  141. responseRecord.rec_headers.replace_header('WARC-Profile', 'http://netpreserve.org/warc/1.1/revisit/identical-payload-digest')
  142. else:
  143. self._dedupeMap[payloadDigest] = (responseRecord.rec_headers.get_header('WARC-Record-ID'), str(r.url), requestDate)
  144. self._warcWriter.write_record(requestRecord)
  145. self._warcWriter.write_record(responseRecord)
  146. if self._maxFileSize and self._file.tell() > self._maxFileSize:
  147. self._close_file()
  148. def _write_resource_records(self):
  149. '''Write spec file and dependencies'''
  150. assert self._metaWarcinfoRecordID is not None, 'write_warcinfo_record must be called first'
  151. 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)):
  152. with open(fn, 'rb') as f:
  153. f.seek(0, io.SEEK_END)
  154. length = f.tell()
  155. f.seek(0)
  156. record = self._warcWriter.create_warc_record(
  157. f'file://{fn}',
  158. 'resource',
  159. payload = f,
  160. length = length,
  161. warc_headers_dict = {'X-QWARC-Type': type_, 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID, 'Content-Type': contentType},
  162. )
  163. self._warcWriter.write_record(record)
  164. def _write_initial_meta_records(self):
  165. self._metaWarcinfoRecordID = self._write_warcinfo_record()
  166. self._write_resource_records()
  167. def _write_log_record(self):
  168. assert self._metaWarcinfoRecordID is not None, 'write_warcinfo_record must be called first'
  169. rootLogger = logging.getLogger()
  170. for handler in rootLogger.handlers: #FIXME: Uses undocumented attribute handlers
  171. handler.flush()
  172. with open(self._logFilename, 'rb') as fp:
  173. fp.seek(0, io.SEEK_END)
  174. length = fp.tell()
  175. fp.seek(0)
  176. record = self._warcWriter.create_warc_record(
  177. f'file://{self._logFilename}',
  178. 'resource',
  179. payload = fp,
  180. length = length,
  181. warc_headers_dict = {'X-QWARC-Type': 'log', 'Content-Type': 'text/plain; charset=utf-8', 'WARC-Warcinfo-ID': self._metaWarcinfoRecordID},
  182. )
  183. self._warcWriter.write_record(record)
  184. def _close_file(self):
  185. '''Close the currently opened WARC'''
  186. if not self._closed:
  187. self._file.close()
  188. self._warcWriter = None
  189. self._file = None
  190. self._closed = True
  191. def _write_meta_warc(self, callback):
  192. filename = f'{self._prefix}-meta.warc.gz'
  193. #TODO: Handle OSError on fcntl.flock and retry
  194. self._file = open(filename, 'ab')
  195. try:
  196. fcntl.flock(self._file.fileno(), fcntl.LOCK_EX)
  197. logging.info(f'Opened {filename}')
  198. self._warcWriter = warcio.warcwriter.WARCWriter(self._file, gzip = True, warc_version = '1.1')
  199. self._closed = False
  200. callback()
  201. finally:
  202. self._close_file()
  203. def close(self):
  204. '''Clean up everything.'''
  205. self._close_file()
  206. self._write_meta_warc(self._write_log_record)