__init__.py 7.7 KB

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