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.

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