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.

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