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.

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