app.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import atexit
  2. import os
  3. import signal
  4. import sys
  5. import threading
  6. from datetime import datetime, timedelta
  7. from dotenv import load_dotenv
  8. from flask import Flask
  9. from flask_apscheduler import APScheduler
  10. from flask_socketio import SocketIO
  11. from config import Config, logger
  12. from database.database import migrate_database
  13. from parsers.log import process_logs
  14. from routes import register_routes
  15. from routes.auth_routes import csrf
  16. from routes.stats_routes import realtime_data_thread
  17. from services.auth_service import AuthConfig
  18. from services.metrics_service import MetricsService
  19. from services.notifications import (
  20. has_remote_commits_with_messages,
  21. set_commit_notifications,
  22. set_socketio_instance,
  23. start_notification_monitor,
  24. stop_notification_monitor,
  25. )
  26. # Import Telegram integration (optional)
  27. try:
  28. from services.telegram_integration import (
  29. cleanup_telegram,
  30. initialize_telegram_service,
  31. )
  32. TELEGRAM_AVAILABLE = True
  33. except Exception:
  34. TELEGRAM_AVAILABLE = False
  35. initialize_telegram_service = None
  36. cleanup_telegram = None
  37. from utils.filters import register_filters
  38. # Load environment variables
  39. load_dotenv()
  40. # Global shutdown event
  41. shutdown_event = threading.Event()
  42. def create_app():
  43. # Run database migration at startup
  44. logger.info("Running database migration at startup...")
  45. try:
  46. migrate_database()
  47. logger.info("Database migration completed successfully")
  48. except Exception as e:
  49. logger.error(f"Database migration failed: {e}")
  50. # Continue anyway - the app might still work with existing schema
  51. app = Flask(__name__, static_folder="./static")
  52. app.config.from_object(Config())
  53. # Configure session for remember me functionality
  54. app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(
  55. days=AuthConfig.REMEMBER_ME_DAYS
  56. )
  57. app.config["SESSION_COOKIE_HTTPONLY"] = AuthConfig.SESSION_COOKIE_HTTPONLY
  58. app.config["SESSION_COOKIE_SECURE"] = AuthConfig.SESSION_COOKIE_SECURE
  59. app.config["SESSION_COOKIE_SAMESITE"] = AuthConfig.SESSION_COOKIE_SAMESITE
  60. # Initialize CSRF protection (shared instance with routes)
  61. csrf.init_app(app)
  62. # Initialize extensions
  63. scheduler = APScheduler()
  64. scheduler.init_app(app)
  65. scheduler.start()
  66. # Register custom filters
  67. register_filters(app)
  68. # Register the date format filter for notifications
  69. @app.template_filter("datetime_format")
  70. def datetime_format(value, format="%d/%m/%Y %H:%M"):
  71. """Filtro para formatear fechas en las plantillas"""
  72. if isinstance(value, str):
  73. try:
  74. # Handle ISO format
  75. if "T" in value:
  76. value = datetime.fromisoformat(value.replace("Z", "+00:00"))
  77. else:
  78. # Try other common formats
  79. for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]:
  80. try:
  81. value = datetime.strptime(value, fmt)
  82. break
  83. except ValueError:
  84. continue
  85. else:
  86. return value # Could not parse, returning original
  87. except Exception:
  88. return value
  89. if isinstance(value, datetime):
  90. return value.strftime(format)
  91. return value
  92. # Register all route blueprints
  93. register_routes(app)
  94. # Configure response headers
  95. @app.after_request
  96. def set_response_headers(response):
  97. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  98. response.headers["Pragma"] = "no-cache"
  99. response.headers["Expires"] = "0"
  100. return response
  101. return app, scheduler
  102. def setup_scheduler_tasks(scheduler):
  103. @scheduler.task(
  104. "interval", id="check_notifications", minutes=30, misfire_grace_time=1800
  105. )
  106. def check_notifications_task():
  107. repo_path = os.path.dirname(os.path.abspath(__file__))
  108. has_updates, messages = has_remote_commits_with_messages(repo_path)
  109. set_commit_notifications(has_updates, messages)
  110. @scheduler.task("interval", id="do_job_1", seconds=30, misfire_grace_time=900)
  111. def init_scheduler():
  112. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  113. logger.info(f"Scheduler for file log: {log_file}")
  114. if not os.path.exists(log_file):
  115. logger.error(f"Log file not found: {log_file}")
  116. return
  117. else:
  118. process_logs(log_file)
  119. @scheduler.task("interval", id="cleanup_metrics", hours=1, misfire_grace_time=3600)
  120. def cleanup_old_metrics():
  121. try:
  122. success = MetricsService.cleanup_old_metrics()
  123. if success:
  124. logger.info("Cleanup of old metrics completed successfully")
  125. else:
  126. logger.warning("Error during cleanup of old metrics")
  127. except Exception as e:
  128. logger.error(f"Error in metrics cleanup task: {e}")
  129. def shutdown_app(scheduler, socketio):
  130. logger.info("\n🛑 Shutting down SquidStats...")
  131. # Set shutdown event to stop all threads
  132. shutdown_event.set()
  133. # Stop notification monitor
  134. logger.info("Stopping notification monitor...")
  135. stop_notification_monitor()
  136. # Cleanup Telegram service
  137. if TELEGRAM_AVAILABLE and cleanup_telegram:
  138. logger.info("Cleaning up Telegram service...")
  139. try:
  140. cleanup_telegram()
  141. except Exception as e:
  142. logger.error(f"Error cleaning up Telegram: {e}")
  143. # Stop scheduler
  144. logger.info("Stopping scheduler...")
  145. try:
  146. if scheduler and scheduler.running:
  147. scheduler.shutdown(wait=False)
  148. except Exception as e:
  149. logger.error(f"Error stopping scheduler: {e}")
  150. # Stop SocketIO
  151. logger.info("Stopping SocketIO...")
  152. try:
  153. if socketio:
  154. socketio.stop()
  155. except Exception as e:
  156. logger.error(f"Error stopping SocketIO: {e}")
  157. logger.info("✅ Shutdown complete")
  158. def main():
  159. # Create Flask app and scheduler
  160. app, scheduler = create_app()
  161. # Setup scheduler tasks
  162. setup_scheduler_tasks(scheduler)
  163. # Initialize SocketIO
  164. socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
  165. # Set up Socket.IO in the notifications module
  166. set_socketio_instance(socketio)
  167. # Initialize Telegram service if available
  168. if TELEGRAM_AVAILABLE and initialize_telegram_service:
  169. logger.info("Initializing Telegram service...")
  170. try:
  171. initialize_telegram_service()
  172. except Exception as e:
  173. logger.error(f"Failed to initialize Telegram: {e}")
  174. # Start the notification monitor
  175. start_notification_monitor()
  176. # Start real-time data collection thread
  177. socketio.start_background_task(realtime_data_thread, socketio, shutdown_event)
  178. # Register signal handlers for graceful shutdown
  179. def signal_handler(signum, frame):
  180. logger.info(f"\n⚠️ Received signal {signum}")
  181. shutdown_app(scheduler, socketio)
  182. sys.exit(0)
  183. signal.signal(signal.SIGINT, signal_handler) # Ctrl+C
  184. signal.signal(signal.SIGTERM, signal_handler) # kill command
  185. # Register cleanup on exit
  186. atexit.register(lambda: shutdown_app(scheduler, socketio))
  187. # Run the application
  188. debug_mode = Config.DEBUG
  189. logger.info(
  190. f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
  191. )
  192. # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT)
  193. host = Config.LISTEN_HOST
  194. port = Config.LISTEN_PORT
  195. try:
  196. socketio.run(
  197. app, debug=debug_mode, host=host, port=port, allow_unsafe_werkzeug=True
  198. )
  199. except KeyboardInterrupt:
  200. logger.info("\n⚠️ Keyboard interrupt received")
  201. shutdown_app(scheduler, socketio)
  202. except Exception as e:
  203. logger.error(f"Application error: {e}")
  204. shutdown_app(scheduler, socketio)
  205. raise
  206. if __name__ == "__main__":
  207. main()