app.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import os
  2. from dotenv import load_dotenv
  3. from flask import Flask
  4. from flask_apscheduler import APScheduler
  5. from flask_socketio import SocketIO
  6. from flask_wtf.csrf import CSRFProtect
  7. from config import Config, logger
  8. from database.database import migrate_database
  9. from parsers.log import process_logs
  10. from routes import register_routes
  11. # from routes.main_routes import initialize_proxy_detection
  12. from routes.stats_routes import realtime_data_thread
  13. from services.metrics_service import MetricsService
  14. from services.notifications import (
  15. has_remote_commits_with_messages,
  16. set_commit_notifications,
  17. set_socketio_instance, # Nueva importación
  18. start_notification_monitor, # Nueva importación
  19. )
  20. from utils.filters import register_filters
  21. # Load environment variables
  22. load_dotenv()
  23. def create_app():
  24. # Run database migration at startup
  25. logger.info("Running database migration at startup...")
  26. try:
  27. migrate_database()
  28. logger.info("Database migration completed successfully")
  29. except Exception as e:
  30. logger.error(f"Database migration failed: {e}")
  31. # Continue anyway - the app might still work with existing schema
  32. app = Flask(__name__, static_folder="./static")
  33. app.config.from_object(Config())
  34. # Initialize CSRF protection
  35. CSRFProtect(app)
  36. # Initialize extensions
  37. scheduler = APScheduler()
  38. scheduler.init_app(app)
  39. scheduler.start()
  40. # Register custom filters
  41. register_filters(app)
  42. # Register all route blueprints
  43. register_routes(app)
  44. # Initialize proxy detection
  45. # initialize_proxy_detection()
  46. # Configure response headers
  47. @app.after_request
  48. def set_response_headers(response):
  49. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  50. response.headers["Pragma"] = "no-cache"
  51. response.headers["Expires"] = "0"
  52. return response
  53. return app, scheduler
  54. def setup_scheduler_tasks(scheduler):
  55. @scheduler.task(
  56. "interval", id="check_notifications", minutes=30, misfire_grace_time=1800
  57. )
  58. def check_notifications_task():
  59. repo_path = os.path.dirname(os.path.abspath(__file__))
  60. has_updates, messages = has_remote_commits_with_messages(repo_path)
  61. set_commit_notifications(has_updates, messages)
  62. @scheduler.task("interval", id="do_job_1", seconds=30, misfire_grace_time=900)
  63. def init_scheduler():
  64. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  65. logger.info(f"Scheduler for file log: {log_file}")
  66. if not os.path.exists(log_file):
  67. logger.error(f"Log file not found: {log_file}")
  68. return
  69. else:
  70. process_logs(log_file)
  71. @scheduler.task("interval", id="cleanup_metrics", hours=1, misfire_grace_time=3600)
  72. def cleanup_old_metrics():
  73. try:
  74. success = MetricsService.cleanup_old_metrics()
  75. if success:
  76. logger.info("Cleanup of old metrics completed successfully")
  77. else:
  78. logger.warning("Error during cleanup of old metrics")
  79. except Exception as e:
  80. logger.error(f"Error in metrics cleanup task: {e}")
  81. def main():
  82. # Create Flask app and scheduler
  83. app, scheduler = create_app()
  84. # Setup scheduler tasks
  85. setup_scheduler_tasks(scheduler)
  86. # Initialize SocketIO
  87. socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
  88. # Configurar Socket.IO en el módulo de notificaciones
  89. set_socketio_instance(socketio)
  90. # Iniciar el monitor de notificaciones
  91. start_notification_monitor()
  92. # Start real-time data collection thread
  93. socketio.start_background_task(realtime_data_thread, socketio)
  94. # Run the application
  95. debug_mode = Config.DEBUG
  96. logger.info(
  97. f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
  98. )
  99. # Leer host/port desde variables de entorno si existen (compatibilidad con FLASK_HOST/PORT)
  100. host = os.getenv("LISTEN_HOST") or os.getenv("FLASK_HOST") or "0.0.0.0"
  101. port_str = os.getenv("LISTEN_PORT") or os.getenv("FLASK_PORT") or "5000"
  102. try:
  103. port = int(port_str)
  104. except ValueError:
  105. logger.warning(f"Invalid PORT value '{port_str}', falling back to 5000")
  106. port = 5000
  107. socketio.run(
  108. app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True
  109. )
  110. if __name__ == "__main__":
  111. main()