"""
워커 감시 대시보드
실시간으로 워커 상태, 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
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
# 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()
# 항상 실제 세션 풀 상태 사용 (동적 데이터)
try:
real_session_status = session_pool.get_status()
session_status = real_session_status
logger.debug(f"실시간 세션 풀 상태 사용: {real_session_status}")
if not session_status:
logger.info("세션 상태가 비어있어 기본값 사용")
session_status = self._get_default_session_status()
except Exception as e:
logger.warning(f"실제 세션 풀 상태 조회 실패: {e}")
session_status = status.get("session_status", {})
if not session_status:
logger.info("status.json 세션 상태도 비어있어 기본값 사용")
session_status = self._get_default_session_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()
# 알림 및 경고 (안전하게 가져오기)
alerts = []
try:
logger.info("알림 확인 시작")
alerts = self._check_alerts(worker_status)
logger.info("알림 확인 완료")
except Exception as e:
logger.warning(f"알림 확인 실패: {e}")
alerts = []
logger.info("데이터 구조 생성 시작")
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,
"alerts": alerts
}
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(),
"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 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줄)
로딩 중...
🚨 실시간 시스템 경고
로딩 중...
📈 실시간 성능 차트
🎯 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 < 10000: # 0-10초 범위만 유효
model_name = "Simple LAMA" # 기본값
if "simple_lama" in line.lower():
model_name = "Simple LAMA"
elif "migan" in line.lower():
model_name = "MIGAN"
elif "rembg" in line.lower():
model_name = "RemBG"
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("/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)
@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())
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"
)