__init__.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. import typing
  4. import math
  5. import contextlib
  6. from timeit import default_timer
  7. from operator import itemgetter
  8. from searx.engines import engines
  9. from .models import HistogramStorage, CounterStorage, VoidHistogram, VoidCounterStorage
  10. from .error_recorder import count_error, count_exception, errors_per_engines
  11. __all__ = [
  12. "initialize",
  13. "get_engines_stats",
  14. "get_engine_errors",
  15. "histogram",
  16. "histogram_observe",
  17. "histogram_observe_time",
  18. "counter",
  19. "counter_inc",
  20. "counter_add",
  21. "count_error",
  22. "count_exception",
  23. ]
  24. ENDPOINTS = {'search'}
  25. histogram_storage: typing.Optional[HistogramStorage] = None
  26. counter_storage: typing.Optional[CounterStorage] = None
  27. @contextlib.contextmanager
  28. def histogram_observe_time(*args):
  29. h = histogram_storage.get(*args)
  30. before = default_timer()
  31. yield before
  32. duration = default_timer() - before
  33. if h:
  34. h.observe(duration)
  35. else:
  36. raise ValueError("histogram " + repr((*args,)) + " doesn't not exist")
  37. def histogram_observe(duration, *args):
  38. histogram_storage.get(*args).observe(duration)
  39. def histogram(*args, raise_on_not_found=True):
  40. h = histogram_storage.get(*args)
  41. if raise_on_not_found and h is None:
  42. raise ValueError("histogram " + repr((*args,)) + " doesn't not exist")
  43. return h
  44. def counter_inc(*args):
  45. counter_storage.add(1, *args)
  46. def counter_add(value, *args):
  47. counter_storage.add(value, *args)
  48. def counter(*args):
  49. return counter_storage.get(*args)
  50. def initialize(engine_names=None, enabled=True):
  51. """
  52. Initialize metrics
  53. """
  54. global counter_storage, histogram_storage # pylint: disable=global-statement
  55. if enabled:
  56. counter_storage = CounterStorage()
  57. histogram_storage = HistogramStorage()
  58. else:
  59. counter_storage = VoidCounterStorage()
  60. histogram_storage = HistogramStorage(histogram_class=VoidHistogram)
  61. # max_timeout = max of all the engine.timeout
  62. max_timeout = 2
  63. for engine_name in engine_names or engines:
  64. if engine_name in engines:
  65. max_timeout = max(max_timeout, engines[engine_name].timeout)
  66. # histogram configuration
  67. histogram_width = 0.1
  68. histogram_size = int(1.5 * max_timeout / histogram_width)
  69. # engines
  70. for engine_name in engine_names or engines:
  71. # search count
  72. counter_storage.configure('engine', engine_name, 'search', 'count', 'sent')
  73. counter_storage.configure('engine', engine_name, 'search', 'count', 'successful')
  74. # global counter of errors
  75. counter_storage.configure('engine', engine_name, 'search', 'count', 'error')
  76. # score of the engine
  77. counter_storage.configure('engine', engine_name, 'score')
  78. # result count per requests
  79. histogram_storage.configure(1, 100, 'engine', engine_name, 'result', 'count')
  80. # time doing HTTP requests
  81. histogram_storage.configure(histogram_width, histogram_size, 'engine', engine_name, 'time', 'http')
  82. # total time
  83. # .time.request and ...response times may overlap .time.http time.
  84. histogram_storage.configure(histogram_width, histogram_size, 'engine', engine_name, 'time', 'total')
  85. def get_engine_errors(engline_name_list):
  86. result = {}
  87. engine_names = list(errors_per_engines.keys())
  88. engine_names.sort()
  89. for engine_name in engine_names:
  90. if engine_name not in engline_name_list:
  91. continue
  92. error_stats = errors_per_engines[engine_name]
  93. sent_search_count = max(counter('engine', engine_name, 'search', 'count', 'sent'), 1)
  94. sorted_context_count_list = sorted(error_stats.items(), key=lambda context_count: context_count[1])
  95. r = []
  96. for context, count in sorted_context_count_list:
  97. percentage = round(20 * count / sent_search_count) * 5
  98. r.append(
  99. {
  100. 'filename': context.filename,
  101. 'function': context.function,
  102. 'line_no': context.line_no,
  103. 'code': context.code,
  104. 'exception_classname': context.exception_classname,
  105. 'log_message': context.log_message,
  106. 'log_parameters': context.log_parameters,
  107. 'secondary': context.secondary,
  108. 'percentage': percentage,
  109. }
  110. )
  111. result[engine_name] = sorted(r, reverse=True, key=lambda d: d['percentage'])
  112. return result
  113. def get_reliabilities(engline_name_list, checker_results):
  114. reliabilities = {}
  115. engine_errors = get_engine_errors(engline_name_list)
  116. for engine_name in engline_name_list:
  117. checker_result = checker_results.get(engine_name, {})
  118. checker_success = checker_result.get('success', True)
  119. errors = engine_errors.get(engine_name) or []
  120. if counter('engine', engine_name, 'search', 'count', 'sent') == 0:
  121. # no request
  122. reliability = None
  123. elif checker_success and not errors:
  124. reliability = 100
  125. elif 'simple' in checker_result.get('errors', {}):
  126. # the basic (simple) test doesn't work: the engine is broken according to the checker
  127. # even if there is no exception
  128. reliability = 0
  129. else:
  130. # pylint: disable=consider-using-generator
  131. reliability = 100 - sum([error['percentage'] for error in errors if not error.get('secondary')])
  132. reliabilities[engine_name] = {
  133. 'reliability': reliability,
  134. 'errors': errors,
  135. 'checker': checker_results.get(engine_name, {}).get('errors', {}),
  136. }
  137. return reliabilities
  138. def get_engines_stats(engine_name_list):
  139. assert counter_storage is not None
  140. assert histogram_storage is not None
  141. list_time = []
  142. max_time_total = max_result_count = None
  143. for engine_name in engine_name_list:
  144. sent_count = counter('engine', engine_name, 'search', 'count', 'sent')
  145. if sent_count == 0:
  146. continue
  147. result_count = histogram('engine', engine_name, 'result', 'count').percentage(50)
  148. result_count_sum = histogram('engine', engine_name, 'result', 'count').sum
  149. successful_count = counter('engine', engine_name, 'search', 'count', 'successful')
  150. time_total = histogram('engine', engine_name, 'time', 'total').percentage(50)
  151. max_time_total = max(time_total or 0, max_time_total or 0)
  152. max_result_count = max(result_count or 0, max_result_count or 0)
  153. stats = {
  154. 'name': engine_name,
  155. 'total': None,
  156. 'total_p80': None,
  157. 'total_p95': None,
  158. 'http': None,
  159. 'http_p80': None,
  160. 'http_p95': None,
  161. 'processing': None,
  162. 'processing_p80': None,
  163. 'processing_p95': None,
  164. 'score': 0,
  165. 'score_per_result': 0,
  166. 'result_count': result_count,
  167. }
  168. if successful_count and result_count_sum:
  169. score = counter('engine', engine_name, 'score')
  170. stats['score'] = score
  171. stats['score_per_result'] = score / float(result_count_sum)
  172. time_http = histogram('engine', engine_name, 'time', 'http').percentage(50)
  173. time_http_p80 = time_http_p95 = 0
  174. if time_http is not None:
  175. time_http_p80 = histogram('engine', engine_name, 'time', 'http').percentage(80)
  176. time_http_p95 = histogram('engine', engine_name, 'time', 'http').percentage(95)
  177. stats['http'] = round(time_http, 1)
  178. stats['http_p80'] = round(time_http_p80, 1)
  179. stats['http_p95'] = round(time_http_p95, 1)
  180. if time_total is not None:
  181. time_total_p80 = histogram('engine', engine_name, 'time', 'total').percentage(80)
  182. time_total_p95 = histogram('engine', engine_name, 'time', 'total').percentage(95)
  183. stats['total'] = round(time_total, 1)
  184. stats['total_p80'] = round(time_total_p80, 1)
  185. stats['total_p95'] = round(time_total_p95, 1)
  186. stats['processing'] = round(time_total - (time_http or 0), 1)
  187. stats['processing_p80'] = round(time_total_p80 - time_http_p80, 1)
  188. stats['processing_p95'] = round(time_total_p95 - time_http_p95, 1)
  189. list_time.append(stats)
  190. return {
  191. 'time': list_time,
  192. 'max_time': math.ceil(max_time_total or 0),
  193. 'max_result_count': math.ceil(max_result_count or 0),
  194. }