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