.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
__init__.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Load and initialize the ``engines``, see :py:func:`load_engines` and register
3:py:obj:`engine_shortcuts`.
4
5usage::
6
7 load_engines( settings['engines'] )
8
9"""
10
11from __future__ import annotations
12
13import sys
14import copy
15from os.path import realpath, dirname
16
17from typing import TYPE_CHECKING, Dict
18import types
19import inspect
20
21from searx import logger, settings
22from searx.utils import load_module
23
24if TYPE_CHECKING:
25 from searx.enginelib import Engine
26
27logger = logger.getChild('engines')
28ENGINE_DIR = dirname(realpath(__file__))
29ENGINE_DEFAULT_ARGS = {
30 # Common options in the engine module
31 "engine_type": "online",
32 "paging": False,
33 "time_range_support": False,
34 "safesearch": False,
35 # settings.yml
36 "categories": ["general"],
37 "enable_http": False,
38 "shortcut": "-",
39 "timeout": settings["outgoing"]["request_timeout"],
40 "display_error_messages": True,
41 "disabled": False,
42 "inactive": False,
43 "about": {},
44 "using_tor_proxy": False,
45 "send_accept_language_header": False,
46 "tokens": [],
47 "max_page": 0,
48}
49# set automatically when an engine does not have any tab category
50DEFAULT_CATEGORY = 'other'
51
52
53# Defaults for the namespace of an engine module, see :py:func:`load_engine`
54
55categories = {'general': []}
56engines: Dict[str, Engine | types.ModuleType] = {}
57engine_shortcuts = {}
58"""Simple map of registered *shortcuts* to name of the engine (or ``None``).
59
60::
61
62 engine_shortcuts[engine.shortcut] = engine.name
63
64:meta hide-value:
65"""
66
67
68def check_engine_module(module: types.ModuleType):
69 # probe unintentional name collisions / for example name collisions caused
70 # by import statements in the engine module ..
71
72 # network: https://github.com/searxng/searxng/issues/762#issuecomment-1605323861
73 obj = getattr(module, 'network', None)
74 if obj and inspect.ismodule(obj):
75 msg = f'type of {module.__name__}.network is a module ({obj.__name__}), expected a string'
76 # logger.error(msg)
77 raise TypeError(msg)
78
79
80def load_engine(engine_data: dict) -> Engine | types.ModuleType | None:
81 """Load engine from ``engine_data``.
82
83 :param dict engine_data: Attributes from YAML ``settings:engines/<engine>``
84 :return: initialized namespace of the ``<engine>``.
85
86 1. create a namespace and load module of the ``<engine>``
87 2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`
88 3. update namespace with values from ``engine_data``
89
90 If engine *is active*, return namespace of the engine, otherwise return
91 ``None``.
92
93 This function also returns ``None`` if initialization of the namespace fails
94 for one of the following reasons:
95
96 - engine name contains underscore
97 - engine name is not lowercase
98 - required attribute is not set :py:func:`is_missing_required_attributes`
99
100 """
101 # pylint: disable=too-many-return-statements
102
103 engine_name = engine_data.get('name')
104 if engine_name is None:
105 logger.error('An engine does not have a "name" field')
106 return None
107 if '_' in engine_name:
108 logger.error('Engine name contains underscore: "{}"'.format(engine_name))
109 return None
110
111 if engine_name.lower() != engine_name:
112 logger.warning('Engine name is not lowercase: "{}", converting to lowercase'.format(engine_name))
113 engine_name = engine_name.lower()
114 engine_data['name'] = engine_name
115
116 # load_module
117 module_name = engine_data.get('engine')
118 if module_name is None:
119 logger.error('The "engine" field is missing for the engine named "{}"'.format(engine_name))
120 return None
121 try:
122 engine = load_module(module_name + '.py', ENGINE_DIR)
123 except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):
124 logger.exception('Fatal exception in engine "{}"'.format(module_name))
125 sys.exit(1)
126 except BaseException:
127 logger.exception('Cannot load engine "{}"'.format(module_name))
128 return None
129
130 check_engine_module(engine)
131 update_engine_attributes(engine, engine_data)
133
134 # avoid cyclic imports
135 # pylint: disable=import-outside-toplevel
136 from searx.enginelib.traits import EngineTraitsMap
137
138 trait_map = EngineTraitsMap.from_data()
139 trait_map.set_traits(engine)
140
141 if not is_engine_active(engine):
142 return None
143
145 return None
146
147 set_loggers(engine, engine_name)
148
149 if not any(cat in settings['categories_as_tabs'] for cat in engine.categories):
150 engine.categories.append(DEFAULT_CATEGORY)
151
152 return engine
153
154
155def set_loggers(engine, engine_name):
156 # set the logger for engine
157 engine.logger = logger.getChild(engine_name)
158 # the engine may have load some other engines
159 # may sure the logger is initialized
160 # use sys.modules.copy() to avoid "RuntimeError: dictionary changed size during iteration"
161 # see https://github.com/python/cpython/issues/89516
162 # and https://docs.python.org/3.10/library/sys.html#sys.modules
163 modules = sys.modules.copy()
164 for module_name, module in modules.items():
165 if (
166 module_name.startswith("searx.engines")
167 and module_name != "searx.engines.__init__"
168 and not hasattr(module, "logger")
169 ):
170 module_engine_name = module_name.split(".")[-1]
171 module.logger = logger.getChild(module_engine_name) # type: ignore
172
173
174def update_engine_attributes(engine: Engine | types.ModuleType, engine_data):
175 # set engine attributes from engine_data
176 for param_name, param_value in engine_data.items():
177 if param_name == 'categories':
178 if isinstance(param_value, str):
179 param_value = list(map(str.strip, param_value.split(',')))
180 engine.categories = param_value # type: ignore
181 elif hasattr(engine, 'about') and param_name == 'about':
182 engine.about = {**engine.about, **engine_data['about']} # type: ignore
183 else:
184 setattr(engine, param_name, param_value)
185
186 # set default attributes
187 for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():
188 if not hasattr(engine, arg_name):
189 setattr(engine, arg_name, copy.deepcopy(arg_value))
190
191
192def update_attributes_for_tor(engine: Engine | types.ModuleType):
193 if using_tor_proxy(engine) and hasattr(engine, 'onion_url'):
194 engine.search_url = engine.onion_url + getattr(engine, 'search_path', '') # type: ignore
195 engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0) # type: ignore
196
197
199 """An attribute is required when its name doesn't start with ``_`` (underline).
200 Required attributes must not be ``None``.
201
202 """
203 missing = False
204 for engine_attr in dir(engine):
205 if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:
206 logger.error('Missing engine config attribute: "{0}.{1}"'.format(engine.name, engine_attr))
207 missing = True
208 return missing
209
210
211def using_tor_proxy(engine: Engine | types.ModuleType):
212 """Return True if the engine configuration declares to use Tor."""
213 return settings['outgoing'].get('using_tor_proxy') or getattr(engine, 'using_tor_proxy', False)
214
215
216def is_engine_active(engine: Engine | types.ModuleType):
217 # check if engine is inactive
218 if engine.inactive is True:
219 return False
220
221 # exclude onion engines if not using tor
222 if 'onions' in engine.categories and not using_tor_proxy(engine):
223 return False
224
225 return True
226
227
228def register_engine(engine: Engine | types.ModuleType):
229 if engine.name in engines:
230 logger.error('Engine config error: ambiguous name: {0}'.format(engine.name))
231 sys.exit(1)
232 engines[engine.name] = engine
233
234 if engine.shortcut in engine_shortcuts:
235 logger.error('Engine config error: ambiguous shortcut: {0}'.format(engine.shortcut))
236 sys.exit(1)
237 engine_shortcuts[engine.shortcut] = engine.name
238
239 for category_name in engine.categories:
240 categories.setdefault(category_name, []).append(engine)
241
242
243def load_engines(engine_list):
244 """usage: ``engine_list = settings['engines']``"""
245 engines.clear()
246 engine_shortcuts.clear()
247 categories.clear()
248 categories['general'] = []
249 for engine_data in engine_list:
250 engine = load_engine(engine_data)
251 if engine:
252 register_engine(engine)
253 return engines
register_engine(Engine|types.ModuleType engine)
Definition __init__.py:228
update_attributes_for_tor(Engine|types.ModuleType engine)
Definition __init__.py:192
using_tor_proxy(Engine|types.ModuleType engine)
Definition __init__.py:211
Engine|types.ModuleType|None load_engine(dict engine_data)
Definition __init__.py:80
is_missing_required_attributes(engine)
Definition __init__.py:198
check_engine_module(types.ModuleType module)
Definition __init__.py:68
load_engines(engine_list)
Definition __init__.py:243
is_engine_active(Engine|types.ModuleType engine)
Definition __init__.py:216
update_engine_attributes(Engine|types.ModuleType engine, engine_data)
Definition __init__.py:174
set_loggers(engine, engine_name)
Definition __init__.py:155