A framework for quick web archiving
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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