Compare commits
31 Commits
59d39a79c3
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| b85f920f40 | |||
| e4851b1153 | |||
| b73aef5cf8 | |||
| 72c8f6a047 | |||
| c7a49ea4ea | |||
| fbef92af55 | |||
| 154db0ac27 | |||
| 9835170cd7 | |||
| fd51f21ba6 | |||
| 776622e0a2 | |||
|
|
4d2d7a9ad1 | ||
|
|
532fbdbee4 | ||
|
|
a2e5bf4e10 | ||
|
|
de2a2e2c35 | ||
|
|
f75ec77ccf | ||
|
|
9fa549285f | ||
|
|
4fbfb31e97 | ||
| 419b3ccdfc | |||
| afb3f57ef6 | |||
| edff3b0ef8 | |||
| 47e93f0d57 | |||
| 449e1dc142 | |||
| ecca537670 | |||
| ca080bf77b | |||
| e64b1f15ba | |||
| 7db77226b7 | |||
| ce404924fd | |||
| bb48cb8610 | |||
| 8b7ff0162d | |||
|
|
02954aa439 | ||
|
|
e3cf7b8909 |
230
deploy/check-nginx.sh
Executable file
230
deploy/check-nginx.sh
Executable file
@@ -0,0 +1,230 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
NGINX_DIR="/data/training/nginx"
|
||||||
|
PASS=0
|
||||||
|
FAIL=0
|
||||||
|
|
||||||
|
# docker compose v1/v2 자동 감지
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
DOCKER_COMPOSE="docker compose"
|
||||||
|
else
|
||||||
|
DOCKER_COMPOSE=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
ok() { echo -e "${GREEN}[OK]${NC} $1"; ((PASS++)); }
|
||||||
|
fail() { echo -e "${RED}[FAIL]${NC} $1"; ((FAIL++)); }
|
||||||
|
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
|
||||||
|
section() { echo ""; echo "=== $1 ==="; }
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "디렉토리 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for dir in \
|
||||||
|
/data/training/request \
|
||||||
|
/data/training/request/tmp \
|
||||||
|
/data/training/response \
|
||||||
|
/data/training/response/v6-cls-checkpoints \
|
||||||
|
/data/training/tmp \
|
||||||
|
"$NGINX_DIR" \
|
||||||
|
"$NGINX_DIR/ssl" \
|
||||||
|
"$NGINX_DIR/logs"; do
|
||||||
|
if [ -d "$dir" ]; then
|
||||||
|
ok "$dir"
|
||||||
|
else
|
||||||
|
fail "$dir 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "nginx 파일 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for f in \
|
||||||
|
"$NGINX_DIR/nginx.conf" \
|
||||||
|
"$NGINX_DIR/docker-compose-nginx.yml" \
|
||||||
|
"$NGINX_DIR/ssl/train-kamco.com.crt" \
|
||||||
|
"$NGINX_DIR/ssl/train-kamco.com.key" \
|
||||||
|
"$NGINX_DIR/ssl/openssl.cnf"; do
|
||||||
|
if [ -f "$f" ]; then
|
||||||
|
ok "$f"
|
||||||
|
else
|
||||||
|
fail "$f 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "파일 권한 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
SSL_DIR_PERM=$(stat -c "%a" "$NGINX_DIR/ssl" 2>/dev/null)
|
||||||
|
KEY_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.key" 2>/dev/null)
|
||||||
|
CRT_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.crt" 2>/dev/null)
|
||||||
|
|
||||||
|
[ "$SSL_DIR_PERM" = "700" ] && ok "ssl/ 권한 700" || fail "ssl/ 권한 오류 (현재: $SSL_DIR_PERM, 기대: 700)"
|
||||||
|
[ "$KEY_PERM" = "600" ] && ok "train-kamco.com.key 권한 600" || fail "key 권한 오류 (현재: $KEY_PERM, 기대: 600)"
|
||||||
|
[ "$CRT_PERM" = "644" ] && ok "train-kamco.com.crt 권한 644" || fail "crt 권한 오류 (현재: $CRT_PERM, 기대: 644)"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "소유권 확인 (kcomu:kcomu)"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
OWNER=$(stat -c "%U:%G" /data/training 2>/dev/null)
|
||||||
|
[ "$OWNER" = "kcomu:kcomu" ] && ok "/data/training 소유권 kcomu:kcomu" || fail "/data/training 소유권 오류 (현재: $OWNER)"
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "SSL 인증서 유효성"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v openssl &>/dev/null && [ -f "$NGINX_DIR/ssl/train-kamco.com.crt" ]; then
|
||||||
|
EXPIRY=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -enddate 2>/dev/null | cut -d= -f2)
|
||||||
|
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null)
|
||||||
|
NOW_EPOCH=$(date +%s)
|
||||||
|
if [ "$EXPIRY_EPOCH" -gt "$NOW_EPOCH" ]; then
|
||||||
|
ok "인증서 유효 (만료: $EXPIRY)"
|
||||||
|
else
|
||||||
|
fail "인증서 만료됨 (만료: $EXPIRY)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
SAN=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -text 2>/dev/null | grep -A1 "Subject Alternative Name" | tail -1)
|
||||||
|
echo " SAN: $SAN"
|
||||||
|
else
|
||||||
|
warn "openssl 없음 또는 인증서 파일 없음 - 인증서 검증 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "Docker 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||||
|
ok "Docker 실행 중"
|
||||||
|
|
||||||
|
# Docker network
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
ok "Docker network kamco-cds 존재"
|
||||||
|
else
|
||||||
|
fail "Docker network kamco-cds 없음 (setup.sh 재실행 필요)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# nginx 컨테이너 상태
|
||||||
|
CONTAINER_STATUS=$(docker inspect --format '{{.State.Status}}' kamco-train-nginx 2>/dev/null)
|
||||||
|
if [ "$CONTAINER_STATUS" = "running" ]; then
|
||||||
|
ok "kamco-train-nginx 컨테이너 실행 중"
|
||||||
|
elif [ -z "$CONTAINER_STATUS" ]; then
|
||||||
|
warn "kamco-train-nginx 컨테이너 없음 (아직 미실행)"
|
||||||
|
else
|
||||||
|
fail "kamco-train-nginx 컨테이너 상태: $CONTAINER_STATUS"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
fail "Docker 미실행 또는 설치 안 됨"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "nginx 설정 문법 검사"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
|
||||||
|
echo " docker run으로 nginx -t 실행 중..."
|
||||||
|
# kamco-cds 네트워크가 있으면 연결 (upstream DNS 조회 가능)
|
||||||
|
NETWORK_OPT=""
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
NETWORK_OPT="--network kamco-cds"
|
||||||
|
fi
|
||||||
|
if docker run --rm $NETWORK_OPT \
|
||||||
|
-v "$NGINX_DIR/nginx.conf:/etc/nginx/nginx.conf:ro,Z" \
|
||||||
|
-v "$NGINX_DIR/ssl:/etc/nginx/ssl:ro,Z" \
|
||||||
|
nginx:alpine nginx -t 2>&1; then
|
||||||
|
ok "nginx 설정 문법 OK"
|
||||||
|
else
|
||||||
|
fail "nginx 설정 문법 오류"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
warn "Docker 없음 - nginx 문법 검사 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "/etc/hosts 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for domain in api.train-kamco.com train-kamco.com; do
|
||||||
|
HOSTS_LINE=$(grep "$domain" /etc/hosts | grep -v "^#" | head -1)
|
||||||
|
if [ -n "$HOSTS_LINE" ]; then
|
||||||
|
ok "$domain 등록됨 → $HOSTS_LINE"
|
||||||
|
else
|
||||||
|
fail "$domain /etc/hosts 미등록"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "도메인 해석 확인"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for domain in api.train-kamco.com train-kamco.com; do
|
||||||
|
RESOLVED=$(getent hosts "$domain" 2>/dev/null | awk '{print $1}' | head -1)
|
||||||
|
if [ -n "$RESOLVED" ]; then
|
||||||
|
ok "$domain → $RESOLVED"
|
||||||
|
else
|
||||||
|
fail "$domain 해석 실패 (DNS 또는 hosts 문제)"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "포트 연결 확인 (80 / 443)"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
for port in 80 443; do
|
||||||
|
if command -v nc &>/dev/null; then
|
||||||
|
if nc -z -w3 api.train-kamco.com "$port" 2>/dev/null; then
|
||||||
|
ok "api.train-kamco.com:$port 열림"
|
||||||
|
else
|
||||||
|
warn "api.train-kamco.com:$port 닫힘 (nginx 미실행일 수 있음)"
|
||||||
|
fi
|
||||||
|
elif command -v curl &>/dev/null; then
|
||||||
|
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 3 \
|
||||||
|
"$([ "$port" = "443" ] && echo https || echo http)://api.train-kamco.com/" 2>/dev/null)
|
||||||
|
if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then
|
||||||
|
ok "api.train-kamco.com:$port 응답 (HTTP $HTTP_CODE)"
|
||||||
|
else
|
||||||
|
warn "api.train-kamco.com:$port 응답 없음 (nginx 미실행일 수 있음)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
warn "nc/curl 없음 - 포트 확인 스킵"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "HTTPS 헬스체크"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
if command -v curl &>/dev/null; then
|
||||||
|
for url in \
|
||||||
|
"https://api.train-kamco.com/monitor/health" \
|
||||||
|
"https://train-kamco.com/monitor/health"; do
|
||||||
|
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>/dev/null)
|
||||||
|
if [ "$HTTP_CODE" = "200" ]; then
|
||||||
|
ok "$url → HTTP $HTTP_CODE"
|
||||||
|
elif [ "$HTTP_CODE" = "000" ] || [ -z "$HTTP_CODE" ]; then
|
||||||
|
warn "$url → 응답 없음 (nginx 미실행일 수 있음)"
|
||||||
|
else
|
||||||
|
warn "$url → HTTP $HTTP_CODE"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
else
|
||||||
|
warn "curl 없음 - HTTPS 헬스체크 스킵"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
section "결과 요약"
|
||||||
|
# ──────────────────────────────────────────
|
||||||
|
echo ""
|
||||||
|
echo -e " ${GREEN}PASS: $PASS${NC} / ${RED}FAIL: $FAIL${NC}"
|
||||||
|
echo ""
|
||||||
|
if [ $FAIL -eq 0 ]; then
|
||||||
|
echo -e "${GREEN}모든 체크 통과. nginx 실행 준비 완료.${NC}"
|
||||||
|
if [ -n "$DOCKER_COMPOSE" ]; then
|
||||||
|
echo " cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
|
||||||
|
else
|
||||||
|
echo " [WARN] docker-compose / docker compose 를 찾을 수 없습니다."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo -e "${RED}$FAIL 개 항목 실패. 위 오류를 확인하세요.${NC}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
25
deploy/docker-compose-nginx.yml
Normal file
25
deploy/docker-compose-nginx.yml
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
services:
|
||||||
|
nginx:
|
||||||
|
image: nginx:alpine
|
||||||
|
container_name: kamco-train-nginx
|
||||||
|
user: "1000:1000"
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- ./nginx.conf:/etc/nginx/nginx.conf:ro,Z
|
||||||
|
- ./ssl:/etc/nginx/ssl:ro,Z
|
||||||
|
- ./logs:/var/log/nginx:Z
|
||||||
|
networks:
|
||||||
|
- kamco-cds
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "--no-check-certificate", "https://localhost/monitor/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kamco-cds:
|
||||||
|
external: true
|
||||||
170
deploy/nginx.conf
Normal file
170
deploy/nginx.conf
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
pid /var/log/nginx/nginx.pid;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
include /etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
# 로그 설정
|
||||||
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
|
access_log /var/log/nginx/access.log main;
|
||||||
|
error_log /var/log/nginx/error.log warn;
|
||||||
|
|
||||||
|
sendfile on;
|
||||||
|
keepalive_timeout 65;
|
||||||
|
|
||||||
|
# user 1000:1000 실행 시 /var/cache/nginx 접근 불가 → logs 경로로 우회
|
||||||
|
client_body_temp_path /var/log/nginx/client_temp;
|
||||||
|
proxy_temp_path /var/log/nginx/proxy_temp;
|
||||||
|
fastcgi_temp_path /var/log/nginx/fastcgi_temp;
|
||||||
|
uwsgi_temp_path /var/log/nginx/uwsgi_temp;
|
||||||
|
scgi_temp_path /var/log/nginx/scgi_temp;
|
||||||
|
|
||||||
|
# 업로드 파일 크기 / 타임아웃 (10GB, 10분)
|
||||||
|
client_max_body_size 10G;
|
||||||
|
client_body_timeout 600s;
|
||||||
|
|
||||||
|
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
|
||||||
|
# HTTP → HTTPS 리다이렉트 서버
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name api.train-kamco.com train-kamco.com;
|
||||||
|
|
||||||
|
# 모든 HTTP 요청을 HTTPS로 리다이렉트
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTPS 서버 설정
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
server_name api.train-kamco.com;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_timeout 10m;
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
# CORS 헤더
|
||||||
|
add_header Access-Control-Allow-Origin "https://train-kamco.com" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, PATCH, OPTIONS" always;
|
||||||
|
add_header Access-Control-Allow-Headers "Authorization, Content-Type, Cookie, X-Requested-With" always;
|
||||||
|
add_header Access-Control-Allow-Credentials "true" always;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
if ($request_method = OPTIONS) {
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_pass_request_headers on;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
proxy_set_header Authorization $http_authorization;
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /monitor/health {
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/monitor/health;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTPS 서버 설정 - Next.js Web Application
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
server_name train-kamco.com;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
|
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_timeout 10m;
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/api/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_pass_request_headers on;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
set $web http://kamco-train-web:3002;
|
||||||
|
proxy_pass $web;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
|
||||||
|
proxy_buffering on;
|
||||||
|
proxy_buffer_size 4k;
|
||||||
|
proxy_buffers 8 4k;
|
||||||
|
proxy_busy_buffers_size 8k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
38
deploy/setup-groups.sh
Executable file
38
deploy/setup-groups.sh
Executable file
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
RED='\033[0;31m'
|
||||||
|
NC='\033[0m'
|
||||||
|
|
||||||
|
ok() { echo -e "${GREEN}[OK]${NC} $1"; }
|
||||||
|
fail() { echo -e "${RED}[FAIL]${NC} $1"; exit 1; }
|
||||||
|
|
||||||
|
echo "=== GID 1000 그룹 설정 ==="
|
||||||
|
|
||||||
|
# GID 1000 그룹 없으면 생성
|
||||||
|
if ! getent group 1000 &>/dev/null; then
|
||||||
|
groupadd -g 1000 docker-users
|
||||||
|
ok "GID 1000 그룹(docker-users) 생성 완료"
|
||||||
|
else
|
||||||
|
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
|
||||||
|
ok "GID 1000 그룹 이미 존재: $GROUP_NAME"
|
||||||
|
fi
|
||||||
|
|
||||||
|
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
|
||||||
|
|
||||||
|
# kcomu, docker 를 GID 1000 그룹에 추가
|
||||||
|
for user in kcomu docker; do
|
||||||
|
if id "$user" &>/dev/null; then
|
||||||
|
usermod -aG "$GROUP_NAME" "$user"
|
||||||
|
ok "$user → $GROUP_NAME($GROUP_NAME) 그룹 추가 완료"
|
||||||
|
else
|
||||||
|
echo " [SKIP] $user 유저 없음"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "현재 $GROUP_NAME 그룹 멤버:"
|
||||||
|
getent group "$GROUP_NAME"
|
||||||
|
echo ""
|
||||||
|
echo "※ 그룹 변경은 재로그인 후 적용됩니다."
|
||||||
97
deploy/setup.sh
Executable file
97
deploy/setup.sh
Executable file
@@ -0,0 +1,97 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
NGINX_DIR="/data/training/nginx"
|
||||||
|
|
||||||
|
# docker compose v1/v2 자동 감지
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
DOCKER_COMPOSE="docker compose"
|
||||||
|
else
|
||||||
|
DOCKER_COMPOSE=""
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== 디렉토리 생성 ==="
|
||||||
|
mkdir -p /data/training/request
|
||||||
|
mkdir -p /data/training/request/tmp
|
||||||
|
mkdir -p /data/training/response
|
||||||
|
mkdir -p /data/training/response/v6-cls-checkpoints
|
||||||
|
mkdir -p /data/training/tmp
|
||||||
|
mkdir -p "$NGINX_DIR/ssl"
|
||||||
|
mkdir -p "$NGINX_DIR/logs"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== nginx 파일 복사 ==="
|
||||||
|
cp "$SCRIPT_DIR/nginx.conf" "$NGINX_DIR/"
|
||||||
|
cp "$SCRIPT_DIR/docker-compose-nginx.yml" "$NGINX_DIR/"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== SSL 파일 복사 ==="
|
||||||
|
cp "$SCRIPT_DIR/ssl/openssl.cnf" "$NGINX_DIR/ssl/"
|
||||||
|
cp "$SCRIPT_DIR/ssl/train-kamco.com.crt" "$NGINX_DIR/ssl/"
|
||||||
|
cp "$SCRIPT_DIR/ssl/train-kamco.com.key" "$NGINX_DIR/ssl/"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== SSL 권한 설정 ==="
|
||||||
|
chmod 700 "$NGINX_DIR/ssl"
|
||||||
|
chmod 600 "$NGINX_DIR/ssl/train-kamco.com.key"
|
||||||
|
chmod 644 "$NGINX_DIR/ssl/train-kamco.com.crt"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== 소유권 설정 (kcomu:kcomu) ==="
|
||||||
|
chown -R kcomu:kcomu /data/training
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== 그룹 설정 (setup-groups.sh) ==="
|
||||||
|
bash "$SCRIPT_DIR/setup-groups.sh"
|
||||||
|
|
||||||
|
echo "=== docker-compose-nginx.yml 소유권 설정 (1000:1000) ==="
|
||||||
|
chown 1000:1000 "$NGINX_DIR/docker-compose-nginx.yml"
|
||||||
|
echo "완료"
|
||||||
|
|
||||||
|
echo "=== docker-compose 래퍼 설정 ==="
|
||||||
|
if command -v docker-compose &>/dev/null; then
|
||||||
|
echo "docker-compose 이미 설치됨 (스킵)"
|
||||||
|
elif docker compose version &>/dev/null 2>&1; then
|
||||||
|
cat > /usr/local/bin/docker-compose << 'EOF'
|
||||||
|
#!/bin/bash
|
||||||
|
exec docker compose "$@"
|
||||||
|
EOF
|
||||||
|
chmod +x /usr/local/bin/docker-compose
|
||||||
|
echo "docker-compose → docker compose 래퍼 생성 완료"
|
||||||
|
DOCKER_COMPOSE="docker-compose"
|
||||||
|
else
|
||||||
|
echo "[WARN] docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Docker network 설정 ==="
|
||||||
|
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
|
||||||
|
echo "kamco-cds 네트워크 이미 존재 (스킵)"
|
||||||
|
else
|
||||||
|
docker network create kamco-cds
|
||||||
|
echo "kamco-cds 네트워크 생성 완료"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== /etc/hosts 설정 ==="
|
||||||
|
if grep -q "train-kamco.com" /etc/hosts; then
|
||||||
|
echo "이미 설정되어 있음 (스킵)"
|
||||||
|
else
|
||||||
|
echo "127.0.0.1 api.train-kamco.com train-kamco.com" >> /etc/hosts
|
||||||
|
echo "추가 완료"
|
||||||
|
fi
|
||||||
|
echo "현재 hosts 설정:"
|
||||||
|
grep "train-kamco" /etc/hosts
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== 설치 완료 ==="
|
||||||
|
echo "생성된 디렉토리:"
|
||||||
|
find /data -type d | sort
|
||||||
|
echo ""
|
||||||
|
echo "=== nginx 실행 방법 ==="
|
||||||
|
if [ -n "$DOCKER_COMPOSE" ]; then
|
||||||
|
echo "cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
|
||||||
|
else
|
||||||
|
echo "[WARN] docker-compose / docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
|
||||||
|
fi
|
||||||
21
deploy/ssl/openssl.cnf
Normal file
21
deploy/ssl/openssl.cnf
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
[req]
|
||||||
|
default_bits = 4096
|
||||||
|
prompt = no
|
||||||
|
default_md = sha256
|
||||||
|
distinguished_name = dn
|
||||||
|
req_extensions = v3_req
|
||||||
|
|
||||||
|
[dn]
|
||||||
|
C=KR
|
||||||
|
ST=Seoul
|
||||||
|
L=Seoul
|
||||||
|
O=KAMCO
|
||||||
|
OU=Training
|
||||||
|
CN=api.train-kamco.com
|
||||||
|
|
||||||
|
[v3_req]
|
||||||
|
subjectAltName = @alt_names
|
||||||
|
|
||||||
|
[alt_names]
|
||||||
|
DNS.1 = api.train-kamco.com
|
||||||
|
DNS.2 = train-kamco.com
|
||||||
38
docker-compose-dev-0420.yml
Normal file
38
docker-compose-dev-0420.yml
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
services:
|
||||||
|
kamco-changedetection-api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile-dev
|
||||||
|
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
||||||
|
container_name: kamco-cd-training-api
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
reservations:
|
||||||
|
devices:
|
||||||
|
- driver: nvidia
|
||||||
|
count: all
|
||||||
|
capabilities: [gpu]
|
||||||
|
ports:
|
||||||
|
- "7200:8080"
|
||||||
|
environment:
|
||||||
|
- SPRING_PROFILES_ACTIVE=dev
|
||||||
|
- TZ=Asia/Seoul
|
||||||
|
volumes:
|
||||||
|
- /mnt/nfs_share/images:/app/original-images
|
||||||
|
- /mnt/nfs_share/model_output:/app/model-outputs
|
||||||
|
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
||||||
|
- /home/kcomu/data:/home/kcomu/data
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
networks:
|
||||||
|
- kamco-cds
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: [ "CMD", "curl", "-f", "http://localhost:8080/monitor/health" ]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 40s
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kamco-cds:
|
||||||
|
external: true
|
||||||
@@ -18,10 +18,7 @@ services:
|
|||||||
- SPRING_PROFILES_ACTIVE=dev
|
- SPRING_PROFILES_ACTIVE=dev
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
volumes:
|
volumes:
|
||||||
- /mnt/nfs_share/images:/app/original-images
|
- /backup/data/training:/backup/data/training
|
||||||
- /mnt/nfs_share/model_output:/app/model-outputs
|
|
||||||
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
|
||||||
- /home/kcomu/data:/home/kcomu/data
|
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
services:
|
services:
|
||||||
kamco-train-api:
|
kamco-changedetection-api:
|
||||||
build:
|
image: kamco-train-app:latest
|
||||||
context: .
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: kamco-train-api:${IMAGE_TAG:-latest}
|
|
||||||
container_name: kamco-train-api
|
container_name: kamco-train-api
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
@@ -17,9 +14,10 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- SPRING_PROFILES_ACTIVE=prod
|
- SPRING_PROFILES_ACTIVE=prod
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
|
- cors.allowed-origins=*
|
||||||
|
- cors.allowed-origins[0]=*
|
||||||
volumes:
|
volumes:
|
||||||
- ./app/model_output:/app/model-outputs
|
- /data/training:/data/training
|
||||||
- ./app/train_dataset:/app/train-dataset
|
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
|
|||||||
356
nginx/nginx.conf
356
nginx/nginx.conf
@@ -1,179 +1,177 @@
|
|||||||
events {
|
events {
|
||||||
worker_connections 1024;
|
worker_connections 1024;
|
||||||
}
|
}
|
||||||
|
|
||||||
http {
|
http {
|
||||||
include /etc/nginx/mime.types;
|
include /etc/nginx/mime.types;
|
||||||
default_type application/octet-stream;
|
default_type application/octet-stream;
|
||||||
|
|
||||||
# 로그 설정
|
# 로그 설정
|
||||||
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
'$status $body_bytes_sent "$http_referer" '
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
'"$http_user_agent" "$http_x_forwarded_for"';
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
access_log /var/log/nginx/access.log main;
|
access_log /var/log/nginx/access.log main;
|
||||||
error_log /var/log/nginx/error.log warn;
|
error_log /var/log/nginx/error.log warn;
|
||||||
|
|
||||||
sendfile on;
|
sendfile on;
|
||||||
keepalive_timeout 65;
|
keepalive_timeout 65;
|
||||||
|
|
||||||
# 업로드 파일 크기 제한 (10GB)
|
# 업로드 파일 크기 제한 (10GB)
|
||||||
client_max_body_size 10G;
|
client_max_body_size 10G;
|
||||||
|
|
||||||
# Upstream 설정
|
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
|
||||||
upstream api_backend {
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
server kamco-train-api:8080;
|
|
||||||
}
|
# HTTP → HTTPS 리다이렉트 서버
|
||||||
|
server {
|
||||||
upstream web_backend {
|
listen 80;
|
||||||
server kamco-train-web:3002;
|
server_name api.train-kamco.com train-kamco.com;
|
||||||
}
|
|
||||||
|
# 모든 HTTP 요청을 HTTPS로 리다이렉트
|
||||||
# HTTP → HTTPS 리다이렉트 서버
|
return 301 https://$server_name$request_uri;
|
||||||
server {
|
}
|
||||||
listen 80;
|
|
||||||
server_name api.train-kamco.com train-kamco.com;
|
# HTTPS 서버 설정
|
||||||
|
server {
|
||||||
# 모든 HTTP 요청을 HTTPS로 리다이렉트
|
listen 443 ssl http2;
|
||||||
return 301 https://$server_name$request_uri;
|
server_name api.train-kamco.com;
|
||||||
}
|
|
||||||
|
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
|
||||||
# HTTPS 서버 설정
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
server {
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
listen 443 ssl http2;
|
|
||||||
server_name api.train-kamco.com;
|
# SSL 프로토콜 및 암호화 설정
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
ssl_prefer_server_ciphers off;
|
||||||
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
|
||||||
|
# SSL 세션 캐시
|
||||||
# SSL 프로토콜 및 암호화 설정
|
ssl_session_cache shared:SSL:10m;
|
||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_session_timeout 10m;
|
||||||
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
|
||||||
ssl_prefer_server_ciphers off;
|
# HSTS (HTTP Strict Transport Security)
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
# SSL 세션 캐시
|
|
||||||
ssl_session_cache shared:SSL:10m;
|
# 보안 헤더
|
||||||
ssl_session_timeout 10m;
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
# HSTS (HTTP Strict Transport Security)
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
|
||||||
|
# 프록시 설정
|
||||||
# 보안 헤더
|
location / {
|
||||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
set $api http://kamco-train-api:8080;
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
proxy_pass $api;
|
||||||
add_header X-XSS-Protection "1; mode=block" always;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 설정
|
# 프록시 헤더 설정
|
||||||
location / {
|
proxy_set_header Host $host;
|
||||||
proxy_pass http://api_backend;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_http_version 1.1;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
# 프록시 헤더 설정
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
# 인증 헤더 및 쿠키 전달 (JWT 토큰 전달 보장)
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_pass_request_headers on;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header Cookie $http_cookie;
|
||||||
proxy_set_header X-Forwarded-Host $server_name;
|
proxy_set_header Authorization $http_authorization;
|
||||||
|
|
||||||
# 인증 헤더 및 쿠키 전달 (JWT 토큰 전달 보장)
|
# 타임아웃 설정 (대용량 파일 업로드 지원)
|
||||||
proxy_pass_request_headers on;
|
proxy_connect_timeout 300s;
|
||||||
proxy_set_header Cookie $http_cookie;
|
proxy_send_timeout 300s;
|
||||||
proxy_set_header Authorization $http_authorization;
|
proxy_read_timeout 300s;
|
||||||
|
|
||||||
# 타임아웃 설정 (대용량 파일 업로드 지원)
|
# 버퍼 설정
|
||||||
proxy_connect_timeout 300s;
|
proxy_buffering on;
|
||||||
proxy_send_timeout 300s;
|
proxy_buffer_size 4k;
|
||||||
proxy_read_timeout 300s;
|
proxy_buffers 8 4k;
|
||||||
|
proxy_busy_buffers_size 8k;
|
||||||
# 버퍼 설정
|
}
|
||||||
proxy_buffering on;
|
|
||||||
proxy_buffer_size 4k;
|
# 헬스체크 엔드포인트
|
||||||
proxy_buffers 8 4k;
|
location /monitor/health {
|
||||||
proxy_busy_buffers_size 8k;
|
set $api http://kamco-train-api:8080;
|
||||||
}
|
proxy_pass $api/monitor/health;
|
||||||
|
access_log off;
|
||||||
# 헬스체크 엔드포인트
|
}
|
||||||
location /monitor/health {
|
}
|
||||||
proxy_pass http://api_backend/monitor/health;
|
|
||||||
access_log off;
|
# HTTPS 서버 설정 - Next.js Web Application
|
||||||
}
|
server {
|
||||||
}
|
listen 443 ssl http2;
|
||||||
|
server_name train-kamco.com;
|
||||||
# HTTPS 서버 설정 - Next.js Web Application
|
|
||||||
server {
|
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
|
||||||
listen 443 ssl http2;
|
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
||||||
server_name train-kamco.com;
|
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
||||||
|
|
||||||
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
|
# SSL 프로토콜 및 암호화 설정
|
||||||
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
# SSL 프로토콜 및 암호화 설정
|
|
||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
# SSL 세션 캐시
|
||||||
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
|
ssl_session_cache shared:SSL:10m;
|
||||||
ssl_prefer_server_ciphers off;
|
ssl_session_timeout 10m;
|
||||||
|
|
||||||
# SSL 세션 캐시
|
# HSTS (HTTP Strict Transport Security)
|
||||||
ssl_session_cache shared:SSL:10m;
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
ssl_session_timeout 10m;
|
|
||||||
|
# 보안 헤더
|
||||||
# HSTS (HTTP Strict Transport Security)
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
# 보안 헤더
|
|
||||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
# API 프록시 설정 (Web에서 API 호출 시)
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
location /api/ {
|
||||||
add_header X-XSS-Protection "1; mode=block" always;
|
set $api http://kamco-train-api:8080;
|
||||||
|
proxy_pass $api/api/;
|
||||||
# API 프록시 설정 (Web에서 API 호출 시)
|
proxy_http_version 1.1;
|
||||||
location /api/ {
|
|
||||||
proxy_pass http://api_backend/api/;
|
# 프록시 헤더 설정
|
||||||
proxy_http_version 1.1;
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
# 프록시 헤더 설정
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
# 인증 헤더 및 쿠키 전달
|
||||||
proxy_set_header X-Forwarded-Host $server_name;
|
proxy_pass_request_headers on;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
# 인증 헤더 및 쿠키 전달
|
|
||||||
proxy_pass_request_headers on;
|
# 타임아웃 설정
|
||||||
proxy_set_header Cookie $http_cookie;
|
proxy_connect_timeout 300s;
|
||||||
|
proxy_send_timeout 300s;
|
||||||
# 타임아웃 설정
|
proxy_read_timeout 300s;
|
||||||
proxy_connect_timeout 300s;
|
}
|
||||||
proxy_send_timeout 300s;
|
|
||||||
proxy_read_timeout 300s;
|
# 프록시 설정
|
||||||
}
|
location / {
|
||||||
|
set $web http://kamco-train-web:3002;
|
||||||
# 프록시 설정
|
proxy_pass $web;
|
||||||
location / {
|
proxy_http_version 1.1;
|
||||||
proxy_pass http://web_backend;
|
|
||||||
proxy_http_version 1.1;
|
# 프록시 헤더 설정
|
||||||
|
proxy_set_header Host $host;
|
||||||
# 프록시 헤더 설정
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-Host $server_name;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
proxy_set_header X-Forwarded-Host $server_name;
|
# Next.js WebSocket 지원을 위한 Upgrade 헤더
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
# Next.js WebSocket 지원을 위한 Upgrade 헤더
|
proxy_set_header Connection "upgrade";
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection "upgrade";
|
# 타임아웃 설정
|
||||||
|
proxy_connect_timeout 600s;
|
||||||
# 타임아웃 설정
|
proxy_send_timeout 600s;
|
||||||
proxy_connect_timeout 600s;
|
proxy_read_timeout 600s;
|
||||||
proxy_send_timeout 600s;
|
|
||||||
proxy_read_timeout 600s;
|
# 버퍼 설정
|
||||||
|
proxy_buffering on;
|
||||||
# 버퍼 설정
|
proxy_buffer_size 4k;
|
||||||
proxy_buffering on;
|
proxy_buffers 8 4k;
|
||||||
proxy_buffer_size 4k;
|
proxy_busy_buffers_size 8k;
|
||||||
proxy_buffers 8 4k;
|
}
|
||||||
proxy_busy_buffers_size 8k;
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package com.kamco.cd.training.common.service;
|
|||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
@@ -13,19 +15,34 @@ import org.springframework.stereotype.Component;
|
|||||||
public class GpuDmonReader {
|
public class GpuDmonReader {
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// GPU 사용률 저장소
|
// GPU 사용률 히스토리 저장소
|
||||||
// key: GPU index (0,1,2...)
|
// key: GPU index (0,1,2...)
|
||||||
// value: 현재 GPU 사용률 (%)
|
// value: 최근 WINDOW_SIZE 개의 sm 사용률 샘플 (1초 간격)
|
||||||
// ConcurrentHashMap → 멀티스레드 안전
|
// ConcurrentHashMap → 멀티스레드 안전 (deque 접근은 synchronized)
|
||||||
// =========================
|
// =========================
|
||||||
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
private static final int WINDOW_SIZE = 10; // 10초 평균
|
||||||
|
|
||||||
|
private final Map<Integer, ArrayDeque<Integer>> historyMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// 외부 조회용
|
// 외부 조회용
|
||||||
|
// GPU 개수만큼 10초 평균값 반환
|
||||||
// SystemMonitorService에서 호출
|
// SystemMonitorService에서 호출
|
||||||
// =========================
|
// =========================
|
||||||
public Map<Integer, Integer> getGpuUtilMap() {
|
public Map<Integer, Integer> getGpuUtilMap() {
|
||||||
return gpuUtilMap;
|
Map<Integer, Integer> result = new HashMap<>();
|
||||||
|
historyMap.forEach(
|
||||||
|
(gpu, deque) -> {
|
||||||
|
synchronized (deque) {
|
||||||
|
int avg =
|
||||||
|
deque.isEmpty()
|
||||||
|
? 0
|
||||||
|
: (int)
|
||||||
|
Math.round(deque.stream().mapToInt(Integer::intValue).average().orElse(0));
|
||||||
|
result.put(gpu, avg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
@@ -76,10 +93,13 @@ public class GpuDmonReader {
|
|||||||
|
|
||||||
// -s u → GPU utilization만 출력
|
// -s u → GPU utilization만 출력
|
||||||
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
||||||
|
// stderr를 stdout에 합쳐서 소비 — 소비하지 않으면 stderr 버퍼가 가득 차
|
||||||
|
// nvidia-smi 프로세스 자체가 block되어 stdout도 멈춤
|
||||||
|
pb.redirectErrorStream(true);
|
||||||
|
|
||||||
|
Process process = pb.start();
|
||||||
// 프로세스 실행 후 stdout 읽기
|
// 프로세스 실행 후 stdout 읽기
|
||||||
try (BufferedReader br =
|
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||||
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
|
||||||
|
|
||||||
String line;
|
String line;
|
||||||
|
|
||||||
@@ -96,21 +116,24 @@ public class GpuDmonReader {
|
|||||||
String[] parts = line.split("\\s+");
|
String[] parts = line.split("\\s+");
|
||||||
|
|
||||||
// 첫 번째 값이 GPU index인지 확인
|
// 첫 번째 값이 GPU index인지 확인
|
||||||
if (!parts[0].matches("\\d+")) continue;
|
if (parts.length < 2 || !parts[0].matches("\\d+")) continue;
|
||||||
|
|
||||||
int index = Integer.parseInt(parts[0]);
|
int index = Integer.parseInt(parts[0]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 두 번째 값이 GPU 사용률 (sm)
|
// 두 번째 값이 GPU 사용률 (sm), "-"이면 N/A (GPU 미활성)
|
||||||
int util = Integer.parseInt(parts[1]);
|
int util = Integer.parseInt(parts[1]);
|
||||||
|
pushSample(index, util);
|
||||||
|
log.debug("[GpuDmon] gpu={} sm={}%", index, util);
|
||||||
|
|
||||||
// 최신 값 갱신
|
} catch (NumberFormatException e) {
|
||||||
gpuUtilMap.put(index, util);
|
// "-" 등 숫자가 아닌 값 → GPU 비활성 상태이므로 0으로 기록
|
||||||
|
pushSample(index, 0);
|
||||||
} catch (Exception ignored) {
|
log.debug("[GpuDmon] gpu={} sm=N/A (raw={}), stored as 0", index, parts[1]);
|
||||||
// 파싱 실패 시 무시
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
process.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||||
@@ -118,6 +141,20 @@ public class GpuDmonReader {
|
|||||||
throw new IllegalStateException("dmon stopped");
|
throw new IllegalStateException("dmon stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// =========================
|
||||||
|
// 샘플 추가 — 윈도우 초과 시 가장 오래된 값 제거
|
||||||
|
// =========================
|
||||||
|
private void pushSample(int gpuIndex, int util) {
|
||||||
|
ArrayDeque<Integer> deque =
|
||||||
|
historyMap.computeIfAbsent(gpuIndex, k -> new ArrayDeque<>(WINDOW_SIZE));
|
||||||
|
synchronized (deque) {
|
||||||
|
deque.addLast(util);
|
||||||
|
if (deque.size() > WINDOW_SIZE) {
|
||||||
|
deque.pollFirst();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// nvidia-smi 존재 여부 확인
|
// nvidia-smi 존재 여부 확인
|
||||||
// =========================
|
// =========================
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
package com.kamco.cd.training.common.utils;
|
package com.kamco.cd.training.common.utils;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.context.request.RequestAttributes;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
public final class HeaderUtil {
|
public final class HeaderUtil {
|
||||||
|
|
||||||
private HeaderUtil() {}
|
private HeaderUtil() {}
|
||||||
@@ -20,4 +25,20 @@ public final class HeaderUtil {
|
|||||||
public static String getRequired(HttpServletRequest request, String headerName) {
|
public static String getRequired(HttpServletRequest request, String headerName) {
|
||||||
return get(request, headerName);
|
return get(request, headerName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static boolean isEnglishRequest() {
|
||||||
|
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
|
||||||
|
|
||||||
|
if (!(attrs instanceof ServletRequestAttributes servletAttrs)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String acceptLanguage = servletAttrs.getRequest().getHeader("Accept-Language");
|
||||||
|
|
||||||
|
if (acceptLanguage == null || acceptLanguage.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return acceptLanguage.toLowerCase().startsWith("en");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.common.utils.enums;
|
package com.kamco.cd.training.common.utils.enums;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -31,10 +32,11 @@ public class Enums {
|
|||||||
// enum -> CodeDto list
|
// enum -> CodeDto list
|
||||||
public static List<CodeDto> toList(Class<? extends Enum<?>> enumClass) {
|
public static List<CodeDto> toList(Class<? extends Enum<?>> enumClass) {
|
||||||
Object[] enums = enumClass.getEnumConstants();
|
Object[] enums = enumClass.getEnumConstants();
|
||||||
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
|
||||||
return Arrays.stream(enums)
|
return Arrays.stream(enums)
|
||||||
.map(e -> (EnumType) e)
|
.map(e -> (EnumType) e)
|
||||||
.map(e -> new CodeDto(e.getId(), e.getText()))
|
.map(e -> new CodeDto(e.getId(), english ? e.getId() : e.getText()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -293,6 +293,8 @@ public class DatasetApiController {
|
|||||||
DatasetService.validateTrainValTestDirs(req.getFilePath());
|
DatasetService.validateTrainValTestDirs(req.getFilePath());
|
||||||
// 파일 개수 검증
|
// 파일 개수 검증
|
||||||
DatasetService.validateDirFileCount(req.getFilePath());
|
DatasetService.validateDirFileCount(req.getFilePath());
|
||||||
|
// 폴더명(uid)으로 등록한 건이 있는지 체크
|
||||||
|
datasetService.validateExistsUidChk(req.getFilePath());
|
||||||
|
|
||||||
datasetAsyncService.insertDeliveriesDatasetAsync(req);
|
datasetAsyncService.insertDeliveriesDatasetAsync(req);
|
||||||
return ApiResponseDto.createOK("ok");
|
return ApiResponseDto.createOK("ok");
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
|
|||||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
@@ -90,7 +91,8 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getStatus(String status) {
|
public String getStatus(String status) {
|
||||||
LearnDataRegister type = Enums.fromId(LearnDataRegister.class, status);
|
LearnDataRegister type = Enums.fromId(LearnDataRegister.class, status);
|
||||||
return type == null ? null : type.getText();
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
return type == null ? null : (english ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
@@ -99,7 +101,8 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getDataTypeName() {
|
public String getDataTypeName() {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, this.dataType);
|
LearnDataType type = Enums.fromId(LearnDataType.class, this.dataType);
|
||||||
return type == null ? null : type.getText();
|
boolean english = HeaderUtil.isEnglishRequest();
|
||||||
|
return type == null ? null : (english ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +318,7 @@ public class DatasetDto {
|
|||||||
|
|
||||||
public String getDataTypeName(String groupTitleCd) {
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
||||||
return type == null ? null : type.getText();
|
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
|||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.kamco.cd.training.common.enums.DetectionClassification;
|
import com.kamco.cd.training.common.enums.DetectionClassification;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -131,7 +132,10 @@ public class DatasetObjDto {
|
|||||||
private String classCd;
|
private String classCd;
|
||||||
|
|
||||||
public String getClassName() {
|
public String getClassName() {
|
||||||
return DetectionClassification.fromString(classCd).getDesc();
|
|
||||||
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? DetectionClassification.fromString(classCd).getId()
|
||||||
|
: DetectionClassification.fromString(classCd).getDesc();
|
||||||
// fromString 메서드를 사용하여 안전하게 변환 (미정의 값은 ETC로 처리)
|
// fromString 메서드를 사용하여 안전하게 변환 (미정의 값은 ETC로 처리)
|
||||||
// return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
// return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,11 @@ import com.kamco.cd.training.common.enums.LearnDataRegister;
|
|||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||||
import java.util.UUID;
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.log4j.Log4j2;
|
import lombok.extern.log4j.Log4j2;
|
||||||
import org.springframework.scheduling.annotation.Async;
|
import org.springframework.scheduling.annotation.Async;
|
||||||
@@ -45,7 +49,11 @@ public class DatasetAsyncService {
|
|||||||
try {
|
try {
|
||||||
|
|
||||||
// ===== 1. UID 생성 =====
|
// ===== 1. UID 생성 =====
|
||||||
String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
|
// String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
|
||||||
|
|
||||||
|
// 26-05-08: UID를 생성하지 않고 folder name 을 uid 로 저장하기 -> req.getFilePath()
|
||||||
|
Path selectedPath = Paths.get(req.getFilePath());
|
||||||
|
String uid = selectedPath.getFileName().toString();
|
||||||
log.info("{} 생성된 UID: {}", LOG_PREFIX, uid);
|
log.info("{} 생성된 UID: {}", LOG_PREFIX, uid);
|
||||||
|
|
||||||
// ===== 2. 마스터 데이터 생성 =====
|
// ===== 2. 마스터 데이터 생성 =====
|
||||||
@@ -71,6 +79,7 @@ public class DatasetAsyncService {
|
|||||||
datasetMngRegDto.setTitle(title);
|
datasetMngRegDto.setTitle(title);
|
||||||
datasetMngRegDto.setMemo(req.getMemo());
|
datasetMngRegDto.setMemo(req.getMemo());
|
||||||
datasetMngRegDto.setDatasetPath(req.getFilePath());
|
datasetMngRegDto.setDatasetPath(req.getFilePath());
|
||||||
|
datasetMngRegDto.setTotalSize(getDirectorySize(req.getFilePath())); // 선택한 폴더 안의 모든 파일 용량 합계
|
||||||
|
|
||||||
// 마스터 저장
|
// 마스터 저장
|
||||||
datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
|
datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
|
||||||
@@ -121,4 +130,24 @@ public class DatasetAsyncService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Long getDirectorySize(String filePath) {
|
||||||
|
Path selectedPath = Paths.get(filePath);
|
||||||
|
|
||||||
|
try (Stream<Path> paths = Files.walk(selectedPath)) {
|
||||||
|
return paths
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.mapToLong(
|
||||||
|
path -> {
|
||||||
|
try {
|
||||||
|
return Files.size(path);
|
||||||
|
} catch (IOException e) {
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
} catch (IOException e) {
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -286,7 +286,7 @@ public class DatasetService {
|
|||||||
.memo(addReq.getMemo())
|
.memo(addReq.getMemo())
|
||||||
.roundNo(stage)
|
.roundNo(stage)
|
||||||
.totalSize(addReq.getFileSize())
|
.totalSize(addReq.getFileSize())
|
||||||
.datasetPath(addReq.getFilePath())
|
.datasetPath(addReq.getFilePath() + uid)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
||||||
@@ -676,4 +676,18 @@ public class DatasetService {
|
|||||||
total,
|
total,
|
||||||
System.currentTimeMillis() - start);
|
System.currentTimeMillis() - start);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void validateExistsUidChk(String filePath) {
|
||||||
|
Path selectedPath = Paths.get(filePath);
|
||||||
|
String uid = selectedPath.getFileName().toString();
|
||||||
|
|
||||||
|
// 같은 uid 로 등록한 파일이 있는지 확인
|
||||||
|
Long existsCnt = datasetCoreService.findDatasetByUidExistsCnt(uid);
|
||||||
|
if (existsCnt > 0) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.DUPLICATE_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"이미 등록된 회차 데이터 파일입니다. 확인 부탁드립니다.");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.kamco.cd.training.filemanager.dto;
|
package com.kamco.cd.training.filemanager.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
@@ -274,5 +276,11 @@ public class FileManagerDto {
|
|||||||
|
|
||||||
@Schema(description = "디스크 사용률 (%)", example = "50.5")
|
@Schema(description = "디스크 사용률 (%)", example = "50.5")
|
||||||
private Double usagePercentage;
|
private Double usagePercentage;
|
||||||
|
|
||||||
|
@JsonFormatDttm private ZonedDateTime lastModifiedDate;
|
||||||
|
|
||||||
|
public ZonedDateTime getLastModifiedDate() {
|
||||||
|
return ZonedDateTime.now();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -617,36 +617,36 @@ public class FileManagerService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 디렉토리 사용량 계산 (재귀적으로 모든 파일 크기 합산)
|
// 디렉토리 사용량 계산 — du -sb 사용 (walkFileTree 대비 수배 빠름)
|
||||||
final long[] usedSize = {0};
|
// fileCount/directoryCount는 du가 제공하지 않으므로 -1(미집계) 반환
|
||||||
final int[] fileCount = {0};
|
long usedSize = 0;
|
||||||
final int[] directoryCount = {0};
|
|
||||||
|
|
||||||
|
log.info("[StorageSpace] du 시작 - path={}", directoryPath);
|
||||||
try {
|
try {
|
||||||
Files.walkFileTree(
|
ProcessBuilder duPb = new ProcessBuilder("du", "-sb", directoryPath);
|
||||||
directory,
|
duPb.redirectErrorStream(true);
|
||||||
new SimpleFileVisitor<>() {
|
Process duProcess = duPb.start();
|
||||||
@Override
|
try (java.io.BufferedReader br =
|
||||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
new java.io.BufferedReader(new java.io.InputStreamReader(duProcess.getInputStream()))) {
|
||||||
usedSize[0] += attrs.size();
|
String line = br.readLine();
|
||||||
fileCount[0]++;
|
if (line != null) {
|
||||||
return FileVisitResult.CONTINUE;
|
// du -sb 출력 형식: "12345678\t/path/to/dir"
|
||||||
}
|
String[] parts = line.split("\t", 2);
|
||||||
|
usedSize = Long.parseLong(parts[0].trim());
|
||||||
@Override
|
}
|
||||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
}
|
||||||
if (!dir.equals(directory)) {
|
int exitCode = duProcess.waitFor();
|
||||||
directoryCount[0]++;
|
log.info(
|
||||||
}
|
"[StorageSpace] du 완료 - exitCode={}, usedSize={} bytes ({})",
|
||||||
return FileVisitResult.CONTINUE;
|
exitCode,
|
||||||
}
|
usedSize,
|
||||||
});
|
formatFileSize(usedSize));
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
log.error("디렉토리 용량 계산 중 오류 발생: {}", directoryPath, e);
|
log.error("[StorageSpace] du 실행 실패: {}", directoryPath, e);
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(0)
|
.fileCount(-1)
|
||||||
.directoryCount(0)
|
.directoryCount(-1)
|
||||||
.usedSize(0L)
|
.usedSize(0L)
|
||||||
.usedSizeFormatted("0 B")
|
.usedSizeFormatted("0 B")
|
||||||
.totalDiskSpace(0L)
|
.totalDiskSpace(0L)
|
||||||
@@ -659,7 +659,7 @@ public class FileManagerService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 디스크 공간 정보 조회 (FileStore 사용)
|
// 디스크 공간 정보 조회 (FileStore 사용) — basePath가 속한 파티션/NFS 마운트 전체 기준
|
||||||
long totalDiskSpace = 0;
|
long totalDiskSpace = 0;
|
||||||
long freeSpace = 0;
|
long freeSpace = 0;
|
||||||
long usableSpace = 0;
|
long usableSpace = 0;
|
||||||
@@ -667,26 +667,37 @@ public class FileManagerService {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
java.nio.file.FileStore fileStore = Files.getFileStore(directory);
|
java.nio.file.FileStore fileStore = Files.getFileStore(directory);
|
||||||
totalDiskSpace = fileStore.getTotalSpace(); // 전체 디스크 용량
|
totalDiskSpace = fileStore.getTotalSpace();
|
||||||
freeSpace = fileStore.getUnallocatedSpace(); // 남은 저장공간 (할당되지 않은 공간)
|
freeSpace = fileStore.getUnallocatedSpace(); // OS 미할당 공간 (root 예약 블록 포함 가능)
|
||||||
usableSpace = fileStore.getUsableSpace(); // 사용 가능한 공간 (실제 사용 가능)
|
usableSpace = fileStore.getUsableSpace(); // 실제 프로세스가 사용 가능한 공간
|
||||||
|
log.info(
|
||||||
|
"[StorageSpace] FileStore - name={}, type={}, total={} bytes ({}), unallocated={} bytes ({}), usable={} bytes ({})",
|
||||||
|
fileStore.name(),
|
||||||
|
fileStore.type(),
|
||||||
|
totalDiskSpace,
|
||||||
|
formatFileSize(totalDiskSpace),
|
||||||
|
freeSpace,
|
||||||
|
formatFileSize(freeSpace),
|
||||||
|
usableSpace,
|
||||||
|
formatFileSize(usableSpace));
|
||||||
|
|
||||||
// 디스크 사용률 계산
|
// 사용률은 usableSpace 기준으로 계산 (더 정확한 실사용 가능 공간 반영)
|
||||||
if (totalDiskSpace > 0) {
|
if (totalDiskSpace > 0) {
|
||||||
long usedDiskSpace = totalDiskSpace - freeSpace;
|
long usedDiskSpace = totalDiskSpace - usableSpace;
|
||||||
usagePercentage = (usedDiskSpace * 100.0) / totalDiskSpace;
|
usagePercentage = (usedDiskSpace * 100.0) / totalDiskSpace;
|
||||||
}
|
}
|
||||||
|
log.info("[StorageSpace] usagePercentage={}%", Math.round(usagePercentage * 100.0) / 100.0);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.debug("디스크 공간 정보 조회 중 오류 발생: {}", directoryPath, e);
|
log.warn("[StorageSpace] 디스크 공간 정보 조회 실패: {}", directoryPath, e);
|
||||||
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
||||||
}
|
}
|
||||||
|
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(fileCount[0])
|
.fileCount(-1)
|
||||||
.directoryCount(directoryCount[0])
|
.directoryCount(-1)
|
||||||
.usedSize(usedSize[0])
|
.usedSize(usedSize)
|
||||||
.usedSizeFormatted(formatFileSize(usedSize[0]))
|
.usedSizeFormatted(formatFileSize(usedSize))
|
||||||
.totalDiskSpace(totalDiskSpace)
|
.totalDiskSpace(totalDiskSpace)
|
||||||
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
||||||
.freeSpace(freeSpace)
|
.freeSpace(freeSpace)
|
||||||
|
|||||||
@@ -369,9 +369,8 @@ public class ModelTrainDetailApiController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Operation(
|
@Operation(
|
||||||
summary = "학습 결과 ZIP 파일 전체 다운로드",
|
summary = "학습 결과 ZIP 파일 목록 조회",
|
||||||
description =
|
description = "모델 UUID에 해당하는 모든 ZIP 파일 목록과 개별 다운로드 링크 반환",
|
||||||
"모델 UUID에 해당하는 모든 ZIP 파일 목록을 조회하고" + "생성된 모든 학습데이터의 ZIP 파일을 하나의 ZIP 파일로 압축하여 다운로드",
|
|
||||||
parameters = {
|
parameters = {
|
||||||
@Parameter(
|
@Parameter(
|
||||||
name = "kamco-download-uuid",
|
name = "kamco-download-uuid",
|
||||||
@@ -388,11 +387,12 @@ public class ModelTrainDetailApiController {
|
|||||||
value = {
|
value = {
|
||||||
@ApiResponse(
|
@ApiResponse(
|
||||||
responseCode = "200",
|
responseCode = "200",
|
||||||
description = "학습데이터 zip파일 다운로드",
|
description = "ZIP 파일 목록 조회 성공",
|
||||||
content =
|
content =
|
||||||
@Content(
|
@Content(
|
||||||
mediaType = "application/octet-stream",
|
mediaType = "application/json",
|
||||||
schema = @Schema(type = "string", format = "binary"))),
|
schema =
|
||||||
|
@Schema(implementation = ModelTrainDetailDto.ZipFileListResponse.class))),
|
||||||
@ApiResponse(responseCode = "404", description = "모델 또는 파일 없음", content = @Content),
|
@ApiResponse(responseCode = "404", description = "모델 또는 파일 없음", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@@ -403,6 +403,7 @@ public class ModelTrainDetailApiController {
|
|||||||
HttpServletRequest request)
|
HttpServletRequest request)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
|
|
||||||
return modelTrainDetailService.downloadZipFile(uuid, downloadUuid, request);
|
return ResponseEntity.ok(
|
||||||
|
modelTrainDetailService.getZipFileListWithFullUrl(uuid, downloadUuid, request));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
|
|||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
@@ -32,6 +33,8 @@ public class ModelTrainDetailDto {
|
|||||||
private String modelNo;
|
private String modelNo;
|
||||||
private String modelVer;
|
private String modelVer;
|
||||||
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
|
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step1EndDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step2StrtDttm;
|
||||||
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
||||||
private String statusCd;
|
private String statusCd;
|
||||||
private String trainType;
|
private String trainType;
|
||||||
@@ -40,7 +43,9 @@ public class ModelTrainDetailDto {
|
|||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -49,18 +54,16 @@ public class ModelTrainDetailDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
|
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
|
||||||
if (end == null) {
|
if (start == null || end == null) {
|
||||||
end = ZonedDateTime.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (start == null) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,11 +73,42 @@ public class ModelTrainDetailDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStepAllDuration() {
|
public String getStepAllDuration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step2EndDttm);
|
if (this.step2EndDttm != null) {
|
||||||
|
// step1 + step2 실제 소요시간 합산
|
||||||
|
long step1Seconds = 0;
|
||||||
|
long step2Seconds = 0;
|
||||||
|
|
||||||
|
if (this.step1StrtDttm != null && this.step1EndDttm != null) {
|
||||||
|
step1Seconds =
|
||||||
|
Math.abs(Duration.between(this.step1StrtDttm, this.step1EndDttm).getSeconds());
|
||||||
|
}
|
||||||
|
if (this.step2StrtDttm != null && this.step2EndDttm != null) {
|
||||||
|
step2Seconds =
|
||||||
|
Math.abs(Duration.between(this.step2StrtDttm, this.step2EndDttm).getSeconds());
|
||||||
|
}
|
||||||
|
|
||||||
|
long totalSeconds = step1Seconds + step2Seconds;
|
||||||
|
long hours = totalSeconds / 3600;
|
||||||
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// step2 없으면 step1만
|
||||||
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,7 +208,7 @@ public class ModelTrainDetailDto {
|
|||||||
|
|
||||||
public String getDataTypeName(String groupTitleCd) {
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
||||||
return type == null ? null : type.getText();
|
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.model.dto;
|
|||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
@@ -44,8 +45,8 @@ public class ModelTrainMngDto {
|
|||||||
private String requestPath;
|
private String requestPath;
|
||||||
|
|
||||||
private String packingState;
|
private String packingState;
|
||||||
private ZonedDateTime packingStrtDttm;
|
@JsonFormatDttm private ZonedDateTime packingStrtDttm;
|
||||||
private ZonedDateTime packingEndDttm;
|
@JsonFormatDttm private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
private Long beforeModelId;
|
private Long beforeModelId;
|
||||||
private Integer bestEpoch;
|
private Integer bestEpoch;
|
||||||
@@ -53,7 +54,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -62,7 +65,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep1StatusName() {
|
public String getStep1StatusName() {
|
||||||
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step1Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step1Status).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -71,7 +76,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep2StatusName() {
|
public String getStep2StatusName() {
|
||||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step2Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step2Status).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -80,7 +87,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return (HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText()); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -97,7 +106,11 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
@@ -176,6 +189,8 @@ public class ModelTrainMngDto {
|
|||||||
|
|
||||||
private String requestPath;
|
private String requestPath;
|
||||||
private String responsePath;
|
private String responsePath;
|
||||||
|
private String tmpFileStatus;
|
||||||
|
private ZonedDateTime tmpFileEndDttm;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -258,7 +273,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.statusCd).getId()
|
||||||
|
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -267,7 +284,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep1StatusName() {
|
public String getStep1StatusName() {
|
||||||
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step1Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -276,7 +295,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep2StatusName() {
|
public String getStep2StatusName() {
|
||||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainStatusType.valueOf(this.step2Status).getId()
|
||||||
|
: TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -285,7 +306,9 @@ public class ModelTrainMngDto {
|
|||||||
public String getTrainTypeName() {
|
public String getTrainTypeName() {
|
||||||
if (this.trainType == null || this.trainType.isBlank()) return null;
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
return HeaderUtil.isEnglishRequest()
|
||||||
|
? TrainType.valueOf(this.trainType).getId()
|
||||||
|
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
}
|
}
|
||||||
@@ -302,7 +325,11 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 60;
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
if (HeaderUtil.isEnglishRequest()) {
|
||||||
|
return String.format("%dh %dm %ds", hours, minutes, seconds);
|
||||||
|
} else {
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
|
|||||||
@@ -444,6 +444,165 @@ public class ModelTrainDetailService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 UUID로 ZIP 파일 목록 조회 및 전체 URL 다운로드 링크 생성
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param downloadUuid 다운로드 추적 UUID
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return ZIP 파일 목록 및 전체 URL 다운로드 링크
|
||||||
|
*/
|
||||||
|
public ZipFileListResponse getZipFileListWithFullUrl(
|
||||||
|
UUID uuid, String downloadUuid, HttpServletRequest request) {
|
||||||
|
log.info("=== ZIP 파일 목록 조회 시작: modelUuid={}, downloadUuid={} ===", uuid, downloadUuid);
|
||||||
|
|
||||||
|
// 1. 모델 정보 조회
|
||||||
|
Basic modelInfo;
|
||||||
|
try {
|
||||||
|
modelInfo = findByModelByUUID(uuid);
|
||||||
|
if (modelInfo == null) {
|
||||||
|
log.warn("모델을 찾을 수 없음: modelUuid={}", uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
}
|
||||||
|
log.debug(
|
||||||
|
"모델 정보 조회 성공: modelNo={}, modelVer={}", modelInfo.getModelNo(), modelInfo.getModelVer());
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
log.error("모델 조회 중 NullPointerException 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
||||||
|
} catch (CustomApiException e) {
|
||||||
|
// CustomApiException은 그대로 재throw
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("모델 조회 중 예상치 못한 오류 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "모델 조회 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
||||||
|
Path baseDir;
|
||||||
|
try {
|
||||||
|
baseDir = findActualBasePath(uuid);
|
||||||
|
|
||||||
|
if (baseDir == null || !Files.exists(baseDir)) {
|
||||||
|
log.warn(
|
||||||
|
"모델 결과 디렉토리를 찾을 수 없음: modelUuid={}, 시도한 경로: {} 또는 {}-out",
|
||||||
|
uuid,
|
||||||
|
responseDir + "/" + uuid,
|
||||||
|
responseDir + "/" + uuid);
|
||||||
|
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 결과 디렉토리가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("디렉토리 발견: basePath={}", baseDir.toString());
|
||||||
|
} catch (CustomApiException e) {
|
||||||
|
// CustomApiException은 그대로 재throw
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("디렉토리 경로 확인 중 오류 발생: modelUuid={}", uuid, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "디렉토리 경로 확인 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 요청에서 도메인 정보 추출
|
||||||
|
String scheme = request.getScheme(); // http 또는 https
|
||||||
|
String serverName = request.getServerName(); // localhost 또는 도메인
|
||||||
|
int serverPort = request.getServerPort(); // 8080 등
|
||||||
|
String contextPath = request.getContextPath(); // /api 등
|
||||||
|
|
||||||
|
// 기본 URL 구성
|
||||||
|
String baseUrl;
|
||||||
|
if ((scheme.equals("http") && serverPort == 80)
|
||||||
|
|| (scheme.equals("https") && serverPort == 443)) {
|
||||||
|
baseUrl = scheme + "://" + serverName + contextPath;
|
||||||
|
} else {
|
||||||
|
baseUrl = scheme + "://" + serverName + ":" + serverPort + contextPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("다운로드 URL 베이스: {}", baseUrl);
|
||||||
|
|
||||||
|
// 3. ZIP 파일 목록 검색
|
||||||
|
List<ZipFileInfo> zipFiles = new ArrayList<>();
|
||||||
|
long totalSize = 0L;
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(baseDir)) {
|
||||||
|
List<Path> files =
|
||||||
|
stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".zip"))
|
||||||
|
.filter(p -> p.getFileName().toString().contains(uuid.toString()))
|
||||||
|
.sorted(
|
||||||
|
Comparator.comparing(p -> p.getFileName().toString(), Comparator.reverseOrder()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
log.debug("ZIP 파일 필터링 완료: 발견된 파일 개수={}", files.size());
|
||||||
|
|
||||||
|
for (Path file : files) {
|
||||||
|
try {
|
||||||
|
String fileName = file.getFileName().toString();
|
||||||
|
long fileSize = Files.size(file);
|
||||||
|
totalSize += fileSize;
|
||||||
|
|
||||||
|
// 파일명에서 버전 추출
|
||||||
|
String version = extractVersionFromZipFileName(fileName);
|
||||||
|
boolean isCurrent = version.equals(modelInfo.getModelVer());
|
||||||
|
|
||||||
|
// 전체 도메인 URL 포함한 다운로드 링크 생성
|
||||||
|
String downloadUrl = baseUrl + "/api/models/download/" + uuid + "?file=" + fileName;
|
||||||
|
|
||||||
|
zipFiles.add(
|
||||||
|
ZipFileInfo.builder()
|
||||||
|
.fileName(fileName)
|
||||||
|
.filePath(file.toString())
|
||||||
|
.version(version)
|
||||||
|
.fileSize(fileSize)
|
||||||
|
.fileSizeFormatted(formatFileSize(fileSize))
|
||||||
|
.lastModified(
|
||||||
|
Files.getLastModifiedTime(file).toInstant().atZone(ZoneId.systemDefault()))
|
||||||
|
.isCurrent(isCurrent)
|
||||||
|
.downloadUrl(downloadUrl)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"ZIP 파일 정보 추가: fileName={}, size={}, version={}, isCurrent={}",
|
||||||
|
fileName,
|
||||||
|
formatFileSize(fileSize),
|
||||||
|
version,
|
||||||
|
isCurrent);
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("ZIP 파일 정보 조회 실패 (건너뜀): file={}", file.getFileName(), e);
|
||||||
|
// 개별 파일 실패 시 전체 프로세스를 중단하지 않고 계속 진행
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("ZIP 파일 정보 처리 중 예상치 못한 오류 (건너뜀): file={}", file.getFileName(), e);
|
||||||
|
// 예상치 못한 오류도 전체 프로세스를 중단하지 않음
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(" ZIP 파일 목록 조회 완료: 총 {}개 파일, 전체 크기={}", zipFiles.size(), formatFileSize(totalSize));
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("ZIP 파일 목록 조회 중 IO 오류 발생: basePath={}", baseDir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR",
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
"ZIP 파일 목록 조회 중 IO 오류가 발생했습니다.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("ZIP 파일 목록 조회 중 예상치 못한 오류 발생: basePath={}", baseDir, e);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "ZIP 파일 목록 조회 중 오류가 발생했습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return ZipFileListResponse.builder()
|
||||||
|
.modelUuid(uuid.toString())
|
||||||
|
.modelNo(modelInfo.getModelNo())
|
||||||
|
.modelVer(modelInfo.getModelVer())
|
||||||
|
.basePath(baseDir.toString())
|
||||||
|
.zipFiles(zipFiles)
|
||||||
|
.totalFiles(zipFiles.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 UUID로 ZIP 파일 목록 조회 및 다운로드 링크 생성
|
* 모델 UUID로 ZIP 파일 목록 조회 및 다운로드 링크 생성
|
||||||
*
|
*
|
||||||
@@ -608,16 +767,24 @@ public class ModelTrainDetailService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 UUID로 모든 ZIP 파일 다운로드 (여러 파일이 있으면 하나의 zip으로 묶어서)
|
* 모델 UUID로 모든 ZIP 파일 다운로드 또는 목록 조회
|
||||||
*
|
*
|
||||||
* @param uuid 모델 UUID
|
* @param uuid 모델 UUID
|
||||||
* @param downloadUuid 다운로드 추적 UUID
|
* @param downloadUuid 다운로드 추적 UUID
|
||||||
|
* @param fileName 개별 파일명 (선택)
|
||||||
|
* @param accept Accept 헤더 (application/json 또는 application/octet-stream)
|
||||||
* @param request HTTP 요청
|
* @param request HTTP 요청
|
||||||
* @return ZIP 파일 다운로드 응답
|
* @return JSON 응답 또는 ZIP 파일 Binary 응답
|
||||||
*/
|
*/
|
||||||
public ResponseEntity<?> downloadZipFile(
|
public ResponseEntity<?> downloadZipFile(
|
||||||
UUID uuid, String downloadUuid, HttpServletRequest request) throws IOException {
|
UUID uuid, String downloadUuid, String fileName, String accept, HttpServletRequest request)
|
||||||
log.info("ZIP 파일 다운로드 시작: modelUuid={}, downloadUuid={}", uuid, downloadUuid);
|
throws IOException {
|
||||||
|
log.info(
|
||||||
|
"ZIP 파일 다운로드/조회 시작: modelUuid={}, downloadUuid={}, file={}, accept={}",
|
||||||
|
uuid,
|
||||||
|
downloadUuid,
|
||||||
|
fileName,
|
||||||
|
accept);
|
||||||
|
|
||||||
// 1. 모델 정보 조회
|
// 1. 모델 정보 조회
|
||||||
Basic modelInfo;
|
Basic modelInfo;
|
||||||
@@ -659,7 +826,134 @@ public class ModelTrainDetailService {
|
|||||||
baseDir,
|
baseDir,
|
||||||
zipFiles.stream().map(p -> p.getFileName().toString()).toList());
|
zipFiles.stream().map(p -> p.getFileName().toString()).toList());
|
||||||
|
|
||||||
// 4. 파일이 1개면 바로 다운로드
|
// 4. Accept 헤더에 따라 분기
|
||||||
|
if (accept != null && accept.contains("application/json")) {
|
||||||
|
// JSON 응답: ZIP 파일 목록과 다운로드 링크 반환
|
||||||
|
log.info("JSON 응답 모드: ZIP 파일 목록 반환");
|
||||||
|
return ResponseEntity.ok(buildZipFileListResponse(modelInfo, baseDir, zipFiles, request));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Binary 응답: 파일 다운로드
|
||||||
|
return handleBinaryDownload(modelInfo, baseDir, zipFiles, fileName, uuid, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ZIP 파일 목록 응답 생성 (JSON)
|
||||||
|
*
|
||||||
|
* @param modelInfo 모델 정보
|
||||||
|
* @param baseDir 기본 디렉토리
|
||||||
|
* @param zipFiles ZIP 파일 목록
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return ZipFileListResponse
|
||||||
|
*/
|
||||||
|
private ZipFileListResponse buildZipFileListResponse(
|
||||||
|
Basic modelInfo, Path baseDir, List<Path> zipFiles, HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// 요청에서 도메인 정보 추출
|
||||||
|
String scheme = request.getScheme(); // http 또는 https
|
||||||
|
String serverName = request.getServerName(); // localhost 또는 도메인
|
||||||
|
int serverPort = request.getServerPort(); // 8080 등
|
||||||
|
String contextPath = request.getContextPath(); // /api 등
|
||||||
|
|
||||||
|
// 기본 URL 구성
|
||||||
|
String baseUrl;
|
||||||
|
if ((scheme.equals("http") && serverPort == 80)
|
||||||
|
|| (scheme.equals("https") && serverPort == 443)) {
|
||||||
|
baseUrl = scheme + "://" + serverName + contextPath;
|
||||||
|
} else {
|
||||||
|
baseUrl = scheme + "://" + serverName + ":" + serverPort + contextPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ZipFileInfo> zipFileInfos = new ArrayList<>();
|
||||||
|
long totalSize = 0L;
|
||||||
|
|
||||||
|
for (Path zipFile : zipFiles) {
|
||||||
|
String zipFileName = zipFile.getFileName().toString();
|
||||||
|
long fileSize = Files.size(zipFile);
|
||||||
|
totalSize += fileSize;
|
||||||
|
|
||||||
|
// 파일명에서 버전 추출
|
||||||
|
String version = extractVersionFromZipFileName(zipFileName);
|
||||||
|
boolean isCurrent = version.equals(modelInfo.getModelVer());
|
||||||
|
|
||||||
|
// 전체 도메인 URL 포함한 다운로드 링크 생성
|
||||||
|
String downloadUrl =
|
||||||
|
baseUrl + "/api/models/downloadzip/" + modelInfo.getUuid() + "?file=" + zipFileName;
|
||||||
|
|
||||||
|
zipFileInfos.add(
|
||||||
|
ZipFileInfo.builder()
|
||||||
|
.fileName(zipFileName)
|
||||||
|
.filePath(zipFile.toString())
|
||||||
|
.version(version)
|
||||||
|
.fileSize(fileSize)
|
||||||
|
.fileSizeFormatted(formatFileSize(fileSize))
|
||||||
|
.lastModified(
|
||||||
|
Files.getLastModifiedTime(zipFile).toInstant().atZone(ZoneId.systemDefault()))
|
||||||
|
.isCurrent(isCurrent)
|
||||||
|
.downloadUrl(downloadUrl)
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
return ZipFileListResponse.builder()
|
||||||
|
.modelUuid(modelInfo.getUuid().toString())
|
||||||
|
.modelNo(modelInfo.getModelNo())
|
||||||
|
.modelVer(modelInfo.getModelVer())
|
||||||
|
.basePath(baseDir.toString())
|
||||||
|
.zipFiles(zipFileInfos)
|
||||||
|
.totalFiles(zipFileInfos.size())
|
||||||
|
.totalSize(totalSize)
|
||||||
|
.totalSizeFormatted(formatFileSize(totalSize))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Binary 다운로드 처리
|
||||||
|
*
|
||||||
|
* @param modelInfo 모델 정보
|
||||||
|
* @param baseDir 기본 디렉토리
|
||||||
|
* @param zipFiles ZIP 파일 목록
|
||||||
|
* @param fileName 개별 파일명 (선택)
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @param request HTTP 요청
|
||||||
|
* @return Binary 응답
|
||||||
|
*/
|
||||||
|
private ResponseEntity<?> handleBinaryDownload(
|
||||||
|
Basic modelInfo,
|
||||||
|
Path baseDir,
|
||||||
|
List<Path> zipFiles,
|
||||||
|
String fileName,
|
||||||
|
UUID uuid,
|
||||||
|
HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
// file 파라미터가 있으면 개별 파일 다운로드
|
||||||
|
if (fileName != null && !fileName.isEmpty()) {
|
||||||
|
log.info("개별 파일 다운로드 요청: fileName={}", fileName);
|
||||||
|
|
||||||
|
Path targetFile =
|
||||||
|
zipFiles.stream()
|
||||||
|
.filter(p -> p.getFileName().toString().equals(fileName))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (targetFile == null) {
|
||||||
|
log.warn("요청한 파일을 찾을 수 없음: fileName={}, basePath={}", fileName, baseDir);
|
||||||
|
throw new CustomApiException(
|
||||||
|
"NOT_FOUND", HttpStatus.NOT_FOUND, "요청한 파일을 찾을 수 없습니다: " + fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"개별 ZIP 파일 다운로드: fileName={}, fileSize={} bytes, basePath={}",
|
||||||
|
targetFile.getFileName(),
|
||||||
|
Files.size(targetFile),
|
||||||
|
baseDir);
|
||||||
|
|
||||||
|
return rangeDownloadResponder.buildZipResponse(targetFile, fileName, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
// file 파라미터가 없으면 모든 파일 다운로드
|
||||||
|
// 파일이 1개면 바로 다운로드
|
||||||
if (zipFiles.size() == 1) {
|
if (zipFiles.size() == 1) {
|
||||||
Path zipPath = zipFiles.get(0);
|
Path zipPath = zipFiles.get(0);
|
||||||
log.info(
|
log.info(
|
||||||
@@ -671,7 +965,7 @@ public class ModelTrainDetailService {
|
|||||||
return rangeDownloadResponder.buildZipResponse(zipPath, downloadFileName, request);
|
return rangeDownloadResponder.buildZipResponse(zipPath, downloadFileName, request);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 파일이 여러 개면 하나의 zip으로 묶어서 다운로드
|
// 파일이 여러 개면 하나의 zip으로 묶어서 다운로드
|
||||||
log.info("여러 ZIP 파일을 하나로 묶어서 다운로드: 총 {}개 파일", zipFiles.size());
|
log.info("여러 ZIP 파일을 하나로 묶어서 다운로드: 총 {}개 파일", zipFiles.size());
|
||||||
|
|
||||||
String combinedZipName = modelInfo.getModelNo() + "." + modelInfo.getModelVer() + ".all.zip";
|
String combinedZipName = modelInfo.getModelNo() + "." + modelInfo.getModelVer() + ".all.zip";
|
||||||
|
|||||||
@@ -305,7 +305,19 @@ public class ModelTrainMngService {
|
|||||||
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
||||||
|
|
||||||
// 데이터셋 임시파일 생성
|
// 데이터셋 임시파일 생성
|
||||||
trainJobService.createTmpFile(modelUuid);
|
List<Long> datasetList = null;
|
||||||
|
if (req.getTrainingDataset() != null) {
|
||||||
|
datasetList = req.getTrainingDataset().getDatasetList();
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isSingleDataset = datasetList != null && datasetList.size() == 1;
|
||||||
|
|
||||||
|
// 데이터셋 1개만 선택한 경우는 symbolic link 미생성 해도 됨 -> train 호출 시 그냥 데이터셋 request 경로로 호출
|
||||||
|
if (isSingleDataset) {
|
||||||
|
trainJobService.updateRequestPath(modelUuid, datasetList);
|
||||||
|
} else {
|
||||||
|
trainJobService.createTmpFile(modelUuid);
|
||||||
|
}
|
||||||
return modelUuid;
|
return modelUuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.kamco.cd.training.postgres.repository.train.ModelTestMetricsJobReposi
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -38,6 +39,10 @@ public class ModelTestMetricsJobCoreService {
|
|||||||
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
|
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId) {
|
||||||
|
return modelTestMetricsJobRepository.getSimpleTestMetricPackingInfo(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||||
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
|
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
|
||||||
}
|
}
|
||||||
@@ -51,4 +56,16 @@ public class ModelTestMetricsJobCoreService {
|
|||||||
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
||||||
modelTestMetricsJobRepository.updatePackingEnd(modelId, now, failSuccState);
|
modelTestMetricsJobRepository.updatePackingEnd(modelId, now, failSuccState);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 Epoch의 메트릭 정보 조회 (하이퍼파라미터별 ZIP 생성용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @param epoch Epoch 번호
|
||||||
|
* @param metricType 메트릭 타입 (fscore, precision, recall)
|
||||||
|
* @return 메트릭 JSON DTO
|
||||||
|
*/
|
||||||
|
public ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType) {
|
||||||
|
return modelTestMetricsJobRepository.getMetricsByEpoch(modelId, epoch, metricType);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -180,6 +180,9 @@ public class ModelTrainMngCoreService {
|
|||||||
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
||||||
entity.setRequestPath(req.getRequestPath());
|
entity.setRequestPath(req.getRequestPath());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
entity.setTmpFileStatus(req.getTmpFileStatus());
|
||||||
|
entity.setTmpFileEndDttm(req.getTmpFileEndDttm());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -416,6 +419,11 @@ public class ModelTrainMngCoreService {
|
|||||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||||
|
if (master.getStep2StrtDttm() != null) {
|
||||||
|
master.setStep2State(TrainStatusType.STOPPED.getId());
|
||||||
|
} else {
|
||||||
|
master.setStep1State(TrainStatusType.STOPPED.getId());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
||||||
@@ -673,4 +681,36 @@ public class ModelTrainMngCoreService {
|
|||||||
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
||||||
return modelDatasetMapRepository.findDatasetTestPath(modelId);
|
return modelDatasetMapRepository.findDatasetTestPath(modelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void updateTrainRequestPath(Long modelId, String datasetUid) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
// 임시폴더 UID업데이트
|
||||||
|
entity.setRequestPath(datasetUid);
|
||||||
|
entity.setReqTmpYn(false); // false 인 것은 train, test 실행 시 docker 명령어에 request 폴더를 바라보게 할 예정
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateTmpFileStatusStart(Long modelId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
entity.setReqTmpYn(true);
|
||||||
|
entity.setTmpFileStatus("IN_PROGRESS");
|
||||||
|
entity.setTmpFileStartDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateTmpFileStatusFail(Long modelId, String message) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
entity.setTmpFileStatus("FAIL");
|
||||||
|
entity.setTmpFileErrMessage(message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,21 @@ public class ModelMasterEntity {
|
|||||||
@Column(name = "packing_end_dttm")
|
@Column(name = "packing_end_dttm")
|
||||||
private ZonedDateTime packingEndDttm;
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
|
@Column(name = "req_tmp_yn")
|
||||||
|
private Boolean reqTmpYn;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_status")
|
||||||
|
private String tmpFileStatus;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_start_dttm")
|
||||||
|
private ZonedDateTime tmpFileStartDttm;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_end_dttm")
|
||||||
|
private ZonedDateTime tmpFileEndDttm;
|
||||||
|
|
||||||
|
@Column(name = "tmp_file_err_message", columnDefinition = "TEXT")
|
||||||
|
private String tmpFileErrMessage;
|
||||||
|
|
||||||
public ModelTrainMngDto.Basic toDto() {
|
public ModelTrainMngDto.Basic toDto() {
|
||||||
return new ModelTrainMngDto.Basic(
|
return new ModelTrainMngDto.Basic(
|
||||||
this.id,
|
this.id,
|
||||||
|
|||||||
@@ -80,6 +80,8 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
|
|||||||
modelMasterEntity.modelNo,
|
modelMasterEntity.modelNo,
|
||||||
modelMasterEntity.modelVer,
|
modelMasterEntity.modelVer,
|
||||||
modelMasterEntity.step1StrtDttm,
|
modelMasterEntity.step1StrtDttm,
|
||||||
|
modelMasterEntity.step1EndDttm,
|
||||||
|
modelMasterEntity.step2StrtDttm,
|
||||||
modelMasterEntity.step2EndDttm,
|
modelMasterEntity.step2EndDttm,
|
||||||
modelMasterEntity.statusCd,
|
modelMasterEntity.statusCd,
|
||||||
modelMasterEntity.trainType,
|
modelMasterEntity.trainType,
|
||||||
|
|||||||
@@ -189,7 +189,8 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
|||||||
modelHyperParamEntity.hueDelta,
|
modelHyperParamEntity.hueDelta,
|
||||||
Expressions.nullExpression(Integer.class),
|
Expressions.nullExpression(Integer.class),
|
||||||
Expressions.nullExpression(String.class),
|
Expressions.nullExpression(String.class),
|
||||||
modelHyperParamEntity.uuid))
|
modelHyperParamEntity.uuid,
|
||||||
|
modelMasterEntity.reqTmpYn))
|
||||||
.from(modelMasterEntity)
|
.from(modelMasterEntity)
|
||||||
.leftJoin(modelHyperParamEntity)
|
.leftJoin(modelHyperParamEntity)
|
||||||
.on(modelHyperParamEntity.id.eq(modelMasterEntity.hyperParamId))
|
.on(modelHyperParamEntity.id.eq(modelMasterEntity.hyperParamId))
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -18,9 +19,27 @@ public interface ModelTestMetricsJobRepositoryCustom {
|
|||||||
|
|
||||||
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 간단한 형식의 테스트 메트릭 정보 조회 (ZIP 파일용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @return 간단한 JSON 형식 DTO
|
||||||
|
*/
|
||||||
|
SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId);
|
||||||
|
|
||||||
ModelTestFileName findModelTestFileNames(Long modelId);
|
ModelTestFileName findModelTestFileNames(Long modelId);
|
||||||
|
|
||||||
void updatePackingStart(Long modelId, ZonedDateTime now);
|
void updatePackingStart(Long modelId, ZonedDateTime now);
|
||||||
|
|
||||||
void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState);
|
void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 특정 Epoch의 메트릭 정보 조회 (하이퍼파라미터별 ZIP 생성용)
|
||||||
|
*
|
||||||
|
* @param modelId 모델 ID
|
||||||
|
* @param epoch Epoch 번호
|
||||||
|
* @param metricType 메트릭 타입 (fscore, precision, recall)
|
||||||
|
* @return 메트릭 JSON DTO
|
||||||
|
*/
|
||||||
|
ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
|
|||||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
||||||
|
import static com.kamco.cd.training.postgres.entity.QModelMetricsValidationEntity.modelMetricsValidationEntity;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
|
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
|
||||||
@@ -10,6 +11,8 @@ import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleProperties;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -99,19 +102,19 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
// TO-BE: modelId, model(best_fscore_10) 같은 데이터가 있으면 update, 없으면 insert
|
// TO-BE: modelId, model(best_fscore_10) 같은 데이터가 있으면 update, 없으면 insert
|
||||||
String updateSql =
|
String updateSql =
|
||||||
"""
|
"""
|
||||||
UPDATE tb_model_metrics_test
|
UPDATE tb_model_metrics_test
|
||||||
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
|
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
|
||||||
detection_count=?, gt_count=?
|
detection_count=?, gt_count=?
|
||||||
WHERE model_id=? AND model=?
|
WHERE model_id=? AND model=?
|
||||||
""";
|
""";
|
||||||
|
|
||||||
String insertSql =
|
String insertSql =
|
||||||
"""
|
"""
|
||||||
INSERT INTO tb_model_metrics_test
|
INSERT INTO tb_model_metrics_test
|
||||||
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||||
detection_count, gt_count)
|
detection_count, gt_count)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""";
|
""";
|
||||||
|
|
||||||
// row 단위 처리 (batch 안에서 upsert)
|
// row 단위 처리 (batch 안에서 upsert)
|
||||||
for (Object[] row : batchArgs) {
|
for (Object[] row : batchArgs) {
|
||||||
@@ -155,6 +158,33 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
.fetchFirst();
|
.fetchFirst();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId) {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SimpleMetricJsonDto.class,
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
modelMasterEntity.modelVer,
|
||||||
|
Projections.constructor(
|
||||||
|
SimpleProperties.class,
|
||||||
|
modelMetricsTestEntity.f1Score,
|
||||||
|
modelMetricsTestEntity.precisions,
|
||||||
|
modelMetricsTestEntity.recall,
|
||||||
|
modelMetricsTestEntity.iou,
|
||||||
|
modelMetricsTrainEntity.loss)))
|
||||||
|
.from(modelMetricsTestEntity)
|
||||||
|
.innerJoin(modelMasterEntity)
|
||||||
|
.on(modelMetricsTestEntity.model.id.eq(modelMasterEntity.id))
|
||||||
|
.innerJoin(modelMetricsTrainEntity)
|
||||||
|
.on(
|
||||||
|
modelMetricsTestEntity.model.eq(modelMetricsTrainEntity.model),
|
||||||
|
modelMasterEntity.bestEpoch.eq(modelMetricsTrainEntity.epoch))
|
||||||
|
.where(modelMetricsTestEntity.model.id.eq(modelId))
|
||||||
|
.orderBy(modelMetricsTestEntity.createdDttm.desc())
|
||||||
|
.fetchFirst();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||||
return queryFactory
|
return queryFactory
|
||||||
@@ -187,4 +217,64 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
.where(modelMasterEntity.id.eq(modelId))
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModelMetricJsonDto getMetricsByEpoch(Long modelId, Integer epoch, String metricType) {
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
ModelMetricJsonDto.class,
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
modelMasterEntity.modelVer,
|
||||||
|
com.querydsl.core.types.dsl.Expressions.constant(metricType),
|
||||||
|
com.querydsl.core.types.dsl.Expressions.constant(epoch),
|
||||||
|
Projections.constructor(
|
||||||
|
Properties.class,
|
||||||
|
// Changed 메트릭
|
||||||
|
modelMetricsValidationEntity.changedFscore,
|
||||||
|
modelMetricsValidationEntity.changedPrecision,
|
||||||
|
modelMetricsValidationEntity.changedRecall,
|
||||||
|
// Unchanged 메트릭
|
||||||
|
modelMetricsValidationEntity.unchangedFscore,
|
||||||
|
modelMetricsValidationEntity.unchangedPrecision,
|
||||||
|
modelMetricsValidationEntity.unchangedRecall,
|
||||||
|
// Mean 메트릭
|
||||||
|
modelMetricsValidationEntity.mFscore,
|
||||||
|
modelMetricsValidationEntity.mPrecision,
|
||||||
|
modelMetricsValidationEntity.mRecall,
|
||||||
|
modelMetricsValidationEntity.mIou,
|
||||||
|
modelMetricsValidationEntity.mAcc,
|
||||||
|
// Overall Accuracy
|
||||||
|
modelMetricsValidationEntity.aAcc,
|
||||||
|
// Train 메트릭 (Loss, LR, Duration)
|
||||||
|
modelMetricsTrainEntity.loss,
|
||||||
|
modelMetricsTrainEntity.lr,
|
||||||
|
modelMetricsTrainEntity.durationTime),
|
||||||
|
Projections.constructor(
|
||||||
|
com.kamco.cd.training.train.dto.ModelTrainMetricsDto.TestMetrics.class,
|
||||||
|
modelMetricsTestEntity.model1,
|
||||||
|
modelMetricsTestEntity.tp,
|
||||||
|
modelMetricsTestEntity.fp,
|
||||||
|
modelMetricsTestEntity.fn,
|
||||||
|
modelMetricsTestEntity.precisions,
|
||||||
|
modelMetricsTestEntity.recall,
|
||||||
|
modelMetricsTestEntity.f1Score,
|
||||||
|
modelMetricsTestEntity.accuracy,
|
||||||
|
modelMetricsTestEntity.iou,
|
||||||
|
modelMetricsTestEntity.detectionCount,
|
||||||
|
modelMetricsTestEntity.gtCount)))
|
||||||
|
.from(modelMetricsValidationEntity)
|
||||||
|
.innerJoin(modelMasterEntity)
|
||||||
|
.on(modelMetricsValidationEntity.model.id.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(modelMetricsTrainEntity)
|
||||||
|
.on(
|
||||||
|
modelMetricsTrainEntity.model.id.eq(modelMasterEntity.id),
|
||||||
|
modelMetricsTrainEntity.epoch.eq(epoch))
|
||||||
|
.leftJoin(modelMetricsTestEntity)
|
||||||
|
.on(modelMetricsTestEntity.model.id.eq(modelId))
|
||||||
|
.where(
|
||||||
|
modelMetricsValidationEntity.model.id.eq(modelId),
|
||||||
|
modelMetricsValidationEntity.epoch.eq(epoch))
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.kamco.cd.training.train;
|
|||||||
|
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.train.dto.TrainingMetricsDto;
|
import com.kamco.cd.training.train.dto.TrainingMetricsDto;
|
||||||
|
import com.kamco.cd.training.train.dto.TrainingProgressDto;
|
||||||
import com.kamco.cd.training.train.service.DataSetCountersService;
|
import com.kamco.cd.training.train.service.DataSetCountersService;
|
||||||
import com.kamco.cd.training.train.service.TestJobService;
|
import com.kamco.cd.training.train.service.TestJobService;
|
||||||
import com.kamco.cd.training.train.service.TrainJobService;
|
import com.kamco.cd.training.train.service.TrainJobService;
|
||||||
@@ -298,4 +299,26 @@ public class TrainApiController {
|
|||||||
trainingMetricsService.getTrainingMetricsByModelUuid(modelUuid);
|
trainingMetricsService.getTrainingMetricsByModelUuid(modelUuid);
|
||||||
return ApiResponseDto.ok(response);
|
return ApiResponseDto.ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "학습 진행률 조회",
|
||||||
|
description = "UUID로 학습 진행률을 실시간 조회합니다. 기존 DB 구조를 활용하여 진행률을 계산합니다.")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = TrainingProgressDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "모델을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/progress/{uuid}")
|
||||||
|
public ApiResponseDto<TrainingProgressDto> getTrainingProgress(
|
||||||
|
@Parameter(description = "모델 UUID", required = true) @PathVariable UUID uuid) {
|
||||||
|
TrainingProgressDto progress = trainJobService.getTrainingProgress(uuid);
|
||||||
|
return ApiResponseDto.ok(progress);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public class EvalRunRequest {
|
|||||||
private Integer timeoutSeconds;
|
private Integer timeoutSeconds;
|
||||||
private String datasetFolder;
|
private String datasetFolder;
|
||||||
private String outputFolder;
|
private String outputFolder;
|
||||||
|
private Boolean reqTmpYn;
|
||||||
|
|
||||||
public String getOutputFolder() {
|
public String getOutputFolder() {
|
||||||
return this.outputFolder.toString();
|
return this.outputFolder.toString();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package com.kamco.cd.training.train.dto;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.util.Properties;
|
import java.nio.file.Path;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
@@ -23,6 +23,17 @@ public class ModelTrainMetricsDto {
|
|||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Schema(name = "BestPthInfo", description = "Best PTH 파일 정보")
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class BestPthInfo {
|
||||||
|
|
||||||
|
private String fileName; // best_changed_fscore_epoch_3.pth
|
||||||
|
private String metricType; // fscore, precision, recall
|
||||||
|
private Integer epoch; // 3
|
||||||
|
private Path filePath; // 파일 전체 경로
|
||||||
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class ModelMetricJsonDto {
|
public static class ModelMetricJsonDto {
|
||||||
@@ -33,20 +44,133 @@ public class ModelTrainMetricsDto {
|
|||||||
@JsonProperty("model_version")
|
@JsonProperty("model_version")
|
||||||
private String modelVersion;
|
private String modelVersion;
|
||||||
|
|
||||||
|
@JsonProperty("metric_type")
|
||||||
|
private String metricType; // fscore, precision, recall
|
||||||
|
|
||||||
|
private Integer epoch; // epoch 번호
|
||||||
|
|
||||||
private Properties properties;
|
private Properties properties;
|
||||||
|
|
||||||
|
@JsonProperty("test_metrics")
|
||||||
|
private TestMetrics testMetrics; // 테스트 메트릭 추가
|
||||||
|
|
||||||
|
// 기존 방식용 생성자 (metricType, epoch, testMetrics 없음)
|
||||||
|
public ModelMetricJsonDto(String cdModelType, String modelVersion, Properties properties) {
|
||||||
|
this.cdModelType = cdModelType;
|
||||||
|
this.modelVersion = modelVersion;
|
||||||
|
this.metricType = null;
|
||||||
|
this.epoch = null;
|
||||||
|
this.properties = properties;
|
||||||
|
this.testMetrics = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public static class TestMetrics {
|
||||||
|
|
||||||
|
private String model; // 모델명
|
||||||
|
|
||||||
|
@JsonProperty("true_positive")
|
||||||
|
private Long tp; // True Positive
|
||||||
|
|
||||||
|
@JsonProperty("false_positive")
|
||||||
|
private Long fp; // False Positive
|
||||||
|
|
||||||
|
@JsonProperty("false_negative")
|
||||||
|
private Long fn; // False Negative
|
||||||
|
|
||||||
|
private Float precisions; // Precision
|
||||||
|
|
||||||
|
private Float recall; // Recall
|
||||||
|
|
||||||
|
@JsonProperty("f1_score")
|
||||||
|
private Float f1Score; // F1 Score
|
||||||
|
|
||||||
|
private Float accuracy; // Accuracy
|
||||||
|
|
||||||
|
private Float iou; // IoU
|
||||||
|
|
||||||
|
@JsonProperty("detection_count")
|
||||||
|
private Long detectionCount; // Detection Count
|
||||||
|
|
||||||
|
@JsonProperty("gt_count")
|
||||||
|
private Long gtCount; // Ground Truth Count
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class Properties {
|
public static class Properties {
|
||||||
|
|
||||||
@JsonProperty("f1_score")
|
// 변화 탐지 관련 메트릭 (Changed)
|
||||||
private Float f1Score;
|
@JsonProperty("changed_fscore")
|
||||||
|
private Float changedFscore;
|
||||||
|
|
||||||
private Float precision;
|
@JsonProperty("changed_precision")
|
||||||
private Float recall;
|
private Float changedPrecision;
|
||||||
private Float loss;
|
|
||||||
private Double iou;
|
@JsonProperty("changed_recall")
|
||||||
|
private Float changedRecall;
|
||||||
|
|
||||||
|
// 비변화 관련 메트릭 (Unchanged)
|
||||||
|
@JsonProperty("unchanged_fscore")
|
||||||
|
private Float unchangedFscore;
|
||||||
|
|
||||||
|
@JsonProperty("unchanged_precision")
|
||||||
|
private Float unchangedPrecision;
|
||||||
|
|
||||||
|
@JsonProperty("unchanged_recall")
|
||||||
|
private Float unchangedRecall;
|
||||||
|
|
||||||
|
// 평균 메트릭 (Mean)
|
||||||
|
@JsonProperty("mean_fscore")
|
||||||
|
private Float mFscore;
|
||||||
|
|
||||||
|
@JsonProperty("mean_precision")
|
||||||
|
private Float mPrecision;
|
||||||
|
|
||||||
|
@JsonProperty("mean_recall")
|
||||||
|
private Float mRecall;
|
||||||
|
|
||||||
|
@JsonProperty("mean_iou")
|
||||||
|
private Float mIou;
|
||||||
|
|
||||||
|
@JsonProperty("mean_accuracy")
|
||||||
|
private Float mAcc;
|
||||||
|
|
||||||
|
// 전체 정확도 (Overall Accuracy)
|
||||||
|
@JsonProperty("overall_accuracy")
|
||||||
|
private Float aAcc;
|
||||||
|
|
||||||
|
// 학습 관련 메트릭
|
||||||
|
@JsonProperty("loss")
|
||||||
|
private Double loss;
|
||||||
|
|
||||||
|
@JsonProperty("learning_rate")
|
||||||
|
private Double lr;
|
||||||
|
|
||||||
|
@JsonProperty("duration_time")
|
||||||
|
private Float durationTime;
|
||||||
|
|
||||||
|
// 기존 방식용 생성자 (getTestMetricPackingInfo에서 사용)
|
||||||
|
public Properties(Float f1Score, Float precisions, Float recall, Float iou, Double loss) {
|
||||||
|
this.changedFscore = f1Score;
|
||||||
|
this.changedPrecision = precisions;
|
||||||
|
this.changedRecall = recall;
|
||||||
|
this.unchangedFscore = null;
|
||||||
|
this.unchangedPrecision = null;
|
||||||
|
this.unchangedRecall = null;
|
||||||
|
this.mFscore = null;
|
||||||
|
this.mPrecision = null;
|
||||||
|
this.mRecall = null;
|
||||||
|
this.mIou = iou;
|
||||||
|
this.mAcc = null;
|
||||||
|
this.aAcc = null;
|
||||||
|
this.loss = loss;
|
||||||
|
this.lr = null;
|
||||||
|
this.durationTime = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -56,4 +180,35 @@ public class ModelTrainMetricsDto {
|
|||||||
private String bestEpochFileName;
|
private String bestEpochFileName;
|
||||||
private String modelVersion;
|
private String modelVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 간단한 JSON 형식용 DTO (ZIP 파일 포함용) */
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class SimpleMetricJsonDto {
|
||||||
|
|
||||||
|
@JsonProperty("cd_model_type")
|
||||||
|
private String cdModelType;
|
||||||
|
|
||||||
|
@JsonProperty("model_version")
|
||||||
|
private String modelVersion;
|
||||||
|
|
||||||
|
private SimpleProperties properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 간단한 Properties (필수 메트릭만 포함) */
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class SimpleProperties {
|
||||||
|
|
||||||
|
@JsonProperty("f1_score")
|
||||||
|
private Float f1Score;
|
||||||
|
|
||||||
|
private Float precision;
|
||||||
|
|
||||||
|
private Float recall;
|
||||||
|
|
||||||
|
private Float iou;
|
||||||
|
|
||||||
|
private Double loss;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ public class TrainRunRequest {
|
|||||||
|
|
||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
|
|
||||||
|
private Boolean reqTmpYn; // tmp 심볼릭 링크를 쓰는지 아닌지 여부
|
||||||
|
|
||||||
public String getOutputFolder() {
|
public String getOutputFolder() {
|
||||||
return String.valueOf(this.outputFolder);
|
return String.valueOf(this.outputFolder);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.kamco.cd.training.train.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
/** 학습 진행률 조회 응답 DTO */
|
||||||
|
@Getter
|
||||||
|
@Builder
|
||||||
|
public class TrainingProgressDto {
|
||||||
|
|
||||||
|
// 기본 정보
|
||||||
|
private Long jobId;
|
||||||
|
private UUID modelUuid;
|
||||||
|
private String statusCd; // QUEUED/RUNNING/SUCCESS/FAILED
|
||||||
|
private String currentPhase; // 현재 단계 (계산된 값)
|
||||||
|
private Double progressPercent; // 진행률 (0.00 ~ 100.00, 계산된 값)
|
||||||
|
|
||||||
|
// Epoch 정보 (기존 DB 컬럼)
|
||||||
|
private Integer currentEpoch; // 현재 Epoch
|
||||||
|
private Integer totalEpoch; // 전체 Epoch
|
||||||
|
|
||||||
|
// 시간 정보 (기존 DB 컬럼) - ISO 8601 형식으로 직렬화
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
|
||||||
|
private ZonedDateTime queuedDttm; // 큐 등록 시각
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
|
||||||
|
private ZonedDateTime startedDttm; // 시작 시각
|
||||||
|
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
|
||||||
|
private ZonedDateTime finishedDttm; // 종료 시각 (완료/실패 시)
|
||||||
|
|
||||||
|
// 계산된 시간 정보
|
||||||
|
private Long elapsedSeconds; // 경과 시간 (초)
|
||||||
|
private Long estimatedRemainingSeconds; // 예상 남은 시간 (초)
|
||||||
|
|
||||||
|
// 상태 메시지
|
||||||
|
private String message; // 현재 상태 메시지 (계산된 값)
|
||||||
|
|
||||||
|
// 에러 정보 (실패 시)
|
||||||
|
private String errorMessage; // 에러 메시지 (기존 DB 컬럼)
|
||||||
|
}
|
||||||
@@ -158,12 +158,42 @@ public class DockerTrainService {
|
|||||||
lastEpoch.set(epoch);
|
lastEpoch.set(epoch);
|
||||||
lastIter.set(iter);
|
lastIter.set(iter);
|
||||||
|
|
||||||
|
// Step 구분 (컨테이너 이름으로 판별)
|
||||||
|
boolean isStep1 = containerName.startsWith("train-");
|
||||||
|
boolean isStep2 = containerName.startsWith("eval-");
|
||||||
|
|
||||||
|
// 진행률 계산 (Step별 구분)
|
||||||
|
double progress = 0.0;
|
||||||
|
if (maxEpochs > 0) {
|
||||||
|
// Epoch + Iteration 기반 정밀 진행률 계산
|
||||||
|
double epochProgress =
|
||||||
|
((double) (epoch - 1) + ((double) iter / totalIter)) / maxEpochs;
|
||||||
|
|
||||||
|
// Step1 (학습): 7.5% ~ 42.5% (0% ~ 50% 중 15% ~ 85%)
|
||||||
|
// Step2 (테스트): 57.5% ~ 92.5% (50% ~ 100% 중 15% ~ 85%)
|
||||||
|
if (isStep1) {
|
||||||
|
// Step1: 0% ~ 50% 범위, 그 중 15% ~ 85% = 7.5% ~ 42.5%
|
||||||
|
progress = 7.5 + (epochProgress * 35.0);
|
||||||
|
} else if (isStep2) {
|
||||||
|
// Step2: 50% ~ 100% 범위, 그 중 15% ~ 85% = 57.5% ~ 92.5%
|
||||||
|
progress = 57.5 + (epochProgress * 35.0);
|
||||||
|
} else {
|
||||||
|
// 기본값 (하위 호환)
|
||||||
|
progress = 15.0 + (epochProgress * 70.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String stepLabel = isStep1 ? "STEP1" : isStep2 ? "STEP2" : "UNKNOWN";
|
||||||
|
|
||||||
log.info(
|
log.info(
|
||||||
"[TRAIN] container={} epoch={} iter={}/{}",
|
"[TRAIN] {} container={} epoch={}/{} iter={}/{} | Progress: {}%",
|
||||||
|
stepLabel,
|
||||||
containerName,
|
containerName,
|
||||||
epoch,
|
epoch,
|
||||||
|
maxEpochs,
|
||||||
iter,
|
iter,
|
||||||
totalIter);
|
totalIter,
|
||||||
|
String.format("%.2f", progress));
|
||||||
|
|
||||||
modelTrainJobCoreService.updateEpoch(containerName, epoch);
|
modelTrainJobCoreService.updateEpoch(containerName, epoch);
|
||||||
}
|
}
|
||||||
@@ -271,7 +301,11 @@ public class DockerTrainService {
|
|||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(symbolicDir + ":/data"); // 요청할경로
|
if (req.getReqTmpYn()) {
|
||||||
|
c.add(symbolicDir + ":/data"); // 요청할경로 : tmp 심볼릭 사용하는 것이니 symbolicDir로 호출
|
||||||
|
} else {
|
||||||
|
c.add(requestDir + ":/data"); // 요청할경로 : tmp 심볼릭 사용하지 않으니 request로 호출
|
||||||
|
}
|
||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(responseDir + ":/checkpoints"); // 저장될경로
|
c.add(responseDir + ":/checkpoints"); // 저장될경로
|
||||||
|
|
||||||
@@ -472,11 +506,17 @@ public class DockerTrainService {
|
|||||||
|
|
||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||||
c.add("-v");
|
|
||||||
c.add(basePath + "/tmp:/data");
|
|
||||||
|
|
||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(responseDir + ":/checkpoints");
|
if (req.getReqTmpYn()) {
|
||||||
|
c.add(symbolicDir + ":/data"); // tmp 사용하는 모델은 심볼릭 링크
|
||||||
|
} else {
|
||||||
|
c.add(requestDir + ":/data"); // tmp 사용하지 않는 모델은 request 경로
|
||||||
|
}
|
||||||
|
|
||||||
|
c.add("-v");
|
||||||
|
// c.add(responseDir + ":/checkpoints");
|
||||||
|
c.add(responseDir + "/" + req.getOutputFolder() + ":/checkpoints");
|
||||||
|
|
||||||
c.add("kamco-cd-train:latest");
|
c.add("kamco-cd-train:latest");
|
||||||
|
|
||||||
@@ -484,7 +524,7 @@ public class DockerTrainService {
|
|||||||
c.add("/workspace/change-detection-code/run_evaluation_pipeline.py");
|
c.add("/workspace/change-detection-code/run_evaluation_pipeline.py");
|
||||||
|
|
||||||
addArg(c, "--dataset-folder", req.getDatasetFolder());
|
addArg(c, "--dataset-folder", req.getDatasetFolder());
|
||||||
addArg(c, "--output-folder", req.getOutputFolder());
|
// addArg(c, "--output-folder", req.getOutputFolder());
|
||||||
|
|
||||||
c.add("--epoch");
|
c.add("--epoch");
|
||||||
c.add(modelFile);
|
c.add(modelFile);
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTestMetricsJobCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTestMetricsJobCoreService;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.BestPthInfo;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
@@ -19,6 +21,8 @@ import java.time.ZonedDateTime;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
@@ -48,6 +52,9 @@ public class ModelTestMetricsJobService {
|
|||||||
@Value("${file.pt-path}")
|
@Value("${file.pt-path}")
|
||||||
private String ptPathDir;
|
private String ptPathDir;
|
||||||
|
|
||||||
|
@Value("${file.pt-FileName}")
|
||||||
|
private String ptFileName;
|
||||||
|
|
||||||
/** 결과 csv 파일 정보 등록 */
|
/** 결과 csv 파일 정보 등록 */
|
||||||
public void findTestValidMetricCsvFiles() {
|
public void findTestValidMetricCsvFiles() {
|
||||||
|
|
||||||
@@ -78,13 +85,13 @@ public class ModelTestMetricsJobService {
|
|||||||
/**
|
/**
|
||||||
* 베스트 에폭 zip파일 생성, 테스트결과 db등록
|
* 베스트 에폭 zip파일 생성, 테스트결과 db등록
|
||||||
*
|
*
|
||||||
* @param modelInfo
|
* @param modelInfo 모델 정보 (modelId, responsePath, uuid)
|
||||||
*/
|
*/
|
||||||
private void createFile(ResponsePathDto modelInfo) {
|
private void createFile(ResponsePathDto modelInfo) {
|
||||||
|
|
||||||
String testPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/test.csv";
|
String testPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/test.csv";
|
||||||
try (BufferedReader reader =
|
try (BufferedReader reader =
|
||||||
Files.newBufferedReader(Paths.get(testPath), StandardCharsets.UTF_8); ) {
|
Files.newBufferedReader(Paths.get(testPath), StandardCharsets.UTF_8)) {
|
||||||
|
|
||||||
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
||||||
|
|
||||||
@@ -133,8 +140,9 @@ public class ModelTestMetricsJobService {
|
|||||||
// 패키징할 파일 만들기
|
// 패키징할 파일 만들기
|
||||||
modelTestMetricsJobCoreService.updatePackingStart(modelInfo.getModelId(), ZonedDateTime.now());
|
modelTestMetricsJobCoreService.updatePackingStart(modelInfo.getModelId(), ZonedDateTime.now());
|
||||||
|
|
||||||
ModelMetricJsonDto jsonDto =
|
// 간단한 형식의 JSON 생성 (ZIP 파일용)
|
||||||
modelTestMetricsJobCoreService.getTestMetricPackingInfo(modelInfo.getModelId());
|
SimpleMetricJsonDto jsonDto =
|
||||||
|
modelTestMetricsJobCoreService.getSimpleTestMetricPackingInfo(modelInfo.getModelId());
|
||||||
try {
|
try {
|
||||||
writeJsonFile(
|
writeJsonFile(
|
||||||
jsonDto,
|
jsonDto,
|
||||||
@@ -158,37 +166,270 @@ public class ModelTestMetricsJobService {
|
|||||||
fileInfo.getBestEpochFileName() + ".pth",
|
fileInfo.getBestEpochFileName() + ".pth",
|
||||||
fileInfo.getModelVersion() + ".json");
|
fileInfo.getModelVersion() + ".json");
|
||||||
|
|
||||||
List<Path> files = new ArrayList<>();
|
|
||||||
try (Stream<Path> s = Files.list(responsePath)) {
|
|
||||||
files.addAll(
|
|
||||||
s.filter(Files::isRegularFile)
|
|
||||||
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
try (Stream<Path> s = Files.list(Path.of(ptPathDir))) {
|
|
||||||
files.addAll(
|
|
||||||
s.filter(Files::isRegularFile)
|
|
||||||
.limit(1) // yolov8_6th-6m.pt 파일 1개만
|
|
||||||
.collect(Collectors.toList()));
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
zipFiles(files, zipPath);
|
List<Path> files = new ArrayList<>();
|
||||||
|
try (Stream<Path> s = Files.list(responsePath)) {
|
||||||
|
files.addAll(
|
||||||
|
s.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
||||||
|
.collect(Collectors.toList()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// PT 파일 정확하게 조회
|
||||||
|
Path ptFile = Paths.get(ptPathDir, ptFileName);
|
||||||
|
if (Files.exists(ptFile)) {
|
||||||
|
files.add(ptFile);
|
||||||
|
} else {
|
||||||
|
log.warn("PT 파일을 찾을 수 없습니다: {}", ptFile);
|
||||||
|
throw new IOException("PT 파일 누락: " + ptFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 기본 ZIP 생성
|
||||||
|
zipFiles(files, zipPath);
|
||||||
|
log.info(" 기본 ZIP 생성 완료: {}", zipPath.getFileName());
|
||||||
|
|
||||||
|
// 개별 best*.pth ZIP 생성
|
||||||
|
int individualZipCount = createIndividualBestPthZips(modelInfo, responsePath);
|
||||||
|
|
||||||
|
// 모든 ZIP 생성 성공 시 COMPLETED
|
||||||
modelTestMetricsJobCoreService.updatePackingEnd(
|
modelTestMetricsJobCoreService.updatePackingEnd(
|
||||||
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.COMPLETED.getId());
|
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.COMPLETED.getId());
|
||||||
|
|
||||||
|
log.info(" 전체 ZIP 생성 완료: 기본 1개 + 개별 {}개", individualZipCount);
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
modelTestMetricsJobCoreService.updatePackingEnd(
|
modelTestMetricsJobCoreService.updatePackingEnd(
|
||||||
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.ERROR.getId());
|
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.ERROR.getId());
|
||||||
|
log.error("ZIP 생성 중 오류 발생: modelId={}", modelInfo.getModelId(), e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Response 폴더의 모든 best*.pth 파일을 각각 개별 ZIP 파일로 생성
|
||||||
|
*
|
||||||
|
* <p>각 PTH 파일의 Epoch과 메트릭 타입을 파싱하여 해당 Epoch의 메트릭 정보를 조회한 후, 개별 JSON 파일을 생성하고 ZIP으로 패키징합니다.
|
||||||
|
*
|
||||||
|
* @param modelInfo 모델 정보
|
||||||
|
* @param responsePath Response 디렉토리 경로
|
||||||
|
* @return 생성된 개별 ZIP 파일 개수
|
||||||
|
*/
|
||||||
|
private int createIndividualBestPthZips(ResponsePathDto modelInfo, Path responsePath) {
|
||||||
|
|
||||||
|
log.info("=== 개별 best*.pth ZIP 파일 생성 시작: modelId={} ===", modelInfo.getModelId());
|
||||||
|
|
||||||
|
int successCount = 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Response 폴더에서 모든 best*.pth 파일 찾기
|
||||||
|
List<Path> bestPthFiles;
|
||||||
|
try (Stream<Path> stream = Files.list(responsePath)) {
|
||||||
|
bestPthFiles =
|
||||||
|
stream
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.filter(p -> p.getFileName().toString().startsWith("best"))
|
||||||
|
.filter(p -> p.getFileName().toString().endsWith(".pth"))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bestPthFiles.isEmpty()) {
|
||||||
|
log.warn("best*.pth 파일을 찾을 수 없습니다: path={}", responsePath);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("발견된 best*.pth 파일 개수: {}", bestPthFiles.size());
|
||||||
|
|
||||||
|
// 2. PT 파일 경로 확인 (모든 ZIP에 공통으로 포함)
|
||||||
|
Path ptFile = Paths.get(ptPathDir, ptFileName);
|
||||||
|
if (!Files.exists(ptFile)) {
|
||||||
|
log.warn("PT 파일을 찾을 수 없습니다: {}", ptFile);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// model_config.py 경로 (선택적)
|
||||||
|
Path modelConfigPath = responsePath.resolve("model_config.py");
|
||||||
|
|
||||||
|
// 3. 각 best*.pth 파일별로 개별 ZIP 생성
|
||||||
|
for (Path bestPthFile : bestPthFiles) {
|
||||||
|
String pthFileName = bestPthFile.getFileName().toString();
|
||||||
|
log.info("처리 중인 best PTH 파일: {}", pthFileName);
|
||||||
|
|
||||||
|
Path individualJsonPath = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 파싱 성공 여부와 관계없이 기본 간단한 JSON 사용
|
||||||
|
// (개별 ZIP도 동일한 간단한 형식 적용)
|
||||||
|
log.debug("PTH 파일: {}, 간단한 JSON 형식 사용", pthFileName);
|
||||||
|
|
||||||
|
SimpleMetricJsonDto simpleJsonDto =
|
||||||
|
modelTestMetricsJobCoreService.getSimpleTestMetricPackingInfo(modelInfo.getModelId());
|
||||||
|
|
||||||
|
if (simpleJsonDto == null) {
|
||||||
|
log.warn("메트릭 정보 없음, 건너뜀: {}", pthFileName);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3-2. 개별 JSON 파일 생성
|
||||||
|
individualJsonPath = createIndividualJson(responsePath, pthFileName, simpleJsonDto);
|
||||||
|
log.debug("개별 JSON 생성: file={}", individualJsonPath.getFileName());
|
||||||
|
|
||||||
|
// 3-3. 개별 ZIP 파일명 생성
|
||||||
|
// 형식: {modelVersion}.{pthFileNameWithoutExt}.zip
|
||||||
|
// 예: G1_000001.best_fscore_5.zip, G1_000001.best_precision_7.zip
|
||||||
|
String pthFileNameWithoutExt = pthFileName.replace(".pth", "");
|
||||||
|
|
||||||
|
// modelVersion 조회 (JSON에서 추출)
|
||||||
|
ModelTestFileName fileInfo =
|
||||||
|
modelTestMetricsJobCoreService.findModelTestFileNames(modelInfo.getModelId());
|
||||||
|
String individualZipName =
|
||||||
|
fileInfo.getModelVersion() + "." + pthFileNameWithoutExt + ".zip";
|
||||||
|
Path individualZipPath = responsePath.resolve(individualZipName);
|
||||||
|
|
||||||
|
// 3-4. ZIP에 포함될 파일 목록 구성
|
||||||
|
List<Path> zipFileList = new ArrayList<>();
|
||||||
|
zipFileList.add(bestPthFile); // best*.pth 파일
|
||||||
|
zipFileList.add(individualJsonPath); // 개별 JSON 파일
|
||||||
|
zipFileList.add(ptFile); // PT 파일
|
||||||
|
|
||||||
|
// model_config.py 파일이 있으면 추가
|
||||||
|
if (Files.exists(modelConfigPath)) {
|
||||||
|
zipFileList.add(modelConfigPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3-5. 개별 ZIP 생성
|
||||||
|
zipFiles(zipFileList, individualZipPath);
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"개별 ZIP 생성 완료: fileName={}, pthFile={}, size={} bytes",
|
||||||
|
individualZipName,
|
||||||
|
pthFileName,
|
||||||
|
Files.size(individualZipPath));
|
||||||
|
|
||||||
|
// 3-6. 임시 JSON 파일 정리
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(individualJsonPath);
|
||||||
|
log.debug("임시 JSON 파일 삭제: {}", individualJsonPath.getFileName());
|
||||||
|
} catch (IOException deleteEx) {
|
||||||
|
log.warn("임시 JSON 파일 삭제 실패: {}", individualJsonPath, deleteEx);
|
||||||
|
}
|
||||||
|
|
||||||
|
successCount++;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("개별 ZIP 생성 실패: pthFile={}", pthFileName, e);
|
||||||
|
|
||||||
|
// 실패한 임시 JSON 파일도 정리 시도
|
||||||
|
if (individualJsonPath != null) {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(individualJsonPath);
|
||||||
|
} catch (IOException deleteEx) {
|
||||||
|
log.warn("실패한 임시 JSON 파일 삭제 실패: {}", individualJsonPath, deleteEx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 개별 ZIP 실패는 전체 프로세스를 중단하지 않음
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("=== 개별 best*.pth ZIP 파일 생성 완료: 성공 {}/{}개 ===", successCount, bestPthFiles.size());
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("개별 ZIP 생성 중 오류 발생", e);
|
||||||
|
// 에러 발생해도 기존 ZIP은 이미 생성되었으므로 예외를 던지지 않음
|
||||||
|
}
|
||||||
|
|
||||||
|
return successCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PTH 파일명에서 Epoch과 메트릭 타입을 추출
|
||||||
|
*
|
||||||
|
* <p>지원되는 파일명 패턴:
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>best_{metricType}_{epoch}.pth (예: best_fscore_5.pth)
|
||||||
|
* <li>best_epoch_{epoch}.pth (예: best_epoch_10.pth)
|
||||||
|
* <li>best_changed_{metricType}_{epoch}.pth (예: best_changed_fscore_5.pth)
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @param fileName PTH 파일명
|
||||||
|
* @return 파싱된 PTH 정보, 실패 시 null
|
||||||
|
*/
|
||||||
|
private BestPthInfo parsePthFileName(String fileName) {
|
||||||
|
try {
|
||||||
|
// 패턴 1: best_changed_{metricType}_{epoch}.pth
|
||||||
|
Pattern pattern1 = Pattern.compile("best_changed_([a-z_]+)_(\\d+)\\.pth");
|
||||||
|
Matcher matcher1 = pattern1.matcher(fileName);
|
||||||
|
if (matcher1.matches()) {
|
||||||
|
String metricType = matcher1.group(1); // "fscore", "precision", "recall"
|
||||||
|
Integer epoch = Integer.parseInt(matcher1.group(2));
|
||||||
|
Path filePath = Paths.get(fileName);
|
||||||
|
return new BestPthInfo(fileName, metricType, epoch, filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 패턴 2: best_{metricType}_{epoch}.pth
|
||||||
|
Pattern pattern2 = Pattern.compile("best_([a-z_]+)_(\\d+)\\.pth");
|
||||||
|
Matcher matcher2 = pattern2.matcher(fileName);
|
||||||
|
if (matcher2.matches()) {
|
||||||
|
String metricType = matcher2.group(1); // "fscore", "precision", "recall"
|
||||||
|
Integer epoch = Integer.parseInt(matcher2.group(2));
|
||||||
|
Path filePath = Paths.get(fileName);
|
||||||
|
return new BestPthInfo(fileName, metricType, epoch, filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 패턴 3: best_epoch_{epoch}.pth (메트릭 타입 없음)
|
||||||
|
Pattern pattern3 = Pattern.compile("best_epoch_(\\d+)\\.pth");
|
||||||
|
Matcher matcher3 = pattern3.matcher(fileName);
|
||||||
|
if (matcher3.matches()) {
|
||||||
|
Integer epoch = Integer.parseInt(matcher3.group(1));
|
||||||
|
Path filePath = Paths.get(fileName);
|
||||||
|
// 메트릭 타입을 "epoch"로 설정 (기본값)
|
||||||
|
return new BestPthInfo(fileName, "epoch", epoch, filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.warn("알 수 없는 PTH 파일명 패턴: {}", fileName);
|
||||||
|
return null;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("PTH 파일명 파싱 중 오류: {}", fileName, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 개별 JSON 파일 생성
|
||||||
|
*
|
||||||
|
* @param responsePath Response 디렉토리 경로
|
||||||
|
* @param pthFileName PTH 파일명
|
||||||
|
* @param jsonDto JSON 메타데이터
|
||||||
|
* @return 생성된 JSON 파일 경로
|
||||||
|
* @throws IOException JSON 쓰기 실패 시
|
||||||
|
*/
|
||||||
|
private Path createIndividualJson(
|
||||||
|
Path responsePath, String pthFileName, ModelMetricJsonDto jsonDto) throws IOException {
|
||||||
|
String individualJsonName = pthFileName.replace(".pth", ".json");
|
||||||
|
Path individualJsonPath = responsePath.resolve(individualJsonName);
|
||||||
|
writeJsonFile(jsonDto, individualJsonPath);
|
||||||
|
return individualJsonPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 개별 JSON 파일 생성 (간단한 형식)
|
||||||
|
*
|
||||||
|
* @param responsePath Response 디렉토리 경로
|
||||||
|
* @param pthFileName PTH 파일명
|
||||||
|
* @param jsonDto 간단한 JSON 메타데이터
|
||||||
|
* @return 생성된 JSON 파일 경로
|
||||||
|
* @throws IOException JSON 쓰기 실패 시
|
||||||
|
*/
|
||||||
|
private Path createIndividualJson(
|
||||||
|
Path responsePath, String pthFileName, SimpleMetricJsonDto jsonDto) throws IOException {
|
||||||
|
String individualJsonName = pthFileName.replace(".pth", ".json");
|
||||||
|
Path individualJsonPath = responsePath.resolve(individualJsonName);
|
||||||
|
writeJsonFile(jsonDto, individualJsonPath);
|
||||||
|
return individualJsonPath;
|
||||||
|
}
|
||||||
|
|
||||||
private void writeJsonFile(Object data, Path outputPath) throws IOException {
|
private void writeJsonFile(Object data, Path outputPath) throws IOException {
|
||||||
|
|
||||||
Path parent = outputPath.getParent();
|
Path parent = outputPath.getParent();
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ public class TestJobService {
|
|||||||
params.put("epoch", epoch);
|
params.put("epoch", epoch);
|
||||||
params.put("datasetFolder", trainRunRequest.getDatasetFolder());
|
params.put("datasetFolder", trainRunRequest.getDatasetFolder());
|
||||||
params.put("outputFolder", trainRunRequest.getOutputFolder());
|
params.put("outputFolder", trainRunRequest.getOutputFolder());
|
||||||
|
params.put("reqTmpYn", trainRunRequest.getReqTmpYn());
|
||||||
|
|
||||||
int nextAttemptNo = modelTrainJobCoreService.findMaxAttemptNo(modelId) + 1;
|
int nextAttemptNo = modelTrainJobCoreService.findMaxAttemptNo(modelId) + 1;
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import com.kamco.cd.training.train.dto.ModelTrainJobQueuedEvent;
|
|||||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||||
import com.kamco.cd.training.train.dto.OutputResult;
|
import com.kamco.cd.training.train.dto.OutputResult;
|
||||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||||
|
import com.kamco.cd.training.train.dto.TrainingProgressDto;
|
||||||
|
import com.kamco.cd.training.train.util.TrainingProgressCalculator;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
@@ -204,6 +206,18 @@ public class TrainJobService {
|
|||||||
return jobId;
|
return jobId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 1개일 때, 파일 경로 업데이트
|
||||||
|
*
|
||||||
|
* @param modelUuid
|
||||||
|
* @param datasetList
|
||||||
|
*/
|
||||||
|
public void updateRequestPath(UUID modelUuid, List<Long> datasetList) {
|
||||||
|
Long modelId = modelTrainMngCoreService.findModelIdByUuid(modelUuid);
|
||||||
|
List<String> datasetUid = modelTrainMngCoreService.findDatasetUid(datasetList);
|
||||||
|
modelTrainMngCoreService.updateTrainRequestPath(modelId, datasetUid.getFirst());
|
||||||
|
}
|
||||||
|
|
||||||
private enum ResumeMode {
|
private enum ResumeMode {
|
||||||
NONE, // 새로 시작
|
NONE, // 새로 시작
|
||||||
REQUIRE // 이어하기
|
REQUIRE // 이어하기
|
||||||
@@ -274,6 +288,9 @@ public class TrainJobService {
|
|||||||
List<String> uids = modelTrainMngCoreService.findDatasetUid(datasetIds);
|
List<String> uids = modelTrainMngCoreService.findDatasetUid(datasetIds);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 1. 시작 상태 업데이트
|
||||||
|
modelTrainMngCoreService.updateTmpFileStatusStart(modelId);
|
||||||
|
|
||||||
// 데이터셋 심볼링크 생성
|
// 데이터셋 심볼링크 생성
|
||||||
// String pathUid = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
|
// String pathUid = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
|
||||||
// train path 모델 클래스별 조회
|
// train path 모델 클래스별 조회
|
||||||
@@ -298,6 +315,8 @@ public class TrainJobService {
|
|||||||
|
|
||||||
ModelTrainMngDto.UpdateReq updateReq = new ModelTrainMngDto.UpdateReq();
|
ModelTrainMngDto.UpdateReq updateReq = new ModelTrainMngDto.UpdateReq();
|
||||||
updateReq.setRequestPath(raw);
|
updateReq.setRequestPath(raw);
|
||||||
|
updateReq.setTmpFileStatus("COMPLETE");
|
||||||
|
updateReq.setTmpFileEndDttm(ZonedDateTime.now());
|
||||||
|
|
||||||
// 학습모델을 수정한다.
|
// 학습모델을 수정한다.
|
||||||
modelTrainMngCoreService.updateModelMaster(modelId, updateReq);
|
modelTrainMngCoreService.updateModelMaster(modelId, updateReq);
|
||||||
@@ -311,6 +330,9 @@ public class TrainJobService {
|
|||||||
(uids == null ? null : uids.size()),
|
(uids == null ? null : uids.size()),
|
||||||
e);
|
e);
|
||||||
|
|
||||||
|
// 3. 실패 처리
|
||||||
|
modelTrainMngCoreService.updateTmpFileStatusFail(modelId, e.getMessage());
|
||||||
|
|
||||||
// 런타임 예외로 래핑하되, 메시지에 핵심 정보 포함
|
// 런타임 예외로 래핑하되, 메시지에 핵심 정보 포함
|
||||||
throw new CustomApiException(
|
throw new CustomApiException(
|
||||||
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "임시 데이터셋 생성에 실패했습니다.");
|
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "임시 데이터셋 생성에 실패했습니다.");
|
||||||
@@ -446,4 +468,136 @@ public class TrainJobService {
|
|||||||
modelTrainMngCoreService.markStep1Stop(job.getModelId(), msg);
|
modelTrainMngCoreService.markStep1Stop(job.getModelId(), msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UUID로 학습 진행률 조회 기존 DB 컬럼만을 활용하여 실시간으로 진행률 계산
|
||||||
|
*
|
||||||
|
* @param uuid 모델 UUID
|
||||||
|
* @return 학습 진행률 정보
|
||||||
|
*/
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public TrainingProgressDto getTrainingProgress(UUID uuid) {
|
||||||
|
// 1. UUID로 모델 조회
|
||||||
|
Long modelId = getModelIdByUuid(uuid);
|
||||||
|
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelById(modelId);
|
||||||
|
|
||||||
|
// 2. Step 상태 확인 (step1Status, step2Status)
|
||||||
|
String step1Status = model.getStep1Status(); // READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR
|
||||||
|
String step2Status = model.getStep2Status(); // READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR
|
||||||
|
|
||||||
|
// 3. 현재 실행중인 Job ID 확인
|
||||||
|
Long jobId = model.getCurrentAttemptId();
|
||||||
|
|
||||||
|
if (jobId == null) {
|
||||||
|
// Job이 없는 경우 모델 상태만 반환
|
||||||
|
// Step1 완료 여부에 따라 진행률 결정
|
||||||
|
double progressPercent = 0.0;
|
||||||
|
String currentPhase = "NOT_STARTED";
|
||||||
|
|
||||||
|
if ("COMPLETED".equals(step1Status) && "COMPLETED".equals(step2Status)) {
|
||||||
|
progressPercent = 100.0;
|
||||||
|
currentPhase = "COMPLETED";
|
||||||
|
} else if ("COMPLETED".equals(step1Status)) {
|
||||||
|
progressPercent = 50.0;
|
||||||
|
currentPhase = "STEP1_COMPLETED";
|
||||||
|
}
|
||||||
|
|
||||||
|
return TrainingProgressDto.builder()
|
||||||
|
.modelUuid(uuid)
|
||||||
|
.statusCd(model.getStatusCd())
|
||||||
|
.currentPhase(currentPhase)
|
||||||
|
.progressPercent(progressPercent)
|
||||||
|
.message(getMessageForPhase(currentPhase, null, null))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Job 정보 조회 (기존 컬럼만 사용)
|
||||||
|
ModelTrainJobDto job =
|
||||||
|
modelTrainJobCoreService
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new IllegalStateException("Job을 찾을 수 없습니다: " + jobId));
|
||||||
|
|
||||||
|
// 5. totalEpoch 추출 (DB 컬럼 우선, 없으면 params_json에서 추출)
|
||||||
|
Integer totalEpoch = job.getTotalEpoch();
|
||||||
|
if (totalEpoch == null && job.getParamsJson() != null) {
|
||||||
|
Object totalEpochObj = job.getParamsJson().get("totalEpoch");
|
||||||
|
if (totalEpochObj != null) {
|
||||||
|
totalEpoch = Integer.valueOf(String.valueOf(totalEpochObj));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. jobType 추출 (TRAIN/EVAL)
|
||||||
|
String jobType = "TRAIN"; // 기본값
|
||||||
|
if (job.getParamsJson() != null) {
|
||||||
|
Object jobTypeObj = job.getParamsJson().get("jobType");
|
||||||
|
if (jobTypeObj != null) {
|
||||||
|
jobType = String.valueOf(jobTypeObj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 진행률 계산 (Step 구분하여 계산)
|
||||||
|
double progressPercent =
|
||||||
|
TrainingProgressCalculator.calculateProgress(
|
||||||
|
job.getStatusCd(),
|
||||||
|
job.getCurrentEpoch(),
|
||||||
|
totalEpoch,
|
||||||
|
job.getStartedDttm(),
|
||||||
|
job.getFinishedDttm(),
|
||||||
|
jobType,
|
||||||
|
step1Status,
|
||||||
|
step2Status);
|
||||||
|
|
||||||
|
// 8. 현재 Phase 추정
|
||||||
|
String currentPhase =
|
||||||
|
TrainingProgressCalculator.estimateCurrentPhase(
|
||||||
|
job.getStatusCd(), job.getCurrentEpoch(), totalEpoch, job.getStartedDttm(), jobType);
|
||||||
|
|
||||||
|
// 9. 경과 시간 계산
|
||||||
|
Long elapsedSeconds = TrainingProgressCalculator.calculateElapsedSeconds(job.getStartedDttm());
|
||||||
|
|
||||||
|
// 10. 예상 남은 시간 계산
|
||||||
|
Long estimatedRemaining =
|
||||||
|
TrainingProgressCalculator.estimateRemainingSeconds(progressPercent, elapsedSeconds);
|
||||||
|
|
||||||
|
// 11. 상태 메시지 생성
|
||||||
|
String message =
|
||||||
|
TrainingProgressCalculator.generateProgressMessage(
|
||||||
|
currentPhase, job.getCurrentEpoch(), totalEpoch);
|
||||||
|
|
||||||
|
// 12. DTO 생성 및 반환
|
||||||
|
return TrainingProgressDto.builder()
|
||||||
|
.jobId(job.getId())
|
||||||
|
.modelUuid(uuid)
|
||||||
|
.statusCd(job.getStatusCd())
|
||||||
|
.currentPhase(currentPhase)
|
||||||
|
.progressPercent(progressPercent)
|
||||||
|
.currentEpoch(job.getCurrentEpoch())
|
||||||
|
.totalEpoch(totalEpoch)
|
||||||
|
.queuedDttm(job.getQueuedDttm())
|
||||||
|
.startedDttm(job.getStartedDttm())
|
||||||
|
.finishedDttm(job.getFinishedDttm())
|
||||||
|
.elapsedSeconds(elapsedSeconds)
|
||||||
|
.estimatedRemainingSeconds(estimatedRemaining)
|
||||||
|
.message(message)
|
||||||
|
.errorMessage(job.getErrorMessage())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase에 맞는 메시지 반환 (Job이 없는 경우)
|
||||||
|
*
|
||||||
|
* @param phase 현재 Phase
|
||||||
|
* @param currentEpoch 현재 Epoch
|
||||||
|
* @param totalEpoch 전체 Epoch
|
||||||
|
* @return 상태 메시지
|
||||||
|
*/
|
||||||
|
private String getMessageForPhase(String phase, Integer currentEpoch, Integer totalEpoch) {
|
||||||
|
if ("COMPLETED".equals(phase)) {
|
||||||
|
return "모든 학습 및 테스트가 완료되었습니다.";
|
||||||
|
} else if ("STEP1_COMPLETED".equals(phase)) {
|
||||||
|
return "학습이 완료되었습니다. 테스트를 시작할 수 있습니다.";
|
||||||
|
} else {
|
||||||
|
return "학습 작업이 시작되지 않았습니다.";
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ public class TrainJobWorker {
|
|||||||
(isEval ? "eval-" : "train-") + jobId + "-" + params.get("uuid").toString().substring(0, 8);
|
(isEval ? "eval-" : "train-") + jobId + "-" + params.get("uuid").toString().substring(0, 8);
|
||||||
|
|
||||||
String type = isEval ? "TEST" : "TRAIN";
|
String type = isEval ? "TEST" : "TRAIN";
|
||||||
|
String step = isEval ? "STEP2" : "STEP1";
|
||||||
|
|
||||||
Integer totalEpoch = null;
|
Integer totalEpoch = null;
|
||||||
if (params.containsKey("totalEpoch")) {
|
if (params.containsKey("totalEpoch")) {
|
||||||
@@ -65,6 +66,21 @@ public class TrainJobWorker {
|
|||||||
totalEpoch = Integer.parseInt(params.get("totalEpoch").toString());
|
totalEpoch = Integer.parseInt(params.get("totalEpoch").toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Phase 1: 준비 단계
|
||||||
|
// Step1: 0% ~ 2.5%, Step2: 50% ~ 52.5%
|
||||||
|
double preparingProgress = isEval ? 50.0 : 0.0;
|
||||||
|
log.info(
|
||||||
|
"[JOB] {} jobId={} | Phase: PREPARING | Progress: {}%",
|
||||||
|
step, jobId, String.format("%.1f", preparingProgress + 2.5));
|
||||||
|
|
||||||
|
// Phase 2: 컨테이너 시작
|
||||||
|
// Step1: 2.5% ~ 5%, Step2: 52.5% ~ 55%
|
||||||
|
double containerStartProgress = isEval ? 52.5 : 2.5;
|
||||||
|
log.info(
|
||||||
|
"[JOB] {} jobId={} | Phase: CONTAINER_STARTING | Progress: {}%",
|
||||||
|
step, jobId, String.format("%.1f", containerStartProgress + 2.5));
|
||||||
|
|
||||||
log.info("[JOB] markRunning start jobId={}, containerName={}", jobId, containerName);
|
log.info("[JOB] markRunning start jobId={}, containerName={}", jobId, containerName);
|
||||||
// 실행 시작 처리
|
// 실행 시작 처리
|
||||||
modelTrainJobCoreService.markRunning(
|
modelTrainJobCoreService.markRunning(
|
||||||
@@ -87,14 +103,24 @@ public class TrainJobWorker {
|
|||||||
evalReq.setTimeoutSeconds(null);
|
evalReq.setTimeoutSeconds(null);
|
||||||
evalReq.setDatasetFolder(datasetFolder);
|
evalReq.setDatasetFolder(datasetFolder);
|
||||||
evalReq.setOutputFolder(outputFolder);
|
evalReq.setOutputFolder(outputFolder);
|
||||||
|
evalReq.setReqTmpYn((Boolean) params.get("reqTmpYn"));
|
||||||
log.info("[JOB] selected test epoch={}", epoch);
|
log.info("[JOB] selected test epoch={}", epoch);
|
||||||
|
|
||||||
|
// Phase 3: 테스트 시작
|
||||||
|
// Step2: 55% ~ 57.5%
|
||||||
|
log.info("[JOB] STEP2 jobId={} | Phase: EVAL_STARTED | Progress: 57.5%", jobId);
|
||||||
|
|
||||||
// 도커 실행 후 로그 수집
|
// 도커 실행 후 로그 수집
|
||||||
result = dockerTrainService.runEvalSync(containerName, evalReq);
|
result = dockerTrainService.runEvalSync(containerName, evalReq);
|
||||||
} else {
|
} else {
|
||||||
// step1 진행중 처리
|
// step1 진행중 처리
|
||||||
modelTrainMngCoreService.markStep1InProgress(modelId, jobId);
|
modelTrainMngCoreService.markStep1InProgress(modelId, jobId);
|
||||||
TrainRunRequest trainReq = toTrainRunRequest(params);
|
TrainRunRequest trainReq = toTrainRunRequest(params);
|
||||||
|
|
||||||
|
// Phase 3: 학습 시작
|
||||||
|
// Step1: 5% ~ 7.5%
|
||||||
|
log.info("[JOB] STEP1 jobId={} | Phase: TRAINING_STARTED | Progress: 7.5%", jobId);
|
||||||
|
|
||||||
// 도커 실행 후 로그 수집
|
// 도커 실행 후 로그 수집
|
||||||
result = dockerTrainService.runTrainSync(trainReq, containerName);
|
result = dockerTrainService.runTrainSync(trainReq, containerName);
|
||||||
}
|
}
|
||||||
@@ -108,11 +134,25 @@ public class TrainJobWorker {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Phase 4: 학습/테스트 완료
|
||||||
|
// Step1: 42.5%, Step2: 92.5%
|
||||||
|
double completedProgress = isEval ? 92.5 : 42.5;
|
||||||
|
log.info(
|
||||||
|
"[JOB] {} jobId={} | Phase: TRAINING_COMPLETED | Progress: {}%",
|
||||||
|
step, jobId, String.format("%.1f", completedProgress));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 0 정상 종료 SUCCESS 1~125 학습 코드 에러 FAILED 137 OOMKill FAILED 143 SIGTERM (stop) STOP -1 우리 내부
|
* 0 정상 종료 SUCCESS 1~125 학습 코드 에러 FAILED 137 OOMKill FAILED 143 SIGTERM (stop) STOP -1 우리 내부
|
||||||
* 강제 중단 STOP
|
* 강제 중단 STOP
|
||||||
*/
|
*/
|
||||||
if (result.getExitCode() == 0) {
|
if (result.getExitCode() == 0) {
|
||||||
|
// Phase 5: 결과 처리 중
|
||||||
|
// Step1: 45%, Step2: 95%
|
||||||
|
double processingProgress = isEval ? 95.0 : 45.0;
|
||||||
|
log.info(
|
||||||
|
"[JOB] {} jobId={} | Phase: PROCESSING_RESULTS | Progress: {}%",
|
||||||
|
step, jobId, String.format("%.1f", processingProgress));
|
||||||
|
|
||||||
// 성공 처리
|
// 성공 처리
|
||||||
modelTrainJobCoreService.markSuccess(jobId, result.getExitCode());
|
modelTrainJobCoreService.markSuccess(jobId, result.getExitCode());
|
||||||
|
|
||||||
@@ -127,6 +167,13 @@ public class TrainJobWorker {
|
|||||||
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Phase 6: 완료
|
||||||
|
// Step1: 50%, Step2: 100%
|
||||||
|
double finalProgress = isEval ? 100.0 : 50.0;
|
||||||
|
log.info(
|
||||||
|
"[JOB] {} jobId={} | Phase: COMPLETED | Progress: {}%",
|
||||||
|
step, jobId, String.format("%.1f", finalProgress));
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
String failMsg = result.getStatus() + "\n" + result.getLogs();
|
String failMsg = result.getStatus() + "\n" + result.getLogs();
|
||||||
|
|||||||
@@ -0,0 +1,295 @@
|
|||||||
|
package com.kamco.cd.training.train.util;
|
||||||
|
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습 진행률 계산 유틸리티 기존 DB 컬럼만을 활용하여 진행률을 실시간 계산
|
||||||
|
*
|
||||||
|
* <p>상태전의 STATUS 가이드 기준: - Step1 (학습): TRAIN jobType → 0% ~ 50% - Step2 (테스트): EVAL jobType → 50% ~
|
||||||
|
* 100%
|
||||||
|
*/
|
||||||
|
@UtilityClass
|
||||||
|
public class TrainingProgressCalculator {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습 진행률 계산 (Step 구분)
|
||||||
|
*
|
||||||
|
* @param statusCd 작업 상태 (QUEUED/RUNNING/SUCCESS/FAILED/STOPPED/CANCELED)
|
||||||
|
* @param currentEpoch 현재 Epoch
|
||||||
|
* @param totalEpoch 전체 Epoch
|
||||||
|
* @param startedDttm 시작 시각
|
||||||
|
* @param finishedDttm 종료 시각
|
||||||
|
* @param jobType 작업 타입 (TRAIN/EVAL)
|
||||||
|
* @param step1State Step1 상태 (READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR)
|
||||||
|
* @param step2State Step2 상태 (READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR)
|
||||||
|
* @return 진행률 (0.00 ~ 100.00)
|
||||||
|
*/
|
||||||
|
public static double calculateProgress(
|
||||||
|
String statusCd,
|
||||||
|
Integer currentEpoch,
|
||||||
|
Integer totalEpoch,
|
||||||
|
ZonedDateTime startedDttm,
|
||||||
|
ZonedDateTime finishedDttm,
|
||||||
|
String jobType,
|
||||||
|
String step1State,
|
||||||
|
String step2State) {
|
||||||
|
if (statusCd == null) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step별 진행률 계산
|
||||||
|
boolean isStep1 = "TRAIN".equals(jobType);
|
||||||
|
boolean isStep2 = "EVAL".equals(jobType) || "TEST".equals(jobType);
|
||||||
|
|
||||||
|
// Step1 완료, Step2 완료 여부 확인
|
||||||
|
boolean isStep1Completed = "COMPLETED".equals(step1State);
|
||||||
|
boolean isStep2Completed = "COMPLETED".equals(step2State);
|
||||||
|
|
||||||
|
switch (statusCd) {
|
||||||
|
case "QUEUED":
|
||||||
|
// Step1 대기 중: 0%, Step2 대기 중: 50%
|
||||||
|
return isStep2 ? 50.0 : 0.0;
|
||||||
|
|
||||||
|
case "RUNNING":
|
||||||
|
return calculateRunningProgress(
|
||||||
|
currentEpoch, totalEpoch, startedDttm, isStep1, isStep2, isStep1Completed);
|
||||||
|
|
||||||
|
case "SUCCESS":
|
||||||
|
// Step1 성공: 50%, Step2 성공: 100%
|
||||||
|
if (isStep2 || isStep2Completed) {
|
||||||
|
return 100.0;
|
||||||
|
} else if (isStep1 || isStep1Completed) {
|
||||||
|
return 50.0;
|
||||||
|
}
|
||||||
|
return 100.0; // 기본값
|
||||||
|
|
||||||
|
case "FAILED":
|
||||||
|
case "STOPPED":
|
||||||
|
case "CANCELED":
|
||||||
|
// 실패/취소된 경우 마지막 진행률 반환
|
||||||
|
return calculateRunningProgress(
|
||||||
|
currentEpoch, totalEpoch, startedDttm, isStep1, isStep2, isStep1Completed);
|
||||||
|
|
||||||
|
default:
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 실행 중인 학습의 진행률 계산 (Step 구분)
|
||||||
|
*
|
||||||
|
* <p>Step1 (학습): 0% ~ 50% - PREPARING: 0% ~ 2.5% - CONTAINER_STARTING: 2.5% ~ 5% - DATA_LOADING:
|
||||||
|
* 5% ~ 7.5% - TRAINING: 7.5% ~ 42.5% (35% 비중) - PROCESSING: 42.5% ~ 50%
|
||||||
|
*
|
||||||
|
* <p>Step2 (테스트): 50% ~ 100% - PREPARING: 50% ~ 52.5% - CONTAINER_STARTING: 52.5% ~ 55% -
|
||||||
|
* DATA_LOADING: 55% ~ 57.5% - TESTING: 57.5% ~ 92.5% (35% 비중) - PROCESSING: 92.5% ~ 100%
|
||||||
|
*/
|
||||||
|
private static double calculateRunningProgress(
|
||||||
|
Integer currentEpoch,
|
||||||
|
Integer totalEpoch,
|
||||||
|
ZonedDateTime startedDttm,
|
||||||
|
boolean isStep1,
|
||||||
|
boolean isStep2,
|
||||||
|
boolean isStep1Completed) {
|
||||||
|
|
||||||
|
// Step 기준 계산
|
||||||
|
double baseProgress = 0.0;
|
||||||
|
double maxProgress = 50.0;
|
||||||
|
|
||||||
|
if (isStep2 || isStep1Completed) {
|
||||||
|
// Step2 진행 중 또는 Step1 완료 후
|
||||||
|
baseProgress = 50.0;
|
||||||
|
maxProgress = 100.0;
|
||||||
|
} else if (isStep1) {
|
||||||
|
// Step1 진행 중
|
||||||
|
baseProgress = 0.0;
|
||||||
|
maxProgress = 50.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
double stepRange = maxProgress - baseProgress; // 50%
|
||||||
|
|
||||||
|
// 시작 직후 (Epoch 정보 없음)
|
||||||
|
if (currentEpoch == null || totalEpoch == null || totalEpoch == 0) {
|
||||||
|
return baseProgress + estimateInitialPhaseProgress(startedDttm, stepRange);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Epoch 0 또는 1 (학습 시작 단계)
|
||||||
|
if (currentEpoch <= 1) {
|
||||||
|
return baseProgress + (stepRange * 0.15); // 7.5% (Step1) 또는 57.5% (Step2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 학습 진행 중 (15% ~ 85% of step range)
|
||||||
|
double epochProgress = (double) currentEpoch / totalEpoch;
|
||||||
|
double trainingProgress = 0.15 + (epochProgress * 0.70); // 15% ~ 85%
|
||||||
|
|
||||||
|
// 학습 완료 (마지막 Epoch)
|
||||||
|
if (currentEpoch >= totalEpoch) {
|
||||||
|
// 85% ~ 100% 사이로 추정
|
||||||
|
return baseProgress + (stepRange * 0.90);
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseProgress + (stepRange * trainingProgress);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 초기 단계 진행률 추정 (시작 시간 기반)
|
||||||
|
*
|
||||||
|
* @param startedDttm 시작 시각
|
||||||
|
* @param stepRange Step 범위 (50%)
|
||||||
|
* @return 초기 단계 진행률 (0 ~ 0.15 비율)
|
||||||
|
*/
|
||||||
|
private static double estimateInitialPhaseProgress(ZonedDateTime startedDttm, double stepRange) {
|
||||||
|
if (startedDttm == null) {
|
||||||
|
return stepRange * 0.05; // 5% of step range
|
||||||
|
}
|
||||||
|
|
||||||
|
long elapsedSeconds = ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
|
||||||
|
|
||||||
|
// 시작 후 30초 이내: PREPARING (0% ~ 5% of step)
|
||||||
|
if (elapsedSeconds < 30) {
|
||||||
|
return Math.min(stepRange * 0.05, (elapsedSeconds / 30.0) * stepRange * 0.05);
|
||||||
|
}
|
||||||
|
// 30초 ~ 60초: CONTAINER_STARTING (5% ~ 10% of step)
|
||||||
|
else if (elapsedSeconds < 60) {
|
||||||
|
return stepRange * 0.05 + ((elapsedSeconds - 30) / 30.0) * stepRange * 0.05;
|
||||||
|
}
|
||||||
|
// 60초 이상: DATA_LOADING (10% ~ 15% of step)
|
||||||
|
else {
|
||||||
|
return Math.min(
|
||||||
|
stepRange * 0.15, stepRange * 0.10 + ((elapsedSeconds - 60) / 60.0) * stepRange * 0.05);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 현재 Phase 추정
|
||||||
|
*
|
||||||
|
* @param statusCd 작업 상태
|
||||||
|
* @param currentEpoch 현재 Epoch
|
||||||
|
* @param totalEpoch 전체 Epoch
|
||||||
|
* @param startedDttm 시작 시각
|
||||||
|
* @param jobType 작업 타입 (TRAIN/EVAL)
|
||||||
|
* @return 현재 Phase
|
||||||
|
*/
|
||||||
|
public static String estimateCurrentPhase(
|
||||||
|
String statusCd,
|
||||||
|
Integer currentEpoch,
|
||||||
|
Integer totalEpoch,
|
||||||
|
ZonedDateTime startedDttm,
|
||||||
|
String jobType) {
|
||||||
|
if ("SUCCESS".equals(statusCd)) {
|
||||||
|
return "COMPLETED";
|
||||||
|
}
|
||||||
|
if ("FAILED".equals(statusCd)) {
|
||||||
|
return "FAILED";
|
||||||
|
}
|
||||||
|
if ("STOPPED".equals(statusCd) || "CANCELED".equals(statusCd)) {
|
||||||
|
return "CANCELED";
|
||||||
|
}
|
||||||
|
if ("QUEUED".equals(statusCd)) {
|
||||||
|
return "QUEUED";
|
||||||
|
}
|
||||||
|
|
||||||
|
// RUNNING 상태
|
||||||
|
boolean isStep2 = "EVAL".equals(jobType) || "TEST".equals(jobType);
|
||||||
|
String prefix = isStep2 ? "STEP2_" : "STEP1_";
|
||||||
|
|
||||||
|
if (currentEpoch == null || totalEpoch == null) {
|
||||||
|
if (startedDttm == null) {
|
||||||
|
return prefix + "PREPARING";
|
||||||
|
}
|
||||||
|
long elapsed = ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
|
||||||
|
if (elapsed < 30) return prefix + "PREPARING";
|
||||||
|
if (elapsed < 60) return prefix + "CONTAINER_STARTING";
|
||||||
|
return prefix + "DATA_LOADING";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentEpoch >= totalEpoch) {
|
||||||
|
return prefix + "PROCESSING_RESULTS";
|
||||||
|
}
|
||||||
|
|
||||||
|
return prefix + "TRAINING";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 경과 시간 계산 (초) */
|
||||||
|
public static Long calculateElapsedSeconds(ZonedDateTime startedDttm) {
|
||||||
|
if (startedDttm == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 예상 남은 시간 계산 (초) */
|
||||||
|
public static Long estimateRemainingSeconds(double progressPercent, Long elapsedSeconds) {
|
||||||
|
if (elapsedSeconds == null || progressPercent <= 0.0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
double remaining = (100.0 - progressPercent) / progressPercent;
|
||||||
|
return (long) (elapsedSeconds * remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 상태 메시지 생성
|
||||||
|
*
|
||||||
|
* @param phase 현재 Phase
|
||||||
|
* @param currentEpoch 현재 Epoch
|
||||||
|
* @param totalEpoch 전체 Epoch
|
||||||
|
* @return 상태 메시지
|
||||||
|
*/
|
||||||
|
public static String generateProgressMessage(
|
||||||
|
String phase, Integer currentEpoch, Integer totalEpoch) {
|
||||||
|
if (phase == null) {
|
||||||
|
return "대기중";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 구분
|
||||||
|
boolean isStep1 = phase.startsWith("STEP1_");
|
||||||
|
boolean isStep2 = phase.startsWith("STEP2_");
|
||||||
|
String stepName = isStep1 ? "학습" : isStep2 ? "테스트" : "";
|
||||||
|
|
||||||
|
switch (phase) {
|
||||||
|
case "QUEUED":
|
||||||
|
return "학습 작업이 큐에 등록되었습니다.";
|
||||||
|
|
||||||
|
case "STEP1_PREPARING":
|
||||||
|
return "학습 준비 중입니다.";
|
||||||
|
case "STEP1_CONTAINER_STARTING":
|
||||||
|
return "학습용 Docker 컨테이너를 시작하는 중입니다.";
|
||||||
|
case "STEP1_DATA_LOADING":
|
||||||
|
return "학습 데이터를 로딩하는 중입니다.";
|
||||||
|
case "STEP1_TRAINING":
|
||||||
|
if (currentEpoch != null && totalEpoch != null) {
|
||||||
|
return String.format("학습 진행 중 (Epoch %d/%d)", currentEpoch, totalEpoch);
|
||||||
|
}
|
||||||
|
return "학습 진행 중";
|
||||||
|
case "STEP1_PROCESSING_RESULTS":
|
||||||
|
return "학습 결과를 처리하는 중입니다.";
|
||||||
|
|
||||||
|
case "STEP2_PREPARING":
|
||||||
|
return "테스트 준비 중입니다.";
|
||||||
|
case "STEP2_CONTAINER_STARTING":
|
||||||
|
return "테스트용 Docker 컨테이너를 시작하는 중입니다.";
|
||||||
|
case "STEP2_DATA_LOADING":
|
||||||
|
return "테스트 데이터를 로딩하는 중입니다.";
|
||||||
|
case "STEP2_TRAINING":
|
||||||
|
if (currentEpoch != null && totalEpoch != null) {
|
||||||
|
return String.format("테스트 진행 중 (Epoch %d/%d)", currentEpoch, totalEpoch);
|
||||||
|
}
|
||||||
|
return "테스트 진행 중";
|
||||||
|
case "STEP2_PROCESSING_RESULTS":
|
||||||
|
return "테스트 결과를 처리하는 중입니다.";
|
||||||
|
|
||||||
|
case "COMPLETED":
|
||||||
|
return "학습이 성공적으로 완료되었습니다.";
|
||||||
|
case "FAILED":
|
||||||
|
return "학습이 실패했습니다.";
|
||||||
|
case "CANCELED":
|
||||||
|
return "학습이 취소되었습니다.";
|
||||||
|
|
||||||
|
default:
|
||||||
|
return stepName + " 진행 중";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,20 +30,46 @@ token:
|
|||||||
swagger:
|
swagger:
|
||||||
local-port: 8080
|
local-port: 8080
|
||||||
|
|
||||||
|
# file:
|
||||||
|
# dataset-dir: /home/kcomu/data/request/
|
||||||
|
# dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||||
|
|
||||||
|
# pt-path: /home/kcomu/data/response/v6-cls-checkpoints/
|
||||||
|
# pt-FileName: yolov8_6th-6m.pt
|
||||||
|
|
||||||
|
# train:
|
||||||
|
# docker:
|
||||||
|
# image: kamco-cd-train:latest
|
||||||
|
# base_path: /home/kcomu/data
|
||||||
|
# request_dir: ${train.docker.base_path}/request
|
||||||
|
# response_dir: ${train.docker.base_path}/response
|
||||||
|
# symbolic_link_dir: ${train.docker.base_path}/tmp
|
||||||
|
# container_prefix: kamco-cd-train
|
||||||
|
# shm_size: 16g
|
||||||
|
# ipc_host: true
|
||||||
|
|
||||||
|
|
||||||
file:
|
file:
|
||||||
dataset-dir: /home/kcomu/data/request/
|
base_path: /backup/data/training
|
||||||
|
dataset-dir: ${file.base_path}/request/
|
||||||
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||||
|
|
||||||
pt-path: /home/kcomu/data/response/v6-cls-checkpoints/
|
pt-path: ${file.base_path}/response/v6-cls-checkpoints/
|
||||||
pt-FileName: yolov8_6th-6m.pt
|
pt-FileName: yolov8_6th-6m.pt
|
||||||
|
|
||||||
train:
|
train:
|
||||||
docker:
|
docker:
|
||||||
image: kamco-cd-train:latest
|
image: kamco-cd-train:latest
|
||||||
base_path: /home/kcomu/data
|
base_path: /backup/data/training
|
||||||
request_dir: ${train.docker.base_path}/request
|
request_dir: ${train.docker.base_path}/request
|
||||||
response_dir: ${train.docker.base_path}/response
|
response_dir: ${train.docker.base_path}/response
|
||||||
symbolic_link_dir: ${train.docker.base_path}/tmp
|
symbolic_link_dir: ${train.docker.base_path}/tmp
|
||||||
container_prefix: kamco-cd-train
|
container_prefix: kamco-cd-train
|
||||||
shm_size: 16g
|
shm_size: 16g
|
||||||
ipc_host: true
|
ipc_host: true
|
||||||
|
|
||||||
|
hyper:
|
||||||
|
parameter:
|
||||||
|
gpus: 1
|
||||||
|
gpu-ids: 0
|
||||||
|
batch-size: 10
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ spring:
|
|||||||
max-file-size: 10GB
|
max-file-size: 10GB
|
||||||
max-request-size: 10GB
|
max-request-size: 10GB
|
||||||
|
|
||||||
transaction:
|
#transaction:
|
||||||
default-timeout: 300 # 5분 트랜잭션 타임아웃
|
# default-timeout: 300 # 5분 트랜잭션 타임아웃
|
||||||
|
|
||||||
logging:
|
logging:
|
||||||
level:
|
level:
|
||||||
|
|||||||
Reference in New Issue
Block a user