Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /system.py
| import logging | |
| import platform | |
| import time | |
| from datetime import datetime | |
| from typing import Optional | |
| from fastapi import APIRouter, BackgroundTasks, Depends | |
| try: | |
| import psutil | |
| except ImportError: | |
| psutil = None # psutil optional | |
| from pydantic import BaseModel | |
| from sqlalchemy import text | |
| from api.core.auth import require_permissions | |
| from api.core.cache import get_cache_info, get_redis_client | |
| from api.models.user import User, UserRole | |
| from database.models import SessionLocal, engine | |
| logger = logging.getLogger(__name__) | |
| # Maintenance mode state (in production, this should be stored in Redis or DB) | |
| _maintenance_mode = { | |
| "enabled": False, | |
| "message": "System operational", | |
| "scheduled": None, | |
| } | |
| # Application start time for uptime calculation | |
| _app_start_time = time.time() | |
| # Create router | |
| router = APIRouter() | |
| # ============================================================================= | |
| # Tools Management Endpoints | |
| # ============================================================================= | |
| async def get_tools_status(): | |
| """Get pentest tools installation status""" | |
| try: | |
| from tools.integrations.tool_checker import ToolChecker | |
| checker = ToolChecker() | |
| report = checker.get_status_report() | |
| return report | |
| except Exception as e: | |
| logger.error(f"Tool checker failed: {e}") | |
| return { | |
| "ready": False, | |
| "error": "Internal error occurred", | |
| "message": "Tool checker not available", | |
| } | |
| async def install_tools(background_tasks: BackgroundTasks): | |
| """Trigger tool installation (runs in background)""" | |
| import subprocess | |
| import sys | |
| def run_installer(): | |
| import shutil | |
| try: | |
| if sys.platform == "win32": | |
| powershell_path = shutil.which("powershell") | |
| if powershell_path: | |
| subprocess.Popen( | |
| [ | |
| powershell_path, | |
| "-ExecutionPolicy", | |
| "Bypass", | |
| "-File", | |
| "scripts/install-tools.ps1", | |
| ] | |
| ) | |
| else: | |
| bash_path = shutil.which("bash") | |
| if bash_path: | |
| subprocess.Popen([bash_path, "scripts/install-tools.sh", "--all"]) | |
| except Exception as e: | |
| logger.error(f"Failed to start installer: {e}") | |
| background_tasks.add_task(run_installer) | |
| return { | |
| "status": "installation_started", | |
| "message": "Tool installation started in background. Check /system/tools/status for progress.", | |
| } | |
| # ============================================================================= | |
| # System Management Endpoints | |
| # ============================================================================= | |
| class SystemStatus(BaseModel): | |
| """System status response""" | |
| status: str | |
| version: str | |
| uptime: float | |
| environment: str | |
| class SystemMetrics(BaseModel): | |
| """System resource metrics""" | |
| cpu_percent: float | |
| memory_percent: float | |
| memory_used_gb: float | |
| memory_total_gb: float | |
| disk_percent: float | |
| disk_used_gb: float | |
| disk_total_gb: float | |
| network_io_sent_mb: float | |
| network_io_recv_mb: float | |
| class APIStats(BaseModel): | |
| """API usage statistics""" | |
| total_requests: int | |
| requests_per_minute: float | |
| average_response_time_ms: float | |
| error_rate: float | |
| active_connections: int | |
| async def get_system_status(): | |
| """Get basic system status""" | |
| return { | |
| "status": "operational", | |
| "version": "1.0.0", | |
| "uptime": psutil.boot_time(), | |
| "environment": "production", | |
| } | |
| async def get_system_metrics( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get detailed system resource metrics (admin only)""" | |
| # CPU | |
| cpu_percent = psutil.cpu_percent(interval=1) | |
| # Memory | |
| memory = psutil.virtual_memory() | |
| memory_used_gb = memory.used / (1024**3) | |
| memory_total_gb = memory.total / (1024**3) | |
| # Disk | |
| disk = psutil.disk_usage("/") | |
| disk_used_gb = disk.used / (1024**3) | |
| disk_total_gb = disk.total / (1024**3) | |
| # Network | |
| net_io = psutil.net_io_counters() | |
| network_sent_mb = net_io.bytes_sent / (1024**2) | |
| network_recv_mb = net_io.bytes_recv / (1024**2) | |
| return { | |
| "cpu_percent": cpu_percent, | |
| "memory_percent": memory.percent, | |
| "memory_used_gb": round(memory_used_gb, 2), | |
| "memory_total_gb": round(memory_total_gb, 2), | |
| "disk_percent": disk.percent, | |
| "disk_used_gb": round(disk_used_gb, 2), | |
| "disk_total_gb": round(disk_total_gb, 2), | |
| "network_io_sent_mb": round(network_sent_mb, 2), | |
| "network_io_recv_mb": round(network_recv_mb, 2), | |
| } | |
| async def get_system_info( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get detailed system information (admin only)""" | |
| return { | |
| "platform": platform.platform(), | |
| "python_version": platform.python_version(), | |
| "processor": platform.processor(), | |
| "hostname": platform.node(), | |
| "cpu_count": psutil.cpu_count(), | |
| "cpu_freq_mhz": (psutil.cpu_freq().current if psutil.cpu_freq() else None), | |
| "boot_time": datetime.fromtimestamp(psutil.boot_time()).isoformat(), | |
| "load_average": (psutil.getloadavg() if hasattr(psutil, "getloadavg") else None), | |
| } | |
| # ============================================================================= | |
| # Stats Tracking Helper Functions | |
| # ============================================================================= | |
| async def get_scan_count() -> int: | |
| """Get total number of scans from database""" | |
| try: | |
| db = SessionLocal() | |
| try: | |
| from database.models import Scan | |
| count = db.query(Scan).count() | |
| return count | |
| finally: | |
| db.close() | |
| except Exception: | |
| return 0 | |
| async def get_active_scan_count() -> int: | |
| """Get number of currently active/running scans""" | |
| try: | |
| db = SessionLocal() | |
| try: | |
| from database.models import Scan | |
| count = db.query(Scan).filter(Scan.status == "running").count() | |
| return count | |
| finally: | |
| db.close() | |
| except Exception: | |
| return 0 | |
| async def get_finding_count() -> int: | |
| """Get total number of findings""" | |
| try: | |
| db = SessionLocal() | |
| try: | |
| from database.models import Finding | |
| count = db.query(Finding).count() | |
| return count | |
| finally: | |
| db.close() | |
| except Exception: | |
| return 0 | |
| async def get_critical_finding_count() -> int: | |
| """Get number of critical severity findings""" | |
| try: | |
| db = SessionLocal() | |
| try: | |
| from database.models import Finding | |
| count = db.query(Finding).filter(Finding.severity == "critical").count() | |
| return count | |
| finally: | |
| db.close() | |
| except Exception: | |
| return 0 | |
| def get_uptime() -> float: | |
| """Get system uptime in seconds""" | |
| return time.time() - _app_start_time | |
| async def get_api_stats( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get API usage statistics (admin only)""" | |
| return { | |
| "total_requests": await get_scan_count(), | |
| "requests_per_minute": await get_active_scan_count(), | |
| "average_response_time_ms": await get_finding_count(), | |
| "error_rate": await get_critical_finding_count(), | |
| "active_connections": round(get_uptime()), | |
| } | |
| async def get_system_logs( | |
| lines: int = 100, | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get recent system logs (admin only)""" | |
| try: | |
| with open("logs/zen_ai.log", "r") as f: | |
| logs = f.readlines() | |
| return {"logs": logs[-lines:]} | |
| except FileNotFoundError: | |
| return {"logs": [], "message": "Log file not found"} | |
| # ============================================================================= | |
| # Maintenance Mode Endpoints | |
| # ============================================================================= | |
| async def get_maintenance_status( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get current maintenance mode status (admin only)""" | |
| return { | |
| "maintenance_mode": _maintenance_mode["enabled"], | |
| "message": _maintenance_mode["message"], | |
| "scheduled_maintenance": _maintenance_mode["scheduled"], | |
| } | |
| async def toggle_maintenance_mode( | |
| enabled: bool, | |
| message: Optional[str] = None, | |
| scheduled: Optional[str] = None, | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Toggle maintenance mode (admin only)""" | |
| _maintenance_mode["enabled"] = enabled | |
| if message: | |
| _maintenance_mode["message"] = message | |
| else: | |
| _maintenance_mode["message"] = "System under maintenance" if enabled else "System operational" | |
| if scheduled: | |
| _maintenance_mode["scheduled"] = scheduled | |
| return { | |
| "message": f"Maintenance mode {'enabled' if enabled else 'disabled'}", | |
| "enabled": enabled, | |
| "maintenance_message": _maintenance_mode["message"], | |
| "scheduled_maintenance": _maintenance_mode["scheduled"], | |
| } | |
| async def clear_system_cache( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Clear system cache (admin only)""" | |
| from api.core.cache import clear_cache | |
| await clear_cache() | |
| return {"message": "Cache cleared"} | |
| # ============================================================================= | |
| # Database Status Endpoint | |
| # ============================================================================= | |
| async def get_database_status( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get database connection status (admin only)""" | |
| try: | |
| # Test DB connection with latency measurement | |
| start_time = time.time() | |
| with engine.connect() as connection: | |
| connection.execute(text("SELECT 1")) | |
| connection.commit() | |
| latency_ms = round((time.time() - start_time) * 1000, 2) | |
| # Determine database type from engine URL | |
| db_type = "postgresql" if "postgresql" in str(engine.url) else "sqlite" | |
| return { | |
| "status": "healthy", | |
| "type": db_type, | |
| "latency_ms": latency_ms, | |
| } | |
| except Exception as e: | |
| logger.error(f"Database health check failed: {e}") | |
| return { | |
| "status": "unhealthy", | |
| "type": "unknown", | |
| "error": "Database connection failed", | |
| } | |
| # ============================================================================= | |
| # Cache Status Endpoint | |
| # ============================================================================= | |
| async def get_cache_status( | |
| current_user: User = Depends(require_permissions(UserRole.ADMIN)), | |
| ): | |
| """Get cache status (admin only)""" | |
| try: | |
| cache_info = get_cache_info() | |
| # Get Redis-specific stats if available | |
| redis_client = get_redis_client() | |
| if redis_client: | |
| try: | |
| redis_info = redis_client.info() | |
| used_memory = redis_info.get("used_memory", 0) | |
| memory_usage_mb = round(used_memory / (1024 * 1024), 2) | |
| return { | |
| "status": "healthy", | |
| "type": "redis", | |
| "hit_rate": None, # Redis doesn't track hit rate by default | |
| "entries": cache_info.get("redis_keys", 0), | |
| "memory_usage_mb": memory_usage_mb, | |
| "redis_version": redis_info.get("redis_version"), | |
| } | |
| except Exception: | |
| pass | |
| # In-memory cache fallback | |
| memory_keys = cache_info.get("memory_keys", 0) | |
| return { | |
| "status": "healthy", | |
| "type": "memory", | |
| "hit_rate": None, | |
| "entries": memory_keys, | |
| "memory_usage_mb": 0, # Not tracked for simple memory cache | |
| } | |
| except Exception as e: | |
| logger.error(f"Database health check failed: {e}") | |
| return { | |
| "status": "unhealthy", | |
| "type": "unknown", | |
| "error": "Database connection failed", | |
| } | |
Xet Storage Details
- Size:
- 12.9 kB
- Xet hash:
- f22e95724f94d1c8d786fcc2e7658d3e7b5593532f09f32a49da6081ce73caab
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.