__init__.py 7.9 KB

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