A framework for quick web archiving
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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