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.

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