4
0

stats_routes.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import socket
  2. import sys
  3. from datetime import datetime
  4. from threading import Lock
  5. from flask import Blueprint, render_template # , request, jsonify
  6. from flask_babel import gettext as _
  7. from loguru import logger
  8. # from services.security.icap_service import scan_file_with_icap
  9. from parsers.cache import fetch_squid_cache_stats
  10. from services.system.metrics_service import MetricsService
  11. from services.system.system_info import (
  12. get_cpu_info,
  13. get_network_info,
  14. get_network_stats,
  15. get_os_info,
  16. get_ram_info,
  17. # get_squid_version,
  18. get_swap_info,
  19. get_timezone,
  20. get_uptime,
  21. )
  22. from utils.size import size_to_bytes
  23. stats_bp = Blueprint("stats", __name__)
  24. # Global variables for real-time data
  25. realtime_data_lock = Lock()
  26. realtime_cache_stats = {}
  27. realtime_system_info = {}
  28. @stats_bp.route("/stats")
  29. def cache_stats_realtime():
  30. try:
  31. with realtime_data_lock:
  32. stats_data = realtime_cache_stats if realtime_cache_stats else {}
  33. system_info_data = realtime_system_info if realtime_system_info else {}
  34. if not stats_data:
  35. data = fetch_squid_cache_stats()
  36. stats_data = vars(data) if hasattr(data, "__dict__") else data
  37. if not system_info_data:
  38. system_info_data = {
  39. "hostname": socket.gethostname(),
  40. "ips": get_network_info(),
  41. "os": get_os_info(),
  42. "uptime": get_uptime(),
  43. "ram": get_ram_info(),
  44. "swap": get_swap_info(),
  45. "cpu": get_cpu_info(),
  46. "python_version": sys.version.split()[0],
  47. "squid_version": "Not available",
  48. "timezone": get_timezone(),
  49. "local_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  50. }
  51. network_stats = get_network_stats()
  52. logger.info("Successfully fetched cache statistics and system info")
  53. return render_template(
  54. "cacheView.html",
  55. cache_stats=stats_data,
  56. system_info=system_info_data,
  57. network_stats=network_stats,
  58. page_icon="favicon.ico",
  59. page_title=_("Estadísticas del Sistema"),
  60. icon="fas fa-chart-bar",
  61. subtitle=_("Estadísticas del comportamiento del Sistema"),
  62. )
  63. except Exception as e:
  64. logger.error(f"Error in /stats: {str(e)}")
  65. return render_template(
  66. "error.html", message="Error retrieving cache statistics or system info"
  67. ), 500
  68. """ @stats_bp.route("/print_icap_service", methods=["POST"])
  69. def print_icap_service():
  70. if "file" not in request.files:
  71. return jsonify({"error": _("No file part in the request")}), 400
  72. result, status = scan_file_with_icap(request.files["file"])
  73. return jsonify(result), status """
  74. def realtime_data_thread(socketio, shutdown_event=None):
  75. global realtime_cache_stats, realtime_system_info
  76. import time
  77. data_collection_counter = 0
  78. logger.info("Real-time data collection thread started")
  79. while not (shutdown_event and shutdown_event.is_set()):
  80. try:
  81. cache_data = fetch_squid_cache_stats()
  82. cache_stats = (
  83. vars(cache_data) if hasattr(cache_data, "__dict__") else cache_data
  84. )
  85. # Validar network_info
  86. network_info = get_network_info()
  87. if not isinstance(network_info, list | dict) or network_info in (
  88. "No disponible",
  89. None,
  90. "",
  91. ):
  92. logger.warning(f"get_network_info() returned an error: {network_info}")
  93. network_info = []
  94. # Validar ram_info
  95. ram_info = get_ram_info()
  96. if not isinstance(ram_info, dict) or ram_info in (
  97. "No disponible",
  98. None,
  99. "",
  100. ):
  101. logger.warning(f"get_ram_info() returned an error: {ram_info}")
  102. ram_info = {"used": "0 B"}
  103. # Validar swap_info
  104. swap_info = get_swap_info()
  105. if not isinstance(swap_info, dict) or swap_info in (
  106. "No disponible",
  107. None,
  108. "",
  109. ):
  110. logger.warning(f"get_swap_info() returned an error: {swap_info}")
  111. swap_info = {"used": "0 B"}
  112. # Validar cpu_info
  113. cpu_info = get_cpu_info()
  114. if not isinstance(cpu_info, dict) or cpu_info in (
  115. "No disponible",
  116. None,
  117. "",
  118. ):
  119. logger.warning(f"get_cpu_info() returned an error: {cpu_info}")
  120. cpu_info = {"usage": "0%"}
  121. # Validar network_stats
  122. network_stats = get_network_stats()
  123. if not isinstance(network_stats, dict) or network_stats in (
  124. "No disponible",
  125. None,
  126. "",
  127. ):
  128. logger.warning(
  129. f"get_network_stats() returned an error: {network_stats}"
  130. )
  131. network_stats = {}
  132. system_info = {
  133. "hostname": socket.gethostname(),
  134. "ips": network_info,
  135. "os": get_os_info(),
  136. "uptime": get_uptime(),
  137. "ram": ram_info,
  138. "swap": swap_info,
  139. "cpu": cpu_info,
  140. "python_version": sys.version.split()[0],
  141. "squid_version": "Not available",
  142. "timezone": get_timezone(),
  143. "local_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  144. "timestamp_utc": datetime.now().isoformat(),
  145. }
  146. # Guardar métricas en la base de datos solo cada 60 segundos (cada 4 iteraciones)
  147. data_collection_counter += 1
  148. if data_collection_counter % 4 == 0:
  149. ram_bytes = size_to_bytes(ram_info.get("used", "0 B"))
  150. swap_bytes = size_to_bytes(swap_info.get("used", "0 B"))
  151. # Guardar en base de datos
  152. MetricsService.save_system_metrics(
  153. cpu_usage=cpu_info.get("usage", "0%"),
  154. ram_usage_bytes=ram_bytes,
  155. swap_usage_bytes=swap_bytes,
  156. net_sent_bytes_sec=network_stats.get("bytes_sent_per_sec", 0),
  157. net_recv_bytes_sec=network_stats.get("bytes_recv_per_sec", 0),
  158. )
  159. with realtime_data_lock:
  160. realtime_cache_stats = cache_stats
  161. realtime_system_info = system_info
  162. socketio.emit(
  163. "system_update",
  164. {
  165. "cache_stats": cache_stats,
  166. "system_info": system_info,
  167. "network_stats": network_stats,
  168. },
  169. )
  170. except Exception as e:
  171. logger.error(f"Error in real-time data thread: {str(e)}")
  172. # Use wait with timeout for responsive shutdown
  173. if shutdown_event:
  174. shutdown_event.wait(timeout=15)
  175. else:
  176. time.sleep(15)
  177. logger.info("Real-time data collection thread stopped")