app.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. from services.blacklist_users import find_blacklisted_sites, find_blacklisted_sites_by_date
  19. # set configuration values
  20. class Config:
  21. SCHEDULER_API_ENABLED = True
  22. load_dotenv()
  23. # Initialize Flask application
  24. app = Flask(__name__, static_folder='./static')
  25. app.config.from_object(Config())
  26. scheduler = APScheduler()
  27. app.secret_key = os.urandom(24).hex()
  28. scheduler.init_app(app)
  29. scheduler.start()
  30. # Configure logging
  31. logging.basicConfig(
  32. level=logging.INFO,
  33. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  34. )
  35. logger = logging.getLogger(__name__)
  36. @app.route('/')
  37. def index():
  38. """Main page showing Squid statistics grouped by users."""
  39. try:
  40. raw_data = fetch_squid_data()
  41. if 'Error' in raw_data:
  42. logger.error(f"Failed to fetch Squid data: {raw_data}")
  43. return render_template('error.html', message="Error connecting to Squid"), 500
  44. connections = parse_raw_data(raw_data)
  45. grouped_connections = group_by_user(connections)
  46. return render_template(
  47. 'index.html',
  48. grouped_connections=grouped_connections, page_icon='favicon.ico', page_title='Inicio Dashboard')
  49. except Exception as e:
  50. logger.error(f"Unexpected error in index route: {str(e)}")
  51. return render_template('error.html', message="An unexpected error occurred"), 500
  52. @app.route('/actualizar-conexiones')
  53. def actualizar_conexiones():
  54. try:
  55. raw_data = fetch_squid_data()
  56. if 'Error' in raw_data:
  57. logger.error(f"Failed to fetch Squid data: {raw_data}")
  58. return "Error", 500
  59. connections = parse_raw_data(raw_data)
  60. grouped_connections = group_by_user(connections)
  61. return render_template('partials/conexiones.html', grouped_connections=grouped_connections)
  62. except Exception as e:
  63. logger.error(f"Unexpected error in /actualizar-conexiones route: {str(e)}")
  64. return "Error interno", 500
  65. @app.route('/stats')
  66. def cache_stats():
  67. """Page showing Squid cache statistics."""
  68. try:
  69. data = fetch_squid_cache_stats()
  70. stats_data = vars(data) if hasattr(data, '__dict__') else data
  71. logger.info("Successfully fetched cache statistics")
  72. return render_template('cacheView.html', cache_stats=stats_data, page_icon='statistics.ico', page_title='Estadísticas')
  73. except Exception as e:
  74. logger.error(f"Error fetching cache stats: {str(e)}")
  75. return render_template('error.html', message="Error retrieving cache statistics"), 500
  76. @app.route('/logs')
  77. def logs():
  78. try:
  79. db = get_session()
  80. users_data = get_users_with_logs_optimized(db)
  81. return render_template('logsView.html', users_data=users_data, page_icon='user.ico', page_title='Actividad usuarios' )
  82. except Exception as e:
  83. print(f"Error en ruta /logs: {e}")
  84. return render_template('error.html', message="Error retrieving logs"), 500
  85. @scheduler.task('interval', id='do_job_1', seconds=30, misfire_grace_time=900)
  86. def init_scheduler():
  87. """Initialize and start the background scheduler for log processing"""
  88. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  89. logger.info(f"Configurando scheduler para el archivo de log: {log_file}")
  90. if not os.path.exists(log_file):
  91. logger.error(f"Archivo de log no encontrado: {log_file}")
  92. return
  93. else:
  94. process_logs(log_file)
  95. @app.template_filter('divide')
  96. def divide_filter(value, divisor):
  97. return value / divisor
  98. @app.template_filter('format_bytes')
  99. def format_bytes_filter(value):
  100. value = int(value)
  101. if value >= 1024**3: # GB
  102. return f"{(value / (1024**3)):.2f} GB"
  103. elif value >= 1024**2: # MB
  104. return f"{(value / (1024**2)):.2f} MB"
  105. elif value >= 1024: # KB
  106. return f"{(value / 1024):.2f} KB"
  107. return f"{value} bytes"
  108. @app.route('/get-logs-by-date', methods=['POST'])
  109. def get_logs_by_date():
  110. db = None
  111. try:
  112. date_str = request.json.get('date')
  113. selected_date = datetime.strptime(date_str, '%Y-%m-%d')
  114. date_suffix = selected_date.strftime('%Y%m%d')
  115. db = get_session()
  116. users_data = get_users_with_logs_by_date(db, date_suffix)
  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. '''
  158. @app.route('/blacklist', methods=['GET'])
  159. def check_blacklist():
  160. db = None
  161. db = get_session()
  162. try:
  163. blacklist = ["facebook.com", "twitter.com", "instagram.com", "tiktok.com"] # Ejemplo
  164. resultados = find_blacklisted_sites(db, blacklist)
  165. return render_template('blacklist.html',
  166. results=resultados,
  167. page_icon='shield-exclamation.ico',
  168. page_title='Registros de Blacklist')
  169. except Exception as e:
  170. logger.error(f"Error en check-blacklist: {str(e)}")
  171. return jsonify({'error': 'Error interno del servidor'}), 500
  172. finally:
  173. if db is not None:
  174. db.close()
  175. '''
  176. @app.route('/blacklist', methods=['GET'])
  177. def blacklist_logs():
  178. db = None
  179. try:
  180. # Obtener parámetros de paginación
  181. page = request.args.get('page', 1, type=int)
  182. per_page = request.args.get('per_page', 20, type=int)
  183. # Validar parámetros
  184. if page < 1 or per_page < 1 or per_page > 100:
  185. return render_template('error.html',
  186. message="Parámetros de paginación inválidos"), 400
  187. db = get_session()
  188. # Obtener blacklist (podrías cargarla desde base de datos o config)
  189. blacklist = ["facebook.com", "twitter.com", "instagram.com", "tiktok.com"]
  190. # Obtener resultados paginados
  191. result_data = find_blacklisted_sites(db, blacklist, page, per_page)
  192. if 'error' in result_data:
  193. return render_template('error.html',
  194. message=result_data['error']), 500
  195. return render_template(
  196. 'blacklist.html',
  197. results=result_data['results'],
  198. pagination=result_data['pagination'],
  199. current_page=page,
  200. page_icon='shield-exclamation.ico',
  201. page_title='Registros Bloqueados'
  202. )
  203. except ValueError:
  204. return render_template('error.html',
  205. message="Parámetros inválidos"), 400
  206. except Exception as e:
  207. logger.error(f"Error en blacklist_logs: {str(e)}")
  208. return render_template('error.html',
  209. message="Error interno del servidor"), 500
  210. finally:
  211. if db is not None:
  212. db.close()
  213. if __name__ == "__main__":
  214. # Execute app with Flask
  215. debug_mode = os.getenv("FLASK_DEBUG", "false").lower() == "true"
  216. app.run(debug=debug_mode, host='0.0.0.0', port=5000)