app.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from flask import Flask, render_template, request, redirect, jsonify
  2. from database.database import get_session
  3. from parsers.connections import parse_raw_data, group_by_user
  4. from services.fetch_data import fetch_squid_data
  5. from parsers.cache import fetch_squid_cache_stats
  6. import os
  7. import logging
  8. from parsers.log import process_logs
  9. from flask_apscheduler import APScheduler
  10. from services.fetch_data_logs import get_users_with_logs_optimized
  11. from dotenv import load_dotenv
  12. from services.get_reports import get_important_metrics
  13. from utils.colors import color_map
  14. from utils.updateSquid import update_squid
  15. from utils.updateSquidStats import updateSquidStats
  16. from datetime import datetime
  17. from services.fetch_data_logs import get_users_with_logs_by_date
  18. # set configuration values
  19. class Config:
  20. SCHEDULER_API_ENABLED = True
  21. load_dotenv()
  22. # Initialize Flask application
  23. app = Flask(__name__, static_folder='./static')
  24. app.config.from_object(Config())
  25. scheduler = APScheduler()
  26. app.secret_key = os.urandom(24).hex()
  27. scheduler.init_app(app)
  28. scheduler.start()
  29. # Configure logging
  30. logging.basicConfig(
  31. level=logging.INFO,
  32. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  33. )
  34. logger = logging.getLogger(__name__)
  35. @app.route('/')
  36. def index():
  37. """Main page showing Squid statistics grouped by users."""
  38. try:
  39. raw_data = fetch_squid_data()
  40. if 'Error' in raw_data:
  41. logger.error(f"Failed to fetch Squid data: {raw_data}")
  42. return render_template('error.html', message="Error connecting to Squid"), 500
  43. connections = parse_raw_data(raw_data)
  44. grouped_connections = group_by_user(connections)
  45. return render_template(
  46. 'index.html',
  47. grouped_connections=grouped_connections, page_icon='favicon.ico', page_title='Inicio Dashboard')
  48. except Exception as e:
  49. logger.error(f"Unexpected error in index route: {str(e)}")
  50. return render_template('error.html', message="An unexpected error occurred"), 500
  51. @app.route('/actualizar-conexiones')
  52. def actualizar_conexiones():
  53. try:
  54. raw_data = fetch_squid_data()
  55. if 'Error' in raw_data:
  56. logger.error(f"Failed to fetch Squid data: {raw_data}")
  57. return "Error", 500
  58. connections = parse_raw_data(raw_data)
  59. grouped_connections = group_by_user(connections)
  60. return render_template('partials/conexiones.html', grouped_connections=grouped_connections)
  61. except Exception as e:
  62. logger.error(f"Unexpected error in /actualizar-conexiones route: {str(e)}")
  63. return "Error interno", 500
  64. @app.route('/stats')
  65. def cache_stats():
  66. """Page showing Squid cache statistics."""
  67. try:
  68. data = fetch_squid_cache_stats()
  69. stats_data = vars(data) if hasattr(data, '__dict__') else data
  70. logger.info("Successfully fetched cache statistics")
  71. return render_template('cacheView.html', cache_stats=stats_data, page_icon='statistics.ico', page_title='Estadísticas')
  72. except Exception as e:
  73. logger.error(f"Error fetching cache stats: {str(e)}")
  74. return render_template('error.html', message="Error retrieving cache statistics"), 500
  75. @app.route('/logs')
  76. def logs():
  77. try:
  78. db = get_session()
  79. users_data = get_users_with_logs_optimized(db)
  80. return render_template('logsView.html', users_data=users_data, page_icon='user.ico', page_title='Actividad usuarios' )
  81. except Exception as e:
  82. print(f"Error en ruta /logs: {e}")
  83. return render_template('error.html', message="Error retrieving logs"), 500
  84. @scheduler.task('interval', id='do_job_1', seconds=30, misfire_grace_time=900)
  85. def init_scheduler():
  86. """Initialize and start the background scheduler for log processing"""
  87. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  88. logger.info(f"Configurando scheduler para el archivo de log: {log_file}")
  89. if not os.path.exists(log_file):
  90. logger.error(f"Archivo de log no encontrado: {log_file}")
  91. return
  92. else:
  93. process_logs(log_file)
  94. @app.template_filter('divide')
  95. def divide_filter(value, divisor):
  96. return value / divisor
  97. @app.template_filter('format_bytes')
  98. def format_bytes_filter(value):
  99. value = int(value)
  100. if value >= 1024**3: # GB
  101. return f"{(value / (1024**3)):.2f} GB"
  102. elif value >= 1024**2: # MB
  103. return f"{(value / (1024**2)):.2f} MB"
  104. elif value >= 1024: # KB
  105. return f"{(value / 1024):.2f} KB"
  106. return f"{value} bytes"
  107. @app.route('/get-logs-by-date', methods=['POST'])
  108. def get_logs_by_date():
  109. db = None
  110. try:
  111. date_str = request.json.get('date')
  112. selected_date = datetime.strptime(date_str, '%Y-%m-%d')
  113. date_suffix = selected_date.strftime('%Y%m%d')
  114. db = get_session()
  115. users_data = get_users_with_logs_by_date(db, date_suffix)
  116. print(users_data)
  117. return jsonify(users_data)
  118. except ValueError as ve:
  119. return jsonify({'error': 'Formato de fecha inválido'}), 400
  120. except Exception as e:
  121. print(f"Error: {e}")
  122. return jsonify({'error': str(e)}), 500
  123. finally:
  124. if db is not None:
  125. db.close()
  126. @app.route('/reports')
  127. def reports():
  128. db = get_session()
  129. metrics = get_important_metrics(db)
  130. http_codes = metrics['http_response_distribution']
  131. http_codes = sorted(metrics['http_response_distribution'], key=lambda x: x['count'], reverse=True)
  132. main_codes = http_codes[:8]
  133. other_codes = http_codes[8:]
  134. if other_codes:
  135. other_count = sum(item['count'] for item in other_codes)
  136. main_codes.append({'response_code': 'Otros', 'count': other_count})
  137. metrics['http_response_distribution_chart'] = {
  138. 'labels': [str(item['response_code']) for item in main_codes],
  139. 'data': [item['count'] for item in main_codes],
  140. 'colors': [color_map.get(str(code['response_code']), color_map['Otros']) for code in main_codes]
  141. }
  142. return render_template('reports.html', metrics=metrics, page_icon='bar.ico', page_title='Reportes y gráficas')
  143. @app.route('/install', methods=['POST'])
  144. def install_package():
  145. install = update_squid()
  146. if install == False:
  147. return redirect('/')
  148. else:
  149. return redirect('/')
  150. @app.route('/update', methods=['POST'])
  151. def update_web():
  152. install = updateSquidStats()
  153. if install == False:
  154. return redirect('/')
  155. else:
  156. return redirect('/')
  157. if __name__ == "__main__":
  158. # Execute app with Flask
  159. debug_mode = os.getenv("FLASK_DEBUG", "false").lower() == "true"
  160. app.run(debug=debug_mode, host='0.0.0.0', port=5000)