__init__.py 8.4 KB

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