abstract.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Abstract base classes for engine request processors.
  3. """
  4. import threading
  5. from abc import abstractmethod, ABC
  6. from timeit import default_timer
  7. from typing import Dict, Union
  8. from searx import settings, logger
  9. from searx.engines import engines
  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, SearxEngineResponseException
  13. from searx.utils import get_engine_from_settings
  14. logger = logger.getChild('searx.search.processor')
  15. SUSPENDED_STATUS: Dict[Union[int, str], 'SuspendedStatus'] = {}
  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(
  33. settings['search']['max_ban_time_on_fail'],
  34. self.continuous_errors * settings['search']['ban_time_on_fail'],
  35. )
  36. self.suspend_end_time = default_timer() + suspended_time
  37. self.suspend_reason = suspend_reason
  38. logger.debug('Suspend for %i seconds', suspended_time)
  39. def resume(self):
  40. with self.lock:
  41. # reset the suspend variables
  42. self.continuous_errors = 0
  43. self.suspend_end_time = 0
  44. self.suspend_reason = None
  45. class EngineProcessor(ABC):
  46. """Base classes used for all types of request processors."""
  47. __slots__ = 'engine', 'engine_name', 'lock', 'suspended_status', 'logger'
  48. def __init__(self, engine, engine_name: str):
  49. self.engine = engine
  50. self.engine_name = engine_name
  51. self.logger = engines[engine_name].logger
  52. key = get_network(self.engine_name)
  53. key = id(key) if key else self.engine_name
  54. self.suspended_status = SUSPENDED_STATUS.setdefault(key, SuspendedStatus())
  55. def initialize(self):
  56. try:
  57. self.engine.init(get_engine_from_settings(self.engine_name))
  58. except SearxEngineResponseException as exc:
  59. self.logger.warning('Fail to initialize // %s', exc)
  60. except Exception: # pylint: disable=broad-except
  61. self.logger.exception('Fail to initialize')
  62. else:
  63. self.logger.debug('Initialized')
  64. @property
  65. def has_initialize_function(self):
  66. return hasattr(self.engine, 'init')
  67. def handle_exception(self, result_container, exception_or_message, suspend=False):
  68. # update result_container
  69. if isinstance(exception_or_message, BaseException):
  70. exception_class = exception_or_message.__class__
  71. module_name = getattr(exception_class, '__module__', 'builtins')
  72. module_name = '' if module_name == 'builtins' else module_name + '.'
  73. error_message = module_name + exception_class.__qualname__
  74. else:
  75. error_message = exception_or_message
  76. result_container.add_unresponsive_engine(self.engine_name, error_message)
  77. # metrics
  78. counter_inc('engine', self.engine_name, 'search', 'count', 'error')
  79. if isinstance(exception_or_message, BaseException):
  80. count_exception(self.engine_name, exception_or_message)
  81. else:
  82. count_error(self.engine_name, exception_or_message)
  83. # suspend the engine ?
  84. if suspend:
  85. suspended_time = None
  86. if isinstance(exception_or_message, SearxEngineAccessDeniedException):
  87. suspended_time = exception_or_message.suspended_time
  88. self.suspended_status.suspend(suspended_time, error_message) # pylint: disable=no-member
  89. def _extend_container_basic(self, result_container, start_time, search_results):
  90. # update result_container
  91. result_container.extend(self.engine_name, search_results)
  92. engine_time = default_timer() - start_time
  93. page_load_time = get_time_for_thread()
  94. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  95. # metrics
  96. counter_inc('engine', self.engine_name, 'search', 'count', 'successful')
  97. histogram_observe(engine_time, 'engine', self.engine_name, 'time', 'total')
  98. if page_load_time is not None:
  99. histogram_observe(page_load_time, 'engine', self.engine_name, 'time', 'http')
  100. def extend_container(self, result_container, start_time, search_results):
  101. if getattr(threading.current_thread(), '_timeout', False):
  102. # the main thread is not waiting anymore
  103. self.handle_exception(result_container, 'timeout', None)
  104. else:
  105. # check if the engine accepted the request
  106. if search_results is not None:
  107. self._extend_container_basic(result_container, start_time, search_results)
  108. self.suspended_status.resume()
  109. def extend_container_if_suspended(self, result_container):
  110. if self.suspended_status.is_suspended:
  111. result_container.add_unresponsive_engine(
  112. self.engine_name, self.suspended_status.suspend_reason, suspended=True
  113. )
  114. return True
  115. return False
  116. def get_params(self, search_query, engine_category):
  117. """Returns a set of (see :ref:`request params <engine request arguments>`) or
  118. ``None`` if request is not supported.
  119. Not supported conditions (``None`` is returned):
  120. - A page-number > 1 when engine does not support paging.
  121. - A time range when the engine does not support time range.
  122. """
  123. # if paging is not supported, skip
  124. if search_query.pageno > 1 and not self.engine.paging:
  125. return None
  126. # if max page is reached, skip
  127. max_page = self.engine.max_page or settings['search']['max_page']
  128. if max_page and max_page < search_query.pageno:
  129. return None
  130. # if time_range is not supported, skip
  131. if search_query.time_range and not self.engine.time_range_support:
  132. return None
  133. params = {}
  134. params['category'] = engine_category
  135. params['pageno'] = search_query.pageno
  136. params['safesearch'] = search_query.safesearch
  137. params['time_range'] = search_query.time_range
  138. params['engine_data'] = search_query.engine_data.get(self.engine_name, {})
  139. params['searxng_locale'] = search_query.lang
  140. # deprecated / vintage --> use params['searxng_locale']
  141. #
  142. # Conditions related to engine's traits are implemented in engine.traits
  143. # module. Don't do 'locale' decisions here in the abstract layer of the
  144. # search processor, just pass the value from user's choice unchanged to
  145. # the engine request.
  146. if hasattr(self.engine, 'language') and self.engine.language:
  147. params['language'] = self.engine.language
  148. else:
  149. params['language'] = search_query.lang
  150. return params
  151. @abstractmethod
  152. def search(self, query, params, result_container, start_time, timeout_limit):
  153. pass
  154. def get_tests(self):
  155. tests = getattr(self.engine, 'tests', None)
  156. if tests is None:
  157. tests = getattr(self.engine, 'additional_tests', {})
  158. tests.update(self.get_default_tests())
  159. return tests
  160. def get_default_tests(self):
  161. return {}