A framework for quick web archiving
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

432 Zeilen
16 KiB

  1. import qwarc.aiohttp
  2. from qwarc.const import *
  3. import qwarc.utils
  4. import qwarc.warc
  5. import aiohttp as _aiohttp
  6. if _aiohttp.__version__ != '2.3.10':
  7. raise ImportError('aiohttp must be version 2.3.10')
  8. import asyncio
  9. import collections
  10. import concurrent.futures
  11. import contextlib
  12. import io
  13. import itertools
  14. import logging
  15. import os
  16. import random
  17. import sqlite3
  18. import yarl
  19. class Item:
  20. itemType = None
  21. defaultResponseHandler = staticmethod(qwarc.utils.handle_response_default)
  22. def __init__(self, qwarcObj, itemValue, session, headers, warc):
  23. self.qwarcObj = qwarcObj
  24. self.itemValue = itemValue
  25. self.session = session
  26. self.headers = headers
  27. self.warc = warc
  28. if not hasattr(self, '_baseUrl'): # To allow subclasses to set the baseUrl before calling super().__init__
  29. self._baseUrl = None
  30. self.stats = {'tx': 0, 'rx': 0, 'requests': 0}
  31. self.logger = logging.LoggerAdapter(logging.getLogger(), {'itemType': self.itemType, 'itemValue': self.itemValue})
  32. self.childItems = []
  33. @property
  34. def baseUrl(self):
  35. return self._baseUrl
  36. @baseUrl.setter
  37. def baseUrl(self, baseUrl):
  38. if baseUrl is None:
  39. self._baseUrl = None
  40. elif isinstance(baseUrl, yarl.URL):
  41. self._baseUrl = baseUrl
  42. else:
  43. self._baseUrl = yarl.URL(baseUrl)
  44. def _merge_headers(self, headers, extraHeaders = []):
  45. d = {} # Preserves order from Python 3.7 (guaranteed) or CPython 3.6 (implementation detail)
  46. keys = {} # casefolded key -> d key
  47. for key, value in itertools.chain(self.headers, extraHeaders, headers):
  48. keyc = key.casefold()
  49. if value is None:
  50. if keyc in keys:
  51. del d[keys[keyc]]
  52. del keys[keyc]
  53. else:
  54. if keyc in keys and key != keys[keyc]:
  55. del d[keys[keyc]]
  56. d[key] = value
  57. keys[keyc] = key
  58. out = []
  59. for key, value in d.items():
  60. if isinstance(value, tuple):
  61. for value_ in value:
  62. out.append((key, value_))
  63. else:
  64. out.append((key, value))
  65. return out
  66. async def fetch(self, url, responseHandler = None, method = 'GET', data = None, headers = [], verify_ssl = True, timeout = 60, fromResponse = None):
  67. '''
  68. HTTP GET or POST a URL
  69. url: str or yarl.URL; if this is not a complete URL, it is evaluated relative to self.baseUrl
  70. responseHandler: None or a callable that determines how the response is handled; if None, self.defaultResponseHandler is used. See qwarc.utils.handle_response_default for details.
  71. method: str, must be 'GET' or 'POST'
  72. data: dict or list/tuple of lists/tuples of length two or bytes or file-like or None, the data to be sent in the request body
  73. headers: list of 2-tuples, additional or overriding headers for this request only
  74. To remove one of the default headers, pass a value of None.
  75. If a header appears multiple times, only the last one is used. To send a header multiple times, pass a tuple of values.
  76. verify_ssl: bool, whether the SSL/TLS certificate should be validated
  77. timeout: int or float, how long the fetch may take at most in total (sending request until finishing reading the response)
  78. fromResponse: ClientResponse or None; if provided, use fromResponse.url for the url completion (instead of self.baseUrl) and add it as a Referer header
  79. Returns response (a ClientResponse object or a qwarc.utils.DummyClientResponse object)
  80. '''
  81. #TODO: Rewrite using 'async with self.session.get'
  82. url = yarl.URL(url) # Explicitly convert for normalisation, percent-encoding, etc.
  83. if not url.scheme or not url.host:
  84. if fromResponse is not None:
  85. url = fromResponse.url.join(url)
  86. elif not self.baseUrl:
  87. raise ValueError('Incomplete URL and no baseUrl to join it with')
  88. else:
  89. url = self.baseUrl.join(url)
  90. originalUrl = url
  91. if responseHandler is None:
  92. responseHandler = self.defaultResponseHandler
  93. assert method in ('GET', 'POST'), 'method must be GET or POST'
  94. headers = self._merge_headers(headers, extraHeaders = [('Referer', str(fromResponse.url))] if fromResponse is not None else [])
  95. history = []
  96. attempt = 0
  97. redirectLevel = 0
  98. while True:
  99. attempt += 1
  100. response = None
  101. exc = None
  102. action = ACTION_RETRY
  103. writeToWarc = True
  104. try:
  105. try:
  106. with _aiohttp.Timeout(timeout):
  107. self.logger.info(f'Fetching {url}')
  108. response = await self.session.request(method, url, data = data, headers = headers, allow_redirects = False, verify_ssl = verify_ssl)
  109. try:
  110. while True:
  111. ret = await response.content.read(1048576)
  112. if not ret:
  113. break
  114. except:
  115. # No calling the handleResponse callback here because this is really bad. The not-so-bad exceptions (e.g. an error during reading the response) will be caught further down.
  116. response.close()
  117. raise
  118. else:
  119. response.rawRequestData.seek(0, io.SEEK_END)
  120. tx = response.rawRequestData.tell()
  121. response.rawResponseData.seek(0, io.SEEK_END)
  122. rx = response.rawResponseData.tell()
  123. self.logger.info(f'Fetched {url}: {response.status} (tx {tx}, rx {rx})')
  124. self.stats['tx'] += tx
  125. self.stats['rx'] += rx
  126. self.stats['requests'] += 1
  127. except (asyncio.TimeoutError, _aiohttp.ClientError) as e:
  128. self.logger.warning(f'Request for {url} failed: {e!r}')
  129. action, writeToWarc = await responseHandler(url = url, attempt = attempt, response = response, exc = e, redirectLevel = redirectLevel, item = self)
  130. exc = e # Pass the exception outward for the history
  131. else:
  132. action, writeToWarc = await responseHandler(url = url, attempt = attempt, response = response, exc = None, redirectLevel = redirectLevel, item = self)
  133. if response and exc is None and writeToWarc:
  134. self.warc.write_client_response(response)
  135. history.append((response, exc))
  136. retResponse = response if exc is None else qwarc.utils.DummyClientResponse()
  137. if action in (ACTION_SUCCESS, ACTION_IGNORE):
  138. retResponse.qhistory = tuple(history)
  139. return retResponse
  140. elif action == ACTION_FOLLOW_OR_SUCCESS:
  141. redirectUrl = response.headers.get('Location') or response.headers.get('URI')
  142. if not redirectUrl:
  143. retResponse.qhistory = tuple(history)
  144. return retResponse
  145. url = url.join(yarl.URL(redirectUrl))
  146. if response.status in (301, 302, 303) and method == 'POST':
  147. method = 'GET'
  148. data = None
  149. attempt = 0
  150. redirectLevel += 1
  151. elif action == ACTION_RETRIES_EXCEEDED:
  152. self.logger.error(f'Request for {url} failed {attempt} times')
  153. retResponse.qhistory = tuple(history)
  154. return retResponse
  155. elif action == ACTION_TOO_MANY_REDIRECTS:
  156. self.logger.error(f'Request for {url} (from {originalUrl}) exceeded redirect limit')
  157. retResponse.qhistory = tuple(history)
  158. return retResponse
  159. elif action == ACTION_RETRY:
  160. # Nothing to do, just go to the next cycle
  161. pass
  162. finally:
  163. if response:
  164. await response.release()
  165. async def process(self):
  166. raise NotImplementedError
  167. @classmethod
  168. def generate(cls):
  169. yield from () # Generate no items by default
  170. def add_subitem(self, itemClassOrType, itemValue):
  171. if issubclass(itemClassOrType, Item):
  172. item = (itemClassOrType.itemType, itemValue)
  173. else:
  174. item = (itemClassOrType, itemValue)
  175. if item not in self.childItems:
  176. self.childItems.append(item)
  177. async def flush_subitems(self):
  178. await self.qwarcObj.flush_subitems(self)
  179. def clear_subitems(self):
  180. self.childItems = []
  181. @classmethod
  182. def get_subclasses(cls):
  183. for subclass in cls.__subclasses__():
  184. yield subclass
  185. yield from subclass.get_subclasses()
  186. def __repr__(self):
  187. return f'<{type(self).__module__}.{type(self).__name__} object {id(self)}, itemType = {self.itemType!r}, itemValue = {self.itemValue!r}>'
  188. class QWARC:
  189. def __init__(self, itemClasses, warcBasePath, dbPath, command, specFile, specDependencies, logFilename, concurrency = 1, memoryLimit = 0, minFreeDisk = 0, warcSizeLimit = 0, warcDedupe = False):
  190. '''
  191. itemClasses: iterable of Item
  192. warcBasePath: str, base name of the WARC files
  193. dbPath: str, path to the sqlite3 database file
  194. command: list, the command line used to invoke qwarc
  195. specFile: str, path to the spec file
  196. specDependencies: qwarc.utils.SpecDependencies
  197. logFilename: str, name of the log file written by this process
  198. concurrency: int, number of concurrently processed items
  199. memoryLimit: int, gracefully stop when the process uses more than memoryLimit bytes of RSS; 0 disables the memory check
  200. minFreeDisk: int, pause when there's less than minFreeDisk space on the partition where WARCs are written; 0 disables the disk space check
  201. warcSizeLimit: int, size of each WARC file; 0 if the WARCs should not be split
  202. '''
  203. self._itemClasses = itemClasses
  204. self._itemTypeMap = {cls.itemType: cls for cls in itemClasses}
  205. self._warcBasePath = warcBasePath
  206. self._dbPath = dbPath
  207. self._command = command
  208. self._specFile = specFile
  209. self._specDependencies = specDependencies
  210. self._logFilename = logFilename
  211. self._concurrency = concurrency
  212. self._memoryLimit = memoryLimit
  213. self._minFreeDisk = minFreeDisk
  214. self._warcSizeLimit = warcSizeLimit
  215. self._warcDedupe = warcDedupe
  216. self._reset_working_vars()
  217. def _reset_working_vars(self):
  218. # Working variables
  219. self._db = None
  220. self._tasks = set()
  221. self._sleepTasks = set()
  222. self._sessions = [] # aiohttp.ClientSession instances
  223. self._freeSessions = collections.deque() # ClientSession instances that are currently free
  224. self._warc = None
  225. @contextlib.asynccontextmanager
  226. async def exclusive_db_lock(self):
  227. c = self._db.cursor()
  228. while True:
  229. try:
  230. c.execute('BEGIN EXCLUSIVE')
  231. break
  232. except sqlite3.OperationalError as e:
  233. if str(e) != 'database is locked':
  234. raise
  235. await asyncio.sleep(1)
  236. try:
  237. yield c
  238. c.execute('COMMIT')
  239. except:
  240. c.execute('ROLLBACK')
  241. raise
  242. def _make_item(self, itemType, itemValue, session, headers):
  243. try:
  244. itemClass = self._itemTypeMap[itemType]
  245. except KeyError:
  246. raise RuntimeError(f'No such item type: {itemType!r}')
  247. return itemClass(self, itemValue, session, headers, self._warc)
  248. async def _wait_for_free_task(self):
  249. if not self._tasks:
  250. return
  251. done, pending = await asyncio.wait(self._tasks, return_when = concurrent.futures.FIRST_COMPLETED)
  252. for future in done:
  253. newStatus = STATUS_DONE
  254. if future.taskType == 'sleep':
  255. self._sleepTasks.remove(future)
  256. elif future.taskType == 'process':
  257. item = future.item
  258. try:
  259. future.result()
  260. except asyncio.CancelledError as e:
  261. # Got cancelled, nothing we can do about it, but let's log a warning if it's a process task
  262. if future.taskType == 'process':
  263. logging.error(f'Task for {future.itemType}:{future.itemValue} cancelled: {future!r}')
  264. newStatus = STATUS_ERROR
  265. except Exception as e:
  266. if future.taskType == 'process':
  267. logging.error(f'{future.itemType}:{future.itemValue} failed: {e!r} ({item.stats["requests"]} requests, {item.stats["tx"]} tx, {item.stats["rx"]} rx)', exc_info = e)
  268. newStatus = STATUS_ERROR
  269. else:
  270. if future.taskType == 'process':
  271. logging.info(f'{future.itemType}:{future.itemValue} done: {item.stats["requests"]} requests, {item.stats["tx"]} tx, {item.stats["rx"]} rx')
  272. if future.taskType != 'process':
  273. continue
  274. async with self.exclusive_db_lock() as cursor:
  275. cursor.execute('UPDATE items SET status = ? WHERE id = ?', (newStatus, future.id))
  276. await self._insert_subitems(item)
  277. self._freeSessions.append(item.session)
  278. self._tasks = pending
  279. async def _insert_subitems(self, item):
  280. if item.childItems:
  281. async with self.exclusive_db_lock() as cursor:
  282. it = iter(item.childItems)
  283. while True:
  284. values = [(t, v, STATUS_TODO) for t, v in itertools.islice(it, 100000)]
  285. if not values:
  286. break
  287. cursor.executemany('INSERT OR IGNORE INTO items (type, value, status) VALUES (?, ?, ?)', values)
  288. async def run(self, loop):
  289. for i in range(self._concurrency):
  290. session = _aiohttp.ClientSession(
  291. connector = qwarc.aiohttp.TCPConnector(loop = loop),
  292. request_class = qwarc.aiohttp.ClientRequest,
  293. response_class = qwarc.aiohttp.ClientResponse,
  294. loop = loop
  295. )
  296. self._sessions.append(session)
  297. self._freeSessions.append(session)
  298. self._warc = qwarc.warc.WARC(self._warcBasePath, self._warcSizeLimit, self._warcDedupe, self._command, self._specFile, self._specDependencies, self._logFilename)
  299. self._db = sqlite3.connect(self._dbPath, timeout = 1)
  300. self._db.isolation_level = None # Transactions are handled manually below.
  301. self._db.execute('PRAGMA synchronous = OFF')
  302. async with self.exclusive_db_lock() as cursor:
  303. cursor.execute('SELECT name FROM sqlite_master WHERE type = "table" AND name = "items"')
  304. result = cursor.fetchone()
  305. if not result:
  306. self._create_db(cursor)
  307. self._insert_generated_items(cursor)
  308. try:
  309. while True:
  310. while len(self._tasks) >= self._concurrency:
  311. await self._wait_for_free_task()
  312. if os.path.exists('STOP'):
  313. logging.info('Gracefully shutting down due to STOP file')
  314. break
  315. if self._memoryLimit and qwarc.utils.uses_too_much_memory(self._memoryLimit):
  316. logging.info(f'Gracefully shutting down due to memory usage (current = {qwarc.utils.get_rss()} > limit = {self._memoryLimit})')
  317. break
  318. if self._minFreeDisk and qwarc.utils.too_little_disk_space(self._minFreeDisk):
  319. logging.info('Disk space is low, sleeping')
  320. sleepTask = asyncio.ensure_future(asyncio.sleep(random.uniform(self._concurrency / 2, self._concurrency * 1.5)))
  321. sleepTask.taskType = 'sleep'
  322. self._tasks.add(sleepTask)
  323. self._sleepTasks.add(sleepTask)
  324. continue
  325. async with self.exclusive_db_lock() as cursor:
  326. cursor.execute('SELECT id, type, value, status FROM items WHERE status = ? LIMIT 1', (STATUS_TODO,))
  327. result = cursor.fetchone()
  328. if not result:
  329. if cursor.execute('SELECT id, status FROM items WHERE status != ? LIMIT 1', (STATUS_DONE,)).fetchone():
  330. # There is currently no item to do, but there are still some in progress, so more TODOs may appear in the future.
  331. # It would be nice if we could just await wait_for_free_task() here, but that doesn't work because those TODOs might be in another process.
  332. # So instead, we insert a dummy task which just sleeps a bit. Average sleep time is equal to concurrency, i.e. one check per second.
  333. #TODO: The average sleep time is too large if there are only few sleep tasks; scale with len(sleepTasks)/self._concurrency?
  334. sleepTask = asyncio.ensure_future(asyncio.sleep(random.uniform(self._concurrency / 2, self._concurrency * 1.5)))
  335. sleepTask.taskType = 'sleep'
  336. self._tasks.add(sleepTask)
  337. self._sleepTasks.add(sleepTask)
  338. continue
  339. else:
  340. # Really nothing to do anymore
  341. break
  342. id_, itemType, itemValue, status = result
  343. cursor.execute('UPDATE items SET status = ? WHERE id = ?', (STATUS_INPROGRESS, id_))
  344. session = self._freeSessions.popleft()
  345. item = self._make_item(itemType, itemValue, session, DEFAULT_HEADERS)
  346. task = asyncio.ensure_future(item.process())
  347. #TODO: Is there a better way to add custom information to a task/coroutine object?
  348. task.taskType = 'process'
  349. task.id = id_
  350. task.itemType = itemType
  351. task.itemValue = itemValue
  352. task.item = item
  353. self._tasks.add(task)
  354. for sleepTask in self._sleepTasks:
  355. sleepTask.cancel()
  356. while len(self._tasks):
  357. await self._wait_for_free_task()
  358. logging.info('Done')
  359. except (Exception, KeyboardInterrupt) as e:
  360. # Kill all tasks
  361. for task in self._tasks:
  362. task.cancel()
  363. await asyncio.wait(self._tasks, return_when = concurrent.futures.ALL_COMPLETED)
  364. raise
  365. finally:
  366. for session in self._sessions:
  367. session.close()
  368. self._warc.close()
  369. self._db.close()
  370. self._reset_working_vars()
  371. async def flush_subitems(self, item):
  372. await self._insert_subitems(item)
  373. item.clear_subitems()
  374. def _create_db(self, cursor):
  375. cursor.execute('CREATE TABLE items (id INTEGER PRIMARY KEY, type TEXT, value TEXT, status INTEGER)')
  376. cursor.execute('CREATE INDEX items_status_idx ON items (status)')
  377. cursor.execute('CREATE UNIQUE INDEX items_type_value_idx ON items (type, value)')
  378. def _insert_generated_items(self, cursor):
  379. it = itertools.chain((cls.itemType, value, STATUS_TODO) for cls in self._itemClasses for value in cls.generate())
  380. while True:
  381. values = tuple(itertools.islice(it, 100000))
  382. if not values:
  383. break
  384. cursor.executemany('INSERT OR IGNORE INTO items (type, value, status) VALUES (?, ?, ?)', values)