Compare commits
1 Commits
develop
...
feat/train
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e858c8896 |
@@ -1,230 +0,0 @@
|
|||||||
#!/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
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#!/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 "※ 그룹 변경은 재로그인 후 적용됩니다."
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
#!/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
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
[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
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
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,7 +18,10 @@ services:
|
|||||||
- SPRING_PROFILES_ACTIVE=dev
|
- SPRING_PROFILES_ACTIVE=dev
|
||||||
- TZ=Asia/Seoul
|
- TZ=Asia/Seoul
|
||||||
volumes:
|
volumes:
|
||||||
- /backup/data/training:/backup/data/training
|
- /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
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
services:
|
services:
|
||||||
kamco-changedetection-api:
|
kamco-train-api:
|
||||||
image: kamco-train-app:latest
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: kamco-train-api:${IMAGE_TAG:-latest}
|
||||||
container_name: kamco-train-api
|
container_name: kamco-train-api
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
@@ -14,10 +17,9 @@ 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:
|
||||||
- /data/training:/data/training
|
- ./app/model_output:/app/model-outputs
|
||||||
|
- ./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
|
||||||
|
|||||||
@@ -20,8 +20,14 @@ http {
|
|||||||
# 업로드 파일 크기 제한 (10GB)
|
# 업로드 파일 크기 제한 (10GB)
|
||||||
client_max_body_size 10G;
|
client_max_body_size 10G;
|
||||||
|
|
||||||
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
|
# Upstream 설정
|
||||||
resolver 127.0.0.11 valid=30s ipv6=off;
|
upstream api_backend {
|
||||||
|
server kamco-train-api:8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
upstream web_backend {
|
||||||
|
server kamco-train-web:3002;
|
||||||
|
}
|
||||||
|
|
||||||
# HTTP → HTTPS 리다이렉트 서버
|
# HTTP → HTTPS 리다이렉트 서버
|
||||||
server {
|
server {
|
||||||
@@ -60,8 +66,7 @@ http {
|
|||||||
|
|
||||||
# 프록시 설정
|
# 프록시 설정
|
||||||
location / {
|
location / {
|
||||||
set $api http://kamco-train-api:8080;
|
proxy_pass http://api_backend;
|
||||||
proxy_pass $api;
|
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
@@ -90,8 +95,7 @@ http {
|
|||||||
|
|
||||||
# 헬스체크 엔드포인트
|
# 헬스체크 엔드포인트
|
||||||
location /monitor/health {
|
location /monitor/health {
|
||||||
set $api http://kamco-train-api:8080;
|
proxy_pass http://api_backend/monitor/health;
|
||||||
proxy_pass $api/monitor/health;
|
|
||||||
access_log off;
|
access_log off;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,8 +128,7 @@ http {
|
|||||||
|
|
||||||
# API 프록시 설정 (Web에서 API 호출 시)
|
# API 프록시 설정 (Web에서 API 호출 시)
|
||||||
location /api/ {
|
location /api/ {
|
||||||
set $api http://kamco-train-api:8080;
|
proxy_pass http://api_backend/api/;
|
||||||
proxy_pass $api/api/;
|
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
@@ -147,8 +150,7 @@ http {
|
|||||||
|
|
||||||
# 프록시 설정
|
# 프록시 설정
|
||||||
location / {
|
location / {
|
||||||
set $web http://kamco-train-web:3002;
|
proxy_pass http://web_backend;
|
||||||
proxy_pass $web;
|
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
# 프록시 헤더 설정
|
# 프록시 헤더 설정
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ 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;
|
||||||
@@ -15,34 +13,19 @@ 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: 최근 WINDOW_SIZE 개의 sm 사용률 샘플 (1초 간격)
|
// value: 현재 GPU 사용률 (%)
|
||||||
// ConcurrentHashMap → 멀티스레드 안전 (deque 접근은 synchronized)
|
// ConcurrentHashMap → 멀티스레드 안전
|
||||||
// =========================
|
// =========================
|
||||||
private static final int WINDOW_SIZE = 10; // 10초 평균
|
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private final Map<Integer, ArrayDeque<Integer>> historyMap = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// 외부 조회용
|
// 외부 조회용
|
||||||
// GPU 개수만큼 10초 평균값 반환
|
|
||||||
// SystemMonitorService에서 호출
|
// SystemMonitorService에서 호출
|
||||||
// =========================
|
// =========================
|
||||||
public Map<Integer, Integer> getGpuUtilMap() {
|
public Map<Integer, Integer> getGpuUtilMap() {
|
||||||
Map<Integer, Integer> result = new HashMap<>();
|
return gpuUtilMap;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
@@ -93,13 +76,10 @@ 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 = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
try (BufferedReader br =
|
||||||
|
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
||||||
|
|
||||||
String line;
|
String line;
|
||||||
|
|
||||||
@@ -116,24 +96,21 @@ public class GpuDmonReader {
|
|||||||
String[] parts = line.split("\\s+");
|
String[] parts = line.split("\\s+");
|
||||||
|
|
||||||
// 첫 번째 값이 GPU index인지 확인
|
// 첫 번째 값이 GPU index인지 확인
|
||||||
if (parts.length < 2 || !parts[0].matches("\\d+")) continue;
|
if (!parts[0].matches("\\d+")) continue;
|
||||||
|
|
||||||
int index = Integer.parseInt(parts[0]);
|
int index = Integer.parseInt(parts[0]);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 두 번째 값이 GPU 사용률 (sm), "-"이면 N/A (GPU 미활성)
|
// 두 번째 값이 GPU 사용률 (sm)
|
||||||
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) {
|
// 최신 값 갱신
|
||||||
// "-" 등 숫자가 아닌 값 → GPU 비활성 상태이므로 0으로 기록
|
gpuUtilMap.put(index, util);
|
||||||
pushSample(index, 0);
|
|
||||||
log.debug("[GpuDmon] gpu={} sm=N/A (raw={}), stored as 0", index, parts[1]);
|
} catch (Exception ignored) {
|
||||||
|
// 파싱 실패 시 무시
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
process.destroy();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||||
@@ -141,20 +118,6 @@ 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,12 +1,7 @@
|
|||||||
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() {}
|
||||||
@@ -25,20 +20,4 @@ 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,6 +1,5 @@
|
|||||||
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;
|
||||||
@@ -32,11 +31,10 @@ 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(), english ? e.getId() : e.getText()))
|
.map(e -> new CodeDto(e.getId(), e.getText()))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -293,8 +293,6 @@ 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,7 +4,6 @@ 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;
|
||||||
@@ -91,8 +90,7 @@ 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);
|
||||||
boolean english = HeaderUtil.isEnglishRequest();
|
return type == null ? null : type.getText();
|
||||||
return type == null ? null : (english ? type.getId() : type.getText());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
@@ -101,8 +99,7 @@ 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);
|
||||||
boolean english = HeaderUtil.isEnglishRequest();
|
return type == null ? null : type.getText();
|
||||||
return type == null ? null : (english ? type.getId() : type.getText());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,7 +315,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 : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
return type == null ? null : type.getText();
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getYear() {
|
public String getYear() {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ 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;
|
||||||
@@ -132,12 +131,7 @@ public class DatasetObjDto {
|
|||||||
private String classCd;
|
private String classCd;
|
||||||
|
|
||||||
public String getClassName() {
|
public String getClassName() {
|
||||||
|
return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
||||||
return HeaderUtil.isEnglishRequest()
|
|
||||||
? DetectionClassification.fromString(classCd).getId()
|
|
||||||
: DetectionClassification.fromString(classCd).getDesc();
|
|
||||||
// fromString 메서드를 사용하여 안전하게 변환 (미정의 값은 ETC로 처리)
|
|
||||||
// return DetectionClassification.valueOf(classCd.toUpperCase()).getDesc();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,7 @@ 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.io.IOException;
|
import java.util.UUID;
|
||||||
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;
|
||||||
@@ -49,11 +45,7 @@ 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. 마스터 데이터 생성 =====
|
||||||
@@ -79,7 +71,6 @@ 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);
|
||||||
@@ -130,24 +121,4 @@ 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() + uid)
|
.datasetPath(addReq.getFilePath())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
|
||||||
@@ -676,18 +676,4 @@ 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,9 +1,7 @@
|
|||||||
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;
|
||||||
@@ -276,11 +274,5 @@ 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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,9 +33,6 @@ public class FileManagerService {
|
|||||||
private static final String BASE_DATA_PATH = "/data";
|
private static final String BASE_DATA_PATH = "/data";
|
||||||
private static final long MAX_PATH_LENGTH = 500;
|
private static final long MAX_PATH_LENGTH = 500;
|
||||||
|
|
||||||
@Value("${train.docker.base_path}")
|
|
||||||
private String basePath;
|
|
||||||
|
|
||||||
@Value("${train.docker.request_dir}")
|
@Value("${train.docker.request_dir}")
|
||||||
private String requestDir;
|
private String requestDir;
|
||||||
|
|
||||||
@@ -570,19 +567,17 @@ public class FileManagerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 저장공간 정보 조회 (남은 공간 포함) 고정 경로: train.docker.base_path 설정값 사용
|
* 저장공간 정보 조회 (남은 공간 포함) 고정 경로: /home/kcomu/data
|
||||||
*
|
*
|
||||||
* @return 저장공간 정보 (사용량, 남은 공간, 디스크 용량)
|
* @return 저장공간 정보 (사용량, 남은 공간, 디스크 용량)
|
||||||
*/
|
*/
|
||||||
public FileManagerDto.StorageSpaceRes getStorageSpaceInfo() {
|
public FileManagerDto.StorageSpaceRes getStorageSpaceInfo() {
|
||||||
// 설정값에서 경로 가져오기 (train.docker.base_path)
|
// 고정 경로: /home/kcomu/data
|
||||||
|
String directoryPath = "/home/kcomu/data";
|
||||||
log.info("basePath = {}", basePath);
|
|
||||||
String directoryPath = basePath;
|
|
||||||
|
|
||||||
Path directory = Paths.get(directoryPath);
|
Path directory = Paths.get(directoryPath);
|
||||||
if (!Files.exists(directory)) {
|
if (!Files.exists(directory)) {
|
||||||
log.info("디렉토리가 존재하지 않습니다: {}", directoryPath);
|
log.debug("디렉토리가 존재하지 않습니다: {}", directoryPath);
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(0)
|
.fileCount(0)
|
||||||
@@ -600,7 +595,7 @@ public class FileManagerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!Files.isDirectory(directory)) {
|
if (!Files.isDirectory(directory)) {
|
||||||
log.info("디렉토리 경로가 아닙니다: {}", directoryPath);
|
log.debug("디렉토리 경로가 아닙니다: {}", directoryPath);
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(0)
|
.fileCount(0)
|
||||||
@@ -617,36 +612,36 @@ public class FileManagerService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 디렉토리 사용량 계산 — du -sb 사용 (walkFileTree 대비 수배 빠름)
|
// 디렉토리 사용량 계산 (재귀적으로 모든 파일 크기 합산)
|
||||||
// fileCount/directoryCount는 du가 제공하지 않으므로 -1(미집계) 반환
|
final long[] usedSize = {0};
|
||||||
long usedSize = 0;
|
final int[] fileCount = {0};
|
||||||
|
final int[] directoryCount = {0};
|
||||||
|
|
||||||
log.info("[StorageSpace] du 시작 - path={}", directoryPath);
|
|
||||||
try {
|
try {
|
||||||
ProcessBuilder duPb = new ProcessBuilder("du", "-sb", directoryPath);
|
Files.walkFileTree(
|
||||||
duPb.redirectErrorStream(true);
|
directory,
|
||||||
Process duProcess = duPb.start();
|
new SimpleFileVisitor<>() {
|
||||||
try (java.io.BufferedReader br =
|
@Override
|
||||||
new java.io.BufferedReader(new java.io.InputStreamReader(duProcess.getInputStream()))) {
|
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||||
String line = br.readLine();
|
usedSize[0] += attrs.size();
|
||||||
if (line != null) {
|
fileCount[0]++;
|
||||||
// du -sb 출력 형식: "12345678\t/path/to/dir"
|
return FileVisitResult.CONTINUE;
|
||||||
String[] parts = line.split("\t", 2);
|
|
||||||
usedSize = Long.parseLong(parts[0].trim());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||||
|
if (!dir.equals(directory)) {
|
||||||
|
directoryCount[0]++;
|
||||||
}
|
}
|
||||||
int exitCode = duProcess.waitFor();
|
return FileVisitResult.CONTINUE;
|
||||||
log.info(
|
}
|
||||||
"[StorageSpace] du 완료 - exitCode={}, usedSize={} bytes ({})",
|
});
|
||||||
exitCode,
|
} catch (IOException e) {
|
||||||
usedSize,
|
log.debug("디렉토리 용량 계산 중 오류 발생: {}", directoryPath, e);
|
||||||
formatFileSize(usedSize));
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("[StorageSpace] du 실행 실패: {}", directoryPath, e);
|
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(-1)
|
.fileCount(0)
|
||||||
.directoryCount(-1)
|
.directoryCount(0)
|
||||||
.usedSize(0L)
|
.usedSize(0L)
|
||||||
.usedSizeFormatted("0 B")
|
.usedSizeFormatted("0 B")
|
||||||
.totalDiskSpace(0L)
|
.totalDiskSpace(0L)
|
||||||
@@ -659,7 +654,7 @@ public class FileManagerService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 디스크 공간 정보 조회 (FileStore 사용) — basePath가 속한 파티션/NFS 마운트 전체 기준
|
// 디스크 공간 정보 조회 (FileStore 사용)
|
||||||
long totalDiskSpace = 0;
|
long totalDiskSpace = 0;
|
||||||
long freeSpace = 0;
|
long freeSpace = 0;
|
||||||
long usableSpace = 0;
|
long usableSpace = 0;
|
||||||
@@ -667,37 +662,26 @@ 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(); // OS 미할당 공간 (root 예약 블록 포함 가능)
|
freeSpace = fileStore.getUnallocatedSpace(); // 남은 저장공간 (할당되지 않은 공간)
|
||||||
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 - usableSpace;
|
long usedDiskSpace = totalDiskSpace - freeSpace;
|
||||||
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.warn("[StorageSpace] 디스크 공간 정보 조회 실패: {}", directoryPath, e);
|
log.debug("디스크 공간 정보 조회 중 오류 발생: {}", directoryPath, e);
|
||||||
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
||||||
}
|
}
|
||||||
|
|
||||||
return FileManagerDto.StorageSpaceRes.builder()
|
return FileManagerDto.StorageSpaceRes.builder()
|
||||||
.directoryPath(directoryPath)
|
.directoryPath(directoryPath)
|
||||||
.fileCount(-1)
|
.fileCount(fileCount[0])
|
||||||
.directoryCount(-1)
|
.directoryCount(directoryCount[0])
|
||||||
.usedSize(usedSize)
|
.usedSize(usedSize[0])
|
||||||
.usedSizeFormatted(formatFileSize(usedSize))
|
.usedSizeFormatted(formatFileSize(usedSize[0]))
|
||||||
.totalDiskSpace(totalDiskSpace)
|
.totalDiskSpace(totalDiskSpace)
|
||||||
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
||||||
.freeSpace(freeSpace)
|
.freeSpace(freeSpace)
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ import org.springframework.http.ResponseEntity;
|
|||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.RequestHeader;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
@@ -367,43 +366,4 @@ public class ModelTrainDetailApiController {
|
|||||||
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
||||||
return ApiResponseDto.ok(modelTrainDetailService.cleanup(uuid));
|
return ApiResponseDto.ok(modelTrainDetailService.cleanup(uuid));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(
|
|
||||||
summary = "학습 결과 ZIP 파일 목록 조회",
|
|
||||||
description = "모델 UUID에 해당하는 모든 ZIP 파일 목록과 개별 다운로드 링크 반환",
|
|
||||||
parameters = {
|
|
||||||
@Parameter(
|
|
||||||
name = "kamco-download-uuid",
|
|
||||||
in = ParameterIn.HEADER,
|
|
||||||
required = true,
|
|
||||||
description = "다운로드 요청 UUID",
|
|
||||||
schema =
|
|
||||||
@Schema(
|
|
||||||
type = "string",
|
|
||||||
format = "uuid",
|
|
||||||
example = "6d8d49dc-0c9d-4124-adc7-b9ca610cc394"))
|
|
||||||
})
|
|
||||||
@ApiResponses(
|
|
||||||
value = {
|
|
||||||
@ApiResponse(
|
|
||||||
responseCode = "200",
|
|
||||||
description = "ZIP 파일 목록 조회 성공",
|
|
||||||
content =
|
|
||||||
@Content(
|
|
||||||
mediaType = "application/json",
|
|
||||||
schema =
|
|
||||||
@Schema(implementation = ModelTrainDetailDto.ZipFileListResponse.class))),
|
|
||||||
@ApiResponse(responseCode = "404", description = "모델 또는 파일 없음", content = @Content),
|
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
|
||||||
})
|
|
||||||
@GetMapping("/downloadzip/{uuid}")
|
|
||||||
public ResponseEntity<?> downloadZip(
|
|
||||||
@Parameter(description = "모델 UUID") @PathVariable UUID uuid,
|
|
||||||
@Parameter(hidden = true) @RequestHeader("kamco-download-uuid") String downloadUuid,
|
|
||||||
HttpServletRequest request)
|
|
||||||
throws IOException {
|
|
||||||
|
|
||||||
return ResponseEntity.ok(
|
|
||||||
modelTrainDetailService.getZipFileListWithFullUrl(uuid, downloadUuid, request));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ 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;
|
||||||
@@ -33,8 +32,6 @@ 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;
|
||||||
@@ -43,9 +40,7 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -54,16 +49,18 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
? 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 (start == null || end == null) {
|
if (end == null) {
|
||||||
|
end = ZonedDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,42 +70,11 @@ public class ModelTrainDetailDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 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);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public String getStepAllDuration() {
|
public String getStepAllDuration() {
|
||||||
if (this.step2EndDttm != null) {
|
return formatDuration(this.step1StrtDttm, this.step2EndDttm);
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +174,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 : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
|
return type == null ? null : type.getText();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,73 +266,4 @@ public class ModelTrainDetailDto {
|
|||||||
private Boolean fileExistsYn;
|
private Boolean fileExistsYn;
|
||||||
private String fileName;
|
private String fileName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Builder
|
|
||||||
@Schema(name = "ZipFileListResponse", description = "ZIP 파일 목록 조회 응답")
|
|
||||||
public static class ZipFileListResponse {
|
|
||||||
|
|
||||||
@Schema(description = "모델 UUID", example = "2c5cdd07-5b9b-44ad-a063-8dead628b45f")
|
|
||||||
private String modelUuid;
|
|
||||||
|
|
||||||
@Schema(description = "모델 번호", example = "G2")
|
|
||||||
private String modelNo;
|
|
||||||
|
|
||||||
@Schema(description = "현재 모델 버전", example = "G2_000001")
|
|
||||||
private String modelVer;
|
|
||||||
|
|
||||||
@Schema(
|
|
||||||
description = "기본 경로",
|
|
||||||
example = "/home/kcomu/data/response/2c5cdd07-5b9b-44ad-a063-8dead628b45f")
|
|
||||||
private String basePath;
|
|
||||||
|
|
||||||
@Schema(description = "ZIP 파일 목록")
|
|
||||||
private List<ZipFileInfo> zipFiles;
|
|
||||||
|
|
||||||
@Schema(description = "총 파일 개수", example = "3")
|
|
||||||
private Integer totalFiles;
|
|
||||||
|
|
||||||
@Schema(description = "전체 파일 크기 (bytes)", example = "4048640000")
|
|
||||||
private Long totalSize;
|
|
||||||
|
|
||||||
@Schema(description = "전체 파일 크기 (포맷)", example = "3.77 GB")
|
|
||||||
private String totalSizeFormatted;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Builder
|
|
||||||
@Schema(name = "ZipFileInfo", description = "ZIP 파일 상세 정보")
|
|
||||||
public static class ZipFileInfo {
|
|
||||||
|
|
||||||
@Schema(description = "파일명", example = "G2.G2_000001.{uuid}.zip")
|
|
||||||
private String fileName;
|
|
||||||
|
|
||||||
@Schema(description = "파일 전체 경로")
|
|
||||||
private String filePath;
|
|
||||||
|
|
||||||
@Schema(description = "모델 버전", example = "G2_000001")
|
|
||||||
private String version;
|
|
||||||
|
|
||||||
@Schema(description = "파일 크기 (bytes)", example = "1349516895")
|
|
||||||
private Long fileSize;
|
|
||||||
|
|
||||||
@Schema(description = "파일 크기 (포맷)", example = "1.26 GB")
|
|
||||||
private String fileSizeFormatted;
|
|
||||||
|
|
||||||
@Schema(description = "최종 수정 시간", example = "2026-03-10T23:19:24.347+09:00")
|
|
||||||
@JsonFormatDttm
|
|
||||||
private ZonedDateTime lastModified;
|
|
||||||
|
|
||||||
@Schema(description = "현재 모델 버전 여부", example = "true")
|
|
||||||
private Boolean isCurrent;
|
|
||||||
|
|
||||||
@Schema(description = "다운로드 URL")
|
|
||||||
private String downloadUrl;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ 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;
|
||||||
@@ -45,8 +44,8 @@ public class ModelTrainMngDto {
|
|||||||
private String requestPath;
|
private String requestPath;
|
||||||
|
|
||||||
private String packingState;
|
private String packingState;
|
||||||
@JsonFormatDttm private ZonedDateTime packingStrtDttm;
|
private ZonedDateTime packingStrtDttm;
|
||||||
@JsonFormatDttm private ZonedDateTime packingEndDttm;
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
private Long beforeModelId;
|
private Long beforeModelId;
|
||||||
private Integer bestEpoch;
|
private Integer bestEpoch;
|
||||||
@@ -54,9 +53,7 @@ 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 (HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -65,9 +62,7 @@ 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 (HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -76,9 +71,7 @@ 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 (HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -87,9 +80,7 @@ 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 (HeaderUtil.isEnglishRequest()
|
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -106,12 +97,8 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 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);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
@@ -189,8 +176,6 @@ public class ModelTrainMngDto {
|
|||||||
|
|
||||||
private String requestPath;
|
private String requestPath;
|
||||||
private String responsePath;
|
private String responsePath;
|
||||||
private String tmpFileStatus;
|
|
||||||
private ZonedDateTime tmpFileEndDttm;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -273,9 +258,7 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -284,9 +267,7 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -295,9 +276,7 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -306,9 +285,7 @@ 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 HeaderUtil.isEnglishRequest()
|
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
? 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 처리)
|
||||||
}
|
}
|
||||||
@@ -325,12 +302,8 @@ public class ModelTrainMngDto {
|
|||||||
long minutes = (totalSeconds % 3600) / 60;
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
long seconds = totalSeconds % 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);
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public String getStep1Duration() {
|
public String getStep1Duration() {
|
||||||
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.kamco.cd.training.model.service;
|
package com.kamco.cd.training.model.service;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.download.RangeDownloadResponder;
|
|
||||||
import com.kamco.cd.training.common.enums.ModelType;
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
@@ -17,15 +16,12 @@ import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTrainMetrics;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelValidationMetrics;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferDetailDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferHyperSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.TransferHyperSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ZipFileInfo;
|
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ZipFileListResponse;
|
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.AccessDeniedException;
|
import java.nio.file.AccessDeniedException;
|
||||||
import java.nio.file.FileVisitOption;
|
import java.nio.file.FileVisitOption;
|
||||||
@@ -36,10 +32,7 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.nio.file.SimpleFileVisitor;
|
import java.nio.file.SimpleFileVisitor;
|
||||||
import java.nio.file.attribute.BasicFileAttributes;
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
import java.nio.file.attribute.FileTime;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -48,7 +41,6 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -60,7 +52,6 @@ public class ModelTrainDetailService {
|
|||||||
|
|
||||||
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
||||||
private final ModelTrainMngCoreService mngCoreService;
|
private final ModelTrainMngCoreService mngCoreService;
|
||||||
private final RangeDownloadResponder rangeDownloadResponder;
|
|
||||||
|
|
||||||
@Value("${train.docker.response_dir}")
|
@Value("${train.docker.response_dir}")
|
||||||
private String responseDir;
|
private String responseDir;
|
||||||
@@ -443,657 +434,4 @@ 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 파일 목록 조회 및 다운로드 링크 생성
|
|
||||||
*
|
|
||||||
* @param uuid 모델 UUID
|
|
||||||
* @param downloadUuid 다운로드 추적 UUID
|
|
||||||
* @return ZIP 파일 목록 및 다운로드 링크
|
|
||||||
*/
|
|
||||||
public ZipFileListResponse getZipFileList(UUID uuid, String downloadUuid) {
|
|
||||||
log.info("ZIP 파일 목록 조회 시작: modelUuid={}, downloadUuid={}", uuid, downloadUuid);
|
|
||||||
|
|
||||||
// 1. 모델 정보 조회
|
|
||||||
Basic modelInfo;
|
|
||||||
try {
|
|
||||||
modelInfo = findByModelByUUID(uuid);
|
|
||||||
if (modelInfo == null) {
|
|
||||||
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
|
||||||
}
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
log.error("모델 조회 실패: {}", uuid, e);
|
|
||||||
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
|
||||||
Path 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.info("디렉토리 발견: basePath={}", baseDir.toString());
|
|
||||||
|
|
||||||
// 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();
|
|
||||||
|
|
||||||
for (Path file : files) {
|
|
||||||
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 = String.format("/api/models/download/%s?file=%s", uuid, 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.info("ZIP 파일 {}개 발견", zipFiles.size());
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("ZIP 파일 목록 조회 실패: {}", 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 또는 uuid-out)
|
|
||||||
*
|
|
||||||
* @param uuid 모델 UUID
|
|
||||||
* @return 실제 경로 또는 null
|
|
||||||
*/
|
|
||||||
private Path findActualBasePath(UUID uuid) {
|
|
||||||
// 1순위: {uuid}-out
|
|
||||||
Path pathWithSuffix = Paths.get(responseDir, uuid + "-out");
|
|
||||||
if (Files.exists(pathWithSuffix) && Files.isDirectory(pathWithSuffix)) {
|
|
||||||
log.debug("경로 발견: {} (suffix -out 포함)", pathWithSuffix);
|
|
||||||
return pathWithSuffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2순위: {uuid}
|
|
||||||
Path pathWithoutSuffix = Paths.get(responseDir, uuid.toString());
|
|
||||||
if (Files.exists(pathWithoutSuffix) && Files.isDirectory(pathWithoutSuffix)) {
|
|
||||||
log.debug("경로 발견: {} (suffix 없음)", pathWithoutSuffix);
|
|
||||||
return pathWithoutSuffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ZIP 파일명에서 버전 추출 예: G2.G2_000001.{uuid}.zip → G2_000001
|
|
||||||
*
|
|
||||||
* @param fileName ZIP 파일명
|
|
||||||
* @return 모델 버전
|
|
||||||
*/
|
|
||||||
private String extractVersionFromZipFileName(String fileName) {
|
|
||||||
// 패턴: {modelNo}.{modelVer}.{uuid}.zip
|
|
||||||
// 예: G2.G2_000001.d7dd54e9-1f20-46a7-9c26-89287a7d61b0.zip
|
|
||||||
|
|
||||||
String[] parts = fileName.split("\\.");
|
|
||||||
|
|
||||||
// parts[0] = G2 (modelNo)
|
|
||||||
// parts[1] = G2_000001 (modelVer)
|
|
||||||
// parts[2-7] = uuid parts
|
|
||||||
// parts[8] = zip
|
|
||||||
|
|
||||||
if (parts.length >= 2) {
|
|
||||||
return parts[1]; // G2_000001
|
|
||||||
}
|
|
||||||
|
|
||||||
// fallback: 전체 파일명에서 .zip 제거
|
|
||||||
return fileName.replace(".zip", "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 파일 크기를 읽기 쉬운 형식으로 변환
|
|
||||||
*
|
|
||||||
* @param size 파일 크기 (bytes)
|
|
||||||
* @return 포맷된 문자열 (예: "1.26 GB")
|
|
||||||
*/
|
|
||||||
private String formatFileSize(long size) {
|
|
||||||
if (size < 1024) {
|
|
||||||
return size + " B";
|
|
||||||
} else if (size < 1024 * 1024) {
|
|
||||||
return String.format("%.2f KB", size / 1024.0);
|
|
||||||
} else if (size < 1024 * 1024 * 1024) {
|
|
||||||
return String.format("%.2f MB", size / (1024.0 * 1024.0));
|
|
||||||
} else {
|
|
||||||
return String.format("%.2f GB", size / (1024.0 * 1024.0 * 1024.0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 모델 UUID로 모든 ZIP 파일 다운로드 또는 목록 조회
|
|
||||||
*
|
|
||||||
* @param uuid 모델 UUID
|
|
||||||
* @param downloadUuid 다운로드 추적 UUID
|
|
||||||
* @param fileName 개별 파일명 (선택)
|
|
||||||
* @param accept Accept 헤더 (application/json 또는 application/octet-stream)
|
|
||||||
* @param request HTTP 요청
|
|
||||||
* @return JSON 응답 또는 ZIP 파일 Binary 응답
|
|
||||||
*/
|
|
||||||
public ResponseEntity<?> downloadZipFile(
|
|
||||||
UUID uuid, String downloadUuid, String fileName, String accept, HttpServletRequest request)
|
|
||||||
throws IOException {
|
|
||||||
log.info(
|
|
||||||
"ZIP 파일 다운로드/조회 시작: modelUuid={}, downloadUuid={}, file={}, accept={}",
|
|
||||||
uuid,
|
|
||||||
downloadUuid,
|
|
||||||
fileName,
|
|
||||||
accept);
|
|
||||||
|
|
||||||
// 1. 모델 정보 조회
|
|
||||||
Basic modelInfo;
|
|
||||||
try {
|
|
||||||
modelInfo = findByModelByUUID(uuid);
|
|
||||||
if (modelInfo == null) {
|
|
||||||
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
|
||||||
}
|
|
||||||
} catch (NullPointerException e) {
|
|
||||||
log.warn("모델 조회 실패: {}", uuid);
|
|
||||||
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다: " + uuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 실제 디렉토리 경로 찾기 (uuid 또는 uuid-out)
|
|
||||||
Path 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.info("디렉토리 발견: basePath={}", baseDir);
|
|
||||||
|
|
||||||
// 3. 모든 ZIP 파일 찾기
|
|
||||||
List<Path> zipFiles = findAllZipFiles(baseDir, uuid);
|
|
||||||
|
|
||||||
if (zipFiles.isEmpty()) {
|
|
||||||
log.warn("ZIP 파일을 찾을 수 없음: modelUuid={}, basePath={}", uuid, baseDir);
|
|
||||||
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "ZIP 파일을 찾을 수 없습니다.");
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"ZIP 파일 {}개 발견: basePath={}, files={}",
|
|
||||||
zipFiles.size(),
|
|
||||||
baseDir,
|
|
||||||
zipFiles.stream().map(p -> p.getFileName().toString()).toList());
|
|
||||||
|
|
||||||
// 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) {
|
|
||||||
Path zipPath = zipFiles.get(0);
|
|
||||||
log.info(
|
|
||||||
"ZIP 파일 1개 다운로드: fileName={}, fileSize={} bytes, basePath={}",
|
|
||||||
zipPath.getFileName(),
|
|
||||||
Files.size(zipPath),
|
|
||||||
baseDir);
|
|
||||||
String downloadFileName = zipPath.getFileName().toString();
|
|
||||||
return rangeDownloadResponder.buildZipResponse(zipPath, downloadFileName, request);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 파일이 여러 개면 하나의 zip으로 묶어서 다운로드
|
|
||||||
log.info("여러 ZIP 파일을 하나로 묶어서 다운로드: 총 {}개 파일", zipFiles.size());
|
|
||||||
|
|
||||||
String combinedZipName = modelInfo.getModelNo() + "." + modelInfo.getModelVer() + ".all.zip";
|
|
||||||
Path tempZipPath = createCombinedZipFile(zipFiles, combinedZipName, uuid, baseDir);
|
|
||||||
|
|
||||||
try {
|
|
||||||
long totalSize = Files.size(tempZipPath);
|
|
||||||
log.info(
|
|
||||||
"통합 ZIP 파일 생성 완료: fileName={}, fileSize={} bytes, basePath={}",
|
|
||||||
tempZipPath.getFileName(),
|
|
||||||
totalSize,
|
|
||||||
baseDir);
|
|
||||||
|
|
||||||
ResponseEntity<?> response =
|
|
||||||
rangeDownloadResponder.buildZipResponse(tempZipPath, combinedZipName, request);
|
|
||||||
|
|
||||||
// 다운로드 완료 후 임시 파일 삭제 (비동기)
|
|
||||||
deleteTempFileAsync(tempZipPath);
|
|
||||||
|
|
||||||
return response;
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("통합 ZIP 파일 처리 실패: {}", tempZipPath, e);
|
|
||||||
// 에러 발생 시 임시 파일 삭제
|
|
||||||
try {
|
|
||||||
Files.deleteIfExists(tempZipPath);
|
|
||||||
Path tempDir = tempZipPath.getParent();
|
|
||||||
if (tempDir != null && Files.exists(tempDir)) {
|
|
||||||
Files.deleteIfExists(tempDir);
|
|
||||||
}
|
|
||||||
} catch (IOException ex) {
|
|
||||||
log.warn("임시 파일 삭제 실패: {}", tempZipPath, ex);
|
|
||||||
}
|
|
||||||
throw new CustomApiException(
|
|
||||||
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "ZIP 파일 생성 실패");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 모든 ZIP 파일 찾기
|
|
||||||
*
|
|
||||||
* @param baseDir 기본 디렉토리
|
|
||||||
* @param uuid 모델 UUID
|
|
||||||
* @return ZIP 파일 목록 (최신순 정렬)
|
|
||||||
*/
|
|
||||||
private List<Path> findAllZipFiles(Path baseDir, UUID uuid) {
|
|
||||||
try (Stream<Path> stream = Files.list(baseDir)) {
|
|
||||||
return stream
|
|
||||||
.filter(Files::isRegularFile)
|
|
||||||
.filter(p -> p.getFileName().toString().endsWith(".zip"))
|
|
||||||
.filter(p -> p.getFileName().toString().contains(uuid.toString()))
|
|
||||||
.sorted(
|
|
||||||
Comparator.comparing(
|
|
||||||
p -> {
|
|
||||||
try {
|
|
||||||
return Files.getLastModifiedTime(p);
|
|
||||||
} catch (IOException e) {
|
|
||||||
return FileTime.fromMillis(0);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Comparator.reverseOrder()))
|
|
||||||
.toList();
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("ZIP 파일 검색 실패: basePath={}", baseDir, e);
|
|
||||||
return new ArrayList<>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 여러 ZIP 파일을 하나의 ZIP으로 묶기
|
|
||||||
*
|
|
||||||
* @param zipFiles 원본 ZIP 파일 목록
|
|
||||||
* @param combinedZipName 통합 ZIP 파일명
|
|
||||||
* @param uuid 모델 UUID
|
|
||||||
* @param baseDir 기본 디렉토리 (로그용)
|
|
||||||
* @return 통합 ZIP 파일 경로
|
|
||||||
*/
|
|
||||||
private Path createCombinedZipFile(
|
|
||||||
List<Path> zipFiles, String combinedZipName, UUID uuid, Path baseDir) throws IOException {
|
|
||||||
// 임시 디렉토리에 통합 ZIP 생성
|
|
||||||
Path tempDir = Files.createTempDirectory("kamco-download-" + uuid);
|
|
||||||
Path combinedZipPath = tempDir.resolve(combinedZipName);
|
|
||||||
|
|
||||||
log.debug("통합 ZIP 생성 시작: tempPath={}, 원본 파일 {}개", combinedZipPath, zipFiles.size());
|
|
||||||
|
|
||||||
try (java.util.zip.ZipOutputStream zos =
|
|
||||||
new java.util.zip.ZipOutputStream(Files.newOutputStream(combinedZipPath))) {
|
|
||||||
|
|
||||||
for (Path zipFile : zipFiles) {
|
|
||||||
String entryName = zipFile.getFileName().toString();
|
|
||||||
log.debug("ZIP에 파일 추가: {}", entryName);
|
|
||||||
|
|
||||||
java.util.zip.ZipEntry entry = new java.util.zip.ZipEntry(entryName);
|
|
||||||
zos.putNextEntry(entry);
|
|
||||||
|
|
||||||
Files.copy(zipFile, zos);
|
|
||||||
zos.closeEntry();
|
|
||||||
}
|
|
||||||
|
|
||||||
zos.finish();
|
|
||||||
}
|
|
||||||
|
|
||||||
log.debug("통합 ZIP 생성 완료: {}", combinedZipPath);
|
|
||||||
return combinedZipPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 임시 파일 비동기 삭제
|
|
||||||
*
|
|
||||||
* @param tempFile 삭제할 임시 파일
|
|
||||||
*/
|
|
||||||
private void deleteTempFileAsync(Path tempFile) {
|
|
||||||
new Thread(
|
|
||||||
() -> {
|
|
||||||
try {
|
|
||||||
// 다운로드 완료 후 대기
|
|
||||||
Thread.sleep(10000); // 10초 대기
|
|
||||||
Files.deleteIfExists(tempFile);
|
|
||||||
// 임시 디렉토리도 삭제
|
|
||||||
Path tempDir = tempFile.getParent();
|
|
||||||
if (tempDir != null && Files.exists(tempDir)) {
|
|
||||||
Files.deleteIfExists(tempDir);
|
|
||||||
}
|
|
||||||
log.debug("임시 파일 삭제 완료: {}", tempFile);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("임시 파일 삭제 실패: {}", tempFile, e);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.start();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -305,19 +305,7 @@ public class ModelTrainMngService {
|
|||||||
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
||||||
|
|
||||||
// 데이터셋 임시파일 생성
|
// 데이터셋 임시파일 생성
|
||||||
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);
|
trainJobService.createTmpFile(modelUuid);
|
||||||
}
|
|
||||||
return modelUuid;
|
return modelUuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ 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;
|
||||||
@@ -39,10 +38,6 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -56,16 +51,4 @@ 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,9 +180,6 @@ 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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -419,11 +416,6 @@ 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가 성공 시 호출 */
|
||||||
@@ -681,36 +673,4 @@ 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,21 +121,6 @@ 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,8 +80,6 @@ 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,
|
||||||
|
|||||||
@@ -39,12 +39,4 @@ public interface ModelMngRepositoryCustom {
|
|||||||
*/
|
*/
|
||||||
List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
|
List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
|
||||||
String modelNo, Boolean delYn);
|
String modelNo, Boolean delYn);
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 ID로 모델 조회
|
|
||||||
*
|
|
||||||
* @param hyperParamId 하이퍼파라미터 ID
|
|
||||||
* @return 모델 목록
|
|
||||||
*/
|
|
||||||
List<ModelMasterEntity> findByHyperParamId(Long hyperParamId);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -189,8 +189,7 @@ 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))
|
||||||
@@ -222,13 +221,4 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
|||||||
.orderBy(modelMasterEntity.createdDttm.desc())
|
.orderBy(modelMasterEntity.createdDttm.desc())
|
||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<ModelMasterEntity> findByHyperParamId(Long hyperParamId) {
|
|
||||||
return queryFactory
|
|
||||||
.selectFrom(modelMasterEntity)
|
|
||||||
.where(modelMasterEntity.hyperParamId.eq(hyperParamId), modelMasterEntity.delYn.eq(false))
|
|
||||||
.orderBy(modelMasterEntity.createdDttm.desc())
|
|
||||||
.fetch();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ 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;
|
||||||
|
|
||||||
@@ -19,27 +18,9 @@ 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,7 +3,6 @@ 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;
|
||||||
@@ -11,8 +10,6 @@ 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;
|
||||||
@@ -106,7 +103,7 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
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 =
|
||||||
"""
|
"""
|
||||||
@@ -114,7 +111,7 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
|||||||
(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) {
|
||||||
@@ -158,33 +155,6 @@ 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
|
||||||
@@ -217,64 +187,4 @@ 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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
package com.kamco.cd.training.train;
|
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.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;
|
||||||
import com.kamco.cd.training.train.service.TrainingMetricsService;
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
@@ -32,7 +29,6 @@ public class TrainApiController {
|
|||||||
private final TrainJobService trainJobService;
|
private final TrainJobService trainJobService;
|
||||||
private final TestJobService testJobService;
|
private final TestJobService testJobService;
|
||||||
private final DataSetCountersService dataSetCountersService;
|
private final DataSetCountersService dataSetCountersService;
|
||||||
private final TrainingMetricsService trainingMetricsService;
|
|
||||||
|
|
||||||
@Operation(summary = "학습 실행", description = "학습 실행 API")
|
@Operation(summary = "학습 실행", description = "학습 실행 API")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
@@ -240,85 +236,4 @@ public class TrainApiController {
|
|||||||
trainJobService.status(uuid, modelId);
|
trainJobService.status(uuid, modelId);
|
||||||
return ApiResponseDto.ok("ok");
|
return ApiResponseDto.ok("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(
|
|
||||||
summary = "하이퍼파라미터 기반 학습 메트릭 조회",
|
|
||||||
description =
|
|
||||||
"하이퍼파라미터 UUID로 해당 파라미터를 사용하는 모델의 학습 메트릭을 조회합니다. "
|
|
||||||
+ "val.csv와 train.csv를 우선 사용하며, 없을 경우 processing.log를 파싱합니다.")
|
|
||||||
@ApiResponses(
|
|
||||||
value = {
|
|
||||||
@ApiResponse(
|
|
||||||
responseCode = "200",
|
|
||||||
description = "조회 성공",
|
|
||||||
content =
|
|
||||||
@Content(
|
|
||||||
mediaType = "application/json",
|
|
||||||
schema = @Schema(implementation = TrainingMetricsDto.Response.class))),
|
|
||||||
@ApiResponse(
|
|
||||||
responseCode = "404",
|
|
||||||
description = "하이퍼파라미터 또는 모델을 찾을 수 없음",
|
|
||||||
content = @Content),
|
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
|
||||||
})
|
|
||||||
@GetMapping(
|
|
||||||
path = "/metrics/hyper-param/{hyperParamUuid}",
|
|
||||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
public ApiResponseDto<TrainingMetricsDto.Response> getMetricsByHyperParam(
|
|
||||||
@Parameter(description = "하이퍼파라미터 UUID", example = "57fc9170-64c1-4128-aa7b-0657f08d6d10")
|
|
||||||
@PathVariable
|
|
||||||
UUID hyperParamUuid) {
|
|
||||||
TrainingMetricsDto.Response response =
|
|
||||||
trainingMetricsService.getTrainingMetricsByHyperParam(hyperParamUuid);
|
|
||||||
return ApiResponseDto.ok(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(
|
|
||||||
summary = "모델 기반 학습 메트릭 조회",
|
|
||||||
description =
|
|
||||||
"모델 UUID로 해당 모델의 학습 메트릭을 조회합니다. "
|
|
||||||
+ "val.csv와 train.csv를 우선 사용하며, 없을 경우 processing.log를 파싱합니다.")
|
|
||||||
@ApiResponses(
|
|
||||||
value = {
|
|
||||||
@ApiResponse(
|
|
||||||
responseCode = "200",
|
|
||||||
description = "조회 성공",
|
|
||||||
content =
|
|
||||||
@Content(
|
|
||||||
mediaType = "application/json",
|
|
||||||
schema = @Schema(implementation = TrainingMetricsDto.Response.class))),
|
|
||||||
@ApiResponse(responseCode = "404", description = "모델을 찾을 수 없음", content = @Content),
|
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
|
||||||
})
|
|
||||||
@GetMapping(path = "/metrics/model/{modelUuid}", produces = MediaType.APPLICATION_JSON_VALUE)
|
|
||||||
public ApiResponseDto<TrainingMetricsDto.Response> getMetricsByModel(
|
|
||||||
@Parameter(description = "모델 UUID", example = "b34a2d18-11e6-4b1b-a156-cd314bec45bb")
|
|
||||||
@PathVariable
|
|
||||||
UUID modelUuid) {
|
|
||||||
TrainingMetricsDto.Response response =
|
|
||||||
trainingMetricsService.getTrainingMetricsByModelUuid(modelUuid);
|
|
||||||
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,7 +15,6 @@ 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.nio.file.Path;
|
import java.util.Properties;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
@@ -23,17 +23,6 @@ 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 {
|
||||||
@@ -44,133 +33,20 @@ 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 {
|
||||||
|
|
||||||
// 변화 탐지 관련 메트릭 (Changed)
|
@JsonProperty("f1_score")
|
||||||
@JsonProperty("changed_fscore")
|
private Float f1Score;
|
||||||
private Float changedFscore;
|
|
||||||
|
|
||||||
@JsonProperty("changed_precision")
|
private Float precision;
|
||||||
private Float changedPrecision;
|
private Float recall;
|
||||||
|
private Float loss;
|
||||||
@JsonProperty("changed_recall")
|
private Double iou;
|
||||||
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
|
||||||
@@ -180,35 +56,4 @@ 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,8 +84,6 @@ 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
package com.kamco.cd.training.train.dto;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
|
||||||
import java.util.List;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Builder;
|
|
||||||
import lombok.Data;
|
|
||||||
import lombok.NoArgsConstructor;
|
|
||||||
|
|
||||||
public class TrainingMetricsDto {
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "TrainingMetricsResponse", description = "학습 메트릭 조회 응답")
|
|
||||||
public static class Response {
|
|
||||||
|
|
||||||
@Schema(description = "학습 작업 ID (모델 UUID)", example = "b34a2d18-11e6-4b1b-a156-cd314bec45bb")
|
|
||||||
private String jobId;
|
|
||||||
|
|
||||||
@Schema(
|
|
||||||
description = "기본 경로",
|
|
||||||
example = "/data/training/response/b34a2d18-11e6-4b1b-a156-cd314bec45bb-out")
|
|
||||||
private String basePath;
|
|
||||||
|
|
||||||
@Schema(description = "데이터 소스 (csv 또는 log)", example = "csv")
|
|
||||||
private String source;
|
|
||||||
|
|
||||||
@Schema(description = "응답 상태 (SUCCESS, EMPTY, ERROR)", example = "SUCCESS")
|
|
||||||
private String status;
|
|
||||||
|
|
||||||
@Schema(description = "에러 메시지 (오류 발생 시만 포함)")
|
|
||||||
private String errorMessage;
|
|
||||||
|
|
||||||
@Schema(description = "Epoch별 학습 메트릭 데이터")
|
|
||||||
private List<EpochMetrics> epochs;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "EpochMetrics", description = "Epoch 단위 메트릭 데이터")
|
|
||||||
public static class EpochMetrics {
|
|
||||||
|
|
||||||
@Schema(description = "Epoch 번호", example = "1")
|
|
||||||
private Integer epoch;
|
|
||||||
|
|
||||||
@Schema(description = "학습 데이터 (train.csv에서 추출)")
|
|
||||||
private TrainMetrics train;
|
|
||||||
|
|
||||||
@Schema(description = "검증 데이터 요약 (val.csv에서 추출)")
|
|
||||||
private SummaryMetrics summary;
|
|
||||||
|
|
||||||
@Schema(description = "클래스별 메트릭 (changed, unchanged)")
|
|
||||||
private List<ClassMetrics> classes;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "TrainMetrics", description = "학습 메트릭 (train.csv)")
|
|
||||||
public static class TrainMetrics {
|
|
||||||
|
|
||||||
@Schema(description = "Iteration", example = "37")
|
|
||||||
@JsonProperty("iteration")
|
|
||||||
private Integer iteration;
|
|
||||||
|
|
||||||
@Schema(description = "Loss", example = "0.61584342")
|
|
||||||
@JsonProperty("loss")
|
|
||||||
private Double loss;
|
|
||||||
|
|
||||||
@Schema(description = "Learning Rate", example = "8.4e-07")
|
|
||||||
@JsonProperty("lr")
|
|
||||||
private String lr;
|
|
||||||
|
|
||||||
@Schema(description = "처리 시간 (초)", example = "1.5034")
|
|
||||||
@JsonProperty("time")
|
|
||||||
private Double time;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "SummaryMetrics", description = "검증 메트릭 요약 (val.csv)")
|
|
||||||
public static class SummaryMetrics {
|
|
||||||
|
|
||||||
@Schema(description = "Accuracy (All Accuracy)", example = "29.92")
|
|
||||||
@JsonProperty("aAcc")
|
|
||||||
private Double aAcc;
|
|
||||||
|
|
||||||
@Schema(description = "Mean F-Score", example = "24.49")
|
|
||||||
@JsonProperty("mFscore")
|
|
||||||
private Double mFscore;
|
|
||||||
|
|
||||||
@Schema(description = "Mean Precision", example = "51.07")
|
|
||||||
@JsonProperty("mPrecision")
|
|
||||||
private Double mPrecision;
|
|
||||||
|
|
||||||
@Schema(description = "Mean Recall", example = "64.22")
|
|
||||||
@JsonProperty("mRecall")
|
|
||||||
private Double mRecall;
|
|
||||||
|
|
||||||
@Schema(description = "Mean IoU (Intersection over Union)", example = "15.49")
|
|
||||||
@JsonProperty("mIoU")
|
|
||||||
private Double mIoU;
|
|
||||||
|
|
||||||
@Schema(description = "Mean Accuracy", example = "64.22")
|
|
||||||
@JsonProperty("mAcc")
|
|
||||||
private Double mAcc;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "ClassMetrics", description = "클래스별 메트릭 (changed/unchanged)")
|
|
||||||
public static class ClassMetrics {
|
|
||||||
|
|
||||||
@Schema(description = "클래스명 (changed 또는 unchanged)", example = "unchanged")
|
|
||||||
private String className;
|
|
||||||
|
|
||||||
@Schema(description = "F-Score", example = "44.735149")
|
|
||||||
private Double fscore;
|
|
||||||
|
|
||||||
@Schema(description = "Precision", example = "99.779264")
|
|
||||||
private Double precision;
|
|
||||||
|
|
||||||
@Schema(description = "Recall", example = "28.813878")
|
|
||||||
private Double recall;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
@NoArgsConstructor
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Schema(name = "ProcessingLogMetrics", description = "processing.log 파싱 결과 (내부용)")
|
|
||||||
public static class ProcessingLogMetrics {
|
|
||||||
|
|
||||||
private Integer epoch;
|
|
||||||
private SummaryMetrics summary;
|
|
||||||
private List<ClassMetrics> classes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
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,42 +158,12 @@ 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={}/{} | Progress: {}%",
|
"[TRAIN] container={} epoch={} iter={}/{}",
|
||||||
stepLabel,
|
|
||||||
containerName,
|
containerName,
|
||||||
epoch,
|
epoch,
|
||||||
maxEpochs,
|
|
||||||
iter,
|
iter,
|
||||||
totalIter,
|
totalIter);
|
||||||
String.format("%.2f", progress));
|
|
||||||
|
|
||||||
modelTrainJobCoreService.updateEpoch(containerName, epoch);
|
modelTrainJobCoreService.updateEpoch(containerName, epoch);
|
||||||
}
|
}
|
||||||
@@ -301,11 +271,7 @@ public class DockerTrainService {
|
|||||||
c.add("-v");
|
c.add("-v");
|
||||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||||
c.add("-v");
|
c.add("-v");
|
||||||
if (req.getReqTmpYn()) {
|
c.add(symbolicDir + ":/data"); // 요청할경로
|
||||||
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"); // 저장될경로
|
||||||
|
|
||||||
@@ -506,17 +472,11 @@ 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");
|
||||||
if (req.getReqTmpYn()) {
|
c.add(responseDir + ":/checkpoints");
|
||||||
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");
|
||||||
|
|
||||||
@@ -524,7 +484,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,11 +4,9 @@ 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;
|
||||||
@@ -21,8 +19,6 @@ 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;
|
||||||
@@ -52,9 +48,6 @@ 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() {
|
||||||
|
|
||||||
@@ -85,13 +78,13 @@ public class ModelTestMetricsJobService {
|
|||||||
/**
|
/**
|
||||||
* 베스트 에폭 zip파일 생성, 테스트결과 db등록
|
* 베스트 에폭 zip파일 생성, 테스트결과 db등록
|
||||||
*
|
*
|
||||||
* @param modelInfo 모델 정보 (modelId, responsePath, uuid)
|
* @param modelInfo
|
||||||
*/
|
*/
|
||||||
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);
|
||||||
|
|
||||||
@@ -140,9 +133,8 @@ public class ModelTestMetricsJobService {
|
|||||||
// 패키징할 파일 만들기
|
// 패키징할 파일 만들기
|
||||||
modelTestMetricsJobCoreService.updatePackingStart(modelInfo.getModelId(), ZonedDateTime.now());
|
modelTestMetricsJobCoreService.updatePackingStart(modelInfo.getModelId(), ZonedDateTime.now());
|
||||||
|
|
||||||
// 간단한 형식의 JSON 생성 (ZIP 파일용)
|
ModelMetricJsonDto jsonDto =
|
||||||
SimpleMetricJsonDto jsonDto =
|
modelTestMetricsJobCoreService.getTestMetricPackingInfo(modelInfo.getModelId());
|
||||||
modelTestMetricsJobCoreService.getSimpleTestMetricPackingInfo(modelInfo.getModelId());
|
|
||||||
try {
|
try {
|
||||||
writeJsonFile(
|
writeJsonFile(
|
||||||
jsonDto,
|
jsonDto,
|
||||||
@@ -166,270 +158,37 @@ public class ModelTestMetricsJobService {
|
|||||||
fileInfo.getBestEpochFileName() + ".pth",
|
fileInfo.getBestEpochFileName() + ".pth",
|
||||||
fileInfo.getModelVersion() + ".json");
|
fileInfo.getModelVersion() + ".json");
|
||||||
|
|
||||||
try {
|
|
||||||
List<Path> files = new ArrayList<>();
|
List<Path> files = new ArrayList<>();
|
||||||
try (Stream<Path> s = Files.list(responsePath)) {
|
try (Stream<Path> s = Files.list(responsePath)) {
|
||||||
files.addAll(
|
files.addAll(
|
||||||
s.filter(Files::isRegularFile)
|
s.filter(Files::isRegularFile)
|
||||||
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
||||||
.collect(Collectors.toList()));
|
.collect(Collectors.toList()));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PT 파일 정확하게 조회
|
try (Stream<Path> s = Files.list(Path.of(ptPathDir))) {
|
||||||
Path ptFile = Paths.get(ptPathDir, ptFileName);
|
files.addAll(
|
||||||
if (Files.exists(ptFile)) {
|
s.filter(Files::isRegularFile)
|
||||||
files.add(ptFile);
|
.limit(1) // yolov8_6th-6m.pt 파일 1개만
|
||||||
} else {
|
.collect(Collectors.toList()));
|
||||||
log.warn("PT 파일을 찾을 수 없습니다: {}", ptFile);
|
} catch (IOException e) {
|
||||||
throw new IOException("PT 파일 누락: " + ptFile);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 기본 ZIP 생성
|
try {
|
||||||
zipFiles(files, zipPath);
|
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,7 +52,6 @@ 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,8 +13,6 @@ 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;
|
||||||
@@ -206,18 +204,6 @@ 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 // 이어하기
|
||||||
@@ -288,9 +274,6 @@ 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 모델 클래스별 조회
|
||||||
@@ -315,8 +298,6 @@ 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);
|
||||||
@@ -330,9 +311,6 @@ 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, "임시 데이터셋 생성에 실패했습니다.");
|
||||||
@@ -468,136 +446,4 @@ 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,7 +58,6 @@ 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")) {
|
||||||
@@ -66,21 +65,6 @@ 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(
|
||||||
@@ -103,24 +87,14 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -134,25 +108,11 @@ 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());
|
||||||
|
|
||||||
@@ -167,13 +127,6 @@ 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();
|
||||||
|
|||||||
@@ -1,482 +0,0 @@
|
|||||||
package com.kamco.cd.training.train.service;
|
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
|
||||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
|
||||||
import com.kamco.cd.training.postgres.repository.hyperparam.HyperParamRepository;
|
|
||||||
import com.kamco.cd.training.postgres.repository.model.ModelMngRepository;
|
|
||||||
import com.kamco.cd.training.train.dto.TrainingMetricsDto;
|
|
||||||
import java.io.BufferedReader;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
@Slf4j
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class TrainingMetricsService {
|
|
||||||
|
|
||||||
@Value("${train.docker.response_dir}")
|
|
||||||
private String responseDir;
|
|
||||||
|
|
||||||
private final HyperParamRepository hyperParamRepository;
|
|
||||||
private final ModelMngRepository modelMngRepository;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 UUID로 학습 메트릭 조회
|
|
||||||
*
|
|
||||||
* @param hyperParamUuid 하이퍼파라미터 UUID
|
|
||||||
* @return 학습 메트릭 응답
|
|
||||||
*/
|
|
||||||
public TrainingMetricsDto.Response getTrainingMetricsByHyperParam(UUID hyperParamUuid) {
|
|
||||||
log.info("하이퍼파라미터 UUID로 학습 메트릭 조회 시작: {}", hyperParamUuid);
|
|
||||||
|
|
||||||
// 1. 하이퍼파라미터로 모델 찾기
|
|
||||||
ModelHyperParamEntity hyperParam =
|
|
||||||
hyperParamRepository
|
|
||||||
.findHyperParamByUuid(hyperParamUuid)
|
|
||||||
.orElseThrow(
|
|
||||||
() -> new IllegalArgumentException("하이퍼파라미터를 찾을 수 없습니다: " + hyperParamUuid));
|
|
||||||
|
|
||||||
// 2. 해당 하이퍼파라미터를 사용하는 모델 찾기
|
|
||||||
List<ModelMasterEntity> models = modelMngRepository.findByHyperParamId(hyperParam.getId());
|
|
||||||
|
|
||||||
if (models.isEmpty()) {
|
|
||||||
log.warn("하이퍼파라미터 ID {}를 사용하는 모델이 없습니다.", hyperParam.getId());
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(hyperParamUuid.toString())
|
|
||||||
.basePath(null)
|
|
||||||
.source("none")
|
|
||||||
.status("EMPTY")
|
|
||||||
.errorMessage("해당 하이퍼파라미터를 사용하는 모델이 없습니다.")
|
|
||||||
.epochs(new ArrayList<>())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 가장 최근 모델 선택 (step1이 완료된 것 우선)
|
|
||||||
ModelMasterEntity targetModel =
|
|
||||||
models.stream()
|
|
||||||
.filter(m -> "COMPLETED".equals(m.getStep1State()))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(models.get(0));
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"선택된 모델 UUID: {}, ModelNo: {}, Step1State: {}",
|
|
||||||
targetModel.getUuid(),
|
|
||||||
targetModel.getModelNo(),
|
|
||||||
targetModel.getStep1State());
|
|
||||||
|
|
||||||
// 4. 모델 UUID로 메트릭 조회
|
|
||||||
return getTrainingMetricsByModelUuid(targetModel.getUuid());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 모델 UUID로 학습 메트릭 조회
|
|
||||||
*
|
|
||||||
* @param modelUuid 모델 UUID
|
|
||||||
* @return 학습 메트릭 응답
|
|
||||||
*/
|
|
||||||
public TrainingMetricsDto.Response getTrainingMetricsByModelUuid(UUID modelUuid) {
|
|
||||||
log.info("모델 UUID로 학습 메트릭 조회 시작: {}", modelUuid);
|
|
||||||
|
|
||||||
// 실제 존재하는 basePath 찾기 (uuid 또는 uuid-out)
|
|
||||||
PathInfo pathInfo = findActualBasePath(modelUuid);
|
|
||||||
|
|
||||||
if (pathInfo == null || !Files.exists(pathInfo.basePath)) {
|
|
||||||
log.warn(
|
|
||||||
"모델 결과 디렉토리가 존재하지 않습니다. 시도한 경로: {} 또는 {}-out",
|
|
||||||
responseDir + "/" + modelUuid,
|
|
||||||
responseDir + "/" + modelUuid);
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(modelUuid.toString())
|
|
||||||
.basePath(null)
|
|
||||||
.source("none")
|
|
||||||
.status("EMPTY")
|
|
||||||
.errorMessage("모델 결과 디렉토리가 존재하지 않습니다.")
|
|
||||||
.epochs(new ArrayList<>())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
Path basePathObj = pathInfo.basePath;
|
|
||||||
String basePath = pathInfo.basePathString;
|
|
||||||
|
|
||||||
// 1. CSV 파일 우선 시도
|
|
||||||
Path metricsDir = basePathObj.resolve("metrics");
|
|
||||||
Path valCsvPath = metricsDir.resolve("val.csv");
|
|
||||||
Path trainCsvPath = metricsDir.resolve("train.csv");
|
|
||||||
|
|
||||||
if (Files.exists(valCsvPath) && Files.exists(trainCsvPath)) {
|
|
||||||
log.info("CSV 파일을 사용하여 메트릭 파싱: {}", metricsDir);
|
|
||||||
try {
|
|
||||||
List<TrainingMetricsDto.EpochMetrics> epochs = parseCsvFiles(trainCsvPath, valCsvPath);
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(modelUuid.toString())
|
|
||||||
.basePath(basePath)
|
|
||||||
.source("csv")
|
|
||||||
.status("SUCCESS")
|
|
||||||
.epochs(epochs)
|
|
||||||
.build();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("CSV 파싱 중 오류 발생", e);
|
|
||||||
// CSV 실패 시 log fallback
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. processing.log fallback
|
|
||||||
Path processingDir = basePathObj.resolve("processing");
|
|
||||||
Path logPath = processingDir.resolve("processing.log");
|
|
||||||
|
|
||||||
if (Files.exists(logPath)) {
|
|
||||||
log.info("processing.log 파일을 사용하여 메트릭 파싱: {}", logPath);
|
|
||||||
try {
|
|
||||||
List<TrainingMetricsDto.EpochMetrics> epochs = parseProcessingLog(logPath);
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(modelUuid.toString())
|
|
||||||
.basePath(basePath)
|
|
||||||
.source("log")
|
|
||||||
.status("SUCCESS")
|
|
||||||
.epochs(epochs)
|
|
||||||
.build();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("processing.log 파싱 중 오류 발생", e);
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(modelUuid.toString())
|
|
||||||
.basePath(basePath)
|
|
||||||
.source("log")
|
|
||||||
.status("ERROR")
|
|
||||||
.errorMessage("로그 파싱 중 오류 발생: " + e.getMessage())
|
|
||||||
.epochs(new ArrayList<>())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 둘 다 없으면 EMPTY
|
|
||||||
log.warn("메트릭 파일을 찾을 수 없습니다: {}", basePath);
|
|
||||||
return TrainingMetricsDto.Response.builder()
|
|
||||||
.jobId(modelUuid.toString())
|
|
||||||
.basePath(basePath)
|
|
||||||
.source("none")
|
|
||||||
.status("EMPTY")
|
|
||||||
.errorMessage("메트릭 파일(val.csv 또는 processing.log)을 찾을 수 없습니다.")
|
|
||||||
.epochs(new ArrayList<>())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* train.csv + val.csv 파싱
|
|
||||||
*
|
|
||||||
* @param trainCsvPath train.csv 경로
|
|
||||||
* @param valCsvPath val.csv 경로
|
|
||||||
* @return Epoch별 메트릭 리스트
|
|
||||||
*/
|
|
||||||
private List<TrainingMetricsDto.EpochMetrics> parseCsvFiles(Path trainCsvPath, Path valCsvPath)
|
|
||||||
throws IOException {
|
|
||||||
|
|
||||||
log.debug("CSV 파일 파싱 시작: train={}, val={}", trainCsvPath, valCsvPath);
|
|
||||||
|
|
||||||
// train.csv 파싱
|
|
||||||
Map<Integer, TrainingMetricsDto.TrainMetrics> trainMetricsMap = parseTrainCsv(trainCsvPath);
|
|
||||||
|
|
||||||
// val.csv 파싱
|
|
||||||
Map<Integer, ValMetricsData> valMetricsMap = parseValCsv(valCsvPath);
|
|
||||||
|
|
||||||
// 합치기
|
|
||||||
List<TrainingMetricsDto.EpochMetrics> epochs = new ArrayList<>();
|
|
||||||
|
|
||||||
for (Integer epoch : trainMetricsMap.keySet()) {
|
|
||||||
TrainingMetricsDto.TrainMetrics trainMetrics = trainMetricsMap.get(epoch);
|
|
||||||
ValMetricsData valData = valMetricsMap.get(epoch);
|
|
||||||
|
|
||||||
if (valData != null) {
|
|
||||||
epochs.add(
|
|
||||||
TrainingMetricsDto.EpochMetrics.builder()
|
|
||||||
.epoch(epoch)
|
|
||||||
.train(trainMetrics)
|
|
||||||
.summary(valData.summary)
|
|
||||||
.classes(valData.classes)
|
|
||||||
.build());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.debug("CSV 파싱 완료: {} epoch(s)", epochs.size());
|
|
||||||
return epochs;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* train.csv 파싱
|
|
||||||
*
|
|
||||||
* @param trainCsvPath train.csv 경로
|
|
||||||
* @return Epoch별 TrainMetrics Map
|
|
||||||
*/
|
|
||||||
private Map<Integer, TrainingMetricsDto.TrainMetrics> parseTrainCsv(Path trainCsvPath)
|
|
||||||
throws IOException {
|
|
||||||
|
|
||||||
Map<Integer, TrainingMetricsDto.TrainMetrics> result = new HashMap<>();
|
|
||||||
|
|
||||||
try (BufferedReader reader = Files.newBufferedReader(trainCsvPath)) {
|
|
||||||
String headerLine = reader.readLine(); // 헤더 스킵
|
|
||||||
if (headerLine == null) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
String line;
|
|
||||||
while ((line = reader.readLine()) != null) {
|
|
||||||
String[] parts = line.split(",");
|
|
||||||
if (parts.length >= 5) {
|
|
||||||
try {
|
|
||||||
int epoch = Integer.parseInt(parts[0].trim());
|
|
||||||
int iteration = Integer.parseInt(parts[1].trim());
|
|
||||||
double loss = Double.parseDouble(parts[2].trim());
|
|
||||||
String lr = parts[3].trim();
|
|
||||||
double time = Double.parseDouble(parts[4].trim());
|
|
||||||
|
|
||||||
result.put(
|
|
||||||
epoch,
|
|
||||||
TrainingMetricsDto.TrainMetrics.builder()
|
|
||||||
.iteration(iteration)
|
|
||||||
.loss(loss)
|
|
||||||
.lr(lr)
|
|
||||||
.time(time)
|
|
||||||
.build());
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
log.warn("train.csv 파싱 오류 (라인 스킵): {}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* val.csv 파싱
|
|
||||||
*
|
|
||||||
* @param valCsvPath val.csv 경로
|
|
||||||
* @return Epoch별 ValMetricsData Map
|
|
||||||
*/
|
|
||||||
private Map<Integer, ValMetricsData> parseValCsv(Path valCsvPath) throws IOException {
|
|
||||||
|
|
||||||
Map<Integer, ValMetricsData> result = new HashMap<>();
|
|
||||||
|
|
||||||
try (BufferedReader reader = Files.newBufferedReader(valCsvPath)) {
|
|
||||||
String headerLine = reader.readLine(); // 헤더 스킵
|
|
||||||
if (headerLine == null) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
String line;
|
|
||||||
while ((line = reader.readLine()) != null) {
|
|
||||||
String[] parts = line.split(",");
|
|
||||||
if (parts.length >= 13) {
|
|
||||||
try {
|
|
||||||
int epoch = Integer.parseInt(parts[0].trim());
|
|
||||||
double aAcc = Double.parseDouble(parts[1].trim());
|
|
||||||
double mFscore = Double.parseDouble(parts[2].trim());
|
|
||||||
double mPrecision = Double.parseDouble(parts[3].trim());
|
|
||||||
double mRecall = Double.parseDouble(parts[4].trim());
|
|
||||||
double mIoU = Double.parseDouble(parts[5].trim());
|
|
||||||
double mAcc = Double.parseDouble(parts[6].trim());
|
|
||||||
|
|
||||||
double changedFscore = Double.parseDouble(parts[7].trim());
|
|
||||||
double changedPrecision = Double.parseDouble(parts[8].trim());
|
|
||||||
double changedRecall = Double.parseDouble(parts[9].trim());
|
|
||||||
|
|
||||||
double unchangedFscore = Double.parseDouble(parts[10].trim());
|
|
||||||
double unchangedPrecision = Double.parseDouble(parts[11].trim());
|
|
||||||
double unchangedRecall = Double.parseDouble(parts[12].trim());
|
|
||||||
|
|
||||||
TrainingMetricsDto.SummaryMetrics summary =
|
|
||||||
TrainingMetricsDto.SummaryMetrics.builder()
|
|
||||||
.aAcc(aAcc)
|
|
||||||
.mFscore(mFscore)
|
|
||||||
.mPrecision(mPrecision)
|
|
||||||
.mRecall(mRecall)
|
|
||||||
.mIoU(mIoU)
|
|
||||||
.mAcc(mAcc)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
List<TrainingMetricsDto.ClassMetrics> classes = new ArrayList<>();
|
|
||||||
classes.add(
|
|
||||||
TrainingMetricsDto.ClassMetrics.builder()
|
|
||||||
.className("unchanged")
|
|
||||||
.fscore(unchangedFscore)
|
|
||||||
.precision(unchangedPrecision)
|
|
||||||
.recall(unchangedRecall)
|
|
||||||
.build());
|
|
||||||
classes.add(
|
|
||||||
TrainingMetricsDto.ClassMetrics.builder()
|
|
||||||
.className("changed")
|
|
||||||
.fscore(changedFscore)
|
|
||||||
.precision(changedPrecision)
|
|
||||||
.recall(changedRecall)
|
|
||||||
.build());
|
|
||||||
|
|
||||||
result.put(epoch, new ValMetricsData(summary, classes));
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
log.warn("val.csv 파싱 오류 (라인 스킵): {}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* processing.log 파싱 (fallback)
|
|
||||||
*
|
|
||||||
* @param logPath processing.log 경로
|
|
||||||
* @return Epoch별 메트릭 리스트
|
|
||||||
*/
|
|
||||||
private List<TrainingMetricsDto.EpochMetrics> parseProcessingLog(Path logPath)
|
|
||||||
throws IOException {
|
|
||||||
|
|
||||||
log.debug("processing.log 파싱 시작: {}", logPath);
|
|
||||||
|
|
||||||
List<TrainingMetricsDto.EpochMetrics> epochs = new ArrayList<>();
|
|
||||||
|
|
||||||
// 정규식 패턴
|
|
||||||
Pattern epochPattern = Pattern.compile("Epoch\\(val\\)\\s*\\[(\\d+)\\]");
|
|
||||||
Pattern summaryPattern =
|
|
||||||
Pattern.compile(
|
|
||||||
"aAcc:\\s*([\\d.]+)\\s+mFscore:\\s*([\\d.]+)\\s+mPrecision:\\s*([\\d.]+)\\s+mRecall:\\s*([\\d.]+)\\s+mIoU:\\s*([\\d.]+)\\s+mAcc:\\s*([\\d.]+)");
|
|
||||||
Pattern classPattern =
|
|
||||||
Pattern.compile(
|
|
||||||
"\\|\\s*(unchanged|changed)\\s*\\|\\s*([\\d.]+)\\s*\\|\\s*([\\d.]+)\\s*\\|\\s*([\\d.]+)\\s*\\|\\s*([\\d.]+)\\s*\\|\\s*([\\d.]+)");
|
|
||||||
|
|
||||||
try (BufferedReader reader = Files.newBufferedReader(logPath)) {
|
|
||||||
String line;
|
|
||||||
Integer currentEpoch = null;
|
|
||||||
TrainingMetricsDto.SummaryMetrics currentSummary = null;
|
|
||||||
List<TrainingMetricsDto.ClassMetrics> currentClasses = new ArrayList<>();
|
|
||||||
|
|
||||||
while ((line = reader.readLine()) != null) {
|
|
||||||
// Epoch 추출
|
|
||||||
Matcher epochMatcher = epochPattern.matcher(line);
|
|
||||||
if (epochMatcher.find()) {
|
|
||||||
// 이전 epoch 데이터 저장
|
|
||||||
if (currentEpoch != null && currentSummary != null) {
|
|
||||||
epochs.add(
|
|
||||||
TrainingMetricsDto.EpochMetrics.builder()
|
|
||||||
.epoch(currentEpoch)
|
|
||||||
.train(null) // log에는 train 정보 없음
|
|
||||||
.summary(currentSummary)
|
|
||||||
.classes(new ArrayList<>(currentClasses))
|
|
||||||
.build());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 새 epoch 시작
|
|
||||||
currentEpoch = Integer.parseInt(epochMatcher.group(1));
|
|
||||||
currentSummary = null;
|
|
||||||
currentClasses.clear();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Summary 추출
|
|
||||||
Matcher summaryMatcher = summaryPattern.matcher(line);
|
|
||||||
if (summaryMatcher.find()) {
|
|
||||||
currentSummary =
|
|
||||||
TrainingMetricsDto.SummaryMetrics.builder()
|
|
||||||
.aAcc(Double.parseDouble(summaryMatcher.group(1)))
|
|
||||||
.mFscore(Double.parseDouble(summaryMatcher.group(2)))
|
|
||||||
.mPrecision(Double.parseDouble(summaryMatcher.group(3)))
|
|
||||||
.mRecall(Double.parseDouble(summaryMatcher.group(4)))
|
|
||||||
.mIoU(Double.parseDouble(summaryMatcher.group(5)))
|
|
||||||
.mAcc(Double.parseDouble(summaryMatcher.group(6)))
|
|
||||||
.build();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Class 추출
|
|
||||||
Matcher classMatcher = classPattern.matcher(line);
|
|
||||||
if (classMatcher.find()) {
|
|
||||||
currentClasses.add(
|
|
||||||
TrainingMetricsDto.ClassMetrics.builder()
|
|
||||||
.className(classMatcher.group(1))
|
|
||||||
.fscore(Double.parseDouble(classMatcher.group(2)))
|
|
||||||
.precision(Double.parseDouble(classMatcher.group(3)))
|
|
||||||
.recall(Double.parseDouble(classMatcher.group(4)))
|
|
||||||
.build());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 마지막 epoch 데이터 저장
|
|
||||||
if (currentEpoch != null && currentSummary != null) {
|
|
||||||
epochs.add(
|
|
||||||
TrainingMetricsDto.EpochMetrics.builder()
|
|
||||||
.epoch(currentEpoch)
|
|
||||||
.train(null)
|
|
||||||
.summary(currentSummary)
|
|
||||||
.classes(new ArrayList<>(currentClasses))
|
|
||||||
.build());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.debug("processing.log 파싱 완료: {} epoch(s)", epochs.size());
|
|
||||||
return epochs;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 실제 존재하는 basePath 찾기 (uuid 또는 uuid-out 둘 다 확인)
|
|
||||||
*
|
|
||||||
* @param modelUuid 모델 UUID
|
|
||||||
* @return PathInfo 또는 null
|
|
||||||
*/
|
|
||||||
private PathInfo findActualBasePath(UUID modelUuid) {
|
|
||||||
// 1순위: {uuid}-out 경로 확인
|
|
||||||
String basePathWithSuffix = responseDir + "/" + modelUuid + "-out";
|
|
||||||
Path pathWithSuffix = Paths.get(basePathWithSuffix);
|
|
||||||
|
|
||||||
if (Files.exists(pathWithSuffix) && Files.isDirectory(pathWithSuffix)) {
|
|
||||||
log.debug("경로 발견: {} (suffix -out 포함)", basePathWithSuffix);
|
|
||||||
return new PathInfo(pathWithSuffix, basePathWithSuffix);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2순위: {uuid} 경로 확인 (suffix 없음)
|
|
||||||
String basePathWithoutSuffix = responseDir + "/" + modelUuid;
|
|
||||||
Path pathWithoutSuffix = Paths.get(basePathWithoutSuffix);
|
|
||||||
|
|
||||||
if (Files.exists(pathWithoutSuffix) && Files.isDirectory(pathWithoutSuffix)) {
|
|
||||||
log.debug("경로 발견: {} (suffix 없음)", basePathWithoutSuffix);
|
|
||||||
return new PathInfo(pathWithoutSuffix, basePathWithoutSuffix);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 둘 다 없으면 null 반환
|
|
||||||
log.warn("경로를 찾을 수 없음: {} 또는 {}", basePathWithSuffix, basePathWithoutSuffix);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 경로 정보를 담는 내부 클래스 */
|
|
||||||
private static class PathInfo {
|
|
||||||
Path basePath;
|
|
||||||
String basePathString;
|
|
||||||
|
|
||||||
PathInfo(Path basePath, String basePathString) {
|
|
||||||
this.basePath = basePath;
|
|
||||||
this.basePathString = basePathString;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** val.csv 파싱 결과를 담는 내부 클래스 */
|
|
||||||
private static class ValMetricsData {
|
|
||||||
TrainingMetricsDto.SummaryMetrics summary;
|
|
||||||
List<TrainingMetricsDto.ClassMetrics> classes;
|
|
||||||
|
|
||||||
ValMetricsData(
|
|
||||||
TrainingMetricsDto.SummaryMetrics summary, List<TrainingMetricsDto.ClassMetrics> classes) {
|
|
||||||
this.summary = summary;
|
|
||||||
this.classes = classes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,295 +0,0 @@
|
|||||||
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,46 +30,20 @@ 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:
|
||||||
base_path: /backup/data/training
|
dataset-dir: /home/kcomu/data/request/
|
||||||
dataset-dir: ${file.base_path}/request/
|
|
||||||
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||||
|
|
||||||
pt-path: ${file.base_path}/response/v6-cls-checkpoints/
|
pt-path: /home/kcomu/data/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: /backup/data/training
|
base_path: /home/kcomu/data
|
||||||
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