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.

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