A framework for quick web archiving
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

184 行
6.6 KiB

  1. from qwarc.const import *
  2. import aiohttp
  3. import asyncio
  4. import os
  5. PAGESIZE = os.sysconf('SC_PAGE_SIZE')
  6. def get_rss():
  7. '''Get the current RSS of this process in bytes'''
  8. with open('/proc/self/statm', 'r') as fp:
  9. return int(fp.readline().split()[1]) * PAGESIZE
  10. def get_disk_free():
  11. '''Get the current free disk space on the relevant partition in bytes'''
  12. st = os.statvfs('.')
  13. return st.f_bavail * st.f_frsize
  14. def uses_too_much_memory(limit):
  15. '''
  16. Check whether the process is using too much memory
  17. For performance reasons, this actually only checks the memory usage on every 100th call.
  18. '''
  19. uses_too_much_memory.callCounter += 1
  20. # Only check every hundredth call
  21. if uses_too_much_memory.callCounter % 100 == 0 and get_rss() > limit:
  22. return True
  23. return False
  24. uses_too_much_memory.callCounter = 0
  25. def too_little_disk_space(limit):
  26. '''
  27. Check whether the disk space is too small
  28. For performance reasons, this actually only checks the free disk space on every 100th call.
  29. '''
  30. too_little_disk_space.callCounter += 1
  31. if too_little_disk_space.callCounter % 100 == 0:
  32. too_little_disk_space.currentResult = (get_disk_free() < limit)
  33. return too_little_disk_space.currentResult
  34. too_little_disk_space.callCounter = 0
  35. too_little_disk_space.currentResult = False
  36. # https://stackoverflow.com/a/4665027
  37. def find_all(aStr, sub):
  38. '''Generator yielding the start positions of every non-overlapping occurrence of sub in aStr.'''
  39. start = 0
  40. while True:
  41. start = aStr.find(sub, start)
  42. if start == -1:
  43. return
  44. yield start
  45. start += len(sub)
  46. def str_get_between(aStr, a, b):
  47. '''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.'''
  48. aPos = aStr.find(a)
  49. if aPos == -1:
  50. return None
  51. offset = aPos + len(a)
  52. bPos = aStr.find(b, offset)
  53. if bPos == -1:
  54. return None
  55. return aStr[offset:bPos]
  56. def maybe_str_get_between(x, a, b):
  57. '''Like str_get_between, but returns None if x evaluates to False and converts it to a str before matching.'''
  58. if x:
  59. return str_get_between(str(x), a, b)
  60. def str_get_all_between(aStr, a, b):
  61. '''Generator yielding every string between occurrences of a in aStr and the following occurrence of b.'''
  62. #TODO: This produces half-overlapping matches: str_get_all_between('aabc', 'a', 'c') will yield 'ab' and 'b'.
  63. # 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).
  64. for aOffset in find_all(aStr, a):
  65. offset = aOffset + len(a)
  66. bPos = aStr.find(b, offset)
  67. if bPos != -1:
  68. yield aStr[offset:bPos]
  69. def maybe_str_get_all_between(x, a, b):
  70. '''Like str_get_all_between, but yields no elements if x evaluates to False and converts x to a str before matching.'''
  71. if x:
  72. yield from str_get_all_between(str(x), a, b)
  73. def generate_range_items(start, stop, step):
  74. '''
  75. Generator for items of `step` size between `start` and `stop` (inclusive)
  76. 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`.
  77. `b - a + 1` may be unequal to `step` on the last item if `(stop - start + 1) % step != 0` (see examples below).
  78. Note that `a` and `b` can be equal on the last item if `(stop - start) % step == 0` (see examples below).
  79. Examples:
  80. - generate_range_items(0, 99, 10) yields '0-9', '10-19', '20-29', ..., '90-99'
  81. - generate_range_items(0, 42, 10): '0-9', '10-19', '20-29', '30-39', '40-42'
  82. - generate_range_items(0, 20, 10): '0-9', '10-19', '20-20'
  83. '''
  84. for i in range(start, stop + 1, step):
  85. yield '{}-{}'.format(i, min(i + step - 1, stop))
  86. async def handle_response_default(url, attempt, response, exc):
  87. '''
  88. The default response handler, which behaves as follows:
  89. - If there is no response (e.g. timeout error), retry the retrieval after a delay of 5 seconds.
  90. - If the response has any of the status codes 401, 403, 404, 405, or 410, treat it as a permanent error and return.
  91. - 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.
  92. - If the response has any of the status codes 200, 204, 206, or 304, treat it as a success and return.
  93. - If the response has any of the status codes 301, 302, 303, 307, or 308, follow the redirect target if specified or return otherwise.
  94. - Otherwise, treat as a potentially temporary error and retry the retrieval after a delay of 5 seconds.
  95. - All responses are written to WARC by default.
  96. Note that this handler does not limit the number of retries on errors.
  97. Parameters: url (yarl.URL instance), attempt (int), response (aiohttp.ClientResponse or None), exc (Exception or None)
  98. At least one of response and exc is not None.
  99. Returns: (one of the qwarc.RESPONSE_* constants, bool signifying whether to write to WARC or not)
  100. '''
  101. #TODO: Document that `attempt` is reset on redirects
  102. if response is None:
  103. await asyncio.sleep(5)
  104. return ACTION_RETRY, True
  105. if response.status in (401, 403, 404, 405, 410):
  106. return ACTION_IGNORE, True
  107. if exc is not None and isinstance(exc, (asyncio.TimeoutError, aiohttp.ClientError)):
  108. await asyncio.sleep(5)
  109. return ACTION_RETRY, True
  110. if response.status in (200, 204, 206, 304):
  111. return ACTION_SUCCESS, True
  112. if response.status in (301, 302, 303, 307, 308):
  113. return ACTION_FOLLOW_OR_SUCCESS, True
  114. await asyncio.sleep(5)
  115. return ACTION_RETRY, True
  116. async def handle_response_ignore_redirects(url, attempt, response, exc):
  117. '''A response handler that does not follow redirects, i.e. treats them as a success instead. It behaves as handle_response_default otherwise.'''
  118. action, writeToWarc = await handle_response_default(url, attempt, response, exc)
  119. if action == ACTION_FOLLOW_OR_SUCCESS:
  120. action = ACTION_SUCCESS
  121. return action, writeToWarc
  122. def handle_response_limit_error_retries(maxRetries, handler = handle_response_default):
  123. '''A response handler that limits the number of retries on errors. It behaves as handler otherwise, which defaults to handle_response_default.
  124. Technically, this is actually a response handler factory. This is so that the intuitive use works: fetch(..., responseHandler = handle_response_limit_error_retries(5))
  125. 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.
  126. '''
  127. async def _handler(url, attempt, response, exc):
  128. action, writeToWarc = await handler(url, attempt, response, exc)
  129. if action == ACTION_RETRY and attempt > maxRetries:
  130. action = ACTION_IGNORE
  131. return action, writeToWarc
  132. return _handler