""" 워커 감시 대시보드 실시간으로 워커 상태, GPU 사용량, 세션 풀 상태를 모니터링합니다. Jetson Xavier와 x86 시스템을 모두 지원합니다. """ import asyncio import json import logging import time import psutil import os from datetime import datetime, timedelta from typing import Dict, List, Any from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse import uvicorn from fastapi import APIRouter, Request import websockets.exceptions import requests import subprocess from ..utils.discord_notifier import send_discord_notification from ..core.worker_manager import worker_manager from ..core.session_pool import session_pool from ..utils.gpu_monitor import gpu_monitor from ..core.config import settings from ..utils.session_event_log import get_recent_events, read_events_from_file from ..utils.daily_stats import daily_stats # main_app = None # def init_monitoring(app: FastAPI): # """모니터링 앱을 초기화하고 메인 앱 객체를 설정합니다.""" # global main_app # main_app = app # # lifespan에서 worker_manager와 session_pool이 app.state에 설정되도록 합니다. # @app.on_event("startup") # async def startup_event(): # if not hasattr(app.state, 'worker_manager') or not hasattr(app.state, 'session_pool'): # # main.py의 lifespan에서 설정되므로, 여기서는 경고만 로깅 # logger.warning("worker_manager 또는 session_pool이 app.state에 설정되지 않았습니다.") logger = logging.getLogger(__name__) # main.py에서 공유할 객체들 -> 이제 Request 객체를 통해 접근합니다. # worker_manager = None # session_pool = None # def set_shared_objects(wm, sp): # """메인 서버의 worker_manager와 session_pool을 설정합니다.""" # global worker_manager, session_pool # worker_manager = wm # session_pool = sp def read_status_from_file(): """status.json 파일에서 상태를 읽어옵니다.""" try: with open("status.json", "r") as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): return { "worker_status": {"running": False, "total_workers": 0, "queue_size": 0, "workers_by_status": {}}, "session_status": {}, "timestamp": 0 } # API 라우터 생성 api_router = APIRouter() # 모니터링 앱 생성 monitor_app = FastAPI( title="인페인팅 서버 모니터링 대시보드", description="실시간 서버 상태 모니터링 (Jetson Xavier & x86 지원)", version="1.0.0" ) # 연결된 WebSocket 클라이언트들 connected_clients: List[WebSocket] = [] class MonitoringData: def __init__(self): self.history: List[Dict[str, Any]] = [] self.max_history = 100 # 최대 100개 데이터 포인트 저장 self.api_stats = { "total_requests": 0, "successful_requests": 0, "failed_requests": 0, "endpoint_usage": {}, "response_times": [], "errors": [] } self.alerts = [] async def collect_data(self) -> Dict[str, Any]: """주기적으로 서버 상태 데이터를 수집합니다.""" try: logger.info("데이터 수집 시작") # status.json 파일에서 상태 읽기 status = read_status_from_file() logger.info(f"status.json 읽기 완료: {bool(status)}") worker_status = status.get("worker_status", {}) session_status = status.get("session_status", {}) api_stats = status.get("api_stats", {}) timestamp = status.get("timestamp", 0) logger.info(f"워커 상태: {bool(worker_status)}, 세션 상태: {bool(session_status)}") # status.json에서 읽어온 데이터가 없으면 기본값 사용 if not worker_status: logger.info("워커 상태가 비어있어 기본값 사용") worker_status = self._get_default_worker_status() # 실시간 세션/워커 상태를 메인 서버 API에서 직접 가져오기 try: logger.info("실시간 세션/워커 상태 조회 시작") response = requests.get(f"http://{settings.HOST}:{settings.PORT}/api/v1/realtime_status", timeout=2) if response.status_code == 200: realtime_data = response.json() if realtime_data.get("session_status"): session_status = realtime_data["session_status"] logger.info(f"✅ 실시간 세션 상태 조회 성공: {session_status}") if realtime_data.get("worker_status"): worker_status = realtime_data["worker_status"] logger.info(f"✅ 실시간 워커 상태 조회 성공") else: logger.warning(f"실시간 상태 조회 실패: 상태 코드 {response.status_code}") except requests.RequestException as e: logger.warning(f"실시간 상태 조회 중 예외 발생: {e}") # 실시간 조회 실패 시 status.json 폴백 if not session_status: logger.info("실시간 조회 실패, status.json 값 사용") session_status = status.get("session_status", {}) or self._get_default_session_status() if not worker_status: logger.info("실시간 워커 조회 실패, status.json 값 사용") worker_status = status.get("worker_status", {}) or self._get_default_worker_status() # GPU 정보 (안전하게 가져오기) gpu_info = {} try: logger.info("GPU 정보 수집 시작") gpu_info = { **gpu_monitor.get_gpu_memory_info(), "utilization": gpu_monitor.get_gpu_utilization() } # Jetson의 경우 추가 GPU 정보 if settings.IS_JETSON: jetson_gpu_info = gpu_monitor.get_jetson_specific_info() if jetson_gpu_info: # GPU 온도 정보 if jetson_gpu_info.get("temperature"): temps = jetson_gpu_info["temperature"] # 가장 높은 온도를 GPU 온도로 사용 if temps: gpu_temp = max(temps.values()) if temps else 0 gpu_info["temperature"] = gpu_temp else: gpu_info["temperature"] = "미지원" else: gpu_info["temperature"] = "미지원" # GPU 클럭 정보 gpu_freq = jetson_gpu_info.get("gpu_frequency") if gpu_freq is not None: gpu_info["clock_speed"] = gpu_freq else: gpu_info["clock_speed"] = "미지원" else: # x86 시스템의 경우 NVML을 통해 온도/클럭 정보 시도 try: # 여기에 x86 GPU 정보 추가 로직을 구현할 수 있음 gpu_info["temperature"] = "미지원" gpu_info["clock_speed"] = "미지원" except: gpu_info["temperature"] = "미지원" gpu_info["clock_speed"] = "미지원" logger.info("GPU 정보 수집 완료") except Exception as e: logger.warning(f"GPU 정보 조회 실패: {e}") gpu_info = {"total": 0, "used": 0, "free": 0, "usage_percent": 0, "utilization": 0, "temperature": "오류", "clock_speed": "오류"} # 시스템 메모리 정보 (안전하게 가져오기) system_memory = {} try: logger.info("시스템 메모리 정보 수집 시작") system_memory = gpu_monitor.get_system_memory_info() logger.info("시스템 메모리 정보 수집 완료") except Exception as e: logger.warning(f"시스템 메모리 정보 조회 실패: {e}") system_memory = {"total": 0, "used": 0, "free": 0, "usage_percent": 0} # 시스템 성능 정보 (안전하게 가져오기) system_performance = {} try: logger.info("시스템 성능 정보 수집 시작") system_performance = self._get_system_performance() logger.info("시스템 성능 정보 수집 완료") except Exception as e: logger.warning(f"시스템 성능 정보 조회 실패: {e}") system_performance = {"cpu_percent": 0, "cpu_count": 1, "cpu_freq": 0} # Jetson 전용 정보 (안전하게 가져오기) jetson_info = {} if settings.IS_JETSON: try: logger.info("Jetson 전용 정보 수집 시작") jetson_info = gpu_monitor.get_jetson_specific_info() if jetson_info is None: jetson_info = {} logger.info("Jetson 전용 정보 수집 완료") except Exception as e: logger.warning(f"Jetson 전용 정보 조회 실패: {e}") jetson_info = {} # API 통계는 status.json에서 읽어온 것을 사용 if not api_stats: logger.info("API 통계가 비어있어 기본값 사용") api_stats = self._get_api_statistics() # 모델별 성능 통계 직접 조회 model_performance_stats = {} try: logger.info("모델 성능 통계 조회 시작") # 메인 서버의 stats 엔드포인트 호출 response = requests.get(f"http://{settings.HOST}:{settings.PORT}/api/v1/stats", timeout=2) if response.status_code == 200: model_performance_stats = response.json() logger.info("모델 성능 통계 조회 완료") else: logger.warning(f"모델 성능 통계 조회 실패: 상태 코드 {response.status_code}") except requests.RequestException as e: logger.error(f"모델 성능 통계 조회 중 예외 발생: {e}") # 알림 및 경고 (안전하게 가져오기) alerts = [] try: logger.info("알림 확인 시작") alerts = self._check_alerts(worker_status) logger.info("알림 확인 완료") except Exception as e: logger.warning(f"알림 확인 실패: {e}") alerts = [] logger.info("데이터 구조 생성 시작") # 세션/워커 이벤트 가져오기 (실시간 반영용) session_events = [] try: session_events = get_recent_events(limit=100) except Exception as e: logger.warning(f"세션 이벤트 조회 실패: {e}") data = { "timestamp": datetime.now().isoformat(), "system_type": "Jetson Xavier" if settings.IS_JETSON else "x86_64", "gpu": gpu_info, "system_memory": system_memory, "system_performance": system_performance, "workers": worker_status, "sessions": session_status, "jetson": jetson_info, "api_stats": api_stats, "model_performance_stats": model_performance_stats, "alerts": alerts, "session_events": session_events } logger.info("히스토리에 데이터 추가 시작") # 히스토리에 추가 self.history.append(data) if len(self.history) > self.max_history: self.history.pop(0) logger.info("데이터 수집 완료") return data except Exception as e: logger.error(f"데이터 수집 중 오류 발생: {e}") import traceback logger.error(f"상세 오류: {traceback.format_exc()}") # 기본 데이터 반환 return { "timestamp": datetime.now().isoformat(), "system_type": "Jetson Xavier" if settings.IS_JETSON else "x86_64", "gpu": {"total": 0, "used": 0, "free": 0, "usage_percent": 0, "utilization": 0}, "system_memory": {"total": 0, "used": 0, "free": 0, "usage_percent": 0}, "system_performance": {"cpu_percent": 0, "cpu_count": 1, "cpu_freq": 0}, "workers": self._get_default_worker_status(), "sessions": self._get_default_session_status(), "jetson": {}, "api_stats": self._get_api_statistics(), "model_performance_stats": {}, "alerts": [], "error": str(e) } def _get_system_performance(self) -> Dict[str, Any]: """시스템 성능 지표를 수집합니다.""" try: # CPU 사용률 cpu_percent = psutil.cpu_percent(interval=1) cpu_count = psutil.cpu_count() cpu_freq = psutil.cpu_freq() # 디스크 I/O disk_io = psutil.disk_io_counters() # 네트워크 I/O net_io = psutil.net_io_counters() # 프로세스 정보 processes = len(psutil.pids()) # 시스템 부하 load_avg = os.getloadavg() if hasattr(os, 'getloadavg') else [0, 0, 0] return { "cpu": { "usage_percent": cpu_percent, "count": cpu_count, "frequency_mhz": cpu_freq.current if cpu_freq else 0, "load_average": { "1min": load_avg[0], "5min": load_avg[1], "15min": load_avg[2] } }, "disk": { "read_bytes": disk_io.read_bytes if disk_io else 0, "write_bytes": disk_io.write_bytes if disk_io else 0, "read_count": disk_io.read_count if disk_io else 0, "write_count": disk_io.write_count if disk_io else 0 }, "network": { "bytes_sent": net_io.bytes_sent if net_io else 0, "bytes_recv": net_io.bytes_recv if net_io else 0, "packets_sent": net_io.packets_sent if net_io else 0, "packets_recv": net_io.packets_recv if net_io else 0 }, "processes": processes } except Exception as e: logger.error(f"시스템 성능 정보 수집 실패: {e}") return {} def _get_api_statistics(self) -> Dict[str, Any]: """API 통계 정보를 반환합니다.""" # 실제 구현에서는 API 엔드포인트에서 이 정보를 수집해야 합니다 return { "total_requests": self.api_stats["total_requests"], "successful_requests": self.api_stats["successful_requests"], "failed_requests": self.api_stats["failed_requests"], "success_rate": ( (self.api_stats["successful_requests"] / max(self.api_stats["total_requests"], 1)) * 100 ), "endpoint_usage": self.api_stats["endpoint_usage"], "average_response_time": ( sum(self.api_stats["response_times"]) / max(len(self.api_stats["response_times"]), 1) ) if self.api_stats["response_times"] else 0, "recent_errors": self.api_stats["errors"][-5:] # 최근 5개 에러 } def _check_alerts(self, worker_status: Dict) -> List[Dict]: """시스템 상태를 확인하고 알림을 생성합니다.""" alerts = [] current_time = datetime.now() # 워커 상태 경고 - total_workers 필드 사용 total_workers = worker_status.get("total_workers", 0) running = worker_status.get("running", False) if not running: alerts.append({ "level": "critical", "message": "워커 매니저가 중지되었습니다", "timestamp": current_time.isoformat(), "category": "workers" }) elif total_workers == 0: alerts.append({ "level": "critical", "message": "활성 워커가 없습니다", "timestamp": current_time.isoformat(), "category": "workers" }) elif total_workers < 1: alerts.append({ "level": "warning", "message": f"워커 수가 부족합니다 (현재: {total_workers}개)", "timestamp": current_time.isoformat(), "category": "workers" }) # Jetson 전용 경고 if settings.IS_JETSON: # 온도 경고 (실제 구현에서는 온도 정보를 가져와야 함) pass return alerts def update_api_stats(self, endpoint: str, success: bool, response_time: float, error: str = None): """API 통계를 업데이트합니다.""" self.api_stats["total_requests"] += 1 if success: self.api_stats["successful_requests"] += 1 else: self.api_stats["failed_requests"] += 1 if error: self.api_stats["errors"].append({ "timestamp": datetime.now().isoformat(), "endpoint": endpoint, "error": error }) # 엔드포인트별 사용량 if endpoint not in self.api_stats["endpoint_usage"]: self.api_stats["endpoint_usage"][endpoint] = 0 self.api_stats["endpoint_usage"][endpoint] += 1 # 응답 시간 self.api_stats["response_times"].append(response_time) if len(self.api_stats["response_times"]) > 100: self.api_stats["response_times"].pop(0) # 에러 로그 제한 if len(self.api_stats["errors"]) > 50: self.api_stats["errors"] = self.api_stats["errors"][-50:] def read_recent_errors(self, limit: int = 50) -> List[Dict[str, Any]]: """메인 서버에서 기록한 logs/api_errors.jsonl 에서 최근 에러를 읽어옵니다.""" try: log_path = os.path.join(settings.PROJECT_ROOT, "logs", "api_errors.jsonl") if not os.path.exists(log_path): return [] errors: List[Dict[str, Any]] = [] with open(log_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: errors.append(json.loads(line)) except Exception: continue return errors[-limit:] except Exception as e: logger.error(f"최근 에러 읽기 실패: {e}") return [] def get_history(self) -> List[Dict[str, Any]]: """데이터 히스토리를 반환합니다.""" return self.history def get_statistics(self) -> Dict[str, Any]: """통계 정보를 반환합니다.""" if not self.history: return {} recent_data = self.history[-10:] # 최근 10개 데이터 # GPU 사용률 평균 gpu_usage_avg = sum(d["gpu"]["usage_percent"] for d in recent_data) / len(recent_data) gpu_util_avg = sum(d["gpu"]["utilization"] for d in recent_data) / len(recent_data) # 시스템 메모리 사용률 평균 sys_mem_avg = sum(d["system_memory"]["usage_percent"] for d in recent_data) / len(recent_data) # 워커 수 평균 worker_avg = sum(d["workers"]["active_workers"] for d in recent_data) / len(recent_data) return { "gpu_usage_avg": round(gpu_usage_avg, 2), "gpu_util_avg": round(gpu_util_avg, 2), "system_memory_avg": round(sys_mem_avg, 2), "worker_avg": round(worker_avg, 2), "data_points": len(recent_data) } def _get_default_worker_status(self): return { "total_workers": 0, "queue_size": 0, "workers_by_status": {"idle": [], "busy": [], "starting": [], "stopping": [], "error": []}, "running": False } def _get_default_session_status(self): return { "simple-lama": {"total": 0, "in_use": 0, "available": 0}, "migan": {"total": 0, "in_use": 0, "available": 0}, "rembg": {"total": 0, "in_use": 0, "available": 0} } # 전역 모니터링 데이터 인스턴스 monitoring_data = MonitoringData() # HTML 템플릿 HTML_TEMPLATE = """ 인페인팅 서버 모니터링

