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.

339 lines
13 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 itertools
  12. import logging
  13. import os
  14. import random
  15. import sqlite3
  16. import yarl
  17. class Item:
  18. itemType = None
  19. def __init__(self, itemValue, session, headers, warc):
  20. self.itemValue = itemValue
  21. self.session = session
  22. self.headers = headers
  23. self.warc = warc
  24. self.stats = {'tx': 0, 'rx': 0, 'requests': 0}
  25. self.logger = logging.LoggerAdapter(logging.getLogger(), {'itemType': self.itemType, 'itemValue': self.itemValue})
  26. self.childItems = []
  27. async def fetch(self, url, responseHandler = qwarc.utils.handle_response_default, method = 'GET', data = None, headers = [], verify_ssl = True):
  28. '''
  29. HTTP GET or POST a URL
  30. url: str or yarl.URL
  31. responseHandler: a callable that determines how the response is handled. See qwarc.utils.handle_response_default for details.
  32. method: str, must be 'GET' or 'POST'
  33. 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
  34. headers: list of 2-tuples, additional headers for this request only
  35. Returns response (a ClientResponse object or None) and history (a tuple of (response, exception) tuples).
  36. response can be None and history can be an empty tuple, depending on the circumstances (e.g. timeouts).
  37. '''
  38. #TODO: Rewrite using 'async with self.session.get'
  39. url = yarl.URL(url) # Explicitly convert for normalisation, percent-encoding, etc.
  40. assert method in ('GET', 'POST'), 'method must be GET or POST'
  41. headers = self.headers + headers
  42. #TODO Deduplicate headers with later values overriding earlier ones
  43. history = []
  44. attempt = 0
  45. #TODO redirectLevel
  46. while True:
  47. attempt += 1
  48. response = None
  49. exc = None
  50. action = ACTION_RETRY
  51. writeToWarc = True
  52. try:
  53. try:
  54. with _aiohttp.Timeout(60):
  55. self.logger.info(f'Fetching {url}')
  56. response = await self.session.request(method, url, data = data, headers = headers, allow_redirects = False, verify_ssl = verify_ssl)
  57. try:
  58. ret = await response.read()
  59. except:
  60. # 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.
  61. response.close()
  62. raise
  63. else:
  64. tx = len(response.rawRequestData)
  65. rx = len(response.rawResponseData)
  66. self.logger.info(f'Fetched {url}: {response.status} (tx {tx}, rx {rx})')
  67. self.stats['tx'] += tx
  68. self.stats['rx'] += rx
  69. self.stats['requests'] += 1
  70. except (asyncio.TimeoutError, _aiohttp.ClientError) as e:
  71. self.logger.error(f'Request for {url} failed: {e!r}')
  72. action, writeToWarc = await responseHandler(url, attempt, response, e)
  73. exc = e # Pass the exception outward for the history
  74. else:
  75. action, writeToWarc = await responseHandler(url, attempt, response, None)
  76. history.append((response, exc))
  77. if action in (ACTION_SUCCESS, ACTION_IGNORE):
  78. return response, tuple(history)
  79. elif action == ACTION_FOLLOW_OR_SUCCESS:
  80. redirectUrl = response.headers.get('Location') or response.headers.get('URI')
  81. if not redirectUrl:
  82. return response, tuple(history)
  83. url = url.join(yarl.URL(redirectUrl))
  84. if response.status in (301, 302, 303) and method == 'POST':
  85. method = 'GET'
  86. data = None
  87. attempt = 0
  88. elif action == ACTION_RETRIES_EXCEEDED:
  89. self.logger.error(f'Request for {url} failed {attempt} times')
  90. return response, tuple(history)
  91. elif action == ACTION_RETRY:
  92. # Nothing to do, just go to the next cycle
  93. pass
  94. finally:
  95. if response:
  96. if writeToWarc:
  97. self.warc.write_client_response(response)
  98. await response.release()
  99. async def process(self):
  100. raise NotImplementedError
  101. @classmethod
  102. def generate(cls):
  103. yield from () # Generate no items by default
  104. @classmethod
  105. def _gen(cls):
  106. for x in cls.generate():
  107. yield (cls.itemType, x, STATUS_TODO)
  108. def add_item(self, itemClassOrType, itemValue):
  109. if issubclass(itemClassOrType, Item):
  110. item = (itemClassOrType.itemType, itemValue)
  111. else:
  112. item = (itemClassOrType, itemValue)
  113. if item not in self.childItems:
  114. self.childItems.append(item)
  115. class QWARC:
  116. def __init__(self, itemClasses, warcBasePath, dbPath, command, specFile, specDependencies, logFilename, concurrency = 1, memoryLimit = 0, minFreeDisk = 0, warcSizeLimit = 0, warcDedupe = False):
  117. '''
  118. itemClasses: iterable of Item
  119. warcBasePath: str, base name of the WARC files
  120. dbPath: str, path to the sqlite3 database file
  121. command: list, the command line used to invoke qwarc
  122. specFile: str, path to the spec file
  123. specDependencies: qwarc.utils.SpecDependencies
  124. logFilename: str, name of the log file written by this process
  125. concurrency: int, number of concurrently processed items
  126. memoryLimit: int, gracefully stop when the process uses more than memoryLimit bytes of RSS; 0 disables the memory check
  127. minFreeDisk: int, pause when there's less than minFreeDisk space on the partition where WARCs are written; 0 disables the disk space check
  128. warcSizeLimit: int, size of each WARC file; 0 if the WARCs should not be split
  129. '''
  130. self._itemClasses = itemClasses
  131. self._itemTypeMap = {cls.itemType: cls for cls in itemClasses}
  132. self._warcBasePath = warcBasePath
  133. self._dbPath = dbPath
  134. self._command = command
  135. self._specFile = specFile
  136. self._specDependencies = specDependencies
  137. self._logFilename = logFilename
  138. self._concurrency = concurrency
  139. self._memoryLimit = memoryLimit
  140. self._minFreeDisk = minFreeDisk
  141. self._warcSizeLimit = warcSizeLimit
  142. self._warcDedupe = warcDedupe
  143. async def obtain_exclusive_db_lock(self, db):
  144. c = db.cursor()
  145. while True:
  146. try:
  147. c.execute('BEGIN EXCLUSIVE')
  148. break
  149. except sqlite3.OperationalError as e:
  150. if str(e) != 'database is locked':
  151. raise
  152. await asyncio.sleep(1)
  153. return c
  154. def _make_item(self, itemType, itemValue, session, headers, warc):
  155. try:
  156. itemClass = self._itemTypeMap[itemType]
  157. except KeyError:
  158. raise RuntimeError(f'No such item type: {itemType!r}')
  159. return itemClass(itemValue, session, headers, warc)
  160. async def run(self, loop):
  161. headers = [('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0')] #TODO: Move elsewhere
  162. tasks = set()
  163. sleepTasks = set()
  164. sessions = [] # aiohttp.ClientSession instances
  165. freeSessions = collections.deque() # ClientSession instances that are currently free
  166. for i in range(self._concurrency):
  167. session = _aiohttp.ClientSession(
  168. connector = qwarc.aiohttp.TCPConnector(loop = loop),
  169. request_class = qwarc.aiohttp.ClientRequest,
  170. response_class = qwarc.aiohttp.ClientResponse,
  171. skip_auto_headers = ['Accept-Encoding'],
  172. loop = loop
  173. )
  174. sessions.append(session)
  175. freeSessions.append(session)
  176. warc = qwarc.warc.WARC(self._warcBasePath, self._warcSizeLimit, self._warcDedupe, self._command, self._specFile, self._specDependencies, self._logFilename)
  177. db = sqlite3.connect(self._dbPath, timeout = 1)
  178. db.isolation_level = None # Transactions are handled manually below.
  179. db.execute('PRAGMA synchronous = OFF')
  180. try:
  181. async def wait_for_free_task():
  182. nonlocal tasks, freeSessions, db
  183. done, pending = await asyncio.wait(tasks, return_when = concurrent.futures.FIRST_COMPLETED)
  184. for future in done:
  185. # TODO Replace all of this with `if future.cancelled():`
  186. try:
  187. await future #TODO: Is this actually necessary? asyncio.wait only returns 'done' futures...
  188. except concurrent.futures.CancelledError as e:
  189. # Got cancelled, nothing we can do about it, but let's log a warning if it's a process task
  190. if isinstance(future, asyncio.Task):
  191. if future.taskType == 'process_item':
  192. logging.warning(f'Task for {future.itemType}:{future.itemValue} cancelled: {future!r}')
  193. elif future.taskType == 'sleep':
  194. sleepTasks.remove(future)
  195. continue
  196. if future.taskType == 'sleep':
  197. # Dummy task for empty todo list, see below.
  198. sleepTasks.remove(future)
  199. continue
  200. item = future.item
  201. logging.info(f'{future.itemType}:{future.itemValue} done: {item.stats["requests"]} requests, {item.stats["tx"]} tx, {item.stats["rx"]} rx')
  202. cursor = await self.obtain_exclusive_db_lock(db)
  203. try:
  204. cursor.execute('UPDATE items SET status = ? WHERE id = ?', (STATUS_DONE, future.id))
  205. if item.childItems:
  206. it = iter(item.childItems)
  207. while True:
  208. values = [(t, v, STATUS_TODO) for t, v in itertools.islice(it, 100000)]
  209. if not values:
  210. break
  211. cursor.executemany('INSERT OR IGNORE INTO items (type, value, status) VALUES (?, ?, ?)', values)
  212. cursor.execute('COMMIT')
  213. except:
  214. cursor.execute('ROLLBACK')
  215. raise
  216. freeSessions.append(item.session)
  217. tasks = pending
  218. while True:
  219. while len(tasks) >= self._concurrency:
  220. await wait_for_free_task()
  221. if self._minFreeDisk and qwarc.utils.too_little_disk_space(self._minFreeDisk):
  222. logging.info('Disk space is low, sleeping')
  223. sleepTask = asyncio.ensure_future(asyncio.sleep(random.uniform(self._concurrency / 2, self._concurrency * 1.5)))
  224. sleepTask.taskType = 'sleep'
  225. tasks.add(sleepTask)
  226. sleepTasks.add(sleepTask)
  227. continue
  228. if os.path.exists('STOP'):
  229. logging.info('Gracefully shutting down due to STOP file')
  230. break
  231. if self._memoryLimit and qwarc.utils.uses_too_much_memory(self._memoryLimit):
  232. logging.info(f'Gracefully shutting down due to memory usage (current = {qwarc.utils.get_rss()} > limit = {self._memoryLimit})')
  233. break
  234. cursor = await self.obtain_exclusive_db_lock(db)
  235. try:
  236. cursor.execute('SELECT id, type, value, status FROM items WHERE status = ? LIMIT 1', (STATUS_TODO,))
  237. result = cursor.fetchone()
  238. if not result:
  239. if cursor.execute('SELECT id, status FROM items WHERE status != ? LIMIT 1', (STATUS_DONE,)).fetchone():
  240. # There is currently no item to do, but there are still some in progress, so more TODOs may appear in the future.
  241. # 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.
  242. # 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.
  243. #TODO: The average sleep time is too large if there are only few sleep tasks; scale with len(sleepTasks)/self._concurrency?
  244. sleepTask = asyncio.ensure_future(asyncio.sleep(random.uniform(self._concurrency / 2, self._concurrency * 1.5)))
  245. sleepTask.taskType = 'sleep'
  246. tasks.add(sleepTask)
  247. sleepTasks.add(sleepTask)
  248. cursor.execute('COMMIT')
  249. continue
  250. else:
  251. # Really nothing to do anymore
  252. #TODO: Another process may be running create_db, in which case we'd still want to wait...
  253. # create_db could insert a dummy item which is marked as done when the DB is ready
  254. cursor.execute('COMMIT')
  255. break
  256. id, itemType, itemValue, status = result
  257. cursor.execute('UPDATE items SET status = ? WHERE id = ?', (STATUS_INPROGRESS, id))
  258. cursor.execute('COMMIT')
  259. except:
  260. cursor.execute('ROLLBACK')
  261. raise
  262. session = freeSessions.popleft()
  263. item = self._make_item(itemType, itemValue, session, headers, warc)
  264. task = asyncio.ensure_future(item.process())
  265. #TODO: Is there a better way to add custom information to a task/coroutine object?
  266. task.taskType = 'process'
  267. task.id = id
  268. task.itemType = itemType
  269. task.itemValue = itemValue
  270. task.item = item
  271. tasks.add(task)
  272. for sleepTask in sleepTasks:
  273. sleepTask.cancel()
  274. while len(tasks):
  275. await wait_for_free_task()
  276. logging.info('Done')
  277. except (Exception, KeyboardInterrupt) as e:
  278. # Kill all tasks
  279. for task in tasks:
  280. task.cancel()
  281. await asyncio.wait(tasks, return_when = concurrent.futures.ALL_COMPLETED)
  282. raise
  283. finally:
  284. for session in sessions:
  285. session.close()
  286. warc.close()
  287. db.close()
  288. def create_db(self):
  289. db = sqlite3.connect(self._dbPath, timeout = 1)
  290. db.execute('PRAGMA synchronous = OFF')
  291. with db:
  292. db.execute('CREATE TABLE items (id INTEGER PRIMARY KEY, type TEXT, value TEXT, status INTEGER)')
  293. db.execute('CREATE INDEX items_status_idx ON items (status)')
  294. db.execute('CREATE UNIQUE INDEX items_type_value_idx ON items (type, value)')
  295. it = itertools.chain(*(i._gen() for i in self._itemClasses))
  296. while True:
  297. values = tuple(itertools.islice(it, 100000))
  298. if not values:
  299. break
  300. with db:
  301. db.executemany('INSERT INTO items (type, value, status) VALUES (?, ?, ?)', values)