__init__.py 8.4 KB

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