瀏覽代碼

feat: implement quota scheduler tasks for monitoring user quotas

Manuel 8 月之前
父節點
當前提交
2be69dfc16
共有 3 個文件被更改,包括 106 次插入 和 33 次删除
  1. 3 33
      app.py
  2. 58 0
      services/quota/quota_scheduler.py
  3. 45 0
      services/scheduler/scheduler_tasks.py

+ 3 - 33
app.py

@@ -14,20 +14,17 @@ from loguru import logger
 
 from config import Config
 from database.database import migrate_database
-from parsers.log import process_logs
 from routes import register_routes
 from routes.auth_routes import csrf
 from routes.stats_routes import realtime_data_thread
 from services.auth.auth_service import AuthConfig
 from services.notifications.notifications import (
-    has_remote_commits_with_messages,
-    set_commit_notifications,
     set_socketio_instance,
     start_notification_monitor,
     stop_notification_monitor,
 )
-from services.system.metrics_service import MetricsService
 from utils.filters import register_filters
+from services.scheduler.scheduler_tasks import register_scheduler_tasks
 
 logger.add("logs/app.log", rotation="100 MB", retention="31 days", level="INFO")
 
@@ -136,35 +133,8 @@ def create_app():
 
 
 def setup_scheduler_tasks(scheduler):
-    @scheduler.task(
-        "interval", id="check_notifications", minutes=30, misfire_grace_time=1800
-    )
-    def check_notifications_task():
-        repo_path = os.path.dirname(os.path.abspath(__file__))
-        has_updates, messages = has_remote_commits_with_messages(repo_path)
-        set_commit_notifications(has_updates, messages)
-
-    @scheduler.task("interval", id="do_job_1", seconds=30, misfire_grace_time=900)
-    def init_scheduler():
-        log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
-        logger.info(f"Scheduler for file log: {log_file}")
-
-        if not os.path.exists(log_file):
-            logger.error(f"Log file not found: {log_file}")
-            return
-        else:
-            process_logs(log_file)
-
-    @scheduler.task("interval", id="cleanup_metrics", hours=1, misfire_grace_time=3600)
-    def cleanup_old_metrics():
-        try:
-            success = MetricsService.cleanup_old_metrics()
-            if success:
-                logger.info("Cleanup of old metrics completed successfully")
-            else:
-                logger.warning("Error during cleanup of old metrics")
-        except Exception as e:
-            logger.error(f"Error in metrics cleanup task: {e}")
+    # Register all scheduler tasks from services.scheduler.scheduler_tasks and plugins.
+    register_scheduler_tasks(scheduler)
 
 
 def shutdown_app(scheduler, socketio):

+ 58 - 0
services/quota/quota_scheduler.py

@@ -0,0 +1,58 @@
+import os
+from datetime import datetime
+from loguru import logger
+
+from database.database import get_session
+from database.models.models import QuotaEvent, QuotaUser
+
+
+def register_quota_scheduler_tasks(scheduler):
+    """Registra tareas programadas relacionadas con cuotas."""
+
+    @scheduler.task("interval", id="check_quota_users", minutes=5, misfire_grace_time=300)
+    def check_quota_users():
+        try:
+            session = get_session()
+            now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
+            file_path = os.path.join(os.getcwd(), "blockUsersQuota")
+            exceeded = []
+
+            users = session.query(QuotaUser).all()
+            for user in users:
+                if user.quota_mb and user.used_mb is not None and user.used_mb > user.quota_mb:
+                    exceeded.append(user)
+
+            if exceeded:
+                with open(file_path, "a", encoding="utf-8") as f:
+                    for user in exceeded:
+                        line = (
+                            f"{now} - {user.username} - quota: {user.quota_mb}MB - used: {user.used_mb}MB\n"
+                        )
+                        f.write(line)
+
+                for user in exceeded:
+                    event = QuotaEvent(
+                        event_type="user_quota_exceeded",
+                        username=user.username,
+                        detail=f"Cuota excedida: {user.used_mb}/{user.quota_mb} MB",
+                    )
+                    session.add(event)
+                session.commit()
+
+                logger.info(
+                    f"check_quota_users: {len(exceeded)} usuarios con cuota excedida escritos en {file_path}"
+                )
+            else:
+                logger.debug("check_quota_users: ningún usuario excedió la cuota")
+
+        except Exception as e:
+            logger.error(f"Error en check_quota_users: {e}")
+            try:
+                session.rollback()
+            except Exception:
+                pass
+        finally:
+            try:
+                session.close()
+            except Exception:
+                pass

+ 45 - 0
services/scheduler/scheduler_tasks.py

@@ -0,0 +1,45 @@
+import os
+from loguru import logger
+
+from parsers.log import process_logs
+from services.notifications.notifications import (
+    has_remote_commits_with_messages,
+    set_commit_notifications,
+)
+from services.system.metrics_service import MetricsService
+from services.quota.quota_scheduler import register_quota_scheduler_tasks
+
+
+def register_scheduler_tasks(scheduler):
+    """Registers global scheduler tasks for the app."""
+
+    @scheduler.task("interval", id="check_notifications", minutes=30, misfire_grace_time=1800)
+    def check_notifications_task():
+        repo_path = os.path.dirname(os.path.abspath(__file__))
+        has_updates, messages = has_remote_commits_with_messages(repo_path)
+        set_commit_notifications(has_updates, messages)
+
+    @scheduler.task("interval", id="do_job_1", seconds=30, misfire_grace_time=900)
+    def init_scheduler():
+        log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
+        logger.info(f"Scheduler for file log: {log_file}")
+
+        if not os.path.exists(log_file):
+            logger.error(f"Log file not found: {log_file}")
+            return
+
+        process_logs(log_file)
+
+    @scheduler.task("interval", id="cleanup_metrics", hours=1, misfire_grace_time=3600)
+    def cleanup_old_metrics():
+        try:
+            success = MetricsService.cleanup_old_metrics()
+            if success:
+                logger.info("Cleanup of old metrics completed successfully")
+            else:
+                logger.warning("Error during cleanup of old metrics")
+        except Exception as e:
+            logger.error(f"Error in metrics cleanup task: {e}")
+
+    # Register quota worker tasks along with global tasks.
+    register_quota_scheduler_tasks(scheduler)