__init__.py 7.6 KB

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