__init__.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. import typing
  15. import gc
  16. import threading
  17. from time import time
  18. from uuid import uuid4
  19. from _thread import start_new_thread
  20. from searx import settings
  21. from searx.answerers import ask
  22. from searx.external_bang import get_bang_url
  23. from searx.results import ResultContainer
  24. from searx import logger
  25. from searx.plugins import plugins
  26. from searx.search.models import EngineRef, SearchQuery
  27. from searx.search.processors import processors, initialize as initialize_processors
  28. from searx.search.checker import initialize as initialize_checker
  29. logger = logger.getChild('search')
  30. max_request_timeout = settings.get('outgoing', {}).get('max_request_timeout' or None)
  31. if max_request_timeout is None:
  32. logger.info('max_request_timeout={0}'.format(max_request_timeout))
  33. else:
  34. if isinstance(max_request_timeout, float):
  35. logger.info('max_request_timeout={0} second(s)'.format(max_request_timeout))
  36. else:
  37. logger.critical('outgoing.max_request_timeout if defined has to be float')
  38. import sys
  39. sys.exit(1)
  40. def initialize(settings_engines=None, enable_checker=False):
  41. settings_engines = settings_engines or settings['engines']
  42. initialize_processors(settings_engines)
  43. if enable_checker:
  44. initialize_checker()
  45. class Search:
  46. """Search information container"""
  47. __slots__ = "search_query", "result_container", "start_time", "actual_timeout"
  48. def __init__(self, search_query):
  49. # init vars
  50. super().__init__()
  51. self.search_query = search_query
  52. self.result_container = ResultContainer()
  53. self.start_time = None
  54. self.actual_timeout = None
  55. def search_external_bang(self):
  56. """
  57. Check if there is a external bang.
  58. If yes, update self.result_container and return True
  59. """
  60. if self.search_query.external_bang:
  61. self.result_container.redirect_url = get_bang_url(self.search_query)
  62. # This means there was a valid bang and the
  63. # rest of the search does not need to be continued
  64. if isinstance(self.result_container.redirect_url, str):
  65. return True
  66. return False
  67. def search_answerers(self):
  68. """
  69. Check if an answer return a result.
  70. If yes, update self.result_container and return True
  71. """
  72. answerers_results = ask(self.search_query)
  73. if answerers_results:
  74. for results in answerers_results:
  75. self.result_container.extend('answer', results)
  76. return True
  77. return False
  78. # do search-request
  79. def _get_requests(self):
  80. # init vars
  81. requests = []
  82. # max of all selected engine timeout
  83. default_timeout = 0
  84. # start search-reqest for all selected engines
  85. for engineref in self.search_query.engineref_list:
  86. processor = processors[engineref.name]
  87. # set default request parameters
  88. request_params = processor.get_params(self.search_query, engineref.category)
  89. if request_params is None:
  90. continue
  91. with threading.RLock():
  92. processor.engine.stats['sent_search_count'] += 1
  93. # append request to list
  94. requests.append((engineref.name, self.search_query.query, request_params))
  95. # update default_timeout
  96. default_timeout = max(default_timeout, processor.engine.timeout)
  97. # adjust timeout
  98. actual_timeout = default_timeout
  99. query_timeout = self.search_query.timeout_limit
  100. if max_request_timeout is None and query_timeout is None:
  101. # No max, no user query: default_timeout
  102. pass
  103. elif max_request_timeout is None and query_timeout is not None:
  104. # No max, but user query: From user query except if above default
  105. actual_timeout = min(default_timeout, query_timeout)
  106. elif max_request_timeout is not None and query_timeout is None:
  107. # Max, no user query: Default except if above max
  108. actual_timeout = min(default_timeout, max_request_timeout)
  109. elif max_request_timeout is not None and query_timeout is not None:
  110. # Max & user query: From user query except if above max
  111. actual_timeout = min(query_timeout, max_request_timeout)
  112. logger.debug("actual_timeout={0} (default_timeout={1}, ?timeout_limit={2}, max_request_timeout={3})"
  113. .format(actual_timeout, default_timeout, query_timeout, max_request_timeout))
  114. return requests, actual_timeout
  115. def search_multiple_requests(self, requests):
  116. search_id = uuid4().__str__()
  117. for engine_name, query, request_params in requests:
  118. th = threading.Thread(
  119. target=processors[engine_name].search,
  120. args=(query, request_params, self.result_container, self.start_time, self.actual_timeout),
  121. name=search_id,
  122. )
  123. th._timeout = False
  124. th._engine_name = engine_name
  125. th.start()
  126. for th in threading.enumerate():
  127. if th.name == search_id:
  128. remaining_time = max(0.0, self.actual_timeout - (time() - self.start_time))
  129. th.join(remaining_time)
  130. if th.is_alive():
  131. th._timeout = True
  132. self.result_container.add_unresponsive_engine(th._engine_name, 'timeout')
  133. logger.warning('engine timeout: {0}'.format(th._engine_name))
  134. def search_standard(self):
  135. """
  136. Update self.result_container, self.actual_timeout
  137. """
  138. requests, self.actual_timeout = self._get_requests()
  139. # send all search-request
  140. if requests:
  141. self.search_multiple_requests(requests)
  142. start_new_thread(gc.collect, tuple())
  143. # return results, suggestions, answers and infoboxes
  144. return True
  145. # do search-request
  146. def search(self):
  147. self.start_time = time()
  148. if not self.search_external_bang():
  149. if not self.search_answerers():
  150. self.search_standard()
  151. return self.result_container
  152. class SearchWithPlugins(Search):
  153. """Similar to the Search class but call the plugins."""
  154. __slots__ = 'ordered_plugin_list', 'request'
  155. def __init__(self, search_query, ordered_plugin_list, request):
  156. super().__init__(search_query)
  157. self.ordered_plugin_list = ordered_plugin_list
  158. self.request = request
  159. def search(self):
  160. if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
  161. super().search()
  162. plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
  163. results = self.result_container.get_ordered_results()
  164. for result in results:
  165. plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
  166. return self.result_container