A framework for quick web archiving
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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