🚀 인페인팅 서버 모니터링

실시간 서버 상태 및 성능 모니터링 대시보드

🖥️ 시스템 정보

시스템 타입: -
CPU 사용률: -
시스템 메모리: -
프로세스 수: -

🎮 GPU 상태

GPU 메모리: -
GPU 사용률: -
GPU 온도: -
GPU 클럭: -

⚙️ 워커 상태

활성 워커: -
대기열: -
상태: -

🔄 세션 풀 상태

Simple LAMA: -
MIGAN: -
RemBG: -
총 세션: -

📊 API 통계

총 요청: -
성공률: -
평균 응답시간: -
에러 수: -

🔍 시스템 성능 상세

CPU 정보

코어 수: -
클럭 속도: -
부하 평균 (1분): -
부하 평균 (5분): -

디스크 I/O

읽기 (MB/s): -
쓰기 (MB/s): -
읽기 횟수: -
쓰기 횟수: -

네트워크 I/O

송신 (MB): -
수신 (MB): -
송신 패킷: -
수신 패킷: -

🌐 엔드포인트 분석

로딩 중...
-

⚡ 성능 지표

초당 요청: -
동시 요청: -
최대 동시: -
최소 응답시간: -
최대 응답시간: -
서버 가동시간: -

⚠️ 알림 및 경고

