abstract.py 6.8 KB

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