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.

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