정보: 모니터링 데이터를 수집 중입니다...

📝 최근 로그 (최근 50줄)

로딩 중...

⚡ 모델 로딩 성능 통계

로딩 중...

📊 모델별 사용 통계

로딩 중...

🚨 실시간 시스템 경고

로딩 중...

🚨 최근 API 에러

시간
메서드
상태
엔드포인트
지연(ms)
데이터 없음

📊 오늘의 통계

처리한 이미지
-
-
업로드 용량
-
다운로드 용량
-
최대 동시 요청
-

🔄 세션·워커 타임라인

로딩 중...

⏱️ 모델 처리 시간 통계 (초)

모델 처리 횟수 평균 시간 최소 시간 최대 시간 총 시간

📈 실시간 성능 차트

🎯 GPU 메모리 사용량

🔧 세션 풀 사용량

⚙️ 워커 활성도

마지막 업데이트: - | 연결 상태: 연결 중...
""" @monitor_app.get("/") async def dashboard(): """대시보드 HTML 페이지""" return HTMLResponse(content=HTML_TEMPLATE) @api_router.get("/status") async def get_status(): """실시간 서버 상태 데이터를 반환합니다.""" return await monitoring_data.collect_data() # 간단한 상태 엔드포인트 @api_router.get("/simple") async def get_simple_status(): """간단한 서버 상태를 반환합니다.""" try: # status.json 파일에서 상태 읽기 status = read_status_from_file() # 시스템 메모리 정보 memory_info = gpu_monitor.get_system_memory_info() return { "timestamp": time.time(), "system_type": "Jetson Xavier" if settings.IS_JETSON else "x86_64", "cpu_percent": psutil.cpu_percent(interval=0.1), "memory_percent": memory_info.get("usage_percent", 0), "status": "running" } except Exception as e: logger.error(f"간단한 상태 조회 실패: {e}") return {"error": str(e)} @api_router.get("/logs") async def get_recent_logs(lines: int = 100): """최근 로그 반환""" try: import os log_file = "logs/main.log" if not os.path.exists(log_file): return {"logs": [], "message": "로그 파일이 없습니다"} # 최근 lines 줄 읽기 with open(log_file, 'r', encoding='utf-8') as f: all_lines = f.readlines() recent_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines # 로그 파싱 parsed_logs = [] for line in recent_lines: line = line.strip() if line and " - " in line: try: # 시간, 모듈, 레벨, 메시지 분리 parts = line.split(" - ", 3) if len(parts) >= 4: parsed_logs.append({ "timestamp": parts[0], "module": parts[1], "level": parts[2], "message": parts[3] }) else: parsed_logs.append({"raw": line}) except: parsed_logs.append({"raw": line}) return {"logs": parsed_logs, "total": len(parsed_logs)} except Exception as e: logger.error(f"로그 조회 실패: {e}") return {"logs": [], "error": str(e)} @api_router.get("/model-usage-stats") async def get_model_usage_stats(): """모델별 사용 통계 반환""" try: import os import re from collections import defaultdict from datetime import datetime, timedelta log_file = "logs/main.log" if not os.path.exists(log_file): return {"stats": {}, "message": "로그 파일이 없습니다"} # 최근 1시간 데이터만 분석 one_hour_ago = datetime.now() - timedelta(hours=1) # 모델별 요청 통계 model_requests = defaultdict(int) endpoint_requests = defaultdict(int) hourly_requests = defaultdict(int) with open(log_file, 'r', encoding='utf-8') as f: lines = f.readlines()[-2000:] # 최근 2000줄만 for line in lines: try: # API 요청 로그 패턴 if '"POST /api/v1/inpaint' in line: model_requests['inpaint'] += 1 elif '"POST /api/v1/remove_bg' in line: model_requests['remove_bg'] += 1 elif '"GET /api/v1/model' in line: endpoint_requests['health_check'] += 1 # 시간대별 분석 time_match = re.search(r'(\d{2}:\d{2}):\d{2}', line) if time_match: hour_minute = time_match.group(1) hourly_requests[hour_minute] += 1 except Exception: continue return { "model_usage": dict(model_requests), "endpoint_usage": dict(endpoint_requests), "hourly_distribution": dict(hourly_requests), "total_requests": sum(model_requests.values()) + sum(endpoint_requests.values()), "analysis_window": "최근 2000줄" } except Exception as e: logger.error(f"모델 사용 통계 조회 실패: {e}") return {"stats": {}, "error": str(e)} @api_router.get("/performance-stats") async def get_performance_stats(): """성능 통계 반환""" try: import os import re from collections import defaultdict log_file = "logs/main.log" if not os.path.exists(log_file): return {"stats": {}, "message": "로그 파일이 없습니다"} # 모델 로딩 시간 분석 model_load_times = defaultdict(list) # 최근 1000줄만 분석 with open(log_file, 'r', encoding='utf-8') as f: lines = f.readlines()[-1000:] # 모델 로딩 시간 분석 for i, line in enumerate(lines): if "Loading" in line and "model" in line: loading_time = None success_time = None # 현재 라인에서 시간 추출 try: time_match = re.search(r'(\d{2}:\d{2}:\d{2}),(\d{3})', line) if time_match: loading_time = f"{time_match.group(1)}.{time_match.group(2)}" # 다음 몇 줄에서 "loaded successfully" 찾기 for j in range(i+1, min(i+5, len(lines))): if "loaded successfully" in lines[j]: success_match = re.search(r'(\d{2}:\d{2}:\d{2}),(\d{3})', lines[j]) if success_match: success_time = f"{success_match.group(1)}.{success_match.group(2)}" # 시간 차이 계산 (초 단위) loading_parts = loading_time.split(':') success_parts = success_time.split(':') loading_total = float(loading_parts[0])*3600 + float(loading_parts[1])*60 + float(loading_parts[2]) success_total = float(success_parts[0])*3600 + float(success_parts[1])*60 + float(success_parts[2]) duration_ms = (success_total - loading_total) * 1000 if 0 < duration_ms < 60000: # 0-60초 범위만 유효 (모델 다운로드 시간 고려) model_name = None if "simple lama model loaded successfully" in lines[j].lower(): model_name = "Simple LAMA" elif "migan onnx model loaded successfully" in lines[j].lower(): model_name = "MIGAN" elif "rembg model" in lines[j].lower() and "loaded successfully" in lines[j].lower(): model_name = "RemBG" if model_name: model_load_times[model_name].append(duration_ms) break except Exception as parse_error: continue # 통계 계산 stats = {} for model_name, times in model_load_times.items(): if times: stats[model_name] = { "count": len(times), "avg_ms": round(sum(times) / len(times), 1), "min_ms": round(min(times), 1), "max_ms": round(max(times), 1), "recent_times": [round(t, 1) for t in times[-10:]] # 최근 10개 } return {"stats": stats, "analysis_lines": len(lines)} except Exception as e: logger.error(f"성능 통계 조회 실패: {e}") return {"stats": {}, "error": str(e)} # 테스트용 엔드포인트 @api_router.get("/system-alerts") async def get_system_alerts(): """시스템 알림 반환""" try: alerts = [] # CPU 사용률 체크 cpu_percent = psutil.cpu_percent(interval=1) if cpu_percent > 90: alerts.append({ "level": "critical", "message": f"CPU 사용률이 매우 높습니다: {cpu_percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) elif cpu_percent > 75: alerts.append({ "level": "warning", "message": f"CPU 사용률이 높습니다: {cpu_percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) # 메모리 사용률 체크 memory = psutil.virtual_memory() if memory.percent > 90: alerts.append({ "level": "critical", "message": f"메모리 사용률이 매우 높습니다: {memory.percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) elif memory.percent > 80: alerts.append({ "level": "warning", "message": f"메모리 사용률이 높습니다: {memory.percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) # 디스크 사용률 체크 disk = psutil.disk_usage('/') disk_percent = (disk.used / disk.total) * 100 if disk_percent > 90: alerts.append({ "level": "critical", "message": f"디스크 사용률이 매우 높습니다: {disk_percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) elif disk_percent > 80: alerts.append({ "level": "warning", "message": f"디스크 사용률이 높습니다: {disk_percent:.1f}%", "category": "system", "timestamp": datetime.now().isoformat() }) # GPU 메모리 체크 (가능한 경우) try: gpu_info = gpu_monitor.get_gpu_memory_info() if gpu_info.get("usage_percent", 0) > 95: alerts.append({ "level": "critical", "message": f"GPU 메모리 사용률이 매우 높습니다: {gpu_info['usage_percent']:.1f}%", "category": "gpu", "timestamp": datetime.now().isoformat() }) except Exception: pass return {"alerts": alerts, "count": len(alerts)} except Exception as e: logger.error(f"시스템 알림 조회 실패: {e}") return {"alerts": [], "error": str(e)} @api_router.get("/errors", summary="최근 API 에러 목록") def get_recent_errors(limit: int = 50): """최근 API 에러를 반환합니다 (logs/api_errors.jsonl 기반).""" try: return {"errors": monitoring_data.read_recent_errors(limit=limit)} except Exception as e: logger.error(f"에러 목록 조회 실패: {e}") return {"errors": [], "error": str(e)} @api_router.get("/session_events", summary="최근 세션/워커 이벤트") def get_session_events(limit: int = 100): """최근 세션/워커 생성·해제·스케일 이벤트를 반환합니다.""" try: events = get_recent_events(limit=limit) return {"events": events} except Exception as e: logger.error(f"세션 이벤트 조회 실패: {e}") return {"events": [], "error": str(e)} @api_router.get("/test") async def test_endpoint(): """테스트용 엔드포인트입니다.""" try: # status.json 파일 읽기 테스트 status = read_status_from_file() # GPU 모니터 테스트 gpu_memory = gpu_monitor.get_gpu_memory_info() system_memory = gpu_monitor.get_system_memory_info() return { "message": "테스트 성공", "status_file": "읽기 성공" if status else "읽기 실패", "gpu_memory": gpu_memory, "system_memory": system_memory, "timestamp": time.time() } except Exception as e: logger.error(f"테스트 엔드포인트 실패: {e}") return {"error": str(e)} @api_router.get("/test_data") async def get_test_data(): """테스트용 더미 데이터를 반환합니다.""" import random return { "timestamp": datetime.now().isoformat(), "system_type": "Jetson Xavier", "gpu": { "total": 8.0, "used": round(random.uniform(0.5, 2.0), 2), "free": round(8.0 - random.uniform(0.5, 2.0), 2), "usage_percent": round(random.uniform(5, 25), 1), "utilization": round(random.uniform(0, 15), 1), "temperature": round(random.uniform(35, 45), 1), "clock_speed": random.randint(1100, 1300) }, "system_memory": { "total": 30.26, "used": round(random.uniform(10, 15), 2), "free": round(random.uniform(15, 20), 2), "usage_percent": round(random.uniform(35, 50), 1) }, "system_performance": { "cpu_percent": round(random.uniform(5, 20), 1), "cpu_count": 8, "cpu_freq": {"current": 2266, "min": 1190, "max": 2265}, "load_avg": [round(random.uniform(0.1, 1.0), 2), round(random.uniform(0.1, 1.0), 2), round(random.uniform(0.1, 1.0), 2)], "disk_io": {"read_mb": random.randint(10, 100), "write_mb": random.randint(5, 50), "read_count": random.randint(100, 1000), "write_count": random.randint(50, 500)}, "net_io": {"sent_mb": random.randint(1, 10), "recv_mb": random.randint(1, 10), "sent_packets": random.randint(100, 1000), "recv_packets": random.randint(100, 1000)}, "process_count": random.randint(300, 400) }, "workers": { "total_workers": 2, "queue_size": random.randint(0, 5), "workers_by_status": { "idle": [{"id": "worker_1", "task_count": random.randint(10, 50)}], "busy": [{"id": "worker_2", "current_task": "inpainting", "task_count": random.randint(5, 30)}] if random.random() > 0.5 else [], "starting": [], "stopping": [], "error": [] }, "running": True }, "sessions": { "simple_lama": {"total": 2, "in_use": random.randint(0, 2), "available": 2 - random.randint(0, 2)}, "migan": {"total": 2, "in_use": random.randint(0, 2), "available": 2 - random.randint(0, 2)}, "rembg": {"total": 1, "in_use": random.randint(0, 1), "available": 1 - random.randint(0, 1)} }, "api_stats": { "total_requests": random.randint(100, 500), "successful_requests": random.randint(90, 480), "failed_requests": random.randint(0, 10), "response_times": [round(random.uniform(0.1, 2.0), 2) for _ in range(10)], "success_rate": round(random.uniform(85, 98), 1), "avg_response_time": round(random.uniform(0.5, 1.5), 2), "errors": [] }, "alerts": ["정보: 모니터링 데이터를 수집 중입니다..."] if random.random() > 0.7 else [] } @api_router.get("/history") async def get_history(): """데이터 히스토리를 반환합니다.""" return { "history": monitoring_data.get_history(), "statistics": monitoring_data.get_statistics() } @api_router.get("/worker-status") def get_worker_status_api(): """워커 상태를 반환합니다.""" status = read_status_from_file() return status.get("worker_status", {}) @api_router.get("/session-status") def get_session_status_api(): """세션 풀 상태를 반환합니다.""" status = read_status_from_file() return status.get("session_status", {}) # FastAPI 앱에 라우터 포함 monitor_app.include_router(api_router, prefix="/api") # WebSocket 핸들러 @monitor_app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): """WebSocket 연결을 처리합니다.""" await websocket.accept() connected_clients.append(websocket) logger.info(f"WebSocket 클라이언트 연결됨: {websocket.client}") try: while True: # 주기적으로 데이터 전송 data = await monitoring_data.collect_data() # heartbeat 메시지 추가 data['heartbeat'] = time.time() data['server_status'] = 'running' try: await websocket.send_json(data) except (websockets.exceptions.ConnectionClosedOK, websockets.exceptions.ConnectionClosedError, RuntimeError) as e: logger.info(f"WebSocket 연결이 끊어짐: {e}") break except Exception as e: logger.error(f"데이터 전송 오류: {e}") break await asyncio.sleep(2) # 2초마다 업데이트 except WebSocketDisconnect: logger.info("클라이언트가 연결을 끊음") except Exception as e: logger.error(f"WebSocket 오류: {e}") finally: # 연결된 클라이언트 목록에서 제거 if websocket in connected_clients: connected_clients.remove(websocket) logger.info(f"WebSocket 클라이언트 연결 해제됨: {websocket.client}") async def broadcast_data(): """연결된 모든 클라이언트에게 데이터를 브로드캐스트합니다.""" while True: try: if connected_clients: data = await monitoring_data.collect_data() # WebSocket 연결이 없으므로 None 전달 message = json.dumps(data, ensure_ascii=False) # 연결이 끊어진 클라이언트 제거 disconnected = [] for client in connected_clients: try: await client.send_text(message) except (websockets.exceptions.ConnectionClosedOK, websockets.exceptions.ConnectionClosedError, RuntimeError, Exception) as e: logger.debug(f"브로드캐스트 중 클라이언트 연결 끊어짐: {e}") disconnected.append(client) for client in disconnected: connected_clients.remove(client) await asyncio.sleep(2) # 2초마다 업데이트 except Exception as e: logger.error(f"브로드캐스트 오류: {e}") await asyncio.sleep(5) # --- 서버 감시 및 자동 재시작 --- HEALTH_CHECK_INTERVAL = 30 # 30초마다 확인 RESTART_COOLDOWN = 180 # 재시작 후 3분 대기 last_restart_time = 0 async def health_check_and_restart(): """메인 서버의 상태를 주기적으로 확인하고, 다운 시 재시작합니다.""" global last_restart_time logger.info("🩺 메인 서버 상태 감시 백그라운드 작업 시작...") while True: await asyncio.sleep(HEALTH_CHECK_INTERVAL) try: health_url = f"http://{settings.HOST}:{settings.PORT}/api/v1/health" response = await asyncio.to_thread(requests.get, health_url, timeout=10) if response.status_code == 200: logger.debug(f"✅ 메인 서버 정상 응답 (상태 코드: {response.status_code})") continue else: logger.warning(f"메인 서버 비정상 응답 (상태 코드: {response.status_code})") except requests.RequestException as e: logger.error(f"❌ 메인 서버 연결 실패: {e}") # --- 서버 다운 감지 및 재시작 로직 --- current_time = time.time() if current_time - last_restart_time < RESTART_COOLDOWN: logger.warning(f"재시작 대기 시간({RESTART_COOLDOWN}초)이 지나지 않아 재시작을 건너뜁니다.") continue logger.info("메인 서버 다운 감지. 재시작 절차를 시작합니다.") last_restart_time = current_time # 1. Discord 알림 발송 error_message = f"🚨 메인 서버(http://{settings.HOST}:{settings.PORT})가 응답하지 않습니다. 자동 재시작을 시도합니다." send_discord_notification(error_message, level="error") # 2. 서버 재시작 스크립트 실행 try: script_path = os.path.join(settings.PROJECT_ROOT, "scripts", "start_server.sh") logger.info(f"'{script_path}' 스크립트를 실행하여 서버를 재시작합니다.") # 비동기로 서브프로세스 실행 process = await asyncio.create_subprocess_shell( f"bash {script_path}", stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = await process.communicate() if process.returncode == 0: success_message = "✅ 메인 서버 재시작 스크립트가 성공적으로 실행되었습니다." logger.info(success_message) send_discord_notification(success_message, level="success") else: error_log = stderr.decode(errors='ignore') fail_message = f"❌ 서버 재시작 스크립트 실행 실패 (코드: {process.returncode})\n```\n{error_log}\n```" logger.error(fail_message) send_discord_notification(fail_message, level="error") except Exception as e: restart_fail_message = f"🔥 서버 재시작 중 치명적인 오류 발생: {e}" logger.critical(restart_fail_message, exc_info=True) send_discord_notification(restart_fail_message, level="error") @monitor_app.on_event("startup") async def start_monitoring(): """모니터링 시작""" logger.info("모니터링 대시보드 시작") # Jetson 최적화 (시작 시) if settings.IS_JETSON: logger.info("Jetson Xavier 모드로 모니터링 시작") gpu_monitor.optimize_for_jetson() asyncio.create_task(broadcast_data()) asyncio.create_task(health_check_and_restart()) if __name__ == "__main__": # 로깅 설정 logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) # 모니터링 서버 실행 uvicorn.run( "app.monitoring.dashboard:monitor_app", host="0.0.0.0", port=settings.MONITORING_PORT, log_level="info" )