A framework for quick web archiving
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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