A framework for quick web archiving
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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