abstract.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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, SearxEngineResponseException
  13. from searx.utils import get_engine_from_settings
  14. logger = logger.getChild('searx.search.processor')
  15. SUSPENDED_STATUS = {}
  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 initialize(self):
  53. try:
  54. self.engine.init(get_engine_from_settings(self.engine_name))
  55. except SearxEngineResponseException as exc:
  56. logger.warn('%s engine: Fail to initialize // %s', self.engine_name, exc)
  57. except Exception: # pylint: disable=broad-except
  58. logger.exception('%s engine: Fail to initialize', self.engine_name)
  59. else:
  60. logger.debug('%s engine: Initialized', self.engine_name)
  61. @property
  62. def has_initialize_function(self):
  63. return hasattr(self.engine, 'init')
  64. def handle_exception(self, result_container, exception_or_message, suspend=False):
  65. # update result_container
  66. if isinstance(exception_or_message, BaseException):
  67. exception_class = exception_or_message.__class__
  68. module_name = getattr(exception_class, '__module__', 'builtins')
  69. module_name = '' if module_name == 'builtins' else module_name + '.'
  70. error_message = module_name + exception_class.__qualname__
  71. else:
  72. error_message = exception_or_message
  73. result_container.add_unresponsive_engine(self.engine_name, error_message)
  74. # metrics
  75. counter_inc('engine', self.engine_name, 'search', 'count', 'error')
  76. if isinstance(exception_or_message, BaseException):
  77. count_exception(self.engine_name, exception_or_message)
  78. else:
  79. count_error(self.engine_name, exception_or_message)
  80. # suspend the engine ?
  81. if suspend:
  82. suspended_time = None
  83. if isinstance(exception_or_message, SearxEngineAccessDeniedException):
  84. suspended_time = exception_or_message.suspended_time
  85. self.suspended_status.suspend(suspended_time, error_message) # pylint: disable=no-member
  86. def _extend_container_basic(self, result_container, start_time, search_results):
  87. # update result_container
  88. result_container.extend(self.engine_name, search_results)
  89. engine_time = default_timer() - start_time
  90. page_load_time = get_time_for_thread()
  91. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  92. # metrics
  93. counter_inc('engine', self.engine_name, 'search', 'count', 'successful')
  94. histogram_observe(engine_time, 'engine', self.engine_name, 'time', 'total')
  95. if page_load_time is not None:
  96. histogram_observe(page_load_time, 'engine', self.engine_name, 'time', 'http')
  97. def extend_container(self, result_container, start_time, search_results):
  98. if getattr(threading.current_thread(), '_timeout', False):
  99. # the main thread is not waiting anymore
  100. self.handle_exception(result_container, 'timeout', None)
  101. else:
  102. # check if the engine accepted the request
  103. if search_results is not None:
  104. self._extend_container_basic(result_container, start_time, search_results)
  105. self.suspended_status.resume()
  106. def extend_container_if_suspended(self, result_container):
  107. if self.suspended_status.is_suspended:
  108. result_container.add_unresponsive_engine(self.engine_name,
  109. self.suspended_status.suspend_reason,
  110. suspended=True)
  111. return True
  112. return False
  113. def get_params(self, search_query, engine_category):
  114. # if paging is not supported, skip
  115. if search_query.pageno > 1 and not self.engine.paging:
  116. return None
  117. # if time_range is not supported, skip
  118. if search_query.time_range and not self.engine.time_range_support:
  119. return None
  120. params = {}
  121. params['category'] = engine_category
  122. params['pageno'] = search_query.pageno
  123. params['safesearch'] = search_query.safesearch
  124. params['time_range'] = search_query.time_range
  125. params['engine_data'] = search_query.engine_data.get(self.engine_name, {})
  126. if hasattr(self.engine, 'language') and self.engine.language:
  127. params['language'] = self.engine.language
  128. else:
  129. params['language'] = search_query.lang
  130. return params
  131. @abstractmethod
  132. def search(self, query, params, result_container, start_time, timeout_limit):
  133. pass
  134. def get_tests(self):
  135. tests = getattr(self.engine, 'tests', None)
  136. if tests is None:
  137. tests = getattr(self.engine, 'additional_tests', {})
  138. tests.update(self.get_default_tests())
  139. return tests
  140. def get_default_tests(self): # pylint: disable=no-self-use
  141. return {}