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.

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