abstract.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Abstract base classes for engine request processores.
  4. """
  5. import threading
  6. from abc import abstractmethod, ABC
  7. from timeit import default_timer
  8. from searx import logger
  9. from searx.engines import settings
  10. from searx.network import get_time_for_thread, get_network
  11. from searx.metrics import histogram_observe, counter_inc, count_exception, count_error
  12. from searx.exceptions import SearxEngineAccessDeniedException
  13. logger = logger.getChild('searx.search.processor')
  14. SUSPENDED_STATUS = {}
  15. # pylint: disable=missing-function-docstring
  16. class SuspendedStatus:
  17. """Class to handle suspend state."""
  18. __slots__ = 'suspend_end_time', 'suspend_reason', 'continuous_errors', 'lock'
  19. def __init__(self):
  20. self.lock = threading.Lock()
  21. self.continuous_errors = 0
  22. self.suspend_end_time = 0
  23. self.suspend_reason = None
  24. @property
  25. def is_suspended(self):
  26. return self.suspend_end_time >= default_timer()
  27. def suspend(self, suspended_time, suspend_reason):
  28. with self.lock:
  29. # update continuous_errors / suspend_end_time
  30. self.continuous_errors += 1
  31. if suspended_time is None:
  32. suspended_time = min(settings['search']['max_ban_time_on_fail'],
  33. self.continuous_errors * settings['search']['ban_time_on_fail'])
  34. self.suspend_end_time = default_timer() + suspended_time
  35. self.suspend_reason = suspend_reason
  36. logger.debug('Suspend engine for %i seconds', suspended_time)
  37. def resume(self):
  38. with self.lock:
  39. # reset the suspend variables
  40. self.continuous_errors = 0
  41. self.suspend_end_time = 0
  42. self.suspend_reason = None
  43. class EngineProcessor(ABC):
  44. """Base classes used for all types of reqest processores."""
  45. __slots__ = 'engine', 'engine_name', 'lock', 'suspended_status'
  46. def __init__(self, engine, engine_name):
  47. self.engine = engine
  48. self.engine_name = engine_name
  49. key = get_network(self.engine_name)
  50. key = id(key) if key else self.engine_name
  51. self.suspended_status = SUSPENDED_STATUS.setdefault(key, SuspendedStatus())
  52. def handle_exception(self, result_container, exception_or_message, suspend=False):
  53. # update result_container
  54. if isinstance(exception_or_message, BaseException):
  55. exception_class = exception_or_message.__class__
  56. module_name = getattr(exception_class, '__module__', 'builtins')
  57. module_name = '' if module_name == 'builtins' else module_name + '.'
  58. error_message = module_name + exception_class.__qualname__
  59. else:
  60. error_message = exception_or_message
  61. result_container.add_unresponsive_engine(self.engine_name, error_message)
  62. # metrics
  63. counter_inc('engine', self.engine_name, 'search', 'count', 'error')
  64. if isinstance(exception_or_message, BaseException):
  65. count_exception(self.engine_name, exception_or_message)
  66. else:
  67. count_error(self.engine_name, exception_or_message)
  68. # suspend the engine ?
  69. if suspend:
  70. suspended_time = None
  71. if isinstance(exception_or_message, SearxEngineAccessDeniedException):
  72. suspended_time = exception_or_message.suspended_time
  73. self.suspended_status.suspend(suspended_time, error_message) # pylint: disable=no-member
  74. def _extend_container_basic(self, result_container, start_time, search_results):
  75. # update result_container
  76. result_container.extend(self.engine_name, search_results)
  77. engine_time = default_timer() - start_time
  78. page_load_time = get_time_for_thread()
  79. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  80. # metrics
  81. counter_inc('engine', self.engine_name, 'search', 'count', 'successful')
  82. histogram_observe(engine_time, 'engine', self.engine_name, 'time', 'total')
  83. if page_load_time is not None:
  84. histogram_observe(page_load_time, 'engine', self.engine_name, 'time', 'http')
  85. def extend_container(self, result_container, start_time, search_results):
  86. if getattr(threading.current_thread(), '_timeout', False):
  87. # the main thread is not waiting anymore
  88. self.handle_exception(result_container, 'timeout', None)
  89. else:
  90. # check if the engine accepted the request
  91. if search_results is not None:
  92. self._extend_container_basic(result_container, start_time, search_results)
  93. self.suspended_status.resume()
  94. def extend_container_if_suspended(self, result_container):
  95. if self.suspended_status.is_suspended:
  96. result_container.add_unresponsive_engine(self.engine_name,
  97. self.suspended_status.suspend_reason,
  98. suspended=True)
  99. return True
  100. return False
  101. def get_params(self, search_query, engine_category):
  102. # if paging is not supported, skip
  103. if search_query.pageno > 1 and not self.engine.paging:
  104. return None
  105. # if time_range is not supported, skip
  106. if search_query.time_range and not self.engine.time_range_support:
  107. return None
  108. params = {}
  109. params['category'] = engine_category
  110. params['pageno'] = search_query.pageno
  111. params['safesearch'] = search_query.safesearch
  112. params['time_range'] = search_query.time_range
  113. params['engine_data'] = search_query.engine_data.get(self.engine_name, {})
  114. if hasattr(self.engine, 'language') and self.engine.language:
  115. params['language'] = self.engine.language
  116. else:
  117. params['language'] = search_query.lang
  118. return params
  119. @abstractmethod
  120. def search(self, query, params, result_container, start_time, timeout_limit):
  121. pass
  122. def get_tests(self):
  123. tests = getattr(self.engine, 'tests', None)
  124. if tests is None:
  125. tests = getattr(self.engine, 'additional_tests', {})
  126. tests.update(self.get_default_tests())
  127. return tests
  128. def get_default_tests(self): # pylint: disable=no-self-use
  129. return {}