A framework for quick web archiving
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

218 líneas
7.5 KiB

  1. from qwarc.const import *
  2. import aiohttp
  3. import asyncio
  4. import functools
  5. import logging
  6. import os
  7. import pkg_resources
  8. import platform
  9. PAGESIZE = os.sysconf('SC_PAGE_SIZE')
  10. def get_rss():
  11. '''Get the current RSS of this process in bytes'''
  12. with open('/proc/self/statm', 'r') as fp:
  13. return int(fp.readline().split()[1]) * PAGESIZE
  14. def get_disk_free():
  15. '''Get the current free disk space on the relevant partition in bytes'''
  16. st = os.statvfs('.')
  17. return st.f_bavail * st.f_frsize
  18. def uses_too_much_memory(limit):
  19. '''
  20. Check whether the process is using too much memory
  21. For performance reasons, this actually only checks the memory usage on every 100th call.
  22. '''
  23. uses_too_much_memory.callCounter += 1
  24. # Only check every hundredth call
  25. if uses_too_much_memory.callCounter % 100 == 0 and get_rss() > limit:
  26. return True
  27. return False
  28. uses_too_much_memory.callCounter = 0
  29. def too_little_disk_space(limit):
  30. '''
  31. Check whether the disk space is too small
  32. For performance reasons, this actually only checks the free disk space on every 100th call.
  33. '''
  34. too_little_disk_space.callCounter += 1
  35. if too_little_disk_space.callCounter % 100 == 0:
  36. too_little_disk_space.currentResult = (get_disk_free() < limit)
  37. return too_little_disk_space.currentResult
  38. too_little_disk_space.callCounter = 0
  39. too_little_disk_space.currentResult = False
  40. # https://stackoverflow.com/a/4665027
  41. def find_all(aStr, sub):
  42. '''Generator yielding the start positions of every non-overlapping occurrence of sub in aStr.'''
  43. start = 0
  44. while True:
  45. start = aStr.find(sub, start)
  46. if start == -1:
  47. return
  48. yield start
  49. start += len(sub)
  50. def str_get_between(aStr, a, b):
  51. '''Get the string after the first occurrence of a in aStr and the first occurrence of b after that of a, or None if there is no such string.'''
  52. aPos = aStr.find(a)
  53. if aPos == -1:
  54. return None
  55. offset = aPos + len(a)
  56. bPos = aStr.find(b, offset)
  57. if bPos == -1:
  58. return None
  59. return aStr[offset:bPos]
  60. def maybe_str_get_between(x, a, b):
  61. '''Like str_get_between, but returns None if x evaluates to False and converts it to a str before matching.'''
  62. if x:
  63. return str_get_between(str(x), a, b)
  64. def str_get_all_between(aStr, a, b):
  65. '''Generator yielding every string between occurrences of a in aStr and the following occurrence of b.'''
  66. #TODO: This produces half-overlapping matches: str_get_all_between('aabc', 'a', 'c') will yield 'ab' and 'b'.
  67. # Might need to implement sending an offset to the find_all generator to work around this, or discard aOffset values which are smaller than the previous bPos+len(b).
  68. for aOffset in find_all(aStr, a):
  69. offset = aOffset + len(a)
  70. bPos = aStr.find(b, offset)
  71. if bPos != -1:
  72. yield aStr[offset:bPos]
  73. def maybe_str_get_all_between(x, a, b):
  74. '''Like str_get_all_between, but yields no elements if x evaluates to False and converts x to a str before matching.'''
  75. if x:
  76. yield from str_get_all_between(str(x), a, b)
  77. def generate_range_items(start, stop, step):
  78. '''
  79. Generator for items of `step` size between `start` and `stop` (inclusive)
  80. Yields strings of the form `'a-b'` where `a` and `b` are integers such that `b - a + 1 == step`, `min(a) == start`, and `max(b) == stop`.
  81. `b - a + 1` may be unequal to `step` on the last item if `(stop - start + 1) % step != 0` (see examples below).
  82. Note that `a` and `b` can be equal on the last item if `(stop - start) % step == 0` (see examples below).
  83. Examples:
  84. - generate_range_items(0, 99, 10) yields '0-9', '10-19', '20-29', ..., '90-99'
  85. - generate_range_items(0, 42, 10): '0-9', '10-19', '20-29', '30-39', '40-42'
  86. - generate_range_items(0, 20, 10): '0-9', '10-19', '20-20'
  87. '''
  88. for i in range(start, stop + 1, step):
  89. yield f'{i}-{min(i + step - 1, stop)}'
  90. async def handle_response_default(url, attempt, response, exc):
  91. '''
  92. The default response handler, which behaves as follows:
  93. - If there is no response (e.g. timeout error), retry the retrieval after a delay of 5 seconds.
  94. - If the response has any of the status codes 401, 403, 404, 405, or 410, treat it as a permanent error and return.
  95. - If there was any exception and it is a asyncio.TimeoutError or a aiohttp.ClientError, treat as a potentially temporary error and retry the retrieval after a delay of 5 seconds.
  96. - If the response has any of the status codes 200, 204, 206, or 304, treat it as a success and return.
  97. - If the response has any of the status codes 301, 302, 303, 307, or 308, follow the redirect target if specified or return otherwise.
  98. - Otherwise, treat as a potentially temporary error and retry the retrieval after a delay of 5 seconds.
  99. - All responses are written to WARC by default.
  100. Note that this handler does not limit the number of retries on errors.
  101. Parameters: url (yarl.URL instance), attempt (int), response (aiohttp.ClientResponse or None), exc (Exception or None)
  102. At least one of response and exc is not None.
  103. Returns: (one of the qwarc.RESPONSE_* constants, bool signifying whether to write to WARC or not)
  104. '''
  105. #TODO: Document that `attempt` is reset on redirects
  106. if response is None:
  107. await asyncio.sleep(5)
  108. return ACTION_RETRY, True
  109. if response.status in (401, 403, 404, 405, 410):
  110. return ACTION_IGNORE, True
  111. if exc is not None and isinstance(exc, (asyncio.TimeoutError, aiohttp.ClientError)):
  112. await asyncio.sleep(5)
  113. return ACTION_RETRY, True
  114. if response.status in (200, 204, 206, 304):
  115. return ACTION_SUCCESS, True
  116. if response.status in (301, 302, 303, 307, 308):
  117. return ACTION_FOLLOW_OR_SUCCESS, True
  118. await asyncio.sleep(5)
  119. return ACTION_RETRY, True
  120. async def handle_response_ignore_redirects(url, attempt, response, exc):
  121. '''A response handler that does not follow redirects, i.e. treats them as a success instead. It behaves as handle_response_default otherwise.'''
  122. action, writeToWarc = await handle_response_default(url, attempt, response, exc)
  123. if action == ACTION_FOLLOW_OR_SUCCESS:
  124. action = ACTION_SUCCESS
  125. return action, writeToWarc
  126. def handle_response_limit_error_retries(maxRetries, handler = handle_response_default):
  127. '''A response handler that limits the number of retries on errors. It behaves as handler otherwise, which defaults to handle_response_default.
  128. Technically, this is actually a response handler factory. This is so that the intuitive use works: fetch(..., responseHandler = handle_response_limit_error_retries(5))
  129. If you use the same limit many times, you should keep the return value (the response handler) of this method and reuse it to avoid creating a new function every time.
  130. '''
  131. async def _handler(url, attempt, response, exc):
  132. action, writeToWarc = await handler(url, attempt, response, exc)
  133. if action == ACTION_RETRY and attempt > maxRetries:
  134. action = ACTION_RETRIES_EXCEEDED
  135. return action, writeToWarc
  136. return _handler
  137. def _get_dependency_versions(pkg):
  138. pending = {pkg}
  139. have = {pkg}
  140. while pending:
  141. key = pending.pop()
  142. try:
  143. dist = pkg_resources.get_distribution(key)
  144. except pkg_resources.DistributionNotFound:
  145. logging.error(f'Unable to get distribution {key}')
  146. yield dist.key, dist.version
  147. for requirement in dist.requires():
  148. if requirement.key not in have:
  149. pending.add(requirement.key)
  150. have.add(requirement.key)
  151. @functools.lru_cache(maxsize = 1)
  152. def get_software_info():
  153. # Taken from crocoite.utils, authored by PromyLOPh in commit 6ccd72ab on 2018-12-08 under MIT licence
  154. return {
  155. 'platform': platform.platform(),
  156. 'python': {
  157. 'implementation': platform.python_implementation(),
  158. 'version': platform.python_version(),
  159. 'build': platform.python_build(),
  160. },
  161. 'self': [{"package": package, "version": version} for package, version in _get_dependency_versions(__package__)],
  162. }