82 Commits

Author SHA1 Message Date
b85f920f40 학습 소요시간 로직 수정 2026-05-19 14:55:49 +09:00
e4851b1153 test 실행 도커 명령어 수정 2026-05-19 14:33:36 +09:00
b73aef5cf8 class 명칭 가져오는 부분 영어버전 추가 2026-05-15 14:59:39 +09:00
72c8f6a047 제작 업로드 시 dataset_path 안 맞는 현상 수정 2026-05-15 10:45:44 +09:00
c7a49ea4ea headerUtil 확인 2026-05-15 10:36:05 +09:00
fbef92af55 모델관리 API 영문버전 로직 수정 2026-05-12 14:51:18 +09:00
154db0ac27 영어버전도 나오게 추가 2026-05-12 14:27:09 +09:00
9835170cd7 납품데이터 등록 시 totalSize 추가 2026-05-08 10:40:06 +09:00
fd51f21ba6 납품 데이터 저장 시 uid 수정, 파일 업로드 경로 수정 2026-05-08 09:58:52 +09:00
776622e0a2 트랜잭션 5분 걸려있던 내용 주석처리 2026-05-07 15:29:24 +09:00
dabeeo
4d2d7a9ad1 check 2026-04-20 17:45:33 +09:00
dabeeo
532fbdbee4 hello 2026-04-20 17:35:26 +09:00
dabeeo
a2e5bf4e10 hoony 2026-04-20 17:15:46 +09:00
dabeeo
de2a2e2c35 hoony 2026-04-20 17:15:27 +09:00
dabeeo
f75ec77ccf hoony 2026-04-20 15:30:26 +09:00
dabeeo
9fa549285f hoony 2026-04-20 15:29:44 +09:00
dean
4fbfb31e97 hello 2026-04-14 15:11:00 +09:00
419b3ccdfc daniel 작업본 추가 2026-04-14 08:31:53 +09:00
afb3f57ef6 중단일 때 stop 추가 2026-04-09 17:53:17 +09:00
edff3b0ef8 daniel 작업본 추가 2026-04-09 17:23:59 +09:00
47e93f0d57 reqTmpYn 파라미터 셋팅 추가 2026-04-09 16:32:32 +09:00
449e1dc142 daniel 작업본 추가 2026-04-09 16:26:38 +09:00
ecca537670 데이터셋 1개일 때 심볼릭 링크 생성하지 않게 수정 2026-04-09 16:14:31 +09:00
ca080bf77b test metrics 원복 2026-04-09 15:59:17 +09:00
e64b1f15ba json 생성 수정 2026-04-09 15:05:16 +09:00
7db77226b7 원복 2026-04-09 14:25:41 +09:00
ce404924fd daniel 작업본 수정 2026-04-09 14:21:17 +09:00
bb48cb8610 zip 파일명 변경 커밋 2026-04-09 13:37:23 +09:00
8b7ff0162d daniel 작업 - best epoch의 pth 만큼 zip파일 생성 2026-04-09 13:15:49 +09:00
dean
02954aa439 Merge branch 'develop' of https://kamco.git.gs.dabeeo.com/MVPTeam/kamco-train-api into develop 2026-04-09 09:34:47 +09:00
dean
e3cf7b8909 test 2026-04-09 09:34:26 +09:00
59d39a79c3 daniel 작업 내용 커밋 2026-04-09 09:16:42 +09:00
dean
501b4a6f51 test 2026-04-08 18:26:25 +09:00
dean
be3e32a87a welcome 2026-04-08 17:47:30 +09:00
61d28c4ce3 spotless 2026-04-08 15:23:48 +09:00
593db69245 daniel file manager 수정 반영 2026-04-08 15:19:46 +09:00
5651fd7819 Merge pull request '파일 메니저 api 반영' (#200) from feat/training_260408 into develop
Reviewed-on: #200
2026-04-08 09:39:00 +09:00
71a8b45097 파일 메니저 api 반영 2026-04-08 09:38:00 +09:00
219e17e8ba daniel file manager 수정 반영 2026-04-07 19:35:45 +09:00
a9260c17f4 Merge pull request '파일 메니저 api 반영' (#197) from feat/training_260324 into develop
Reviewed-on: #197
2026-04-07 17:23:52 +09:00
b546e053b6 파일 메니저 api 반영 2026-04-07 17:23:32 +09:00
a66b25dda5 Merge pull request '학습 상세조회 데이터셋 수정' (#196) from feat/training_260324 into develop
Reviewed-on: #196
2026-04-07 17:19:48 +09:00
bc67753b99 학습 상세조회 데이터셋 수정 2026-04-07 17:19:31 +09:00
5dc817ecad Merge pull request '데이터셋 태양광 등록 변수명 수정' (#195) from feat/training_260324 into develop
Reviewed-on: #195
2026-04-07 16:47:06 +09:00
8043e1a41a 데이터셋 태양광 조회 추가 2026-04-07 16:46:33 +09:00
98e3c35d9a Merge pull request '데이터셋 태양광 조회 추가' (#194) from feat/training_260324 into develop
Reviewed-on: #194
2026-04-07 16:35:47 +09:00
d48e96ba82 데이터셋 태양광 조회 추가 2026-04-07 16:35:29 +09:00
3da4b73c59 Merge pull request '모델 파일 경로 조회, 데이터셋 파일 경로 조회, 디렉토리 용량 체크, 모델별 학습 실행 상태 조회' (#193) from feat/training_260324 into develop
Reviewed-on: #193
2026-04-07 14:55:58 +09:00
01a1211e55 모델 파일 경로 조회, 데이터셋 파일 경로 조회, 디렉토리 용량 체크, 모델별 학습 실행 상태 조회 2026-04-07 14:55:27 +09:00
c0532f230c Merge pull request 'batch_size' (#192) from feat/training_260324 into develop
Reviewed-on: #192
2026-04-06 21:42:12 +09:00
a0f4d0b8e2 batch_size 2026-04-06 21:41:11 +09:00
38906a5795 Merge pull request '상태변경 추가' (#191) from feat/training_260324 into develop
Reviewed-on: #191
2026-04-06 21:33:29 +09:00
051082665d 상태변경 추가 2026-04-06 21:32:24 +09:00
13d9d9176b 상태변경 추가 2026-04-06 20:40:42 +09:00
62398846d3 파일관리 기능 api 커밋 2026-04-06 17:36:40 +09:00
260569225c 파일관리 기능 api 커밋 2026-04-06 17:36:19 +09:00
dean
acdffd99ec test 2026-04-06 16:39:58 +09:00
bd6fe924de 모델 삭제할때 임시파일 경로 Null 처리 2026-04-06 14:59:27 +09:00
d7458e3c8b Merge pull request 'feat/training_260324' (#190) from feat/training_260324 into develop
Reviewed-on: #190
2026-04-03 16:05:07 +09:00
92492ca879 하이퍼 파라미터 컬럼 사이즈 변경 2026-04-03 16:04:49 +09:00
a5d79b2504 하이퍼 파라미터 컬럼 사이즈 변경 2026-04-03 16:03:17 +09:00
b8c53aae64 Merge pull request '데이터셋 조회 class count integer -> Long 로 변경' (#189) from feat/training_260324 into develop
Reviewed-on: #189
2026-04-03 15:34:19 +09:00
348d3d0052 데이터셋 조회 class count integer -> Long 로 변경 2026-04-03 15:33:54 +09:00
b85ead36b4 Merge pull request '데이터셋 조회 class count integer -> Long 로 변경' (#188) from feat/training_260324 into develop
Reviewed-on: #188
2026-04-03 15:17:41 +09:00
e77eae8f8b 데이터셋 조회 class count integer -> Long 로 변경 2026-04-03 15:17:17 +09:00
570952df7e Merge pull request 'spotless 적용' (#187) from feat/training_260324 into develop
Reviewed-on: #187
2026-04-03 10:20:58 +09:00
26d34d88eb spotless 적용 2026-04-03 10:20:40 +09:00
46a5d4c2d3 Merge pull request 'Save-best, Save-best-rule 컬럼 varchar100으로 변경, spotless 적용' (#186) from feat/training_260324 into develop
Reviewed-on: #186
2026-04-03 09:20:34 +09:00
91f022889b Save-best, Save-best-rule 컬럼 varchar100으로 변경 2026-04-03 09:18:26 +09:00
dean
f00296cf2c welcome 2026-04-02 21:17:01 +09:00
f98f6cb038 Merge pull request 'solar -> solarCnt 변경' (#185) from feat/training_260324 into develop
Reviewed-on: #185
2026-04-02 18:57:16 +09:00
d1593e57c3 solar -> solarCnt 변경 2026-04-02 18:56:52 +09:00
732dccf2e4 Merge pull request 'solar -> solarCnt 변경' (#184) from feat/training_260324 into develop
Reviewed-on: #184
2026-04-02 18:55:14 +09:00
f6cd553af8 solar -> solarCnt 변경 2026-04-02 18:54:52 +09:00
618dbe4047 Merge pull request '데이터셋 entity 수정, 데이터셋 저장 수정' (#183) from feat/training_260324 into develop
Reviewed-on: #183
2026-04-02 18:42:55 +09:00
5546e8ef89 데이터셋 entity 수정, 데이터셋 저장 수정 2026-04-02 18:42:25 +09:00
b952ec7b47 Merge pull request '임시 데이터셋 폴더 생성 G4 추가' (#182) from feat/training_260324 into develop
Reviewed-on: #182
2026-04-02 18:05:11 +09:00
e93f533c59 임시 데이터셋 폴더 생성 G4 추가 2026-04-02 18:04:41 +09:00
a5267d8065 Merge pull request 'select-dataset-list api solarPanelCnt 추가, spotless 적용' (#181) from feat/training_260324 into develop
Reviewed-on: #181
2026-04-02 17:45:16 +09:00
71d9835b03 select-dataset-list api solarPanelCnt 추가, spotless 적용 2026-04-02 17:44:27 +09:00
39f39a4f0c Merge pull request 'ModelType enum G4 추가' (#180) from feat/training_260324 into develop
Reviewed-on: #180
2026-04-02 16:55:14 +09:00
1df7142544 ModelType enum G4 추가 2026-04-02 16:54:25 +09:00
70 changed files with 7080 additions and 839 deletions

230
deploy/check-nginx.sh Executable file
View File

@@ -0,0 +1,230 @@
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_DIR="/data/training/nginx"
PASS=0
FAIL=0
# docker compose v1/v2 자동 감지
if command -v docker-compose &>/dev/null; then
DOCKER_COMPOSE="docker-compose"
elif docker compose version &>/dev/null 2>&1; then
DOCKER_COMPOSE="docker compose"
else
DOCKER_COMPOSE=""
fi
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'
ok() { echo -e "${GREEN}[OK]${NC} $1"; ((PASS++)); }
fail() { echo -e "${RED}[FAIL]${NC} $1"; ((FAIL++)); }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
section() { echo ""; echo "=== $1 ==="; }
# ──────────────────────────────────────────
section "디렉토리 확인"
# ──────────────────────────────────────────
for dir in \
/data/training/request \
/data/training/request/tmp \
/data/training/response \
/data/training/response/v6-cls-checkpoints \
/data/training/tmp \
"$NGINX_DIR" \
"$NGINX_DIR/ssl" \
"$NGINX_DIR/logs"; do
if [ -d "$dir" ]; then
ok "$dir"
else
fail "$dir 없음"
fi
done
# ──────────────────────────────────────────
section "nginx 파일 확인"
# ──────────────────────────────────────────
for f in \
"$NGINX_DIR/nginx.conf" \
"$NGINX_DIR/docker-compose-nginx.yml" \
"$NGINX_DIR/ssl/train-kamco.com.crt" \
"$NGINX_DIR/ssl/train-kamco.com.key" \
"$NGINX_DIR/ssl/openssl.cnf"; do
if [ -f "$f" ]; then
ok "$f"
else
fail "$f 없음"
fi
done
# ──────────────────────────────────────────
section "파일 권한 확인"
# ──────────────────────────────────────────
SSL_DIR_PERM=$(stat -c "%a" "$NGINX_DIR/ssl" 2>/dev/null)
KEY_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.key" 2>/dev/null)
CRT_PERM=$(stat -c "%a" "$NGINX_DIR/ssl/train-kamco.com.crt" 2>/dev/null)
[ "$SSL_DIR_PERM" = "700" ] && ok "ssl/ 권한 700" || fail "ssl/ 권한 오류 (현재: $SSL_DIR_PERM, 기대: 700)"
[ "$KEY_PERM" = "600" ] && ok "train-kamco.com.key 권한 600" || fail "key 권한 오류 (현재: $KEY_PERM, 기대: 600)"
[ "$CRT_PERM" = "644" ] && ok "train-kamco.com.crt 권한 644" || fail "crt 권한 오류 (현재: $CRT_PERM, 기대: 644)"
# ──────────────────────────────────────────
section "소유권 확인 (kcomu:kcomu)"
# ──────────────────────────────────────────
OWNER=$(stat -c "%U:%G" /data/training 2>/dev/null)
[ "$OWNER" = "kcomu:kcomu" ] && ok "/data/training 소유권 kcomu:kcomu" || fail "/data/training 소유권 오류 (현재: $OWNER)"
# ──────────────────────────────────────────
section "SSL 인증서 유효성"
# ──────────────────────────────────────────
if command -v openssl &>/dev/null && [ -f "$NGINX_DIR/ssl/train-kamco.com.crt" ]; then
EXPIRY=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -enddate 2>/dev/null | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null)
NOW_EPOCH=$(date +%s)
if [ "$EXPIRY_EPOCH" -gt "$NOW_EPOCH" ]; then
ok "인증서 유효 (만료: $EXPIRY)"
else
fail "인증서 만료됨 (만료: $EXPIRY)"
fi
SAN=$(openssl x509 -in "$NGINX_DIR/ssl/train-kamco.com.crt" -noout -text 2>/dev/null | grep -A1 "Subject Alternative Name" | tail -1)
echo " SAN: $SAN"
else
warn "openssl 없음 또는 인증서 파일 없음 - 인증서 검증 스킵"
fi
# ──────────────────────────────────────────
section "Docker 확인"
# ──────────────────────────────────────────
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
ok "Docker 실행 중"
# Docker network
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
ok "Docker network kamco-cds 존재"
else
fail "Docker network kamco-cds 없음 (setup.sh 재실행 필요)"
fi
# nginx 컨테이너 상태
CONTAINER_STATUS=$(docker inspect --format '{{.State.Status}}' kamco-train-nginx 2>/dev/null)
if [ "$CONTAINER_STATUS" = "running" ]; then
ok "kamco-train-nginx 컨테이너 실행 중"
elif [ -z "$CONTAINER_STATUS" ]; then
warn "kamco-train-nginx 컨테이너 없음 (아직 미실행)"
else
fail "kamco-train-nginx 컨테이너 상태: $CONTAINER_STATUS"
fi
else
fail "Docker 미실행 또는 설치 안 됨"
fi
# ──────────────────────────────────────────
section "nginx 설정 문법 검사"
# ──────────────────────────────────────────
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
echo " docker run으로 nginx -t 실행 중..."
# kamco-cds 네트워크가 있으면 연결 (upstream DNS 조회 가능)
NETWORK_OPT=""
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
NETWORK_OPT="--network kamco-cds"
fi
if docker run --rm $NETWORK_OPT \
-v "$NGINX_DIR/nginx.conf:/etc/nginx/nginx.conf:ro,Z" \
-v "$NGINX_DIR/ssl:/etc/nginx/ssl:ro,Z" \
nginx:alpine nginx -t 2>&1; then
ok "nginx 설정 문법 OK"
else
fail "nginx 설정 문법 오류"
fi
else
warn "Docker 없음 - nginx 문법 검사 스킵"
fi
# ──────────────────────────────────────────
section "/etc/hosts 확인"
# ──────────────────────────────────────────
for domain in api.train-kamco.com train-kamco.com; do
HOSTS_LINE=$(grep "$domain" /etc/hosts | grep -v "^#" | head -1)
if [ -n "$HOSTS_LINE" ]; then
ok "$domain 등록됨 → $HOSTS_LINE"
else
fail "$domain /etc/hosts 미등록"
fi
done
# ──────────────────────────────────────────
section "도메인 해석 확인"
# ──────────────────────────────────────────
for domain in api.train-kamco.com train-kamco.com; do
RESOLVED=$(getent hosts "$domain" 2>/dev/null | awk '{print $1}' | head -1)
if [ -n "$RESOLVED" ]; then
ok "$domain$RESOLVED"
else
fail "$domain 해석 실패 (DNS 또는 hosts 문제)"
fi
done
# ──────────────────────────────────────────
section "포트 연결 확인 (80 / 443)"
# ──────────────────────────────────────────
for port in 80 443; do
if command -v nc &>/dev/null; then
if nc -z -w3 api.train-kamco.com "$port" 2>/dev/null; then
ok "api.train-kamco.com:$port 열림"
else
warn "api.train-kamco.com:$port 닫힘 (nginx 미실행일 수 있음)"
fi
elif command -v curl &>/dev/null; then
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 3 \
"$([ "$port" = "443" ] && echo https || echo http)://api.train-kamco.com/" 2>/dev/null)
if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then
ok "api.train-kamco.com:$port 응답 (HTTP $HTTP_CODE)"
else
warn "api.train-kamco.com:$port 응답 없음 (nginx 미실행일 수 있음)"
fi
else
warn "nc/curl 없음 - 포트 확인 스킵"
break
fi
done
# ──────────────────────────────────────────
section "HTTPS 헬스체크"
# ──────────────────────────────────────────
if command -v curl &>/dev/null; then
for url in \
"https://api.train-kamco.com/monitor/health" \
"https://train-kamco.com/monitor/health"; do
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>/dev/null)
if [ "$HTTP_CODE" = "200" ]; then
ok "$url → HTTP $HTTP_CODE"
elif [ "$HTTP_CODE" = "000" ] || [ -z "$HTTP_CODE" ]; then
warn "$url → 응답 없음 (nginx 미실행일 수 있음)"
else
warn "$url → HTTP $HTTP_CODE"
fi
done
else
warn "curl 없음 - HTTPS 헬스체크 스킵"
fi
# ──────────────────────────────────────────
section "결과 요약"
# ──────────────────────────────────────────
echo ""
echo -e " ${GREEN}PASS: $PASS${NC} / ${RED}FAIL: $FAIL${NC}"
echo ""
if [ $FAIL -eq 0 ]; then
echo -e "${GREEN}모든 체크 통과. nginx 실행 준비 완료.${NC}"
if [ -n "$DOCKER_COMPOSE" ]; then
echo " cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
else
echo " [WARN] docker-compose / docker compose 를 찾을 수 없습니다."
fi
else
echo -e "${RED}$FAIL 개 항목 실패. 위 오류를 확인하세요.${NC}"
exit 1
fi

View File

@@ -0,0 +1,25 @@
services:
nginx:
image: nginx:alpine
container_name: kamco-train-nginx
user: "1000:1000"
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro,Z
- ./ssl:/etc/nginx/ssl:ro,Z
- ./logs:/var/log/nginx:Z
networks:
- kamco-cds
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "--no-check-certificate", "https://localhost/monitor/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
networks:
kamco-cds:
external: true

170
deploy/nginx.conf Normal file
View File

@@ -0,0 +1,170 @@
pid /var/log/nginx/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 로그 설정
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
sendfile on;
keepalive_timeout 65;
# user 1000:1000 실행 시 /var/cache/nginx 접근 불가 → logs 경로로 우회
client_body_temp_path /var/log/nginx/client_temp;
proxy_temp_path /var/log/nginx/proxy_temp;
fastcgi_temp_path /var/log/nginx/fastcgi_temp;
uwsgi_temp_path /var/log/nginx/uwsgi_temp;
scgi_temp_path /var/log/nginx/scgi_temp;
# 업로드 파일 크기 / 타임아웃 (10GB, 10분)
client_max_body_size 10G;
client_body_timeout 600s;
# Docker 내부 DNS - 시작 시 upstream 조회 실패 방지
resolver 127.0.0.11 valid=30s ipv6=off;
# HTTP → HTTPS 리다이렉트 서버
server {
listen 80;
server_name api.train-kamco.com train-kamco.com;
# 모든 HTTP 요청을 HTTPS로 리다이렉트
return 301 https://$host$request_uri;
}
# HTTPS 서버 설정
server {
listen 443 ssl;
http2 on;
server_name api.train-kamco.com;
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# CORS 헤더
add_header Access-Control-Allow-Origin "https://train-kamco.com" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, PATCH, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type, Cookie, X-Requested-With" always;
add_header Access-Control-Allow-Credentials "true" always;
location / {
if ($request_method = OPTIONS) {
return 204;
}
set $api http://kamco-train-api:8080;
proxy_pass $api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
proxy_set_header Authorization $http_authorization;
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_request_buffering off;
proxy_buffering off;
}
location /monitor/health {
set $api http://kamco-train-api:8080;
proxy_pass $api/monitor/health;
access_log off;
}
}
# HTTPS 서버 설정 - Next.js Web Application
server {
listen 443 ssl;
http2 on;
server_name train-kamco.com;
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
location /api/ {
set $api http://kamco-train-api:8080;
proxy_pass $api/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_request_buffering off;
proxy_buffering off;
}
location / {
set $web http://kamco-train-web:3002;
proxy_pass $web;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
}
}

38
deploy/setup-groups.sh Executable file
View File

@@ -0,0 +1,38 @@
#!/bin/bash
set -e
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'
ok() { echo -e "${GREEN}[OK]${NC} $1"; }
fail() { echo -e "${RED}[FAIL]${NC} $1"; exit 1; }
echo "=== GID 1000 그룹 설정 ==="
# GID 1000 그룹 없으면 생성
if ! getent group 1000 &>/dev/null; then
groupadd -g 1000 docker-users
ok "GID 1000 그룹(docker-users) 생성 완료"
else
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
ok "GID 1000 그룹 이미 존재: $GROUP_NAME"
fi
GROUP_NAME=$(getent group 1000 | cut -d: -f1)
# kcomu, docker 를 GID 1000 그룹에 추가
for user in kcomu docker; do
if id "$user" &>/dev/null; then
usermod -aG "$GROUP_NAME" "$user"
ok "$user$GROUP_NAME($GROUP_NAME) 그룹 추가 완료"
else
echo " [SKIP] $user 유저 없음"
fi
done
echo ""
echo "현재 $GROUP_NAME 그룹 멤버:"
getent group "$GROUP_NAME"
echo ""
echo "※ 그룹 변경은 재로그인 후 적용됩니다."

97
deploy/setup.sh Executable file
View File

@@ -0,0 +1,97 @@
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NGINX_DIR="/data/training/nginx"
# docker compose v1/v2 자동 감지
if command -v docker-compose &>/dev/null; then
DOCKER_COMPOSE="docker-compose"
elif docker compose version &>/dev/null 2>&1; then
DOCKER_COMPOSE="docker compose"
else
DOCKER_COMPOSE=""
fi
echo "=== 디렉토리 생성 ==="
mkdir -p /data/training/request
mkdir -p /data/training/request/tmp
mkdir -p /data/training/response
mkdir -p /data/training/response/v6-cls-checkpoints
mkdir -p /data/training/tmp
mkdir -p "$NGINX_DIR/ssl"
mkdir -p "$NGINX_DIR/logs"
echo "완료"
echo "=== nginx 파일 복사 ==="
cp "$SCRIPT_DIR/nginx.conf" "$NGINX_DIR/"
cp "$SCRIPT_DIR/docker-compose-nginx.yml" "$NGINX_DIR/"
echo "완료"
echo "=== SSL 파일 복사 ==="
cp "$SCRIPT_DIR/ssl/openssl.cnf" "$NGINX_DIR/ssl/"
cp "$SCRIPT_DIR/ssl/train-kamco.com.crt" "$NGINX_DIR/ssl/"
cp "$SCRIPT_DIR/ssl/train-kamco.com.key" "$NGINX_DIR/ssl/"
echo "완료"
echo "=== SSL 권한 설정 ==="
chmod 700 "$NGINX_DIR/ssl"
chmod 600 "$NGINX_DIR/ssl/train-kamco.com.key"
chmod 644 "$NGINX_DIR/ssl/train-kamco.com.crt"
echo "완료"
echo "=== 소유권 설정 (kcomu:kcomu) ==="
chown -R kcomu:kcomu /data/training
echo "완료"
echo "=== 그룹 설정 (setup-groups.sh) ==="
bash "$SCRIPT_DIR/setup-groups.sh"
echo "=== docker-compose-nginx.yml 소유권 설정 (1000:1000) ==="
chown 1000:1000 "$NGINX_DIR/docker-compose-nginx.yml"
echo "완료"
echo "=== docker-compose 래퍼 설정 ==="
if command -v docker-compose &>/dev/null; then
echo "docker-compose 이미 설치됨 (스킵)"
elif docker compose version &>/dev/null 2>&1; then
cat > /usr/local/bin/docker-compose << 'EOF'
#!/bin/bash
exec docker compose "$@"
EOF
chmod +x /usr/local/bin/docker-compose
echo "docker-compose → docker compose 래퍼 생성 완료"
DOCKER_COMPOSE="docker-compose"
else
echo "[WARN] docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
fi
echo "=== Docker network 설정 ==="
if docker network ls --format '{{.Name}}' | grep -q "^kamco-cds$"; then
echo "kamco-cds 네트워크 이미 존재 (스킵)"
else
docker network create kamco-cds
echo "kamco-cds 네트워크 생성 완료"
fi
echo "=== /etc/hosts 설정 ==="
if grep -q "train-kamco.com" /etc/hosts; then
echo "이미 설정되어 있음 (스킵)"
else
echo "127.0.0.1 api.train-kamco.com train-kamco.com" >> /etc/hosts
echo "추가 완료"
fi
echo "현재 hosts 설정:"
grep "train-kamco" /etc/hosts
echo ""
echo "=== 설치 완료 ==="
echo "생성된 디렉토리:"
find /data -type d | sort
echo ""
echo "=== nginx 실행 방법 ==="
if [ -n "$DOCKER_COMPOSE" ]; then
echo "cd $NGINX_DIR && $DOCKER_COMPOSE -f docker-compose-nginx.yml up -d"
else
echo "[WARN] docker-compose / docker compose 를 찾을 수 없습니다. Docker 설치를 확인하세요."
fi

21
deploy/ssl/openssl.cnf Normal file
View File

@@ -0,0 +1,21 @@
[req]
default_bits = 4096
prompt = no
default_md = sha256
distinguished_name = dn
req_extensions = v3_req
[dn]
C=KR
ST=Seoul
L=Seoul
O=KAMCO
OU=Training
CN=api.train-kamco.com
[v3_req]
subjectAltName = @alt_names
[alt_names]
DNS.1 = api.train-kamco.com
DNS.2 = train-kamco.com

View File

@@ -0,0 +1,38 @@
services:
kamco-changedetection-api:
build:
context: .
dockerfile: Dockerfile-dev
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
container_name: kamco-cd-training-api
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
ports:
- "7200:8080"
environment:
- SPRING_PROFILES_ACTIVE=dev
- TZ=Asia/Seoul
volumes:
- /mnt/nfs_share/images:/app/original-images
- /mnt/nfs_share/model_output:/app/model-outputs
- /mnt/nfs_share/train_dataset:/app/train-dataset
- /home/kcomu/data:/home/kcomu/data
- /var/run/docker.sock:/var/run/docker.sock
networks:
- kamco-cds
restart: unless-stopped
healthcheck:
test: [ "CMD", "curl", "-f", "http://localhost:8080/monitor/health" ]
interval: 10s
timeout: 5s
retries: 5
start_period: 40s
networks:
kamco-cds:
external: true

View File

@@ -18,10 +18,7 @@ services:
- 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
- /backup/data/training:/backup/data/training
- /var/run/docker.sock:/var/run/docker.sock
networks:
- kamco-cds

View File

@@ -1,9 +1,6 @@
services:
kamco-train-api:
build:
context: .
dockerfile: Dockerfile
image: kamco-train-api:${IMAGE_TAG:-latest}
kamco-changedetection-api:
image: kamco-train-app:latest
container_name: kamco-train-api
deploy:
resources:
@@ -17,9 +14,10 @@ services:
environment:
- SPRING_PROFILES_ACTIVE=prod
- TZ=Asia/Seoul
- cors.allowed-origins=*
- cors.allowed-origins[0]=*
volumes:
- ./app/model_output:/app/model-outputs
- ./app/train_dataset:/app/train-dataset
- /data/training:/data/training
- /var/run/docker.sock:/var/run/docker.sock
networks:
- kamco-cds

View File

@@ -1,179 +1,177 @@
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;
# 업로드 파일 크기 제한 (10GB)
client_max_body_size 10G;
# Upstream 설정
upstream api_backend {
server kamco-train-api:8080;
}
upstream web_backend {
server kamco-train-web:3002;
}
# HTTP → HTTPS 리다이렉트 서버
server {
listen 80;
server_name api.train-kamco.com train-kamco.com;
# 모든 HTTP 요청을 HTTPS로 리다이렉트
return 301 https://$server_name$request_uri;
}
# HTTPS 서버 설정
server {
listen 443 ssl http2;
server_name api.train-kamco.com;
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
# SSL 프로토콜 및 암호화 설정
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 세션 캐시
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS (HTTP Strict Transport Security)
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 / {
proxy_pass http://api_backend;
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;
# 인증 헤더 및 쿠키 전달 (JWT 토큰 전달 보장)
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
proxy_set_header Authorization $http_authorization;
# 타임아웃 설정 (대용량 파일 업로드 지원)
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# 버퍼 설정
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# 헬스체크 엔드포인트
location /monitor/health {
proxy_pass http://api_backend/monitor/health;
access_log off;
}
}
# HTTPS 서버 설정 - Next.js Web Application
server {
listen 443 ssl http2;
server_name train-kamco.com;
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
# SSL 프로토콜 및 암호화 설정
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 세션 캐시
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS (HTTP Strict Transport Security)
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;
# API 프록시 설정 (Web에서 API 호출 시)
location /api/ {
proxy_pass http://api_backend/api/;
proxy_http_version 1.1;
# 프록시 헤더 설정
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header 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 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# 프록시 설정
location / {
proxy_pass http://web_backend;
proxy_http_version 1.1;
# 프록시 헤더 설정
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
# Next.js WebSocket 지원을 위한 Upgrade 헤더
proxy_set_header Upgrade $http_upgrade;
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;
}
}
}
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;
# 업로드 파일 크기 제한 (10GB)
client_max_body_size 10G;
# 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://$server_name$request_uri;
}
# HTTPS 서버 설정
server {
listen 443 ssl http2;
server_name api.train-kamco.com;
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
# SSL 프로토콜 및 암호화 설정
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 세션 캐시
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS (HTTP Strict Transport Security)
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 / {
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;
# 인증 헤더 및 쿠키 전달 (JWT 토큰 전달 보장)
proxy_pass_request_headers on;
proxy_set_header Cookie $http_cookie;
proxy_set_header Authorization $http_authorization;
# 타임아웃 설정 (대용량 파일 업로드 지원)
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# 버퍼 설정
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
# 헬스체크 엔드포인트
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;
server_name train-kamco.com;
# SSL 인증서 설정 (사설 인증서 - 멀티 도메인)
ssl_certificate /etc/nginx/ssl/train-kamco.com.crt;
ssl_certificate_key /etc/nginx/ssl/train-kamco.com.key;
# SSL 프로토콜 및 암호화 설정
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 세션 캐시
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS (HTTP Strict Transport Security)
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;
# API 프록시 설정 (Web에서 API 호출 시)
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 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}
# 프록시 설정
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;
# Next.js WebSocket 지원을 위한 Upgrade 헤더
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;
}
}
}

View File

@@ -14,7 +14,7 @@ import lombok.Setter;
public class HyperParam {
@Schema(description = "모델", example = "G1")
private ModelType model; // G1, G2, G3
private ModelType model; // G1, G2, G3, G4
// -------------------------
// Important
@@ -104,7 +104,7 @@ public class HyperParam {
@Schema(description = "Best 모델 선정 규칙", example = "less")
private String saveBestRule; // save_best_rule
@Schema(description = "검증 수행 주기(Epoch)", example = "10")
@Schema(description = "검증 수행 주기(Epoch)", example = "1")
private Integer valInterval; // val_interval
@Schema(description = "로그 기록 주기(Iteration)", example = "400")

View File

@@ -12,7 +12,8 @@ import lombok.Getter;
public enum ModelType implements EnumType {
G1("G1"),
G2("G2"),
G3("G3");
G3("G3"),
G4("G4");
private String desc;

View File

@@ -3,6 +3,8 @@ package com.kamco.cd.training.common.service;
import jakarta.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.log4j.Log4j2;
@@ -13,19 +15,34 @@ import org.springframework.stereotype.Component;
public class GpuDmonReader {
// =========================
// GPU 사용률 저장소
// GPU 사용률 히스토리 저장소
// key: GPU index (0,1,2...)
// value: 현재 GPU 사용률 (%)
// ConcurrentHashMap → 멀티스레드 안전
// value: 최근 WINDOW_SIZE 개의 sm 사용률 샘플 (1초 간격)
// ConcurrentHashMap → 멀티스레드 안전 (deque 접근은 synchronized)
// =========================
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
private static final int WINDOW_SIZE = 10; // 10초 평균
private final Map<Integer, ArrayDeque<Integer>> historyMap = new ConcurrentHashMap<>();
// =========================
// 외부 조회용
// GPU 개수만큼 10초 평균값 반환
// SystemMonitorService에서 호출
// =========================
public Map<Integer, Integer> getGpuUtilMap() {
return gpuUtilMap;
Map<Integer, Integer> result = new HashMap<>();
historyMap.forEach(
(gpu, deque) -> {
synchronized (deque) {
int avg =
deque.isEmpty()
? 0
: (int)
Math.round(deque.stream().mapToInt(Integer::intValue).average().orElse(0));
result.put(gpu, avg);
}
});
return result;
}
// =========================
@@ -76,10 +93,13 @@ public class GpuDmonReader {
// -s u → GPU utilization만 출력
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
// stderr를 stdout에 합쳐서 소비 — 소비하지 않으면 stderr 버퍼가 가득 차
// nvidia-smi 프로세스 자체가 block되어 stdout도 멈춤
pb.redirectErrorStream(true);
Process process = pb.start();
// 프로세스 실행 후 stdout 읽기
try (BufferedReader br =
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
@@ -96,21 +116,24 @@ public class GpuDmonReader {
String[] parts = line.split("\\s+");
// 첫 번째 값이 GPU index인지 확인
if (!parts[0].matches("\\d+")) continue;
if (parts.length < 2 || !parts[0].matches("\\d+")) continue;
int index = Integer.parseInt(parts[0]);
try {
// 두 번째 값이 GPU 사용률 (sm)
// 두 번째 값이 GPU 사용률 (sm), "-"이면 N/A (GPU 미활성)
int util = Integer.parseInt(parts[1]);
pushSample(index, util);
log.debug("[GpuDmon] gpu={} sm={}%", index, util);
// 최신 값 갱신
gpuUtilMap.put(index, util);
} catch (Exception ignored) {
// 파싱 실패 시 무시
} catch (NumberFormatException e) {
// "-" 등 숫자가 아닌 값 → GPU 비활성 상태이므로 0으로 기록
pushSample(index, 0);
log.debug("[GpuDmon] gpu={} sm=N/A (raw={}), stored as 0", index, parts[1]);
}
}
} finally {
process.destroy();
}
// 여기까지 왔다는 건 dmon 프로세스 종료됨
@@ -118,6 +141,20 @@ public class GpuDmonReader {
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 존재 여부 확인
// =========================

View File

@@ -1,7 +1,12 @@
package com.kamco.cd.training.common.utils;
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 {
private HeaderUtil() {}
@@ -20,4 +25,20 @@ public final class HeaderUtil {
public static String getRequired(HttpServletRequest request, String 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");
}
}

View File

@@ -1,5 +1,6 @@
package com.kamco.cd.training.common.utils.enums;
import com.kamco.cd.training.common.utils.HeaderUtil;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@@ -31,10 +32,11 @@ public class Enums {
// enum -> CodeDto list
public static List<CodeDto> toList(Class<? extends Enum<?>> enumClass) {
Object[] enums = enumClass.getEnumConstants();
boolean english = HeaderUtil.isEnglishRequest();
return Arrays.stream(enums)
.map(e -> (EnumType) e)
.map(e -> new CodeDto(e.getId(), e.getText()))
.map(e -> new CodeDto(e.getId(), english ? e.getId() : e.getText()))
.toList();
}

View File

@@ -137,6 +137,6 @@ public class SecurityConfig {
/** 완전 제외(필터 자체를 안 탐) */
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/api/mapsheet/**");
return (web) -> web.ignoring().requestMatchers("/api/mapsheet/**", "/api/file-manager/**");
}
}

View File

@@ -293,6 +293,8 @@ public class DatasetApiController {
DatasetService.validateTrainValTestDirs(req.getFilePath());
// 파일 개수 검증
DatasetService.validateDirFileCount(req.getFilePath());
// 폴더명(uid)으로 등록한 건이 있는지 체크
datasetService.validateExistsUidChk(req.getFilePath());
datasetAsyncService.insertDeliveriesDatasetAsync(req);
return ApiResponseDto.createOK("ok");

View File

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.kamco.cd.training.common.enums.LearnDataRegister;
import com.kamco.cd.training.common.enums.LearnDataType;
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.interfaces.JsonFormatDttm;
import io.swagger.v3.oas.annotations.media.Schema;
@@ -90,7 +91,8 @@ public class DatasetDto {
public String getStatus(String status) {
LearnDataRegister type = Enums.fromId(LearnDataRegister.class, status);
return type == null ? null : type.getText();
boolean english = HeaderUtil.isEnglishRequest();
return type == null ? null : (english ? type.getId() : type.getText());
}
public String getYear() {
@@ -99,7 +101,8 @@ public class DatasetDto {
public String getDataTypeName() {
LearnDataType type = Enums.fromId(LearnDataType.class, this.dataType);
return type == null ? null : type.getText();
boolean english = HeaderUtil.isEnglishRequest();
return type == null ? null : (english ? type.getId() : type.getText());
}
}
@@ -248,12 +251,13 @@ public class DatasetDto {
private Integer targetYyyy;
private String memo;
@JsonIgnore private Long classCount;
private Integer buildingCnt;
private Integer containerCnt;
private Long buildingCnt;
private Long containerCnt;
private String dataTypeName;
private Long wasteCnt;
private Long landCoverCnt;
private Long solarPanelCnt;
public SelectDataSet(
String modelNo,
@@ -266,6 +270,7 @@ public class DatasetDto {
Integer targetYyyy,
String memo,
Long classCount) {
this.modelNo = modelNo;
this.datasetId = datasetId;
this.uuid = uuid;
this.dataType = dataType;
@@ -280,6 +285,8 @@ public class DatasetDto {
this.wasteCnt = classCount;
} else if (modelNo.equals(ModelType.G3.getId())) {
this.landCoverCnt = classCount;
} else if (modelNo.equals(ModelType.G4.getId())) {
this.solarPanelCnt = classCount;
}
}
@@ -293,8 +300,9 @@ public class DatasetDto {
Integer compareYyyy,
Integer targetYyyy,
String memo,
Integer buildingCnt,
Integer containerCnt) {
Long buildingCnt,
Long containerCnt) {
this.modelNo = modelNo;
this.datasetId = datasetId;
this.uuid = uuid;
this.dataType = dataType;
@@ -310,7 +318,7 @@ public class DatasetDto {
public String getDataTypeName(String groupTitleCd) {
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
return type == null ? null : type.getText();
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
}
public String getYear() {

View File

@@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 io.swagger.v3.oas.annotations.media.Schema;
import java.time.ZonedDateTime;
@@ -131,7 +132,12 @@ public class DatasetObjDto {
private String classCd;
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();
}
}

View File

@@ -4,7 +4,11 @@ import com.kamco.cd.training.common.enums.LearnDataRegister;
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
import com.kamco.cd.training.postgres.core.DatasetCoreService;
import java.util.UUID;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
@@ -45,7 +49,11 @@ public class DatasetAsyncService {
try {
// ===== 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);
// ===== 2. 마스터 데이터 생성 =====
@@ -71,6 +79,7 @@ public class DatasetAsyncService {
datasetMngRegDto.setTitle(title);
datasetMngRegDto.setMemo(req.getMemo());
datasetMngRegDto.setDatasetPath(req.getFilePath());
datasetMngRegDto.setTotalSize(getDirectorySize(req.getFilePath())); // 선택한 폴더 안의 모든 파일 용량 합계
// 마스터 저장
datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
@@ -121,4 +130,24 @@ public class DatasetAsyncService {
}
}
}
private Long getDirectorySize(String filePath) {
Path selectedPath = Paths.get(filePath);
try (Stream<Path> paths = Files.walk(selectedPath)) {
return paths
.filter(Files::isRegularFile)
.mapToLong(
path -> {
try {
return Files.size(path);
} catch (IOException e) {
return 0L;
}
})
.sum();
} catch (IOException e) {
return 0L;
}
}
}

View File

@@ -286,7 +286,7 @@ public class DatasetService {
.memo(addReq.getMemo())
.roundNo(stage)
.totalSize(addReq.getFileSize())
.datasetPath(addReq.getFilePath())
.datasetPath(addReq.getFilePath() + uid)
.build();
datasetUid = datasetCoreService.insertDatasetMngData(mngRegDto); // tb_dataset 에 insert
@@ -676,4 +676,18 @@ public class DatasetService {
total,
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,
"이미 등록된 회차 데이터 파일입니다. 확인 부탁드립니다.");
}
}
}

View File

@@ -0,0 +1,259 @@
package com.kamco.cd.training.filemanager;
import com.kamco.cd.training.config.api.ApiResponseDto;
import com.kamco.cd.training.filemanager.dto.FileManagerDto;
import com.kamco.cd.training.filemanager.service.FileManagerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@Tag(name = "파일 관리", description = "/data 디렉토리 파일 관리 API")
@RestController
@RequestMapping("/api/file-manager")
@RequiredArgsConstructor
public class FileManagerApiController {
private final FileManagerService fileManagerService;
@Operation(
summary = "파일 목록 조회",
description = "/data 디렉토리 내 파일 및 디렉토리 목록을 조회합니다. recursive=true로 설정하면 하위 디렉토리까지 조회합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.ListFilesRes.class))),
@ApiResponse(responseCode = "400", description = "잘못된 요청 (유효하지 않은 경로)", content = @Content),
@ApiResponse(responseCode = "404", description = "디렉토리를 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/files")
public ApiResponseDto<FileManagerDto.ListFilesRes> listFiles(
@Parameter(description = "조회할 디렉토리 경로 (기본값: /data)", example = "/data/request")
@RequestParam(required = false)
String directoryPath,
@Parameter(description = "하위 디렉토리 포함 여부", example = "false")
@RequestParam(required = false, defaultValue = "false")
Boolean recursive) {
FileManagerDto.ListFilesReq request =
FileManagerDto.ListFilesReq.builder()
.directoryPath(directoryPath)
.recursive(recursive)
.build();
FileManagerDto.ListFilesRes response = fileManagerService.listFiles(request);
return ApiResponseDto.ok(response);
}
@Operation(
summary = "파일/디렉토리 삭제",
description = "지정된 파일 또는 디렉토리를 삭제합니다. recursive=true로 설정하면 디렉토리 내 모든 파일을 삭제합니다.",
requestBody =
@io.swagger.v3.oas.annotations.parameters.RequestBody(
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.DeleteFileReq.class),
examples = {
@ExampleObject(
name = "단일 파일 삭제",
value =
"""
{
"filePaths": ["/data/request/old_file.zip"],
"recursive": false
}
"""),
@ExampleObject(
name = "여러 파일 삭제",
value =
"""
{
"filePaths": ["/data/file1.txt", "/data/file2.txt"],
"recursive": false
}
"""),
@ExampleObject(
name = "디렉토리 전체 삭제",
value =
"""
{
"filePaths": ["/data/old_folder"],
"recursive": true
}
""")
})))
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "삭제 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.DeleteFileRes.class))),
@ApiResponse(responseCode = "400", description = "잘못된 요청 (유효하지 않은 경로)", content = @Content),
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@DeleteMapping("/files")
public ApiResponseDto<FileManagerDto.DeleteFileRes> deleteFiles(
@RequestBody FileManagerDto.DeleteFileReq request) {
FileManagerDto.DeleteFileRes response = fileManagerService.deleteFiles(request);
return ApiResponseDto.ok(response);
}
@Operation(
summary = "모델 파일 경로 조회",
description =
"특정 모델 UUID로 파일 위치 경로와 하위 파일 목록을 조회합니다. "
+ "request_path(심볼릭 링크 디렉토리)와 response_path(모델 결과)를 동시에 반환합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.ModelFilePathRes.class))),
@ApiResponse(responseCode = "404", description = "모델을 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/model-path/{modelUuid}")
public ApiResponseDto<FileManagerDto.ModelFilePathRes> getModelFilePath(
@Parameter(description = "모델 UUID", example = "df284755-c0b7-4070-bfee-ef554e8d0fe4")
@PathVariable
UUID modelUuid) {
FileManagerDto.ModelFilePathRes response = fileManagerService.getModelFilePath(modelUuid);
return ApiResponseDto.ok(response);
}
@Operation(
summary = "데이터셋 파일 경로 조회",
description =
"특정 데이터셋 UUID로 파일 위치 경로와 하위 파일 목록을 조회합니다. " + "dataset_path 컬럼의 request_dir 경로를 반환합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.DatasetFilePathRes.class))),
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/dataset-path/{datasetUuid}")
public ApiResponseDto<FileManagerDto.DatasetFilePathRes> getDatasetFilePath(
@Parameter(description = "데이터셋 UUID", example = "037b09a0-b315-4e2e-b88d-b9011f9eaa15")
@PathVariable
UUID datasetUuid) {
FileManagerDto.DatasetFilePathRes response = fileManagerService.getDatasetFilePath(datasetUuid);
return ApiResponseDto.ok(response);
}
@Operation(
summary = "디렉토리 용량 체크",
description = "특정 디렉토리의 총 용량, 파일 개수, 디렉토리 개수를 조회합니다. " + "basepath 하위 폴더의 용량을 재귀적으로 계산합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.DirectoryCapacityRes.class))),
@ApiResponse(responseCode = "400", description = "잘못된 경로", content = @Content),
@ApiResponse(responseCode = "404", description = "디렉토리를 찾을 수 없음", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/directory-capacity")
public ApiResponseDto<FileManagerDto.DirectoryCapacityRes> checkDirectoryCapacity(
@Parameter(
description = "디렉토리 경로",
example = "/home/kcomu/data/request/037b09a0-b315-4e2e-b88d-b9011f9eaa15")
@RequestParam
String directoryPath) {
FileManagerDto.DirectoryCapacityRes response =
fileManagerService.checkDirectoryCapacity(directoryPath);
return ApiResponseDto.ok(response);
}
@Operation(
summary = "모델별 학습 실행 상태 조회",
description =
"G1~G4 모델의 현재 학습 실행 상태를 조회합니다. "
+ "step1_state, step2_state를 체크하여 어떤 모델이 학습 중인지 확인합니다. "
+ "step1과 step2는 동시 진행되지 않습니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema =
@Schema(
implementation = FileManagerDto.AllModelsExecutionStatusRes.class))),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/models-execution-status")
public ApiResponseDto<FileManagerDto.AllModelsExecutionStatusRes> getModelsExecutionStatus() {
FileManagerDto.AllModelsExecutionStatusRes response =
fileManagerService.getModelsExecutionStatus();
return ApiResponseDto.ok(response);
}
@Operation(
summary = "저장공간 정보 조회",
description =
"/home/kcomu/data 경로의 사용 중인 용량, 전체 디스크 용량, 남은 저장공간을 조회합니다. "
+ "파라미터 없이 호출하면 자동으로 /home/kcomu/data 경로 정보를 반환합니다.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "조회 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = FileManagerDto.StorageSpaceRes.class))),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/storage-space")
public ApiResponseDto<FileManagerDto.StorageSpaceRes> getStorageSpaceInfo() {
FileManagerDto.StorageSpaceRes response = fileManagerService.getStorageSpaceInfo();
return ApiResponseDto.ok(response);
}
}

View File

@@ -0,0 +1,286 @@
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 java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
public class FileManagerDto {
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "파일 정보")
public static class FileInfo {
@Schema(description = "파일명", example = "dataset.zip")
private String fileName;
@Schema(description = "파일 전체 경로", example = "/data/request/dataset.zip")
private String filePath;
@Schema(description = "파일 크기 (bytes)", example = "1024000")
private Long fileSize;
@Schema(description = "파일인지 디렉토리인지 여부", example = "true")
private Boolean isFile;
@Schema(description = "디렉토리인지 여부", example = "false")
private Boolean isDirectory;
@Schema(description = "마지막 수정 시간", example = "2026-04-06T15:30:00")
private LocalDateTime lastModified;
@Schema(description = "읽기 권한", example = "true")
private Boolean readable;
@Schema(description = "쓰기 권한", example = "true")
private Boolean writable;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "디렉토리 목록 조회 요청")
public static class ListFilesReq {
@Schema(description = "조회할 디렉토리 경로 (기본값: /data)", example = "/data/request")
private String directoryPath;
@Schema(description = "하위 디렉토리 포함 여부", example = "false")
private Boolean recursive;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "디렉토리 목록 조회 응답")
public static class ListFilesRes {
@Schema(description = "조회된 디렉토리 경로", example = "/data/request")
private String directoryPath;
@Schema(description = "파일 목록")
private List<FileInfo> files;
@Schema(description = "총 파일 개수", example = "10")
private Integer totalCount;
@Schema(description = "총 파일 크기 (bytes)", example = "10240000")
private Long totalSize;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "파일 삭제 요청")
public static class DeleteFileReq {
@Schema(
description = "삭제할 파일 또는 디렉토리 경로 목록",
example = "[\"/data/request/old_file.zip\", \"/data/tmp/test_folder\"]")
private List<String> filePaths;
@Schema(description = "디렉토리일 경우 하위 파일 포함 삭제 여부", example = "true")
private Boolean recursive;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "파일 삭제 응답")
public static class DeleteFileRes {
@Schema(description = "삭제 성공한 파일 경로 목록")
private List<String> deletedFiles;
@Schema(description = "삭제 실패한 파일 경로 목록")
private List<String> failedFiles;
@Schema(description = "삭제 성공 개수", example = "5")
private Integer successCount;
@Schema(description = "삭제 실패 개수", example = "0")
private Integer failureCount;
@Schema(description = "전체 메시지", example = "5개 파일 삭제 성공")
private String message;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "디스크 사용량 조회 응답")
public static class DiskUsageRes {
@Schema(description = "디렉토리 경로", example = "/data")
private String directoryPath;
@Schema(description = "총 용량 (bytes)", example = "1000000000000")
private Long totalSpace;
@Schema(description = "사용 가능 용량 (bytes)", example = "500000000000")
private Long usableSpace;
@Schema(description = "사용 중인 용량 (bytes)", example = "500000000000")
private Long usedSpace;
@Schema(description = "사용률 (%)", example = "50.0")
private Double usagePercentage;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "모델 파일 경로 정보 응답")
public static class ModelFilePathRes {
@Schema(description = "모델 UUID", example = "df284755-c0b7-4070-bfee-ef554e8d0fe4")
private String modelUuid;
@Schema(
description = "요청 경로 (심볼릭 링크 디렉토리)",
example = "/home/kcomu/data/tmp/AE366F3076504FACBF12106986202AB5")
private String requestPath;
@Schema(
description = "응답 경로 (모델 결과 저장)",
example = "/home/kcomu/data/response/df284755-c0b7-4070-bfee-ef554e8d0fe4")
private String responsePath;
@Schema(description = "요청 경로 파일 목록")
private List<FileInfo> requestFiles;
@Schema(description = "응답 경로 파일 목록")
private List<FileInfo> responseFiles;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "데이터셋 파일 경로 정보 응답")
public static class DatasetFilePathRes {
@Schema(description = "데이터셋 UUID", example = "037b09a0-b315-4e2e-b88d-b9011f9eaa15")
private String datasetUuid;
@Schema(
description = "데이터셋 경로",
example = "/home/kcomu/data/request/037b09a0-b315-4e2e-b88d-b9011f9eaa15")
private String datasetPath;
@Schema(description = "데이터셋 파일 목록")
private List<FileInfo> files;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "디렉토리 용량 체크 응답")
public static class DirectoryCapacityRes {
@Schema(description = "디렉토리 경로", example = "/home/kcomu/data/request/dataset-uuid")
private String directoryPath;
@Schema(description = "파일 개수", example = "1234")
private Integer fileCount;
@Schema(description = "디렉토리 개수", example = "56")
private Integer directoryCount;
@Schema(description = "총 용량 (bytes)", example = "10485760000")
private Long totalSize;
@Schema(description = "총 용량 (읽기 쉬운 형식)", example = "9.77 GB")
private String totalSizeFormatted;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "모델별 학습 실행 상태 응답")
public static class ModelExecutionStatusRes {
@Schema(description = "모델 번호", example = "G1")
private String modelNo;
@Schema(description = "실행 상태 메시지", example = "G1 모델에 테스트를 진행중입니다.")
private String statusMessage;
@Schema(description = "1단계 상태", example = "COMPLETED")
private String step1State;
@Schema(description = "2단계 상태", example = "IN_PROGRESS")
private String step2State;
@Schema(description = "현재 실행 중인 단계", example = "2")
private Integer currentStep;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "전체 모델 학습 실행 상태 목록 응답")
public static class AllModelsExecutionStatusRes {
@Schema(description = "모델별 실행 상태 목록")
private List<ModelExecutionStatusRes> modelStatuses;
@Schema(description = "현재 실행 중인 모델 개수", example = "2")
private Integer runningCount;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "저장공간 정보 응답 (남은 공간 포함)")
public static class StorageSpaceRes {
@Schema(description = "디렉토리 경로", example = "/home/kcomu/data")
private String directoryPath;
@Schema(description = "파일 개수", example = "1234")
private Integer fileCount;
@Schema(description = "디렉토리 개수", example = "56")
private Integer directoryCount;
@Schema(description = "사용 중인 용량 (bytes)", example = "10485760000")
private Long usedSize;
@Schema(description = "사용 중인 용량 (읽기 쉬운 형식)", example = "9.77 GB")
private String usedSizeFormatted;
@Schema(description = "전체 디스크 용량 (bytes)", example = "1000000000000")
private Long totalDiskSpace;
@Schema(description = "전체 디스크 용량 (읽기 쉬운 형식)", example = "931.32 GB")
private String totalDiskSpaceFormatted;
@Schema(description = "남은 저장공간 (bytes)", example = "500000000000")
private Long freeSpace;
@Schema(description = "남은 저장공간 (읽기 쉬운 형식)", example = "465.66 GB")
private String freeSpaceFormatted;
@Schema(description = "사용 가능한 공간 (bytes)", example = "480000000000")
private Long usableSpace;
@Schema(description = "사용 가능한 공간 (읽기 쉬운 형식)", example = "447.03 GB")
private String usableSpaceFormatted;
@Schema(description = "디스크 사용률 (%)", example = "50.5")
private Double usagePercentage;
@JsonFormatDttm private ZonedDateTime lastModifiedDate;
public ZonedDateTime getLastModifiedDate() {
return ZonedDateTime.now();
}
}
}

View File

@@ -0,0 +1,710 @@
package com.kamco.cd.training.filemanager.service;
import com.kamco.cd.training.filemanager.dto.FileManagerDto;
import com.kamco.cd.training.postgres.entity.DatasetEntity;
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
import com.kamco.cd.training.postgres.repository.dataset.DatasetRepository;
import com.kamco.cd.training.postgres.repository.model.ModelMngRepository;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
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 FileManagerService {
private static final String BASE_DATA_PATH = "/data";
private static final long MAX_PATH_LENGTH = 500;
@Value("${train.docker.base_path}")
private String basePath;
@Value("${train.docker.request_dir}")
private String requestDir;
@Value("${train.docker.response_dir}")
private String responseDir;
@Value("${train.docker.symbolic_link_dir}")
private String symbolicLinkDir;
private final ModelMngRepository modelMngRepository;
private final DatasetRepository datasetRepository;
/**
* 디렉토리 내 파일 목록 조회
*
* @param request 조회 요청 정보
* @return 파일 목록 응답
*/
public FileManagerDto.ListFilesRes listFiles(FileManagerDto.ListFilesReq request) {
String targetPath =
request.getDirectoryPath() != null ? request.getDirectoryPath() : BASE_DATA_PATH;
boolean recursive = request.getRecursive() != null && request.getRecursive();
// 경로 검증은 수행하되, 예외를 throw하지 않고 빈 데이터 반환
try {
validatePath(targetPath);
} catch (IllegalArgumentException e) {
log.debug("유효하지 않은 경로: {}", targetPath);
return FileManagerDto.ListFilesRes.builder()
.directoryPath(targetPath)
.files(new ArrayList<>())
.totalCount(0)
.totalSize(0L)
.build();
}
Path directory = Paths.get(targetPath);
if (!Files.exists(directory)) {
log.debug("디렉토리가 존재하지 않습니다: {}", targetPath);
return FileManagerDto.ListFilesRes.builder()
.directoryPath(targetPath)
.files(new ArrayList<>())
.totalCount(0)
.totalSize(0L)
.build();
}
if (!Files.isDirectory(directory)) {
log.debug("디렉토리 경로가 아닙니다: {}", targetPath);
return FileManagerDto.ListFilesRes.builder()
.directoryPath(targetPath)
.files(new ArrayList<>())
.totalCount(0)
.totalSize(0L)
.build();
}
List<FileManagerDto.FileInfo> files = new ArrayList<>();
long totalSize = 0;
try {
if (recursive) {
// 재귀적으로 모든 하위 파일 조회
Files.walkFileTree(
directory,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
files.add(createFileInfo(file));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (!dir.equals(directory)) {
files.add(createFileInfo(dir));
}
return FileVisitResult.CONTINUE;
}
});
} else {
// 현재 디렉토리의 파일만 조회
try (Stream<Path> stream = Files.list(directory)) {
stream.forEach(path -> files.add(createFileInfo(path)));
}
}
// 총 파일 크기 계산
for (FileManagerDto.FileInfo file : files) {
if (file.getIsFile() && file.getFileSize() != null) {
totalSize += file.getFileSize();
}
}
} catch (IOException e) {
log.debug("파일 목록 조회 중 오류 발생: {}", targetPath, e);
return FileManagerDto.ListFilesRes.builder()
.directoryPath(targetPath)
.files(new ArrayList<>())
.totalCount(0)
.totalSize(0L)
.build();
}
return FileManagerDto.ListFilesRes.builder()
.directoryPath(targetPath)
.files(files)
.totalCount(files.size())
.totalSize(totalSize)
.build();
}
/**
* 파일 또는 디렉토리 삭제
*
* @param request 삭제 요청 정보
* @return 삭제 결과
*/
public FileManagerDto.DeleteFileRes deleteFiles(FileManagerDto.DeleteFileReq request) {
List<String> deletedFiles = new ArrayList<>();
List<String> failedFiles = new ArrayList<>();
boolean recursive = request.getRecursive() != null && request.getRecursive();
for (String filePath : request.getFilePaths()) {
try {
try {
validatePath(filePath);
} catch (IllegalArgumentException e) {
log.debug("유효하지 않은 경로: {}", filePath);
failedFiles.add(filePath + " (유효하지 않은 경로)");
continue;
}
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
log.debug("삭제하려는 파일이 존재하지 않습니다: {}", filePath);
failedFiles.add(filePath + " (파일이 존재하지 않음)");
continue;
}
if (Files.isDirectory(path)) {
if (recursive) {
// 디렉토리 및 하위 파일 모두 삭제
deleteDirectoryRecursively(path);
deletedFiles.add(filePath);
} else {
// 빈 디렉토리만 삭제
if (isDirectoryEmpty(path)) {
Files.delete(path);
deletedFiles.add(filePath);
} else {
failedFiles.add(filePath + " (디렉토리가 비어있지 않음)");
}
}
} else {
// 파일 삭제
Files.delete(path);
deletedFiles.add(filePath);
}
log.info("파일 삭제 성공: {}", filePath);
} catch (Exception e) {
log.debug("파일 삭제 실패: {}", filePath, e);
failedFiles.add(filePath + " (" + e.getMessage() + ")");
}
}
String message =
String.format("%d개 파일 삭제 성공, %d개 파일 삭제 실패", deletedFiles.size(), failedFiles.size());
return FileManagerDto.DeleteFileRes.builder()
.deletedFiles(deletedFiles)
.failedFiles(failedFiles)
.successCount(deletedFiles.size())
.failureCount(failedFiles.size())
.message(message)
.build();
}
/** FileInfo 객체 생성 */
private FileManagerDto.FileInfo createFileInfo(Path path) {
try {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return FileManagerDto.FileInfo.builder()
.fileName(path.getFileName().toString())
.filePath(path.toString())
.fileSize(attrs.isRegularFile() ? attrs.size() : null)
.isFile(attrs.isRegularFile())
.isDirectory(attrs.isDirectory())
.lastModified(
LocalDateTime.ofInstant(
Instant.ofEpochMilli(attrs.lastModifiedTime().toMillis()),
ZoneId.systemDefault()))
.readable(Files.isReadable(path))
.writable(Files.isWritable(path))
.build();
} catch (IOException e) {
log.warn("파일 정보 조회 실패: {}", path, e);
return FileManagerDto.FileInfo.builder()
.fileName(path.getFileName().toString())
.filePath(path.toString())
.build();
}
}
/** 디렉토리 재귀 삭제 */
private void deleteDirectoryRecursively(Path directory) throws IOException {
Files.walkFileTree(
directory,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/** 디렉토리가 비어있는지 확인 */
private boolean isDirectoryEmpty(Path directory) throws IOException {
try (Stream<Path> stream = Files.list(directory)) {
return stream.findFirst().isEmpty();
}
}
/** 경로 검증 (보안) */
private void validatePath(String path) {
if (path == null || path.trim().isEmpty()) {
throw new IllegalArgumentException("경로가 비어있습니다");
}
if (path.length() > MAX_PATH_LENGTH) {
throw new IllegalArgumentException("경로가 너무 깁니다");
}
// 경로 순회 공격 방지 - 상대경로 패턴만 제한
if (path.contains("..")) {
throw new IllegalArgumentException("상대 경로(..)는 사용할 수 없습니다");
}
}
/**
* 모델 파일 경로 조회
*
* @param modelUuid 모델 UUID
* @return 모델 파일 경로 및 파일 목록
*/
public FileManagerDto.ModelFilePathRes getModelFilePath(UUID modelUuid) {
// tb_model_master 테이블에서 모델 조회
ModelMasterEntity model = modelMngRepository.findByUuid(modelUuid).orElse(null);
// 모델이 존재하지 않으면 빈 데이터 반환
if (model == null) {
return FileManagerDto.ModelFilePathRes.builder()
.modelUuid(modelUuid.toString())
.requestPath(null)
.responsePath(null)
.requestFiles(new ArrayList<>())
.responseFiles(new ArrayList<>())
.build();
}
// request_path: tb_model_master.request_path 컬럼 값 사용
// request_path 컬럼에는 'AE366F3076504FACBF12106986202AB5' 형태의 값이 저장되어 있음
String requestPathFromDb = model.getRequestPath();
String requestPath;
if (requestPathFromDb != null && !requestPathFromDb.isEmpty()) {
// DB에 저장된 값이 있으면 symbolic_link_dir + request_path 조합
requestPath = symbolicLinkDir + "/" + requestPathFromDb;
} else {
// 없으면 기본값: symbolic_link_dir + model_uuid
requestPath = symbolicLinkDir + "/" + modelUuid;
}
// response_path: response_dir + model_uuid (UUID 사용)
String responsePath = responseDir + "/" + modelUuid;
// 파일 목록 조회
List<FileManagerDto.FileInfo> requestFiles = getFilesInDirectory(requestPath);
List<FileManagerDto.FileInfo> responseFiles = getFilesInDirectory(responsePath);
return FileManagerDto.ModelFilePathRes.builder()
.modelUuid(modelUuid.toString())
.requestPath(requestPath)
.responsePath(responsePath)
.requestFiles(requestFiles)
.responseFiles(responseFiles)
.build();
}
/**
* 데이터셋 파일 경로 조회
*
* @param datasetUuid 데이터셋 UUID
* @return 데이터셋 파일 경로 및 파일 목록
*/
public FileManagerDto.DatasetFilePathRes getDatasetFilePath(UUID datasetUuid) {
// tb_dataset 테이블에서 데이터셋 조회
DatasetEntity dataset = datasetRepository.findByUuid(datasetUuid).orElse(null);
// 데이터셋이 존재하지 않으면 빈 데이터 반환
if (dataset == null) {
return FileManagerDto.DatasetFilePathRes.builder()
.datasetUuid(datasetUuid.toString())
.datasetPath(null)
.files(new ArrayList<>())
.build();
}
// dataset_path 컬럼이 있으면 사용, 없으면 request_dir + uuid 사용
String datasetPath = dataset.getDatasetPath();
if (datasetPath == null || datasetPath.isEmpty()) {
datasetPath = requestDir + "/" + datasetUuid;
}
// 파일 목록 조회
List<FileManagerDto.FileInfo> files = getFilesInDirectory(datasetPath);
return FileManagerDto.DatasetFilePathRes.builder()
.datasetUuid(datasetUuid.toString())
.datasetPath(datasetPath)
.files(files)
.build();
}
/**
* 디렉토리 용량 체크
*
* @param directoryPath 디렉토리 경로
* @return 디렉토리 용량 정보
*/
public FileManagerDto.DirectoryCapacityRes checkDirectoryCapacity(String directoryPath) {
// 경로 검증은 수행하되, 예외를 throw하지 않고 빈 데이터 반환
try {
validatePath(directoryPath);
} catch (IllegalArgumentException e) {
log.debug("유효하지 않은 경로: {}", directoryPath);
return FileManagerDto.DirectoryCapacityRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.totalSize(0L)
.totalSizeFormatted("0 B")
.build();
}
Path directory = Paths.get(directoryPath);
if (!Files.exists(directory)) {
log.debug("디렉토리가 존재하지 않습니다: {}", directoryPath);
return FileManagerDto.DirectoryCapacityRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.totalSize(0L)
.totalSizeFormatted("0 B")
.build();
}
if (!Files.isDirectory(directory)) {
log.debug("디렉토리 경로가 아닙니다: {}", directoryPath);
return FileManagerDto.DirectoryCapacityRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.totalSize(0L)
.totalSizeFormatted("0 B")
.build();
}
final long[] totalSize = {0};
final int[] fileCount = {0};
final int[] directoryCount = {0};
try {
Files.walkFileTree(
directory,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
totalSize[0] += attrs.size();
fileCount[0]++;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (!dir.equals(directory)) {
directoryCount[0]++;
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
log.debug("디렉토리 용량 체크 중 오류 발생: {}", directoryPath, e);
return FileManagerDto.DirectoryCapacityRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.totalSize(0L)
.totalSizeFormatted("0 B")
.build();
}
return FileManagerDto.DirectoryCapacityRes.builder()
.directoryPath(directoryPath)
.fileCount(fileCount[0])
.directoryCount(directoryCount[0])
.totalSize(totalSize[0])
.totalSizeFormatted(formatFileSize(totalSize[0]))
.build();
}
/**
* 모델별 학습 실행 상태 조회
*
* @return 모델별 학습 실행 상태 목록
*/
public FileManagerDto.AllModelsExecutionStatusRes getModelsExecutionStatus() {
// G1 ~ G4 모델 조회
List<String> modelNumbers = Arrays.asList("G1", "G2", "G3", "G4");
List<FileManagerDto.ModelExecutionStatusRes> modelStatuses = new ArrayList<>();
int runningCount = 0;
for (String modelNo : modelNumbers) {
// model_no로 가장 최근 모델 조회 (del_yn = false)
List<ModelMasterEntity> models =
modelMngRepository.findByModelNoAndDelYnOrderByCreatedDttmDesc(modelNo, false);
if (models.isEmpty()) {
// 모델이 없으면 대기 상태
modelStatuses.add(
FileManagerDto.ModelExecutionStatusRes.builder()
.modelNo(modelNo)
.statusMessage(modelNo + " 모델은 대기 중입니다.")
.step1State(null)
.step2State(null)
.currentStep(null)
.build());
continue;
}
ModelMasterEntity model = models.getFirst();
String step1State = model.getStep1State();
String step2State = model.getStep2State();
String statusMessage;
Integer currentStep = null;
// step1, step2 상태 확인
boolean step1Running = "IN_PROGRESS".equals(step1State);
boolean step2Running = "IN_PROGRESS".equals(step2State);
if (step1Running) {
statusMessage = modelNo + " 모델에 학습(1단계)을 진행중입니다.";
currentStep = 1;
runningCount++;
} else if (step2Running) {
statusMessage = modelNo + " 모델에 테스트(2단계)를 진행중입니다.";
currentStep = 2;
runningCount++;
} else if ("COMPLETED".equals(step1State) && "COMPLETED".equals(step2State)) {
statusMessage = modelNo + " 모델은 학습이 완료되었습니다.";
} else if ("COMPLETED".equals(step1State)) {
statusMessage = modelNo + " 모델은 1단계 학습이 완료되었습니다.";
} else {
statusMessage = modelNo + " 모델은 대기 중입니다.";
}
modelStatuses.add(
FileManagerDto.ModelExecutionStatusRes.builder()
.modelNo(modelNo)
.statusMessage(statusMessage)
.step1State(step1State)
.step2State(step2State)
.currentStep(currentStep)
.build());
}
return FileManagerDto.AllModelsExecutionStatusRes.builder()
.modelStatuses(modelStatuses)
.runningCount(runningCount)
.build();
}
/** 디렉토리 내 파일 목록 조회 (내부 사용) */
private List<FileManagerDto.FileInfo> getFilesInDirectory(String directoryPath) {
List<FileManagerDto.FileInfo> files = new ArrayList<>();
Path directory = Paths.get(directoryPath);
if (!Files.exists(directory)) {
log.debug("디렉토리가 존재하지 않습니다: {}", directoryPath);
return files;
}
if (!Files.isDirectory(directory)) {
log.debug("디렉토리 경로가 아닙니다: {}", directoryPath);
return files;
}
try (Stream<Path> stream = Files.list(directory)) {
stream.forEach(path -> files.add(createFileInfo(path)));
} catch (IOException e) {
log.debug("파일 목록 조회 중 오류 발생: {}", directoryPath, e);
}
return files;
}
/** 파일 크기 포맷팅 (읽기 쉬운 형식) */
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));
}
}
/**
* 저장공간 정보 조회 (남은 공간 포함) 고정 경로: train.docker.base_path 설정값 사용
*
* @return 저장공간 정보 (사용량, 남은 공간, 디스크 용량)
*/
public FileManagerDto.StorageSpaceRes getStorageSpaceInfo() {
// 설정값에서 경로 가져오기 (train.docker.base_path)
log.info("basePath = {}", basePath);
String directoryPath = basePath;
Path directory = Paths.get(directoryPath);
if (!Files.exists(directory)) {
log.info("디렉토리가 존재하지 않습니다: {}", directoryPath);
return FileManagerDto.StorageSpaceRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.usedSize(0L)
.usedSizeFormatted("0 B")
.totalDiskSpace(0L)
.totalDiskSpaceFormatted("0 B")
.freeSpace(0L)
.freeSpaceFormatted("0 B")
.usableSpace(0L)
.usableSpaceFormatted("0 B")
.usagePercentage(0.0)
.build();
}
if (!Files.isDirectory(directory)) {
log.info("디렉토리 경로가 아닙니다: {}", directoryPath);
return FileManagerDto.StorageSpaceRes.builder()
.directoryPath(directoryPath)
.fileCount(0)
.directoryCount(0)
.usedSize(0L)
.usedSizeFormatted("0 B")
.totalDiskSpace(0L)
.totalDiskSpaceFormatted("0 B")
.freeSpace(0L)
.freeSpaceFormatted("0 B")
.usableSpace(0L)
.usableSpaceFormatted("0 B")
.usagePercentage(0.0)
.build();
}
// 디렉토리 사용량 계산 — du -sb 사용 (walkFileTree 대비 수배 빠름)
// fileCount/directoryCount는 du가 제공하지 않으므로 -1(미집계) 반환
long usedSize = 0;
log.info("[StorageSpace] du 시작 - path={}", directoryPath);
try {
ProcessBuilder duPb = new ProcessBuilder("du", "-sb", directoryPath);
duPb.redirectErrorStream(true);
Process duProcess = duPb.start();
try (java.io.BufferedReader br =
new java.io.BufferedReader(new java.io.InputStreamReader(duProcess.getInputStream()))) {
String line = br.readLine();
if (line != null) {
// du -sb 출력 형식: "12345678\t/path/to/dir"
String[] parts = line.split("\t", 2);
usedSize = Long.parseLong(parts[0].trim());
}
}
int exitCode = duProcess.waitFor();
log.info(
"[StorageSpace] du 완료 - exitCode={}, usedSize={} bytes ({})",
exitCode,
usedSize,
formatFileSize(usedSize));
} catch (Exception e) {
log.error("[StorageSpace] du 실행 실패: {}", directoryPath, e);
return FileManagerDto.StorageSpaceRes.builder()
.directoryPath(directoryPath)
.fileCount(-1)
.directoryCount(-1)
.usedSize(0L)
.usedSizeFormatted("0 B")
.totalDiskSpace(0L)
.totalDiskSpaceFormatted("0 B")
.freeSpace(0L)
.freeSpaceFormatted("0 B")
.usableSpace(0L)
.usableSpaceFormatted("0 B")
.usagePercentage(0.0)
.build();
}
// 디스크 공간 정보 조회 (FileStore 사용) — basePath가 속한 파티션/NFS 마운트 전체 기준
long totalDiskSpace = 0;
long freeSpace = 0;
long usableSpace = 0;
double usagePercentage = 0.0;
try {
java.nio.file.FileStore fileStore = Files.getFileStore(directory);
totalDiskSpace = fileStore.getTotalSpace();
freeSpace = fileStore.getUnallocatedSpace(); // OS 미할당 공간 (root 예약 블록 포함 가능)
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) {
long usedDiskSpace = totalDiskSpace - usableSpace;
usagePercentage = (usedDiskSpace * 100.0) / totalDiskSpace;
}
log.info("[StorageSpace] usagePercentage={}%", Math.round(usagePercentage * 100.0) / 100.0);
} catch (IOException e) {
log.warn("[StorageSpace] 디스크 공간 정보 조회 실패: {}", directoryPath, e);
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
}
return FileManagerDto.StorageSpaceRes.builder()
.directoryPath(directoryPath)
.fileCount(-1)
.directoryCount(-1)
.usedSize(usedSize)
.usedSizeFormatted(formatFileSize(usedSize))
.totalDiskSpace(totalDiskSpace)
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
.freeSpace(freeSpace)
.freeSpaceFormatted(formatFileSize(freeSpace))
.usableSpace(usableSpace)
.usableSpaceFormatted(formatFileSize(usableSpace))
.usagePercentage(Math.round(usagePercentage * 100.0) / 100.0)
.build();
}
}

View File

@@ -101,7 +101,7 @@ public class HyperParamApiController {
LocalDate endDate,
@Parameter(description = "버전명", example = "G1_000019") @RequestParam(required = false)
String hyperVer,
@Parameter(description = "모델 타입 (G1, G2, G3 중 하나)", example = "G1")
@Parameter(description = "모델 타입 (G1, G2, G3, G4 중 하나)", example = "G1")
@RequestParam(required = false)
ModelType model,
@Parameter(

View File

@@ -37,6 +37,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
@@ -366,4 +367,43 @@ public class ModelTrainDetailApiController {
@Parameter(description = "모델 uuid") @PathVariable UUID 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));
}
}

View File

@@ -1,6 +1,7 @@
package com.kamco.cd.training.model;
import com.kamco.cd.training.common.dto.MonitorDto;
import com.kamco.cd.training.common.enums.ModelType;
import com.kamco.cd.training.common.service.SystemMonitorService;
import com.kamco.cd.training.config.api.ApiResponseDto;
import com.kamco.cd.training.dataset.dto.DatasetDto;
@@ -68,7 +69,7 @@ public class ModelTrainMngApiController {
@Parameter(
description = "모델",
example = "G1",
schema = @Schema(allowableValues = {"G1", "G2", "G3"}))
schema = @Schema(allowableValues = {"G1", "G2", "G3", "G4"}))
@RequestParam(required = false)
String modelNo,
@Parameter(description = "페이지 번호") @RequestParam(defaultValue = "0") int page,
@@ -143,9 +144,9 @@ public class ModelTrainMngApiController {
@Parameter(
description = "모델 구분",
example = "",
schema = @Schema(allowableValues = {"G1", "G2", "G3"}))
schema = @Schema(allowableValues = {"G1", "G2", "G3", "G4"}))
@RequestParam
String modelType,
ModelType modelType,
@Parameter(
description = "선택 구분",
example = "",
@@ -153,7 +154,7 @@ public class ModelTrainMngApiController {
@RequestParam
String selectType) {
DatasetReq req = new DatasetReq();
req.setModelNo(modelType);
req.setModelNo(modelType.getId());
req.setDataType(selectType);
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
}

View File

@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.kamco.cd.training.common.enums.LearnDataType;
import com.kamco.cd.training.common.enums.TrainStatusType;
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.interfaces.JsonFormatDttm;
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
@@ -32,6 +33,8 @@ public class ModelTrainDetailDto {
private String modelNo;
private String modelVer;
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
@JsonFormatDttm private ZonedDateTime step1EndDttm;
@JsonFormatDttm private ZonedDateTime step2StrtDttm;
@JsonFormatDttm private ZonedDateTime step2EndDttm;
private String statusCd;
private String trainType;
@@ -40,7 +43,9 @@ public class ModelTrainDetailDto {
public String getStatusName() {
if (this.statusCd == null || this.statusCd.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.statusCd).getId()
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -49,18 +54,16 @@ public class ModelTrainDetailDto {
public String getTrainTypeName() {
if (this.trainType == null || this.trainType.isBlank()) return null;
try {
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainType.valueOf(this.trainType).getId()
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
}
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
if (end == null) {
end = ZonedDateTime.now();
}
if (start == null) {
if (start == null || end == null) {
return null;
}
@@ -70,11 +73,42 @@ public class ModelTrainDetailDto {
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
if (HeaderUtil.isEnglishRequest()) {
return String.format("%dh %dm %ds", hours, minutes, seconds);
} else {
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
}
}
public String getStepAllDuration() {
return formatDuration(this.step1StrtDttm, this.step2EndDttm);
if (this.step2EndDttm != null) {
// step1 + step2 실제 소요시간 합산
long step1Seconds = 0;
long step2Seconds = 0;
if (this.step1StrtDttm != null && this.step1EndDttm != null) {
step1Seconds =
Math.abs(Duration.between(this.step1StrtDttm, this.step1EndDttm).getSeconds());
}
if (this.step2StrtDttm != null && this.step2EndDttm != null) {
step2Seconds =
Math.abs(Duration.between(this.step2StrtDttm, this.step2EndDttm).getSeconds());
}
long totalSeconds = step1Seconds + step2Seconds;
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
if (HeaderUtil.isEnglishRequest()) {
return String.format("%dh %dm %ds", hours, minutes, seconds);
} else {
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
}
} else {
// step2 없으면 step1만
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
}
}
}
@@ -142,6 +176,9 @@ public class ModelTrainDetailDto {
@JsonInclude(JsonInclude.Include.NON_NULL)
private Long landCoverCnt;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Long solarPanelCnt;
public MappingDataset(
Long modelId,
Long datasetId,
@@ -152,26 +189,33 @@ public class ModelTrainDetailDto {
Long buildingCnt,
Long containerCnt,
Long wasteCnt,
Long landCoverCnt) {
Long landCoverCnt,
Long solarPanelCnt) {
this.modelId = modelId;
this.datasetId = datasetId;
this.dataType = dataType;
this.compareYyyy = compareYyyy;
this.targetYyyy = targetYyyy;
this.roundNo = roundNo;
this.buildingCnt = buildingCnt;
this.containerCnt = containerCnt;
this.wasteCnt = wasteCnt;
this.landCoverCnt = landCoverCnt;
this.buildingCnt = toNullIfZero(buildingCnt);
this.containerCnt = toNullIfZero(containerCnt);
this.wasteCnt = toNullIfZero(wasteCnt);
this.landCoverCnt = toNullIfZero(landCoverCnt);
this.solarPanelCnt = toNullIfZero(solarPanelCnt);
this.dataTypeName = getDataTypeName(this.dataType);
}
public String getDataTypeName(String groupTitleCd) {
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
return type == null ? null : type.getText();
return type == null ? null : (HeaderUtil.isEnglishRequest() ? type.getId() : type.getText());
}
}
private static Long toNullIfZero(Long value) {
return (value == null || value == 0L) ? null : value;
}
@Getter
@Setter
@NoArgsConstructor
@@ -256,4 +300,73 @@ public class ModelTrainDetailDto {
private Boolean fileExistsYn;
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;
}
}

View File

@@ -3,6 +3,7 @@ package com.kamco.cd.training.model.dto;
import com.kamco.cd.training.common.dto.HyperParam;
import com.kamco.cd.training.common.enums.TrainStatusType;
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 io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
@@ -44,8 +45,8 @@ public class ModelTrainMngDto {
private String requestPath;
private String packingState;
private ZonedDateTime packingStrtDttm;
private ZonedDateTime packingEndDttm;
@JsonFormatDttm private ZonedDateTime packingStrtDttm;
@JsonFormatDttm private ZonedDateTime packingEndDttm;
private Long beforeModelId;
private Integer bestEpoch;
@@ -53,7 +54,9 @@ public class ModelTrainMngDto {
public String getStatusName() {
if (this.statusCd == null || this.statusCd.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
return (HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.statusCd).getId()
: TrainStatusType.valueOf(this.statusCd).getText()); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -62,7 +65,9 @@ public class ModelTrainMngDto {
public String getStep1StatusName() {
if (this.step1Status == null || this.step1Status.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
return (HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.step1Status).getId()
: TrainStatusType.valueOf(this.step1Status).getText()); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -71,7 +76,9 @@ public class ModelTrainMngDto {
public String getStep2StatusName() {
if (this.step2Status == null || this.step2Status.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
return (HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.step2Status).getId()
: TrainStatusType.valueOf(this.step2Status).getText()); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -80,7 +87,9 @@ public class ModelTrainMngDto {
public String getTrainTypeName() {
if (this.trainType == null || this.trainType.isBlank()) return null;
try {
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
return (HeaderUtil.isEnglishRequest()
? TrainType.valueOf(this.trainType).getId()
: TrainType.valueOf(this.trainType).getText()); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -97,7 +106,11 @@ public class ModelTrainMngDto {
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
if (HeaderUtil.isEnglishRequest()) {
return String.format("%dh %dm %ds", hours, minutes, seconds);
} else {
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
}
}
public String getStep1Duration() {
@@ -139,7 +152,7 @@ public class ModelTrainMngDto {
public static class AddReq {
@NotNull
@Schema(description = "모델 종류 G1, G2, G3", example = "G1")
@Schema(description = "모델 종류 G1, G2, G3, G4", example = "G1")
private String modelNo;
@NotNull
@@ -176,6 +189,8 @@ public class ModelTrainMngDto {
private String requestPath;
private String responsePath;
private String tmpFileStatus;
private ZonedDateTime tmpFileEndDttm;
}
@Getter
@@ -197,10 +212,11 @@ public class ModelTrainMngDto {
@Schema(description = "폐기물", example = "0")
private Long wasteCnt;
@Schema(
description = "도로, 비닐하우스, 밭, 과수원, 초지, 숲, 물, 모재/자갈, 토분(무덤), 일반토지, 태양광, 기타",
example = "0")
@Schema(description = "도로, 비닐하우스, 밭, 과수원, 초지, 숲, 물, 모재/자갈, 토분(무덤), 일반토지, 기타", example = "0")
private Long LandCoverCnt;
@Schema(description = "태양광", example = "0")
private Long solarPanelCnt;
}
@Getter
@@ -257,7 +273,9 @@ public class ModelTrainMngDto {
public String getStatusName() {
if (this.statusCd == null || this.statusCd.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.statusCd).getId()
: TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -266,7 +284,9 @@ public class ModelTrainMngDto {
public String getStep1StatusName() {
if (this.step1Status == null || this.step1Status.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.step1Status).getId()
: TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -275,7 +295,9 @@ public class ModelTrainMngDto {
public String getStep2StatusName() {
if (this.step2Status == null || this.step2Status.isBlank()) return null;
try {
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainStatusType.valueOf(this.step2Status).getId()
: TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -284,7 +306,9 @@ public class ModelTrainMngDto {
public String getTrainTypeName() {
if (this.trainType == null || this.trainType.isBlank()) return null;
try {
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
return HeaderUtil.isEnglishRequest()
? TrainType.valueOf(this.trainType).getId()
: TrainType.valueOf(this.trainType).getText(); // 또는 getName()
} catch (IllegalArgumentException e) {
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
}
@@ -301,7 +325,11 @@ public class ModelTrainMngDto {
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
if (HeaderUtil.isEnglishRequest()) {
return String.format("%dh %dm %ds", hours, minutes, seconds);
} else {
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
}
}
public String getStep1Duration() {

View File

@@ -1,5 +1,6 @@
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.TrainStatusType;
import com.kamco.cd.training.common.exception.CustomApiException;
@@ -16,12 +17,15 @@ 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.TransferDetailDto;
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.Basic;
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileVisitOption;
@@ -32,7 +36,10 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.UUID;
@@ -41,6 +48,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -52,6 +60,7 @@ public class ModelTrainDetailService {
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
private final ModelTrainMngCoreService mngCoreService;
private final RangeDownloadResponder rangeDownloadResponder;
@Value("${train.docker.response_dir}")
private String responseDir;
@@ -434,4 +443,657 @@ 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();
}
}

View File

@@ -82,6 +82,10 @@ public class ModelTrainMngService {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "모델 없음");
}
if (model.getRequestPath() == null) {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "임시파일 경로 없음");
}
// ===== 2. 경로 생성 =====
Path tmpBase = Path.of(symbolicDir).toAbsolutePath().normalize();
Path tmp = tmpBase.resolve(model.getRequestPath()).normalize();
@@ -301,7 +305,19 @@ public class ModelTrainMngService {
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
// 데이터셋 임시파일 생성
trainJobService.createTmpFile(modelUuid);
List<Long> datasetList = null;
if (req.getTrainingDataset() != null) {
datasetList = req.getTrainingDataset().getDatasetList();
}
boolean isSingleDataset = datasetList != null && datasetList.size() == 1;
// 데이터셋 1개만 선택한 경우는 symbolic link 미생성 해도 됨 -> train 호출 시 그냥 데이터셋 request 경로로 호출
if (isSingleDataset) {
trainJobService.updateRequestPath(modelUuid, datasetList);
} else {
trainJobService.createTmpFile(modelUuid);
}
return modelUuid;
}
@@ -324,6 +340,8 @@ public class ModelTrainMngService {
public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
if (req.getModelNo().equals(ModelType.G1.getId())) {
return modelTrainMngCoreService.getDatasetSelectG1List(req);
} else if (req.getModelNo().equals(ModelType.G4.getId())) {
return modelTrainMngCoreService.getDatasetSelectG4List(req);
} else {
return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
}

View File

@@ -4,6 +4,7 @@ import com.kamco.cd.training.postgres.repository.train.ModelTestMetricsJobReposi
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
import java.time.ZonedDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
@@ -26,6 +27,10 @@ public class ModelTestMetricsJobCoreService {
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelIds();
}
public ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId) {
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelId(modelId);
}
public void insertModelMetricsTest(List<Object[]> batchArgs) {
modelTestMetricsJobRepository.insertModelMetricsTest(batchArgs);
}
@@ -34,6 +39,10 @@ public class ModelTestMetricsJobCoreService {
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
}
public SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId) {
return modelTestMetricsJobRepository.getSimpleTestMetricPackingInfo(modelId);
}
public ModelTestFileName findModelTestFileNames(Long modelId) {
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
}
@@ -47,4 +56,16 @@ public class ModelTestMetricsJobCoreService {
public void updatePackingEnd(Long modelId, ZonedDateTime now, String 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);
}
}

View File

@@ -80,6 +80,17 @@ public class ModelTrainJobCoreService {
}
}
/** 실행 시작 처리 수정 */
@Transactional
public void updateJobStatus(Long jobId, String jobStatus) {
ModelTrainJobEntity job =
modelTrainJobRepository
.findById(jobId)
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
job.setStatusCd(jobStatus);
}
/**
* 성공 처리
*

View File

@@ -17,6 +17,10 @@ public class ModelTrainMetricsJobCoreService {
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelIds();
}
public ResponsePathDto getTrainMetricSaveNotYetModelId(Long modelId) {
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelId(modelId);
}
public void insertModelMetricsTrain(List<Object[]> batchArgs) {
modelTrainMetricsJobRepository.insertModelMetricsTrain(batchArgs);
}

View File

@@ -140,6 +140,7 @@ public class ModelTrainMngCoreService {
* @param addReq 요청 파라미터
*/
public void saveModelDataset(Long modelId, ModelTrainMngDto.AddReq addReq) {
TrainingDataset dataset = addReq.getTrainingDataset();
ModelMasterEntity modelMasterEntity = new ModelMasterEntity();
ModelDatasetEntity datasetEntity = new ModelDatasetEntity();
@@ -154,6 +155,8 @@ public class ModelTrainMngCoreService {
datasetEntity.setWasteCnt(dataset.getSummary().getWasteCnt());
} else if (addReq.getModelNo().equals(ModelType.G3.getId())) {
datasetEntity.setLandCoverCnt(dataset.getSummary().getLandCoverCnt());
} else if (addReq.getModelNo().equals(ModelType.G4.getId())) {
datasetEntity.setSolarCnt(dataset.getSummary().getSolarPanelCnt());
}
datasetEntity.setCreatedUid(userUtil.getId());
@@ -177,6 +180,9 @@ public class ModelTrainMngCoreService {
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
entity.setRequestPath(req.getRequestPath());
}
entity.setTmpFileStatus(req.getTmpFileStatus());
entity.setTmpFileEndDttm(req.getTmpFileEndDttm());
}
/**
@@ -337,6 +343,16 @@ public class ModelTrainMngCoreService {
return datasetRepository.getDatasetTransferSelectG2G3List(modelId, modelNo);
}
/**
* 데이터셋 G4 목록
*
* @param req
* @return
*/
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
return datasetRepository.getDatasetSelectG4List(req);
}
// TODO 미사용 끝
/**
@@ -403,6 +419,11 @@ public class ModelTrainMngCoreService {
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
master.setStatusCd(TrainStatusType.STOPPED.getId());
if (master.getStep2StrtDttm() != null) {
master.setStep2State(TrainStatusType.STOPPED.getId());
} else {
master.setStep1State(TrainStatusType.STOPPED.getId());
}
}
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
@@ -660,4 +681,36 @@ public class ModelTrainMngCoreService {
public List<ModelTrainLinkDto> findDatasetTestPath(Long 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);
}
}

View File

@@ -43,6 +43,9 @@ public class ModelDatasetEntity {
@Column(name = "land_cover_cnt")
private Long landCoverCnt;
@Column(name = "solar_cnt")
private Long solarCnt;
@ColumnDefault("now()")
@Column(name = "created_dttm")
private ZonedDateTime createdDttm = ZonedDateTime.now();

View File

@@ -181,15 +181,15 @@ public class ModelHyperParamEntity {
private String metrics = "mFscore,mIoU";
/** Default: changed_fscore */
@Size(max = 30)
@Size(max = 50)
@NotNull
@Column(name = "save_best", nullable = false, length = 30)
@Column(name = "save_best", nullable = false, length = 50)
private String saveBest = "changed_fscore";
/** Default: greater */
@Size(max = 10)
@Size(max = 50)
@NotNull
@Column(name = "save_best_rule", nullable = false, length = 10)
@Column(name = "save_best_rule", nullable = false, length = 50)
private String saveBestRule = "greater";
/** Default: 1 */

View File

@@ -121,6 +121,21 @@ public class ModelMasterEntity {
@Column(name = "packing_end_dttm")
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() {
return new ModelTrainMngDto.Basic(
this.id,

View File

@@ -27,6 +27,8 @@ public interface DatasetRepositoryCustom {
List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req);
List<SelectDataSet> getDatasetSelectG4List(DatasetReq req);
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);

View File

@@ -4,6 +4,7 @@ import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObj
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
import com.kamco.cd.training.common.enums.DetectionClassification;
import com.kamco.cd.training.common.enums.ModelType;
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
@@ -104,10 +105,6 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
builder.and(dataset.dataType.eq(req.getDataType()));
}
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
builder.and(dataset.dataType.eq(req.getDataType()));
}
if (req.getIds() != null) {
builder.and(dataset.id.in(req.getIds()));
}
@@ -126,14 +123,17 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
dataset.targetYyyy,
dataset.memo,
new CaseBuilder()
.when(datasetObjEntity.targetClassCd.eq("building"))
.then(1)
.otherwise(0)
.when(
datasetObjEntity.targetClassCd.eq(DetectionClassification.BUILDING.getId()))
.then(1L)
.otherwise(0L)
.sum(),
new CaseBuilder()
.when(datasetObjEntity.targetClassCd.eq("container"))
.then(1)
.otherwise(0)
.when(
datasetObjEntity.targetClassCd.eq(
DetectionClassification.CONTAINER.getId()))
.then(1L)
.otherwise(0L)
.sum()))
.from(dataset)
.leftJoin(datasetObjEntity)
@@ -249,29 +249,40 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
}
// TODO 미사용 끝
@Override
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
String building = DetectionClassification.BUILDING.getId();
String container = DetectionClassification.CONTAINER.getId();
String waste = DetectionClassification.WASTE.getId();
String solar = DetectionClassification.SOLAR.getId();
BooleanBuilder builder = new BooleanBuilder();
builder.and(dataset.deleted.isFalse());
NumberExpression<Long> selectedCnt = null;
// G2
NumberExpression<Long> wasteCnt =
datasetObjEntity.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
NumberExpression<Long> elseCnt =
new CaseBuilder()
.when(datasetObjEntity.targetClassCd.notIn("building", "container", "waste"))
datasetObjEntity
.targetClassCd
.when(DetectionClassification.WASTE.getId())
.then(1L)
.otherwise(0L)
.sum();
if (StringUtils.isNotBlank(req.getModelNo())) {
if (req.getModelNo().equals(ModelType.G2.getId())) {
selectedCnt = wasteCnt;
} else {
selectedCnt = elseCnt;
}
// G3 (G1, G2, G4 제외)
NumberExpression<Long> elseCnt =
new CaseBuilder()
.when(datasetObjEntity.targetClassCd.notIn(building, container, waste, solar))
.then(1L)
.otherwise(0L)
.sum();
if (req.getModelNo().equals(ModelType.G2.getId())) {
selectedCnt = wasteCnt;
} else {
selectedCnt = elseCnt;
}
if (StringUtils.isNotBlank(req.getDataType())) {
@@ -481,4 +492,51 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
.where(dataset.uid.eq(uid), dataset.deleted.isFalse())
.fetchOne();
}
@Override
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
BooleanBuilder builder = new BooleanBuilder();
builder.and(dataset.deleted.isFalse());
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
builder.and(dataset.dataType.eq(req.getDataType()));
}
if (req.getIds() != null) {
builder.and(dataset.id.in(req.getIds()));
}
return queryFactory
.select(
Projections.constructor(
SelectDataSet.class,
Expressions.constant(req.getModelNo()),
dataset.id,
dataset.uuid,
dataset.dataType,
dataset.title,
dataset.roundNo,
dataset.compareYyyy,
dataset.targetYyyy,
dataset.memo,
new CaseBuilder()
.when(datasetObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()))
.then(1L)
.otherwise(0L)
.sum()))
.from(dataset)
.leftJoin(datasetObjEntity)
.on(dataset.id.eq(datasetObjEntity.datasetUid))
.where(builder)
.groupBy(
dataset.id,
dataset.uuid,
dataset.dataType,
dataset.title,
dataset.roundNo,
dataset.memo)
.orderBy(dataset.createdDttm.desc())
.fetch();
}
}

View File

@@ -1,9 +1,11 @@
package com.kamco.cd.training.postgres.repository.model;
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
import com.kamco.cd.training.common.enums.DetectionClassification;
import com.kamco.cd.training.common.enums.ModelType;
import com.kamco.cd.training.postgres.entity.ModelDatasetMappEntity;
import com.kamco.cd.training.postgres.entity.QDatasetObjEntity;
@@ -11,6 +13,7 @@ import com.kamco.cd.training.postgres.entity.QDatasetTestObjEntity;
import com.kamco.cd.training.postgres.entity.QDatasetValObjEntity;
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import lombok.RequiredArgsConstructor;
@@ -33,9 +36,44 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
@Override
public List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId) {
QDatasetObjEntity datasetObjEntity = QDatasetObjEntity.datasetObjEntity;
// =====================
// 조건 분리
// =====================
BooleanExpression g1 =
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(
datasetObjEntity.targetClassCd.in(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId()));
BooleanExpression g2 =
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
BooleanExpression g4 =
modelMasterEntity
.modelNo
.eq(ModelType.G4.getId())
.and(datasetObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
// G3 = 전체 허용 (fallback)
BooleanExpression g3 =
modelMasterEntity
.modelNo
.eq(ModelType.G3.getId())
.and(
datasetObjEntity.targetClassCd.notIn(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId(),
DetectionClassification.WASTE.getId(),
DetectionClassification.SOLAR.getId()));
return queryFactory
.select(
Projections.constructor(
@@ -60,17 +98,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
datasetObjEntity
.datasetUid
.eq(modelDatasetMappEntity.datasetUid)
.and(
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(datasetObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
.or(
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetObjEntity.targetClassCd.upper().eq("WASTE")))
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
.and(g1.or(g2).or(g4).or(g3)))
.where(modelMasterEntity.id.eq(modelId))
.fetch();
}
@@ -80,6 +108,42 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
QDatasetValObjEntity datasetValObjEntity = QDatasetValObjEntity.datasetValObjEntity;
// =====================
// 조건 분리
// =====================
BooleanExpression g1 =
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(
datasetValObjEntity.targetClassCd.in(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId()));
BooleanExpression g2 =
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetValObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
BooleanExpression g4 =
modelMasterEntity
.modelNo
.eq(ModelType.G4.getId())
.and(datasetValObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
// G3 = 전체 허용 (fallback)
BooleanExpression g3 =
modelMasterEntity
.modelNo
.eq(ModelType.G3.getId())
.and(
datasetValObjEntity.targetClassCd.notIn(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId(),
DetectionClassification.WASTE.getId(),
DetectionClassification.SOLAR.getId()));
return queryFactory
.select(
Projections.constructor(
@@ -104,17 +168,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
datasetValObjEntity
.datasetUid
.eq(modelDatasetMappEntity.datasetUid)
.and(
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(datasetValObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
.or(
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetValObjEntity.targetClassCd.upper().eq("WASTE")))
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
.and(g1.or(g2).or(g4).or(g3)))
.where(modelMasterEntity.id.eq(modelId))
.fetch();
}
@@ -124,6 +178,42 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
QDatasetTestObjEntity datasetTestObjEntity = QDatasetTestObjEntity.datasetTestObjEntity;
// =====================
// 조건 분리
// =====================
BooleanExpression g1 =
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(
datasetTestObjEntity.targetClassCd.in(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId()));
BooleanExpression g2 =
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetTestObjEntity.targetClassCd.eq(DetectionClassification.WASTE.getId()));
BooleanExpression g4 =
modelMasterEntity
.modelNo
.eq(ModelType.G4.getId())
.and(datasetTestObjEntity.targetClassCd.eq(DetectionClassification.SOLAR.getId()));
// G3 = 전체 허용 (fallback)
BooleanExpression g3 =
modelMasterEntity
.modelNo
.eq(ModelType.G3.getId())
.and(
datasetTestObjEntity.targetClassCd.notIn(
DetectionClassification.CONTAINER.getId(),
DetectionClassification.BUILDING.getId(),
DetectionClassification.WASTE.getId(),
DetectionClassification.SOLAR.getId()));
return queryFactory
.select(
Projections.constructor(
@@ -148,17 +238,7 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
datasetTestObjEntity
.datasetUid
.eq(modelDatasetMappEntity.datasetUid)
.and(
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(datasetTestObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
.or(
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(datasetTestObjEntity.targetClassCd.upper().eq("WASTE")))
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
.and(g1.or(g2).or(g4).or(g3)))
.where(modelMasterEntity.id.eq(modelId))
.fetch();
}

View File

@@ -1,6 +1,7 @@
package com.kamco.cd.training.postgres.repository.model;
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
import static com.kamco.cd.training.postgres.entity.QModelDatasetEntity.modelDatasetEntity;
import static com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity.modelDatasetMappEntity;
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
@@ -9,6 +10,8 @@ import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.mode
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.DetectionClassification;
import com.kamco.cd.training.common.enums.ModelType;
import com.kamco.cd.training.common.enums.TrainStatusType;
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
@@ -25,6 +28,7 @@ import com.kamco.cd.training.postgres.entity.QModelHyperParamEntity;
import com.kamco.cd.training.postgres.entity.QModelMasterEntity;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.ArrayList;
@@ -76,6 +80,8 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
modelMasterEntity.modelNo,
modelMasterEntity.modelVer,
modelMasterEntity.step1StrtDttm,
modelMasterEntity.step1EndDttm,
modelMasterEntity.step2StrtDttm,
modelMasterEntity.step2EndDttm,
modelMasterEntity.statusCd,
modelMasterEntity.trainType,
@@ -154,10 +160,78 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
datasetEntity.compareYyyy,
datasetEntity.targetYyyy,
datasetEntity.roundNo,
modelDatasetEntity.buildingCnt,
modelDatasetEntity.containerCnt,
modelDatasetEntity.wasteCnt,
modelDatasetEntity.landCoverCnt))
// G1 - building
new CaseBuilder()
.when(
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(
datasetObjEntity.targetClassCd.eq(
DetectionClassification.BUILDING.getId())))
.then(1L)
.otherwise(0L)
.sum(),
// G1 - container
new CaseBuilder()
.when(
modelMasterEntity
.modelNo
.eq(ModelType.G1.getId())
.and(
datasetObjEntity.targetClassCd.eq(
DetectionClassification.CONTAINER.getId())))
.then(1L)
.otherwise(0L)
.sum(),
// G2 - waste
new CaseBuilder()
.when(
modelMasterEntity
.modelNo
.eq(ModelType.G2.getId())
.and(
datasetObjEntity.targetClassCd.eq(
DetectionClassification.WASTE.getId())))
.then(1L)
.otherwise(0L)
.sum(),
// G3 - 나머지
new CaseBuilder()
.when(
modelMasterEntity
.modelNo
.eq(ModelType.G3.getId())
.and(
datasetObjEntity
.targetClassCd
.isNotNull()
.and(
datasetObjEntity.targetClassCd.notIn(
DetectionClassification.BUILDING.getId(),
DetectionClassification.CONTAINER.getId(),
DetectionClassification.WASTE.getId(),
DetectionClassification.SOLAR.getId()))))
.then(1L)
.otherwise(0L)
.sum(),
// G4 - solar
new CaseBuilder()
.when(
modelMasterEntity
.modelNo
.eq(ModelType.G4.getId())
.and(
datasetObjEntity.targetClassCd.eq(
DetectionClassification.SOLAR.getId())))
.then(1L)
.otherwise(0L)
.sum()))
.from(modelMasterEntity)
.innerJoin(modelDatasetEntity)
.on(modelMasterEntity.id.eq(modelDatasetEntity.model.id))
@@ -165,7 +239,16 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
.on(modelMasterEntity.id.eq(modelDatasetMappEntity.modelUid))
.innerJoin(datasetEntity)
.on(modelDatasetMappEntity.datasetUid.eq(datasetEntity.id))
.leftJoin(datasetObjEntity)
.on(datasetEntity.id.eq(datasetObjEntity.datasetUid))
.where(modelMasterEntity.uuid.eq(uuid))
.groupBy(
modelMasterEntity.id,
datasetEntity.id,
datasetEntity.dataType,
datasetEntity.compareYyyy,
datasetEntity.targetYyyy,
datasetEntity.roundNo)
.fetch();
}

View File

@@ -4,6 +4,7 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
import com.kamco.cd.training.train.dto.TrainRunRequest;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.domain.Page;
@@ -28,4 +29,22 @@ public interface ModelMngRepositoryCustom {
TrainRunRequest findTrainRunRequest(Long modelId);
Long findModelStep1InProgressCnt();
/**
* 모델 번호와 삭제 여부로 모델 조회 (최신순)
*
* @param modelNo 모델 번호 (G1, G2, G3, G4)
* @param delYn 삭제 여부
* @return 모델 목록
*/
List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
String modelNo, Boolean delYn);
/**
* 하이퍼파라미터 ID로 모델 조회
*
* @param hyperParamId 하이퍼파라미터 ID
* @return 모델 목록
*/
List<ModelMasterEntity> findByHyperParamId(Long hyperParamId);
}

View File

@@ -189,7 +189,8 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
modelHyperParamEntity.hueDelta,
Expressions.nullExpression(Integer.class),
Expressions.nullExpression(String.class),
modelHyperParamEntity.uuid))
modelHyperParamEntity.uuid,
modelMasterEntity.reqTmpYn))
.from(modelMasterEntity)
.leftJoin(modelHyperParamEntity)
.on(modelHyperParamEntity.id.eq(modelMasterEntity.hyperParamId))
@@ -211,4 +212,23 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
.or(modelMasterEntity.step2State.eq(TrainStatusType.IN_PROGRESS.getId())))
.fetchOne();
}
@Override
public List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
String modelNo, Boolean delYn) {
return queryFactory
.selectFrom(modelMasterEntity)
.where(modelMasterEntity.modelNo.eq(modelNo), modelMasterEntity.delYn.eq(delYn))
.orderBy(modelMasterEntity.createdDttm.desc())
.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();
}
}

View File

@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.SimpleMetricJsonDto;
import java.time.ZonedDateTime;
import java.util.List;
@@ -12,13 +13,33 @@ public interface ModelTestMetricsJobRepositoryCustom {
List<ResponsePathDto> getTestMetricSaveNotYetModelIds();
ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId);
void insertModelMetricsTest(List<Object[]> batchArgs);
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
/**
* 간단한 형식의 테스트 메트릭 정보 조회 (ZIP 파일용)
*
* @param modelId 모델 ID
* @return 간단한 JSON 형식 DTO
*/
SimpleMetricJsonDto getSimpleTestMetricPackingInfo(Long modelId);
ModelTestFileName findModelTestFileNames(Long modelId);
void updatePackingStart(Long modelId, ZonedDateTime now);
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);
}

View File

@@ -3,6 +3,7 @@ package com.kamco.cd.training.postgres.repository.train;
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
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.postgres.entity.ModelMetricsTestEntity;
@@ -10,6 +11,8 @@ import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
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.jpa.impl.JPAQueryFactory;
import java.time.ZonedDateTime;
@@ -63,6 +66,25 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
.fetch();
}
@Override
public ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId) {
return queryFactory
.select(
Projections.constructor(
ResponsePathDto.class,
modelMasterEntity.id,
modelMasterEntity.responsePath,
modelMasterEntity.uuid))
.from(modelMasterEntity)
.where(
modelMasterEntity.id.eq(modelId),
modelMasterEntity
.step2MetricSaveYn
.isNull()
.or(modelMasterEntity.step2MetricSaveYn.isFalse()))
.fetchOne();
}
@Override
public void insertModelMetricsTest(List<Object[]> batchArgs) {
// AS-IS
@@ -80,19 +102,19 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
// TO-BE: modelId, model(best_fscore_10) 같은 데이터가 있으면 update, 없으면 insert
String updateSql =
"""
UPDATE tb_model_metrics_test
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
detection_count=?, gt_count=?
WHERE model_id=? AND model=?
""";
UPDATE tb_model_metrics_test
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
detection_count=?, gt_count=?
WHERE model_id=? AND model=?
""";
String insertSql =
"""
INSERT INTO tb_model_metrics_test
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
detection_count, gt_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""";
INSERT INTO tb_model_metrics_test
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
detection_count, gt_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""";
// row 단위 처리 (batch 안에서 upsert)
for (Object[] row : batchArgs) {
@@ -136,6 +158,33 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
.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
public ModelTestFileName findModelTestFileNames(Long modelId) {
return queryFactory
@@ -168,4 +217,64 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
.where(modelMasterEntity.id.eq(modelId))
.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();
}
}

View File

@@ -7,6 +7,8 @@ public interface ModelTrainMetricsJobRepositoryCustom {
List<ResponsePathDto> getTrainMetricSaveNotYetModelIds();
ResponsePathDto getTrainMetricSaveNotYetModelId(Long modelId);
void insertModelMetricsTrain(List<Object[]> batchArgs);
void updateModelMetricsTrainSaveYn(Long modelId, String stepNo);

View File

@@ -44,6 +44,25 @@ public class ModelTrainMetricsJobRepositoryImpl extends QuerydslRepositorySuppor
.fetch();
}
@Override
public ResponsePathDto getTrainMetricSaveNotYetModelId(Long modelId) {
return queryFactory
.select(
Projections.constructor(
ResponsePathDto.class,
modelMasterEntity.id,
modelMasterEntity.responsePath,
modelMasterEntity.uuid))
.from(modelMasterEntity)
.where(
modelMasterEntity.id.eq(modelId),
modelMasterEntity
.step1MetricSaveYn
.isNull()
.or(modelMasterEntity.step1MetricSaveYn.isFalse()))
.fetchOne();
}
@Override
public void insertModelMetricsTrain(List<Object[]> batchArgs) {
String sql =

View File

@@ -1,9 +1,12 @@
package com.kamco.cd.training.train;
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.TestJobService;
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.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
@@ -29,6 +32,7 @@ public class TrainApiController {
private final TrainJobService trainJobService;
private final TestJobService testJobService;
private final DataSetCountersService dataSetCountersService;
private final TrainingMetricsService trainingMetricsService;
@Operation(summary = "학습 실행", description = "학습 실행 API")
@ApiResponses(
@@ -213,4 +217,108 @@ public class TrainApiController {
Long modelId = trainJobService.getModelIdByUuid(uuid);
return ApiResponseDto.ok(dataSetCountersService.getCount(modelId));
}
@Operation(summary = "학습 상태 확인", description = "학습 상태 확인")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "학습 상태 변경",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = String.class))),
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@PostMapping(path = "/status/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE)
public ApiResponseDto<String> status(
@Parameter(description = "uuid", example = "e22181eb-2ac4-4100-9941-d06efce25c49")
@PathVariable
UUID uuid) {
Long modelId = trainJobService.getModelIdByUuid(uuid);
trainJobService.status(uuid, modelId);
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);
}
}

View File

@@ -0,0 +1,8 @@
package com.kamco.cd.training.train.dto;
public record DockerInspectState(boolean exists, boolean running, Integer exitCode, String status) {
public static DockerInspectState missing() {
return new DockerInspectState(false, false, null, "missing");
}
}

View File

@@ -15,6 +15,7 @@ public class EvalRunRequest {
private Integer timeoutSeconds;
private String datasetFolder;
private String outputFolder;
private Boolean reqTmpYn;
public String getOutputFolder() {
return this.outputFolder.toString();

View File

@@ -2,7 +2,7 @@ package com.kamco.cd.training.train.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Properties;
import java.nio.file.Path;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -23,6 +23,17 @@ public class ModelTrainMetricsDto {
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
@AllArgsConstructor
public static class ModelMetricJsonDto {
@@ -33,20 +44,133 @@ public class ModelTrainMetricsDto {
@JsonProperty("model_version")
private String modelVersion;
@JsonProperty("metric_type")
private String metricType; // fscore, precision, recall
private Integer epoch; // epoch 번호
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
@AllArgsConstructor
public static class Properties {
@JsonProperty("f1_score")
private Float f1Score;
// 변화 탐지 관련 메트릭 (Changed)
@JsonProperty("changed_fscore")
private Float changedFscore;
private Float precision;
private Float recall;
private Float loss;
private Double iou;
@JsonProperty("changed_precision")
private Float changedPrecision;
@JsonProperty("changed_recall")
private Float changedRecall;
// 비변화 관련 메트릭 (Unchanged)
@JsonProperty("unchanged_fscore")
private Float unchangedFscore;
@JsonProperty("unchanged_precision")
private Float unchangedPrecision;
@JsonProperty("unchanged_recall")
private Float unchangedRecall;
// 평균 메트릭 (Mean)
@JsonProperty("mean_fscore")
private Float mFscore;
@JsonProperty("mean_precision")
private Float mPrecision;
@JsonProperty("mean_recall")
private Float mRecall;
@JsonProperty("mean_iou")
private Float mIou;
@JsonProperty("mean_accuracy")
private Float mAcc;
// 전체 정확도 (Overall Accuracy)
@JsonProperty("overall_accuracy")
private Float aAcc;
// 학습 관련 메트릭
@JsonProperty("loss")
private Double loss;
@JsonProperty("learning_rate")
private Double lr;
@JsonProperty("duration_time")
private Float durationTime;
// 기존 방식용 생성자 (getTestMetricPackingInfo에서 사용)
public Properties(Float f1Score, Float precisions, Float recall, Float iou, Double loss) {
this.changedFscore = f1Score;
this.changedPrecision = precisions;
this.changedRecall = recall;
this.unchangedFscore = null;
this.unchangedPrecision = null;
this.unchangedRecall = null;
this.mFscore = null;
this.mPrecision = null;
this.mRecall = null;
this.mIou = iou;
this.mAcc = null;
this.aAcc = null;
this.loss = loss;
this.lr = null;
this.durationTime = null;
}
}
@Getter
@@ -56,4 +180,35 @@ public class ModelTrainMetricsDto {
private String bestEpochFileName;
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;
}
}

View File

@@ -0,0 +1,20 @@
package com.kamco.cd.training.train.dto;
public class OutputResult {
private final boolean completed;
private final String reason;
public OutputResult(boolean completed, String reason) {
this.completed = completed;
this.reason = reason;
}
public boolean completed() {
return completed;
}
public String reason() {
return reason;
}
}

View File

@@ -84,6 +84,8 @@ public class TrainRunRequest {
private UUID uuid;
private Boolean reqTmpYn; // tmp 심볼릭 링크를 쓰는지 아닌지 여부
public String getOutputFolder() {
return String.valueOf(this.outputFolder);
}

View File

@@ -0,0 +1,148 @@
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;
}
}

View File

@@ -0,0 +1,44 @@
package com.kamco.cd.training.train.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.ZonedDateTime;
import java.util.UUID;
import lombok.Builder;
import lombok.Getter;
/** 학습 진행률 조회 응답 DTO */
@Getter
@Builder
public class TrainingProgressDto {
// 기본 정보
private Long jobId;
private UUID modelUuid;
private String statusCd; // QUEUED/RUNNING/SUCCESS/FAILED
private String currentPhase; // 현재 단계 (계산된 값)
private Double progressPercent; // 진행률 (0.00 ~ 100.00, 계산된 값)
// Epoch 정보 (기존 DB 컬럼)
private Integer currentEpoch; // 현재 Epoch
private Integer totalEpoch; // 전체 Epoch
// 시간 정보 (기존 DB 컬럼) - ISO 8601 형식으로 직렬화
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private ZonedDateTime queuedDttm; // 큐 등록 시각
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private ZonedDateTime startedDttm; // 시작 시각
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private ZonedDateTime finishedDttm; // 종료 시각 (완료/실패 시)
// 계산된 시간 정보
private Long elapsedSeconds; // 경과 시간 (초)
private Long estimatedRemainingSeconds; // 예상 남은 시간 (초)
// 상태 메시지
private String message; // 현재 상태 메시지 (계산된 값)
// 에러 정보 (실패 시)
private String errorMessage; // 에러 메시지 (기존 DB 컬럼)
}

View File

@@ -56,6 +56,15 @@ public class DockerTrainService {
@Value("${spring.profiles.active}")
private String profile;
@Value("${hyper.parameter.gpus}")
private String hyperGpus;
@Value("${hyper.parameter.gpu-ids}")
private String hyperGpuIds;
@Value("${hyper.parameter.batch-size}")
private Integer batchSize;
private final ModelTrainJobCoreService modelTrainJobCoreService;
/**
@@ -149,12 +158,42 @@ public class DockerTrainService {
lastEpoch.set(epoch);
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(
"[TRAIN] container={} epoch={} iter={}/{}",
"[TRAIN] {} container={} epoch={}/{} iter={}/{} | Progress: {}%",
stepLabel,
containerName,
epoch,
maxEpochs,
iter,
totalIter);
totalIter,
String.format("%.2f", progress));
modelTrainJobCoreService.updateEpoch(containerName, epoch);
}
@@ -262,7 +301,11 @@ public class DockerTrainService {
c.add("-v");
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
c.add("-v");
c.add(symbolicDir + ":/data"); // 요청할경로
if (req.getReqTmpYn()) {
c.add(symbolicDir + ":/data"); // 요청할경로 : tmp 심볼릭 사용하는 것이니 symbolicDir로 호출
} else {
c.add(requestDir + ":/data"); // 요청할경로 : tmp 심볼릭 사용하지 않으니 request로 호출
}
c.add("-v");
c.add(responseDir + ":/checkpoints"); // 저장될경로
@@ -285,11 +328,13 @@ public class DockerTrainService {
// addArg(c, "--gpu-ids", req.getGpuIds()); // null
if ("prod".equals(profile)) {
addArg(c, "--batch-size", 2); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
addArg(c, "--gpus", "1"); // 학습서버 GPU 1개인 곳은 1이어야 함
addArg(c, "--gpu-ids", "0"); // 학습서버 GPU 1개인 곳은 0이어야 함
} else {
addArg(c, "--batch-size", req.getBatchSize()); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
addArg(c, "--batch-size", batchSize); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
}
addArg(c, "--gpus", hyperGpus); // 학습서버 GPU 1개인 곳은 1이어야 함
addArg(c, "--gpu-ids", hyperGpuIds); // 학습서버 GPU 1개인 곳은 0이어야 함
addArg(c, "--lr", req.getLearningRate());
addArg(c, "--backbone", req.getBackbone());
addArg(c, "--epochs", req.getEpochs());
@@ -461,11 +506,17 @@ public class DockerTrainService {
c.add("-v");
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
c.add("-v");
c.add(basePath + "/tmp:/data");
c.add("-v");
c.add(responseDir + ":/checkpoints");
if (req.getReqTmpYn()) {
c.add(symbolicDir + ":/data"); // tmp 사용하는 모델은 심볼릭 링크
} else {
c.add(requestDir + ":/data"); // tmp 사용하지 않는 모델은 request 경로
}
c.add("-v");
// c.add(responseDir + ":/checkpoints");
c.add(responseDir + "/" + req.getOutputFolder() + ":/checkpoints");
c.add("kamco-cd-train:latest");
@@ -473,7 +524,7 @@ public class DockerTrainService {
c.add("/workspace/change-detection-code/run_evaluation_pipeline.py");
addArg(c, "--dataset-folder", req.getDatasetFolder());
addArg(c, "--output-folder", req.getOutputFolder());
// addArg(c, "--output-folder", req.getOutputFolder());
c.add("--epoch");
c.add(modelFile);

View File

@@ -1,25 +1,16 @@
package com.kamco.cd.training.train.service;
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.postgres.core.ModelTrainJobCoreService;
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
import com.kamco.cd.training.train.dto.DockerInspectState;
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
import java.io.BufferedReader;
import com.kamco.cd.training.train.dto.OutputResult;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
@@ -44,14 +35,7 @@ public class JobRecoveryOnStartupService {
private final ModelTrainJobCoreService modelTrainJobCoreService;
private final ModelTrainMngCoreService modelTrainMngCoreService;
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
/**
* Docker 컨테이너가 쓰는 response(산출물) 디렉토리의 "호스트 측" 베이스 경로. 예) /data/train/response
*
* <p>컨테이너가 --rm 으로 삭제된 경우에도 이 경로에 val.csv / *.pth 등이 남아있으면 정상 종료 여부를 "파일 기반"으로 판정합니다.
*/
@Value("${train.docker.response_dir}")
private String responseDir;
private final TrainUtilService trainUtilService;
/**
* 스프링 부팅 완료 시점(빈 생성/초기화 모두 끝난 뒤)에 복구 로직 실행.
@@ -77,7 +61,7 @@ public class JobRecoveryOnStartupService {
try {
// 2-1) docker inspect로 컨테이너 상태 조회
DockerInspectState state = inspectContainer(containerName);
DockerInspectState state = trainUtilService.inspectContainer(containerName);
// 3) 컨테이너가 "없음"
// - docker run --rm 로 실행한 컨테이너는 정상 종료 시 바로 삭제될 수 있음
@@ -88,7 +72,7 @@ public class JobRecoveryOnStartupService {
containerName);
// 3-1) 컨테이너가 없을 때는 산출물(responseDir)을 보고 완료 여부를 "추정"
OutputResult out = probeOutputs(job);
OutputResult out = trainUtilService.probeOutputs(job);
// 3-2) 산출물이 충분하면 성공 처리
if (out.completed()) {
@@ -109,11 +93,9 @@ public class JobRecoveryOnStartupService {
job.getId(),
out.reason());
Integer modelId = job.getModelId() == null ? null : Math.toIntExact(job.getModelId());
// PAUSED/STOP
modelTrainJobCoreService.markPaused(
job.getId(), modelId, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE");
job.getId(), -1, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE");
// 모델도 에러가 아니라 STOP으로
markStepStopByJobType(
@@ -152,7 +134,7 @@ public class JobRecoveryOnStartupService {
// ============================================================
// 2) kill 후 실제로 죽었는지 확인
// ============================================================
DockerInspectState after = inspectContainer(containerName);
DockerInspectState after = trainUtilService.inspectContainer(containerName);
if (after.exists() && after.running()) {
throw new IOException("docker kill returned 0 but container still running");
}
@@ -162,10 +144,8 @@ public class JobRecoveryOnStartupService {
// ============================================================
// 3) job 상태를 PAUSED로 변경 (서버 재기동으로 강제 중단)
// ============================================================
Integer modelId = job.getModelId() == null ? null : Math.toIntExact(job.getModelId());
modelTrainJobCoreService.markPaused(
job.getId(), modelId, "AUTO_KILLED_ON_SERVER_RESTART");
modelTrainJobCoreService.markPaused(job.getId(), -1, "AUTO_KILLED_ON_SERVER_RESTART");
log.info("job = {}", job);
markStepStopByJobType(job, "AUTO_KILLED_ON_SERVER_RESTART");
@@ -264,270 +244,4 @@ public class JobRecoveryOnStartupService {
modelTrainMngCoreService.markError(job.getModelId(), msg);
}
}
/**
* docker inspect를 사용해서 컨테이너 상태를 조회합니다.
*
* <p>사용하는 템플릿: {{.State.Status}} {{.State.Running}} {{.State.ExitCode}}
*
* <p>예상 출력 예: - "running true 0" - "exited false 0" - "exited false 137"
*
* <p>주의: - 컨테이너가 없거나 inspect 실패 시 exitCode != 0 또는 output이 비어서 missing() 반환 - 무한 대기 방지를 위해 5초
* 타임아웃을 둠
*/
private DockerInspectState inspectContainer(String containerName)
throws IOException, InterruptedException {
ProcessBuilder pb =
new ProcessBuilder(
"docker",
"inspect",
"-f",
"{{.State.Status}} {{.State.Running}} {{.State.ExitCode}}",
containerName);
// stderr를 stdout으로 합쳐서 한 스트림으로 읽기(에러 메시지도 함께 받음)
pb.redirectErrorStream(true);
Process p = pb.start();
// inspect 출력은 1줄이면 충분하므로 readLine()만 수행
String output;
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
output = br.readLine();
}
// 무한대기 방지: 5초 내에 종료되지 않으면 강제 종료
boolean finished = p.waitFor(5, TimeUnit.SECONDS);
if (!finished) {
p.destroyForcibly();
throw new IOException("docker inspect timeout");
}
// docker inspect 자체의 프로세스 exit code
int code = p.exitValue();
// 실패(코드 !=0) 또는 출력이 없으면 "컨테이너 없음"으로 간주
if (code != 0 || output == null || output.isBlank()) {
return DockerInspectState.missing();
}
// "status running exitCode" 형태로 split
String[] parts = output.trim().split("\\s+");
// status: running/exited/dead 등
String status = parts.length > 0 ? parts[0] : "unknown";
// running: true/false
boolean running = parts.length > 1 && Boolean.parseBoolean(parts[1]);
// exitCode: 정수 파싱(파싱 실패하면 null)
Integer exitCode = null;
if (parts.length > 2) {
try {
exitCode = Integer.parseInt(parts[2]);
} catch (Exception ignore) {
// ignore
}
}
return new DockerInspectState(true, running, exitCode, status);
}
/**
* docker inspect 결과를 담는 레코드.
*
* <p>exists: - true : docker inspect 성공 (컨테이너 존재) - false : 컨테이너 없음(또는 inspect 실패를 missing으로 간주)
*/
private record DockerInspectState(
boolean exists, boolean running, Integer exitCode, String status) {
static DockerInspectState missing() {
return new DockerInspectState(false, false, null, "missing");
}
}
// ============================================================================================
// 컨테이너가 "없을 때" 파일 기반으로 완료/미완료를 판정하는 로직
// ============================================================================================
/**
* 컨테이너가 없을 때(responseDir 산출물만 남아있는 상태) 완료 여부를 파일 기반으로 판정합니다.
*
* <p>판정 규칙(보수적으로 설계): 1) total_epoch가 paramsJson에 있어야 함 (없으면 완료 판단 불가) 2) val.csv 존재 + 헤더 제외 라인 수
* >= total_epoch 이어야 함 3) *.pth 파일이 total_epoch 이상 존재하거나, best*.pth(또는 *best*.pth)가 존재해야 함
*
* <p>왜 이렇게? - 어떤 학습은 epoch마다 pth를 남기고 - 어떤 학습은 best만 남기기도 해서 "pthCount >= total_epoch"만 쓰면 정상 종료를
* 실패로 오판할 수 있음.
*/
private OutputResult probeOutputs(ModelTrainJobDto job) {
try {
log.info(
"[RECOVERY] probeOutputs start. jobId={}, modelId={}", job.getId(), job.getModelId());
// 1) 출력 디렉토리 확인
Path outDir = resolveOutputDir(job);
if (outDir == null || !Files.isDirectory(outDir)) {
log.warn("[RECOVERY] output directory missing. jobId={}, path={}", job.getId(), outDir);
return new OutputResult(false, "output-dir-missing");
}
log.info("[RECOVERY] output directory found. jobId={}, path={}", job.getId(), outDir);
// 2) totalEpoch 확인
Integer totalEpoch = extractTotalEpoch(job).orElse(null);
if (totalEpoch == null || totalEpoch <= 0) {
log.warn(
"[RECOVERY] totalEpoch missing or invalid. jobId={}, totalEpoch={}",
job.getId(),
totalEpoch);
return new OutputResult(false, "total-epoch-missing");
}
log.info("[RECOVERY] totalEpoch={}. jobId={}", totalEpoch, job.getId());
// 3) val.csv 존재 확인
Path valCsv = outDir.resolve("val.csv");
if (!Files.exists(valCsv)) {
log.warn("[RECOVERY] val.csv missing. jobId={}, path={}", job.getId(), valCsv);
return new OutputResult(false, "val.csv-missing");
}
// 4) val.csv 라인 수 확인
long lines = countNonHeaderLines(valCsv);
log.info(
"[RECOVERY] val.csv lines counted. jobId={}, lines={}, expected={}",
job.getId(),
lines,
totalEpoch);
// 5) 완료 판정
if (lines == totalEpoch) {
log.info("[RECOVERY] outputs look COMPLETE. jobId={}", job.getId());
return new OutputResult(true, "ok");
}
log.warn(
"[RECOVERY] val.csv line mismatch. jobId={}, lines={}, expected={}",
job.getId(),
lines,
totalEpoch);
return new OutputResult(
false, "val.csv-lines-mismatch lines=" + lines + " expected=" + totalEpoch);
} catch (Exception e) {
log.error("[RECOVERY] probeOutputs error. jobId={}", job.getId(), e);
return new OutputResult(false, "probe-error");
}
}
/**
* responseDir 아래에서 job 산출물 디렉토리를 찾습니다.
*
* <p>가장 중요한 커스터마이징 포인트: - 실제 운영 환경에서 산출물이 어떤 경로 규칙으로 저장되는지에 따라 여기만 수정하면 됩니다.
*
* <p>현재 기본 탐색 순서: 1) {responseDir}/{jobId} 2) {responseDir}/{modelId} 3)
* {responseDir}/{containerName} 4) 마지막 fallback: responseDir 자체
*
* <p>추천: - 여러분 규칙이 "{responseDir}/{modelId}/{jobId}" 같은 형태라면 base.resolve(modelId).resolve(jobId)
* 형태를 1순위로 두세요.
*/
private Path resolveOutputDir(ModelTrainJobDto job) {
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelById(job.getModelId());
Path base = Paths.get(responseDir, model.getUuid().toString(), "metrics");
return Files.isDirectory(base) ? base : null;
}
/**
* paramsJson에서 total_epoch 값을 추출합니다.
*
* <p>키 후보: - "total_epoch" (snake_case) - "totalEpoch" (camelCase)
*
* <p>예: paramsJson = {"jobType":"TRAIN","total_epoch":50,...}
*/
private Optional<Integer> extractTotalEpoch(ModelTrainJobDto job) {
Map<String, Object> params = job.getParamsJson();
if (params == null) return Optional.empty();
Object v = params.get("total_epoch");
if (v == null) v = params.get("totalEpoch");
if (v == null) return Optional.empty();
try {
return Optional.of(Integer.parseInt(String.valueOf(v)));
} catch (Exception ignore) {
return Optional.empty();
}
}
/**
* CSV 파일에서 "헤더(첫 줄)"를 제외한 라인 수를 계산합니다.
*
* <p>가정: - val.csv 첫 줄은 헤더 - 이후 라인들이 epoch별 기록(또는 유사한 누적 기록)
*
* <p>주의: - 파일 인코딩은 UTF-8로 가정 - 빈 줄은 제외
*/
private long countNonHeaderLines(Path csv) throws IOException {
try (Stream<String> lines = Files.lines(csv, StandardCharsets.UTF_8)) {
return lines.skip(1).filter(s -> s != null && !s.isBlank()).count();
}
}
/**
* 디렉토리에서 glob 패턴에 맞는 파일 수를 셉니다.
*
* <p>예: - "*.pth" - "best*.pth"
*/
private long countFilesByGlob(Path dir, String glob) throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, glob)) {
long cnt = 0;
for (Path p : ds) {
if (Files.isRegularFile(p)) cnt++;
}
return cnt;
}
}
/** 디렉토리에서 glob 패턴에 맞는 파일이 "하나라도" 존재하는지 체크합니다. */
private boolean existsByGlob(Path dir, String glob) throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, glob)) {
return ds.iterator().hasNext();
}
}
// ============================================================================================
// probeOutputs() 결과 객체
// ============================================================================================
/**
* 컨테이너가 없을 때(responseDir 기반) 완료 여부 판정 결과.
*
* <p>completed: - true : 산출물이 완료로 보임(성공 처리 가능) - false : 산출물이 부족/불명확(실패 또는 유예 판단)
*
* <p>reason: - 실패/미완료 사유(로그/DB 메시지로 남기기 용도)
*/
private static final class OutputResult {
private final boolean completed;
private final String reason;
private OutputResult(boolean completed, String reason) {
this.completed = completed;
this.reason = reason;
}
boolean completed() {
return completed;
}
String reason() {
return reason;
}
}
}

View File

@@ -4,9 +4,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kamco.cd.training.common.enums.TrainStatusType;
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.ModelTestFileName;
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.IOException;
import java.io.OutputStream;
@@ -19,6 +21,8 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
@@ -48,6 +52,9 @@ public class ModelTestMetricsJobService {
@Value("${file.pt-path}")
private String ptPathDir;
@Value("${file.pt-FileName}")
private String ptFileName;
/** 결과 csv 파일 정보 등록 */
public void findTestValidMetricCsvFiles() {
@@ -59,122 +66,370 @@ public class ModelTestMetricsJobService {
}
for (ResponsePathDto modelInfo : modelIds) {
createFile(modelInfo);
}
}
String testPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/test.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(testPath), StandardCharsets.UTF_8); ) {
/** 단건 결과 csv 파일 정보 등록 */
public void testValidMetricCsvFiles(Long modelId) {
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
ResponsePathDto model = modelTestMetricsJobCoreService.getTestMetricSaveNotYetModelId(modelId);
List<Object[]> batchArgs = new ArrayList<>();
if (model == null) {
return;
}
for (CSVRecord record : parser) {
createFile(model);
}
String model = record.get("model");
long TP = Long.parseLong(record.get("TP"));
long FP = Long.parseLong(record.get("FP"));
long FN = Long.parseLong(record.get("FN"));
float precision = Float.parseFloat(record.get("precision"));
float recall = Float.parseFloat(record.get("recall"));
float f1_score = Float.parseFloat(record.get("f1_score"));
float accuracy = Float.parseFloat(record.get("accuracy"));
float iou = Float.parseFloat(record.get("iou"));
long detection_count = Long.parseLong(record.get("detection_count"));
long gt_count = Long.parseLong(record.get("gt_count"));
/**
* 베스트 에폭 zip파일 생성, 테스트결과 db등록
*
* @param modelInfo 모델 정보 (modelId, responsePath, uuid)
*/
private void createFile(ResponsePathDto modelInfo) {
batchArgs.add(
new Object[] {
modelInfo.getModelId(),
model,
TP,
FP,
FN,
precision,
recall,
f1_score,
accuracy,
iou,
detection_count,
gt_count
});
}
String testPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/test.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(testPath), StandardCharsets.UTF_8)) {
modelTestMetricsJobCoreService.insertModelMetricsTest(batchArgs);
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
// test.csv 파일 읽어서 저장한 여부로만 사용하기
modelTestMetricsJobCoreService.updateModelMetricsTrainSaveYn(
modelInfo.getModelId(), "step2");
List<Object[]> batchArgs = new ArrayList<>();
} catch (IOException e) {
throw new RuntimeException(e);
for (CSVRecord record : parser) {
String model = record.get("model");
long TP = Long.parseLong(record.get("TP"));
long FP = Long.parseLong(record.get("FP"));
long FN = Long.parseLong(record.get("FN"));
float precision = Float.parseFloat(record.get("precision"));
float recall = Float.parseFloat(record.get("recall"));
float f1_score = Float.parseFloat(record.get("f1_score"));
float accuracy = Float.parseFloat(record.get("accuracy"));
float iou = Float.parseFloat(record.get("iou"));
long detection_count = Long.parseLong(record.get("detection_count"));
long gt_count = Long.parseLong(record.get("gt_count"));
batchArgs.add(
new Object[] {
modelInfo.getModelId(),
model,
TP,
FP,
FN,
precision,
recall,
f1_score,
accuracy,
iou,
detection_count,
gt_count
});
}
// 패키징할 파일 만들기
modelTestMetricsJobCoreService.updatePackingStart(
modelInfo.getModelId(), ZonedDateTime.now());
modelTestMetricsJobCoreService.insertModelMetricsTest(batchArgs);
ModelMetricJsonDto jsonDto =
modelTestMetricsJobCoreService.getTestMetricPackingInfo(modelInfo.getModelId());
try {
writeJsonFile(
jsonDto,
Paths.get(
responseDir
+ "/"
+ modelInfo.getUuid()
+ "/"
+ jsonDto.getModelVersion()
+ ".json"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// test.csv 파일 읽어서 저장한 여부로만 사용하기
modelTestMetricsJobCoreService.updateModelMetricsTrainSaveYn(modelInfo.getModelId(), "step2");
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
} catch (IOException e) {
throw new RuntimeException(e);
}
ModelTestFileName fileInfo =
modelTestMetricsJobCoreService.findModelTestFileNames(modelInfo.getModelId());
// 패키징할 파일 만들기
modelTestMetricsJobCoreService.updatePackingStart(modelInfo.getModelId(), ZonedDateTime.now());
Path zipPath =
// 간단한 형식의 JSON 생성 (ZIP 파일용)
SimpleMetricJsonDto jsonDto =
modelTestMetricsJobCoreService.getSimpleTestMetricPackingInfo(modelInfo.getModelId());
try {
writeJsonFile(
jsonDto,
Paths.get(
responseDir + "/" + modelInfo.getUuid() + "/" + fileInfo.getModelVersion() + ".zip");
Set<String> targetNames =
Set.of(
"model_config.py",
fileInfo.getBestEpochFileName() + ".pth",
fileInfo.getModelVersion() + ".json");
responseDir + "/" + modelInfo.getUuid() + "/" + jsonDto.getModelVersion() + ".json"));
} catch (IOException e) {
throw new RuntimeException(e);
}
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
ModelTestFileName fileInfo =
modelTestMetricsJobCoreService.findModelTestFileNames(modelInfo.getModelId());
Path zipPath =
Paths.get(
responseDir + "/" + modelInfo.getUuid() + "/" + fileInfo.getModelVersion() + ".zip");
Set<String> targetNames =
Set.of(
"model_config.py",
fileInfo.getBestEpochFileName() + ".pth",
fileInfo.getModelVersion() + ".json");
try {
List<Path> files = new ArrayList<>();
try (Stream<Path> s = Files.list(responsePath)) {
files.addAll(
s.filter(Files::isRegularFile)
.filter(p -> targetNames.contains(p.getFileName().toString()))
.collect(Collectors.toList()));
} catch (IOException e) {
throw new RuntimeException(e);
}
try (Stream<Path> s = Files.list(Path.of(ptPathDir))) {
files.addAll(
s.filter(Files::isRegularFile)
.limit(1) // yolov8_6th-6m.pt 파일 1개만
.collect(Collectors.toList()));
} catch (IOException e) {
throw new RuntimeException(e);
// PT 파일 정확하게 조회
Path ptFile = Paths.get(ptPathDir, ptFileName);
if (Files.exists(ptFile)) {
files.add(ptFile);
} else {
log.warn("PT 파일을 찾을 수 없습니다: {}", ptFile);
throw new IOException("PT 파일 누락: " + ptFile);
}
try {
zipFiles(files, zipPath);
// 기본 ZIP 생성
zipFiles(files, zipPath);
log.info(" 기본 ZIP 생성 완료: {}", zipPath.getFileName());
modelTestMetricsJobCoreService.updatePackingEnd(
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.COMPLETED.getId());
} catch (IOException e) {
modelTestMetricsJobCoreService.updatePackingEnd(
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.ERROR.getId());
throw new RuntimeException(e);
}
// 개별 best*.pth ZIP 생성
int individualZipCount = createIndividualBestPthZips(modelInfo, responsePath);
// 모든 ZIP 생성 성공 시 COMPLETED
modelTestMetricsJobCoreService.updatePackingEnd(
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.COMPLETED.getId());
log.info(" 전체 ZIP 생성 완료: 기본 1개 + 개별 {}개", individualZipCount);
} catch (IOException e) {
modelTestMetricsJobCoreService.updatePackingEnd(
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.ERROR.getId());
log.error("ZIP 생성 중 오류 발생: modelId={}", modelInfo.getModelId(), 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 {
Path parent = outputPath.getParent();

View File

@@ -48,115 +48,135 @@ public class ModelTrainMetricsJobService {
for (ResponsePathDto modelInfo : modelIds) {
String trainPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/train.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(trainPath), StandardCharsets.UTF_8); ) {
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
List<Object[]> batchArgs = new ArrayList<>();
for (CSVRecord record : parser) {
int epoch = Integer.parseInt(record.get("Epoch"));
long iteration = Long.parseLong(record.get("Iteration"));
double Loss = Double.parseDouble(record.get("Loss"));
double LR = Double.parseDouble(record.get("LR"));
float time = Float.parseFloat(record.get("Time"));
batchArgs.add(new Object[] {modelInfo.getModelId(), epoch, iteration, Loss, LR, time});
}
modelTrainMetricsJobCoreService.insertModelMetricsTrain(batchArgs);
} catch (IOException e) {
throw new RuntimeException(e);
}
String validationPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/val.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(validationPath), StandardCharsets.UTF_8); ) {
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
List<Object[]> batchArgs = new ArrayList<>();
for (CSVRecord record : parser) {
int epoch = Integer.parseInt(record.get("Epoch"));
Float aAcc = parseFloatSafe(record.get("aAcc"));
Float mFscore = parseFloatSafe(record.get("mFscore"));
Float mPrecision = parseFloatSafe(record.get("mPrecision"));
Float mRecall = parseFloatSafe(record.get("mRecall"));
Float mIoU = parseFloatSafe(record.get("mIoU"));
Float mAcc = parseFloatSafe(record.get("mAcc"));
Float changed_fscore = parseFloatSafe(record.get("changed_fscore"));
Float changed_precision = parseFloatSafe(record.get("changed_precision"));
Float changed_recall = parseFloatSafe(record.get("changed_recall"));
Float unchanged_fscore = parseFloatSafe(record.get("unchanged_fscore"));
Float unchanged_precision = parseFloatSafe(record.get("unchanged_precision"));
Float unchanged_recall = parseFloatSafe(record.get("unchanged_recall"));
batchArgs.add(
new Object[] {
modelInfo.getModelId(),
epoch,
aAcc,
mFscore,
mPrecision,
mRecall,
mIoU,
mAcc,
changed_fscore,
changed_precision,
changed_recall,
unchanged_fscore,
unchanged_precision,
unchanged_recall
});
}
modelTrainMetricsJobCoreService.insertModelMetricsValidation(batchArgs);
} catch (IOException e) {
throw new RuntimeException(e);
}
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
Integer epoch = null;
boolean exists;
Pattern pattern = Pattern.compile("best_changed_fscore_epoch_(\\d+)\\.pth");
try (Stream<Path> s = Files.list(responsePath)) {
epoch =
s.filter(Files::isRegularFile)
.map(
p -> {
Matcher matcher = pattern.matcher(p.getFileName().toString());
if (matcher.matches()) {
return Integer.parseInt(matcher.group(1)); // ← 숫자 부분 추출
}
return null;
})
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} catch (IOException e) {
throw new RuntimeException(e);
}
// best_changed_fscore_epoch_숫자.pth -> 숫자 값 가지고 와서 베스트 에폭에 업데이트 하기
modelTrainMetricsJobCoreService.updateModelSelectedBestEpoch(modelInfo.getModelId(), epoch);
modelTrainMetricsJobCoreService.updateModelMetricsTrainSaveYn(
modelInfo.getModelId(), "step1");
createFile(modelInfo);
}
}
/** 단건 결과 csv 파일 정보 등록 */
public void trainValidMetricCsvFile(Long modelId) {
ResponsePathDto modelInfo =
modelTrainMetricsJobCoreService.getTrainMetricSaveNotYetModelId(modelId);
if (modelInfo == null) {
return;
}
createFile(modelInfo);
}
/**
* 학습 csv 파일 db 등록
*
* @param modelInfo
*/
private void createFile(ResponsePathDto modelInfo) {
String trainPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/train.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(trainPath), StandardCharsets.UTF_8); ) {
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
List<Object[]> batchArgs = new ArrayList<>();
for (CSVRecord record : parser) {
int epoch = Integer.parseInt(record.get("Epoch"));
long iteration = Long.parseLong(record.get("Iteration"));
double Loss = Double.parseDouble(record.get("Loss"));
double LR = Double.parseDouble(record.get("LR"));
float time = Float.parseFloat(record.get("Time"));
batchArgs.add(new Object[] {modelInfo.getModelId(), epoch, iteration, Loss, LR, time});
}
modelTrainMetricsJobCoreService.insertModelMetricsTrain(batchArgs);
} catch (IOException e) {
throw new RuntimeException(e);
}
String validationPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/val.csv";
try (BufferedReader reader =
Files.newBufferedReader(Paths.get(validationPath), StandardCharsets.UTF_8); ) {
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
List<Object[]> batchArgs = new ArrayList<>();
for (CSVRecord record : parser) {
int epoch = Integer.parseInt(record.get("Epoch"));
Float aAcc = parseFloatSafe(record.get("aAcc"));
Float mFscore = parseFloatSafe(record.get("mFscore"));
Float mPrecision = parseFloatSafe(record.get("mPrecision"));
Float mRecall = parseFloatSafe(record.get("mRecall"));
Float mIoU = parseFloatSafe(record.get("mIoU"));
Float mAcc = parseFloatSafe(record.get("mAcc"));
Float changed_fscore = parseFloatSafe(record.get("changed_fscore"));
Float changed_precision = parseFloatSafe(record.get("changed_precision"));
Float changed_recall = parseFloatSafe(record.get("changed_recall"));
Float unchanged_fscore = parseFloatSafe(record.get("unchanged_fscore"));
Float unchanged_precision = parseFloatSafe(record.get("unchanged_precision"));
Float unchanged_recall = parseFloatSafe(record.get("unchanged_recall"));
batchArgs.add(
new Object[] {
modelInfo.getModelId(),
epoch,
aAcc,
mFscore,
mPrecision,
mRecall,
mIoU,
mAcc,
changed_fscore,
changed_precision,
changed_recall,
unchanged_fscore,
unchanged_precision,
unchanged_recall
});
}
modelTrainMetricsJobCoreService.insertModelMetricsValidation(batchArgs);
} catch (IOException e) {
throw new RuntimeException(e);
}
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
Integer epoch = null;
boolean exists;
Pattern pattern = Pattern.compile("best_changed_fscore_epoch_(\\d+)\\.pth");
try (Stream<Path> s = Files.list(responsePath)) {
epoch =
s.filter(Files::isRegularFile)
.map(
p -> {
Matcher matcher = pattern.matcher(p.getFileName().toString());
if (matcher.matches()) {
return Integer.parseInt(matcher.group(1)); // ← 숫자 부분 추출
}
return null;
})
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} catch (IOException e) {
throw new RuntimeException(e);
}
// best_changed_fscore_epoch_숫자.pth -> 숫자 값 가지고 와서 베스트 에폭에 업데이트 하기
modelTrainMetricsJobCoreService.updateModelSelectedBestEpoch(modelInfo.getModelId(), epoch);
modelTrainMetricsJobCoreService.updateModelMetricsTrainSaveYn(modelInfo.getModelId(), "step1");
}
private Float parseFloatSafe(String value) {
try {
if (value == null) return null;

View File

@@ -52,6 +52,7 @@ public class TestJobService {
params.put("epoch", epoch);
params.put("datasetFolder", trainRunRequest.getDatasetFolder());
params.put("outputFolder", trainRunRequest.getOutputFolder());
params.put("reqTmpYn", trainRunRequest.getReqTmpYn());
int nextAttemptNo = modelTrainJobCoreService.findMaxAttemptNo(modelId) + 1;

View File

@@ -1,14 +1,20 @@
package com.kamco.cd.training.train.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kamco.cd.training.common.enums.JobStatusType;
import com.kamco.cd.training.common.enums.TrainStatusType;
import com.kamco.cd.training.common.exception.CustomApiException;
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.postgres.core.ModelTrainJobCoreService;
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
import com.kamco.cd.training.train.dto.DockerInspectState;
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
import com.kamco.cd.training.train.dto.ModelTrainJobQueuedEvent;
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
import com.kamco.cd.training.train.dto.OutputResult;
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.nio.file.Files;
import java.nio.file.Path;
@@ -16,6 +22,7 @@ import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
@@ -33,11 +40,14 @@ public class TrainJobService {
private final ModelTrainJobCoreService modelTrainJobCoreService;
private final ModelTrainMngCoreService modelTrainMngCoreService;
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
private final ModelTestMetricsJobService modelTestMetricsJobService;
private final DockerTrainService dockerTrainService;
private final ObjectMapper objectMapper;
private final ApplicationEventPublisher eventPublisher;
private final TmpDatasetService tmpDatasetService;
private final DataSetCountersService dataSetCounters;
private final TrainUtilService trainUtilService;
// 학습 결과가 저장될 호스트 디렉토리
@Value("${train.docker.response_dir}")
@@ -196,6 +206,18 @@ public class TrainJobService {
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 {
NONE, // 새로 시작
REQUIRE // 이어하기
@@ -266,6 +288,9 @@ public class TrainJobService {
List<String> uids = modelTrainMngCoreService.findDatasetUid(datasetIds);
try {
// 1. 시작 상태 업데이트
modelTrainMngCoreService.updateTmpFileStatusStart(modelId);
// 데이터셋 심볼링크 생성
// String pathUid = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
// train path 모델 클래스별 조회
@@ -290,6 +315,8 @@ public class TrainJobService {
ModelTrainMngDto.UpdateReq updateReq = new ModelTrainMngDto.UpdateReq();
updateReq.setRequestPath(raw);
updateReq.setTmpFileStatus("COMPLETE");
updateReq.setTmpFileEndDttm(ZonedDateTime.now());
// 학습모델을 수정한다.
modelTrainMngCoreService.updateModelMaster(modelId, updateReq);
@@ -303,10 +330,274 @@ public class TrainJobService {
(uids == null ? null : uids.size()),
e);
// 3. 실패 처리
modelTrainMngCoreService.updateTmpFileStatusFail(modelId, e.getMessage());
// 런타임 예외로 래핑하되, 메시지에 핵심 정보 포함
throw new CustomApiException(
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "임시 데이터셋 생성에 실패했습니다.");
}
return modelUuid;
}
/**
* 동작되고잇는 pid을 확인하고 pid 목록에 있으면 진행중, 없으면 종료(결과 csv, zip 파일 확인하여 완료 여부 체크)
*
* @param uuid
* @param modelId
*/
public void status(UUID uuid, Long modelId) {
ModelTrainJobDto job =
modelTrainJobCoreService
.findLatestByModelId(modelId)
.orElseThrow(() -> new NoSuchElementException("job not found"));
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelById(modelId);
// TODO 실행중 상태인것만 변경해야하면 주석 해제
// if(job.getStatusCd().equals(JobStatusType.RUNNING.getId())) {
// return;
// }
String containerName = job.getContainerName();
try {
// docker inspect로 컨테이너 상태 조회
DockerInspectState state = trainUtilService.inspectContainer(containerName);
// 컨테이너가 "없음"
// - docker run --rm 로 실행한 컨테이너는 정상 종료 시 바로 삭제될 수 있음
// - 즉 "컨테이너 없음"이 무조건 실패는 아님
if (!state.exists()) {
log.warn("container missing. try file-based reconcile. container={}", containerName);
// 컨테이너가 없을 때는 산출물(responseDir)을 보고 완료 여부를 "추정"
OutputResult out = trainUtilService.probeOutputs(job);
// 산출물이 충분하면 성공 처리
if (out.completed()) {
// 테스트 완료인지 zip파일로 확인
if (trainUtilService.existsZipFile(uuid)) {
// 테스트 완료일때
log.info("outputs look completed. mark SUCCESS. jobId={}", job.getId());
// job 완료처리
modelTrainJobCoreService.markSuccess(job.getId(), 0);
// 학습 완료가 아니면 완료 업데이트
if (!model.getStep1Status().equals(TrainStatusType.COMPLETED.getId())) {
// model 상태 변경 (학습)
modelTrainMngCoreService.markStep1Success(job.getModelId());
// 학습 결과 csv 파일 정보 등록
modelTrainMetricsJobService.trainValidMetricCsvFile(modelId);
}
// 테스트 완료가 아니면 완료 업데이트
if (!model.getStep2Status().equals(TrainStatusType.COMPLETED.getId())) {
// model 상태 변경 (테스트)
modelTrainMngCoreService.markStep2Success(job.getModelId());
// 테스트 결과 csv 파일 정보 등록
modelTestMetricsJobService.testValidMetricCsvFiles(modelId);
}
} else {
// 학습 완료일때
log.info("outputs look completed. mark SUCCESS. jobId={}", job.getId());
modelTrainJobCoreService.markSuccess(job.getId(), 0);
// 학습 완료가 아니면 완료 업데이트
if (!model.getStep1Status().equals(TrainStatusType.COMPLETED.getId())) {
// model 상태 변경 (학습)
modelTrainMngCoreService.markStep1Success(job.getModelId());
// 학습 결과 csv 파일 정보 등록
modelTrainMetricsJobService.trainValidMetricCsvFile(modelId);
}
}
} else {
// 산출물이 부족하면 중단처리
// 산출물이 부족하면 "중단/보류"로 처리
// 운영자가 재시작 할 수 있게 한다.
log.warn(
"outputs incomplete. mark PAUSED/STOP for restart. jobId={} reason={}",
job.getId(),
out.reason());
// PAUSED/STOP
modelTrainJobCoreService.markPaused(
job.getId(), -1, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE");
// STOP으로 변경
markStepStopByJobType(
job, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE: " + out.reason());
}
} else {
// 컨테이너가 있으면 진행중처리
Map<String, Object> params = job.getParamsJson();
boolean isEval = params != null && "EVAL".equals(String.valueOf(params.get("jobType")));
if (isEval) {
// 테스트 진행중 상태로 업데이트
modelTrainMngCoreService.markStep2InProgress(job.getModelId(), job.getId());
} else {
// 학습 진행중 상태로 업데이트
modelTrainMngCoreService.markStep1InProgress(job.getModelId(), job.getId());
}
// job 테이블 진행중으로 업데이트
modelTrainJobCoreService.updateJobStatus(job.getId(), JobStatusType.RUNNING.getId());
}
} catch (Exception e) {
log.error("container inspect failed. container={}", containerName, e);
}
}
/**
* jobType에 따라 학습 관리 테이블의 "에러 단계"를 업데이트.
*
* <p>예: - jobType == "EVAL" → step2(평가 단계) 에러 - 그 외 → step1 혹은 전체 에러
*/
private void markStepStopByJobType(ModelTrainJobDto job, String msg) {
Map<String, Object> params = job.getParamsJson();
boolean isEval = params != null && "EVAL".equals(String.valueOf(params.get("jobType")));
if (isEval) {
modelTrainMngCoreService.markStep2Stop(job.getModelId(), msg);
} else {
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 "학습 작업이 시작되지 않았습니다.";
}
}
}

View File

@@ -58,6 +58,7 @@ public class TrainJobWorker {
(isEval ? "eval-" : "train-") + jobId + "-" + params.get("uuid").toString().substring(0, 8);
String type = isEval ? "TEST" : "TRAIN";
String step = isEval ? "STEP2" : "STEP1";
Integer totalEpoch = null;
if (params.containsKey("totalEpoch")) {
@@ -65,6 +66,21 @@ public class TrainJobWorker {
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);
// 실행 시작 처리
modelTrainJobCoreService.markRunning(
@@ -87,14 +103,24 @@ public class TrainJobWorker {
evalReq.setTimeoutSeconds(null);
evalReq.setDatasetFolder(datasetFolder);
evalReq.setOutputFolder(outputFolder);
evalReq.setReqTmpYn((Boolean) params.get("reqTmpYn"));
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);
} else {
// step1 진행중 처리
modelTrainMngCoreService.markStep1InProgress(modelId, jobId);
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);
}
@@ -108,11 +134,25 @@ public class TrainJobWorker {
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 우리 내부
* 강제 중단 STOP
*/
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());
@@ -127,12 +167,21 @@ public class TrainJobWorker {
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 {
String failMsg = result.getStatus() + "\n" + result.getLogs();
log.info("training fail exitCode={} Msg ={}", result.getExitCode(), failMsg);
if (result.getExitCode() == -1 || result.getExitCode() == 143) {
if (result.getExitCode() == -1
|| result.getExitCode() == 143
|| result.getExitCode() == 137) {
// 실패 처리
modelTrainJobCoreService.markPaused(
jobId, result.getExitCode(), result.getStatus() + "\n" + result.getLogs());

View File

@@ -0,0 +1,228 @@
package com.kamco.cd.training.train.service;
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
import com.kamco.cd.training.train.dto.DockerInspectState;
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
import com.kamco.cd.training.train.dto.OutputResult;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class TrainUtilService {
private final ModelTrainMngCoreService modelTrainMngCoreService;
/**
* Docker 컨테이너가 쓰는 response(산출물) 디렉토리의 "호스트 측" 베이스 경로. 예) /data/train/response
*
* <p>컨테이너가 --rm 으로 삭제된 경우에도 이 경로에 val.csv / *.pth 등이 남아있으면 정상 종료 여부를 "파일 기반"으로 판정합니다.
*/
@Value("${train.docker.response_dir}")
private String responseDir;
/**
* docker inspect를 사용해서 컨테이너 상태를 조회합니다.
*
* <p>사용하는 템플릿: {{.State.Status}} {{.State.Running}} {{.State.ExitCode}}
*
* <p>예상 출력 예: - "running true 0" - "exited false 0" - "exited false 137"
*
* <p>주의: - 컨테이너가 없거나 inspect 실패 시 exitCode != 0 또는 output이 비어서 missing() 반환 - 무한 대기 방지를 위해 5초
* 타임아웃을 둠
*/
public DockerInspectState inspectContainer(String containerName)
throws IOException, InterruptedException {
ProcessBuilder pb =
new ProcessBuilder(
"docker",
"inspect",
"-f",
"{{.State.Status}} {{.State.Running}} {{.State.ExitCode}}",
containerName);
pb.redirectErrorStream(true);
Process p = pb.start();
String output;
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
output = br.readLine();
}
boolean finished = p.waitFor(5, TimeUnit.SECONDS);
if (!finished) {
p.destroyForcibly();
throw new IOException("docker inspect timeout");
}
int code = p.exitValue();
if (code != 0 || output == null || output.isBlank()) {
return DockerInspectState.missing();
}
String[] parts = output.trim().split("\\s+");
String status = parts.length > 0 ? parts[0] : "unknown";
boolean running = parts.length > 1 && Boolean.parseBoolean(parts[1]);
Integer exitCode = null;
if (parts.length > 2) {
try {
exitCode = Integer.parseInt(parts[2]);
} catch (Exception ignore) {
}
}
return new DockerInspectState(true, running, exitCode, status);
}
/**
* 컨테이너가 없을 때(responseDir 산출물만 남아있는 상태) 완료 여부를 파일 기반으로 판정합니다.
*
* <p>판정 규칙(보수적으로 설계): 1) total_epoch가 paramsJson에 있어야 함 (없으면 완료 판단 불가) 2) val.csv 존재 + 헤더 제외 라인 수
* >= total_epoch 이어야 함 3) *.pth 파일이 total_epoch 이상 존재하거나, best*.pth(또는 *best*.pth)가 존재해야 함
*
* <p>왜 이렇게? - 어떤 학습은 epoch마다 pth를 남기고 - 어떤 학습은 best만 남기기도 해서 "pthCount >= total_epoch"만 쓰면 정상 종료를
* 실패로 오판할 수 있음.
*/
public OutputResult probeOutputs(ModelTrainJobDto job) {
try {
Path outDir = resolveOutputDir(job);
if (outDir == null || !Files.isDirectory(outDir)) {
return new OutputResult(false, "output-dir-missing");
}
Integer totalEpoch = extractTotalEpoch(job).orElse(null);
if (totalEpoch == null || totalEpoch <= 0) {
return new OutputResult(false, "total-epoch-missing");
}
Integer valInterval = extractValInterval(job).orElse(null);
if (valInterval == null || valInterval <= 0) {
return new OutputResult(false, "val-interval-missing");
}
Path valCsv = outDir.resolve("val.csv");
if (!Files.exists(valCsv)) {
return new OutputResult(false, "val.csv-missing");
}
long lines = countNonHeaderLines(valCsv);
int expectedLines = totalEpoch / valInterval;
if (lines >= expectedLines) {
return new OutputResult(true, "ok");
}
return new OutputResult(false, "val.csv-lines-mismatch");
} catch (Exception e) {
return new OutputResult(false, "probe-error");
}
}
/**
* 테스트 완료후 zip 파일 있는지 확인
*
* @param uuid
* @return
*/
public boolean existsZipFile(UUID uuid) {
Path path = Paths.get(responseDir, uuid.toString());
if (!Files.isDirectory(path)) {
return false;
}
String pattern = "*" + uuid + "*.zip";
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, pattern)) {
return stream.iterator().hasNext();
} catch (IOException e) {
return false;
}
}
/**
* responseDir 아래에서 job 산출물 디렉토리를 찾습니다.
*
* <p>가장 중요한 커스터마이징 포인트: - 실제 운영 환경에서 산출물이 어떤 경로 규칙으로 저장되는지에 따라 여기만 수정하면 됩니다.
*
* <p>현재 기본 탐색 순서: 1) {responseDir}/{jobId} 2) {responseDir}/{modelId} 3)
* {responseDir}/{containerName} 4) 마지막 fallback: responseDir 자체
*
* <p>추천: - 여러분 규칙이 "{responseDir}/{modelId}/{jobId}" 같은 형태라면 base.resolve(modelId).resolve(jobId)
* 형태를 1순위로 두세요.
*/
private Path resolveOutputDir(ModelTrainJobDto job) {
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelById(job.getModelId());
Path base = Paths.get(responseDir, model.getUuid().toString(), "metrics");
return Files.isDirectory(base) ? base : null;
}
/**
* paramsJson에서 total_epoch 값을 추출합니다.
*
* <p>키 후보: - "total_epoch" (snake_case) - "totalEpoch" (camelCase)
*
* <p>예: paramsJson = {"jobType":"TRAIN","total_epoch":50,...}
*/
private Optional<Integer> extractTotalEpoch(ModelTrainJobDto job) {
Map<String, Object> params = job.getParamsJson();
if (params == null) return Optional.empty();
Object v = params.get("total_epoch");
if (v == null) v = params.get("totalEpoch");
try {
return v == null ? Optional.empty() : Optional.of(Integer.parseInt(String.valueOf(v)));
} catch (Exception e) {
return Optional.empty();
}
}
/** paramsJson에서 valInterval 추출 */
private Optional<Integer> extractValInterval(ModelTrainJobDto job) {
Map<String, Object> params = job.getParamsJson();
if (params == null) return Optional.empty();
Object v = params.get("valInterval");
try {
return v == null ? Optional.empty() : Optional.of(Integer.parseInt(String.valueOf(v)));
} catch (Exception e) {
return Optional.empty();
}
}
/**
* CSV 파일에서 "헤더(첫 줄)"를 제외한 라인 수를 계산합니다.
*
* <p>가정: - val.csv 첫 줄은 헤더 - 이후 라인들이 epoch별 기록(또는 유사한 누적 기록)
*
* <p>주의: - 파일 인코딩은 UTF-8로 가정 - 빈 줄은 제외
*/
private long countNonHeaderLines(Path csv) throws IOException {
try (Stream<String> lines = Files.lines(csv, StandardCharsets.UTF_8)) {
return lines.skip(1).filter(s -> s != null && !s.isBlank()).count();
}
}
}

View File

@@ -0,0 +1,482 @@
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;
}
}
}

View File

@@ -0,0 +1,295 @@
package com.kamco.cd.training.train.util;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import lombok.experimental.UtilityClass;
/**
* 학습 진행률 계산 유틸리티 기존 DB 컬럼만을 활용하여 진행률을 실시간 계산
*
* <p>상태전의 STATUS 가이드 기준: - Step1 (학습): TRAIN jobType → 0% ~ 50% - Step2 (테스트): EVAL jobType → 50% ~
* 100%
*/
@UtilityClass
public class TrainingProgressCalculator {
/**
* 학습 진행률 계산 (Step 구분)
*
* @param statusCd 작업 상태 (QUEUED/RUNNING/SUCCESS/FAILED/STOPPED/CANCELED)
* @param currentEpoch 현재 Epoch
* @param totalEpoch 전체 Epoch
* @param startedDttm 시작 시각
* @param finishedDttm 종료 시각
* @param jobType 작업 타입 (TRAIN/EVAL)
* @param step1State Step1 상태 (READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR)
* @param step2State Step2 상태 (READY/IN_PROGRESS/COMPLETED/STOPPED/ERROR)
* @return 진행률 (0.00 ~ 100.00)
*/
public static double calculateProgress(
String statusCd,
Integer currentEpoch,
Integer totalEpoch,
ZonedDateTime startedDttm,
ZonedDateTime finishedDttm,
String jobType,
String step1State,
String step2State) {
if (statusCd == null) {
return 0.0;
}
// Step별 진행률 계산
boolean isStep1 = "TRAIN".equals(jobType);
boolean isStep2 = "EVAL".equals(jobType) || "TEST".equals(jobType);
// Step1 완료, Step2 완료 여부 확인
boolean isStep1Completed = "COMPLETED".equals(step1State);
boolean isStep2Completed = "COMPLETED".equals(step2State);
switch (statusCd) {
case "QUEUED":
// Step1 대기 중: 0%, Step2 대기 중: 50%
return isStep2 ? 50.0 : 0.0;
case "RUNNING":
return calculateRunningProgress(
currentEpoch, totalEpoch, startedDttm, isStep1, isStep2, isStep1Completed);
case "SUCCESS":
// Step1 성공: 50%, Step2 성공: 100%
if (isStep2 || isStep2Completed) {
return 100.0;
} else if (isStep1 || isStep1Completed) {
return 50.0;
}
return 100.0; // 기본값
case "FAILED":
case "STOPPED":
case "CANCELED":
// 실패/취소된 경우 마지막 진행률 반환
return calculateRunningProgress(
currentEpoch, totalEpoch, startedDttm, isStep1, isStep2, isStep1Completed);
default:
return 0.0;
}
}
/**
* 실행 중인 학습의 진행률 계산 (Step 구분)
*
* <p>Step1 (학습): 0% ~ 50% - PREPARING: 0% ~ 2.5% - CONTAINER_STARTING: 2.5% ~ 5% - DATA_LOADING:
* 5% ~ 7.5% - TRAINING: 7.5% ~ 42.5% (35% 비중) - PROCESSING: 42.5% ~ 50%
*
* <p>Step2 (테스트): 50% ~ 100% - PREPARING: 50% ~ 52.5% - CONTAINER_STARTING: 52.5% ~ 55% -
* DATA_LOADING: 55% ~ 57.5% - TESTING: 57.5% ~ 92.5% (35% 비중) - PROCESSING: 92.5% ~ 100%
*/
private static double calculateRunningProgress(
Integer currentEpoch,
Integer totalEpoch,
ZonedDateTime startedDttm,
boolean isStep1,
boolean isStep2,
boolean isStep1Completed) {
// Step 기준 계산
double baseProgress = 0.0;
double maxProgress = 50.0;
if (isStep2 || isStep1Completed) {
// Step2 진행 중 또는 Step1 완료 후
baseProgress = 50.0;
maxProgress = 100.0;
} else if (isStep1) {
// Step1 진행 중
baseProgress = 0.0;
maxProgress = 50.0;
}
double stepRange = maxProgress - baseProgress; // 50%
// 시작 직후 (Epoch 정보 없음)
if (currentEpoch == null || totalEpoch == null || totalEpoch == 0) {
return baseProgress + estimateInitialPhaseProgress(startedDttm, stepRange);
}
// Epoch 0 또는 1 (학습 시작 단계)
if (currentEpoch <= 1) {
return baseProgress + (stepRange * 0.15); // 7.5% (Step1) 또는 57.5% (Step2)
}
// 학습 진행 중 (15% ~ 85% of step range)
double epochProgress = (double) currentEpoch / totalEpoch;
double trainingProgress = 0.15 + (epochProgress * 0.70); // 15% ~ 85%
// 학습 완료 (마지막 Epoch)
if (currentEpoch >= totalEpoch) {
// 85% ~ 100% 사이로 추정
return baseProgress + (stepRange * 0.90);
}
return baseProgress + (stepRange * trainingProgress);
}
/**
* 초기 단계 진행률 추정 (시작 시간 기반)
*
* @param startedDttm 시작 시각
* @param stepRange Step 범위 (50%)
* @return 초기 단계 진행률 (0 ~ 0.15 비율)
*/
private static double estimateInitialPhaseProgress(ZonedDateTime startedDttm, double stepRange) {
if (startedDttm == null) {
return stepRange * 0.05; // 5% of step range
}
long elapsedSeconds = ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
// 시작 후 30초 이내: PREPARING (0% ~ 5% of step)
if (elapsedSeconds < 30) {
return Math.min(stepRange * 0.05, (elapsedSeconds / 30.0) * stepRange * 0.05);
}
// 30초 ~ 60초: CONTAINER_STARTING (5% ~ 10% of step)
else if (elapsedSeconds < 60) {
return stepRange * 0.05 + ((elapsedSeconds - 30) / 30.0) * stepRange * 0.05;
}
// 60초 이상: DATA_LOADING (10% ~ 15% of step)
else {
return Math.min(
stepRange * 0.15, stepRange * 0.10 + ((elapsedSeconds - 60) / 60.0) * stepRange * 0.05);
}
}
/**
* 현재 Phase 추정
*
* @param statusCd 작업 상태
* @param currentEpoch 현재 Epoch
* @param totalEpoch 전체 Epoch
* @param startedDttm 시작 시각
* @param jobType 작업 타입 (TRAIN/EVAL)
* @return 현재 Phase
*/
public static String estimateCurrentPhase(
String statusCd,
Integer currentEpoch,
Integer totalEpoch,
ZonedDateTime startedDttm,
String jobType) {
if ("SUCCESS".equals(statusCd)) {
return "COMPLETED";
}
if ("FAILED".equals(statusCd)) {
return "FAILED";
}
if ("STOPPED".equals(statusCd) || "CANCELED".equals(statusCd)) {
return "CANCELED";
}
if ("QUEUED".equals(statusCd)) {
return "QUEUED";
}
// RUNNING 상태
boolean isStep2 = "EVAL".equals(jobType) || "TEST".equals(jobType);
String prefix = isStep2 ? "STEP2_" : "STEP1_";
if (currentEpoch == null || totalEpoch == null) {
if (startedDttm == null) {
return prefix + "PREPARING";
}
long elapsed = ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
if (elapsed < 30) return prefix + "PREPARING";
if (elapsed < 60) return prefix + "CONTAINER_STARTING";
return prefix + "DATA_LOADING";
}
if (currentEpoch >= totalEpoch) {
return prefix + "PROCESSING_RESULTS";
}
return prefix + "TRAINING";
}
/** 경과 시간 계산 (초) */
public static Long calculateElapsedSeconds(ZonedDateTime startedDttm) {
if (startedDttm == null) {
return null;
}
return ChronoUnit.SECONDS.between(startedDttm, ZonedDateTime.now());
}
/** 예상 남은 시간 계산 (초) */
public static Long estimateRemainingSeconds(double progressPercent, Long elapsedSeconds) {
if (elapsedSeconds == null || progressPercent <= 0.0) {
return null;
}
double remaining = (100.0 - progressPercent) / progressPercent;
return (long) (elapsedSeconds * remaining);
}
/**
* 상태 메시지 생성
*
* @param phase 현재 Phase
* @param currentEpoch 현재 Epoch
* @param totalEpoch 전체 Epoch
* @return 상태 메시지
*/
public static String generateProgressMessage(
String phase, Integer currentEpoch, Integer totalEpoch) {
if (phase == null) {
return "대기중";
}
// Step 구분
boolean isStep1 = phase.startsWith("STEP1_");
boolean isStep2 = phase.startsWith("STEP2_");
String stepName = isStep1 ? "학습" : isStep2 ? "테스트" : "";
switch (phase) {
case "QUEUED":
return "학습 작업이 큐에 등록되었습니다.";
case "STEP1_PREPARING":
return "학습 준비 중입니다.";
case "STEP1_CONTAINER_STARTING":
return "학습용 Docker 컨테이너를 시작하는 중입니다.";
case "STEP1_DATA_LOADING":
return "학습 데이터를 로딩하는 중입니다.";
case "STEP1_TRAINING":
if (currentEpoch != null && totalEpoch != null) {
return String.format("학습 진행 중 (Epoch %d/%d)", currentEpoch, totalEpoch);
}
return "학습 진행 중";
case "STEP1_PROCESSING_RESULTS":
return "학습 결과를 처리하는 중입니다.";
case "STEP2_PREPARING":
return "테스트 준비 중입니다.";
case "STEP2_CONTAINER_STARTING":
return "테스트용 Docker 컨테이너를 시작하는 중입니다.";
case "STEP2_DATA_LOADING":
return "테스트 데이터를 로딩하는 중입니다.";
case "STEP2_TRAINING":
if (currentEpoch != null && totalEpoch != null) {
return String.format("테스트 진행 중 (Epoch %d/%d)", currentEpoch, totalEpoch);
}
return "테스트 진행 중";
case "STEP2_PROCESSING_RESULTS":
return "테스트 결과를 처리하는 중입니다.";
case "COMPLETED":
return "학습이 성공적으로 완료되었습니다.";
case "FAILED":
return "학습이 실패했습니다.";
case "CANCELED":
return "학습이 취소되었습니다.";
default:
return stepName + " 진행 중";
}
}
}

View File

@@ -30,20 +30,46 @@ token:
swagger:
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:
dataset-dir: /home/kcomu/data/request/
base_path: /backup/data/training
dataset-dir: ${file.base_path}/request/
dataset-tmp-dir: ${file.dataset-dir}tmp/
pt-path: /home/kcomu/data/response/v6-cls-checkpoints/
pt-path: ${file.base_path}/response/v6-cls-checkpoints/
pt-FileName: yolov8_6th-6m.pt
train:
docker:
image: kamco-cd-train:latest
base_path: /home/kcomu/data
base_path: /backup/data/training
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
hyper:
parameter:
gpus: 1
gpu-ids: 0
batch-size: 10

View File

@@ -41,3 +41,8 @@ train:
container_prefix: kamco-cd-train
shm_size: 16g
ipc_host: true
hyper:
parameter:
gpus: 4
gpu-ids: 0,1,2,3
batch-size: 30

View File

@@ -37,8 +37,8 @@ spring:
max-file-size: 10GB
max-request-size: 10GB
transaction:
default-timeout: 300 # 5분 트랜잭션 타임아웃
#transaction:
# default-timeout: 300 # 5분 트랜잭션 타임아웃
logging:
level:
@@ -78,3 +78,8 @@ management:
exposure:
include:
- "health"
hyper:
parameter:
gpus: 1
gpu-ids: 0
batch-size: 2

View File

@@ -0,0 +1,964 @@
# POST /api/train/status/{uuid} - 상태 전이 다이어그램 완전 가이드
> **프론트엔드 표시 방법 및 상태 제어 API 포함**
---
## 📊 1. DB 테이블 상태 필드
### 1.1 **Job 테이블** (`tb_model_train_job`)
| 필드명 | 설명 | 가능한 값 | UI 표시명 |
|--------|------|-----------|-----------|
| `status_cd` | Job 실행 상태 | `QUEUED`, `RUNNING`, `SUCCESS`, `FAILED`, `STOPPED`, `CANCELED` | 대기중, 실행중, 성공, 실패, 중단됨, 취소 |
| `exit_code` | 종료 코드 | 정수 (0: 정상, -1: 중단, 기타: 에러) | - |
| `error_message` | 에러 메시지 | 문자열 | 에러 상세 내용 |
| `finished_dttm` | 완료 시간 | timestamp | YYYY-MM-DD HH:mm:ss |
### 1.2 **Model Master 테이블** (`tb_model_master`)
| 필드명 | 설명 | 가능한 값 | UI 표시명 |
|--------|------|-----------|-----------|
| `status_cd` | 전체 모델 상태 | `READY`, `IN_PROGRESS`, `COMPLETED`, `STOPPED`, `ERROR` | 대기, 진행중, 완료, 중단됨, 오류 |
| `step1_state` | Step1(학습) 상태 | `READY`, `IN_PROGRESS`, `COMPLETED`, `STOPPED`, `ERROR` | 대기, 진행중, 완료, 중단됨, 오류 |
| `step2_state` | Step2(테스트) 상태 | `READY`, `IN_PROGRESS`, `COMPLETED`, `STOPPED`, `ERROR` | 대기, 진행중, 완료, 중단됨, 오류 |
| `step1_strt_dttm` | Step1 시작 시간 | timestamp | YYYY-MM-DD HH:mm:ss |
| `step1_end_dttm` | Step1 종료 시간 | timestamp | YYYY-MM-DD HH:mm:ss |
| `step2_strt_dttm` | Step2 시작 시간 | timestamp | YYYY-MM-DD HH:mm:ss |
| `step2_end_dttm` | Step2 종료 시간 | timestamp | YYYY-MM-DD HH:mm:ss |
| `step1_metric_save_yn` | Step1 메트릭 저장 여부 | `true`, `false` | - |
| `step2_metric_save_yn` | Step2 메트릭 저장 여부 | `true`, `false` | - |
| `current_attempt_id` | 현재 실행 중인 Job ID | Long | - |
| `best_epoch` | 최적 에폭 | Integer | Best Epoch: {값} |
| `last_error` | 마지막 에러 메시지 | 문자열 | 에러 상세 내용 |
---
## 🎨 2. 프론트엔드 API 응답 및 표시
### 2.1 모델 목록 조회 API
**엔드포인트**: `GET /api/models/list`
**요청 파라미터**:
```json
{
"status": "IN_PROGRESS", // "", "IN_PROGRESS", "COMPLETED"
"modelNo": "G1", // "G1", "G2", "G3", "G4"
"page": 0,
"size": 20
}
```
**응답 예시**:
```json
{
"success": true,
"data": {
"content": [
{
"id": 123,
"uuid": "e22181eb-2ac4-4100-9941-d06efce25c49",
"modelVer": "v1.0.0",
"statusCd": "IN_PROGRESS",
"statusName": "진행중",
"step1Status": "COMPLETED",
"step1StatusName": "완료",
"step2Status": "IN_PROGRESS",
"step2StatusName": "진행중",
"step1StrtDttm": "2026-04-05 10:30:00",
"step1EndDttm": "2026-04-05 12:45:00",
"step1Duration": "2시간 15분 0초",
"step2StrtDttm": "2026-04-05 12:50:00",
"step2EndDttm": null,
"step2Duration": null,
"modelNo": "G1",
"trainType": "GENERAL",
"trainTypeName": "일반",
"currentAttemptId": 456,
"memo": "테스트 학습"
}
],
"totalElements": 100,
"totalPages": 5
}
}
```
### 2.2 프론트엔드 표시 예시
#### 📋 **모델 목록 테이블**
| 모델 번호 | 버전 | 전체 상태 | 학습(Step1) | 테스트(Step2) | 학습 시간 | 테스트 시간 | 작업 |
|----------|------|----------|------------|------------|----------|----------|------|
| G1 | v1.0.0 | 🟢 진행중 | ✅ 완료 (2시간 15분) | 🔄 진행중 | 2026-04-05 10:30 ~ 12:45 | 2026-04-05 12:50 ~ | [취소] |
| G2 | v1.0.1 | ✅ 완료 | ✅ 완료 (1시간 30분) | ✅ 완료 (45분) | 2026-04-04 14:00 ~ 15:30 | 2026-04-04 15:35 ~ 16:20 | [결과보기] |
| G3 | v1.0.2 | ⚠️ 중단됨 | ⚠️ 중단됨 | - | 2026-04-03 09:00 ~ | - | [재시작] [이어하기] |
| G4 | v1.0.3 | ❌ 오류 | ❌ 오류 | - | 2026-04-02 11:00 ~ | - | [재시작] |
#### 🎯 **상태별 UI 컬러 가이드**
```javascript
// 상태별 배지 색상 매핑
const STATUS_COLORS = {
'READY': { bg: '#e3f2fd', text: '#1976d2', icon: '⏸️' }, // 파란색 - 대기
'IN_PROGRESS': { bg: '#e8f5e9', text: '#388e3c', icon: '🔄' }, // 녹색 - 진행중
'COMPLETED': { bg: '#f1f8e9', text: '#689f38', icon: '✅' }, // 연두색 - 완료
'STOPPED': { bg: '#fff3e0', text: '#f57c00', icon: '⚠️' }, // 주황색 - 중단됨
'ERROR': { bg: '#ffebee', text: '#d32f2f', icon: '❌' } // 빨간색 - 오류
};
// 상태명 한글 변환
const STATUS_NAMES = {
'READY': '대기',
'IN_PROGRESS': '진행중',
'COMPLETED': '완료',
'STOPPED': '중단됨',
'ERROR': '오류'
};
// React 컴포넌트 예시
function StatusBadge({ statusCd }) {
const { bg, text, icon } = STATUS_COLORS[statusCd] || {};
const name = STATUS_NAMES[statusCd] || statusCd;
return (
<span style={{ backgroundColor: bg, color: text, padding: '4px 12px', borderRadius: '12px' }}>
{icon} {name}
</span>
);
}
```
#### 📊 **상세 진행 상황 표시**
```javascript
// Step별 진행률 계산
function ModelProgressBar({ model }) {
const steps = [
{
name: '학습 (Step1)',
status: model.step1Status,
statusName: model.step1StatusName,
startTime: model.step1StrtDttm,
endTime: model.step1EndDttm,
duration: model.step1Duration
},
{
name: '테스트 (Step2)',
status: model.step2Status,
statusName: model.step2StatusName,
startTime: model.step2StrtDttm,
endTime: model.step2EndDttm,
duration: model.step2Duration
}
];
return (
<div className="progress-container">
{steps.map((step, index) => (
<div key={index} className="step-item">
<div className="step-header">
<span className="step-name">{step.name}</span>
<StatusBadge statusCd={step.status} />
</div>
<div className="step-time">
{step.startTime && (
<>
<span>시작: {step.startTime}</span>
{step.endTime && <span> ~ 종료: {step.endTime}</span>}
{step.duration && <span> (소요시간: {step.duration})</span>}
</>
)}
</div>
{step.status === 'IN_PROGRESS' && (
<div className="loading-bar">
<div className="loading-animation"></div>
</div>
)}
</div>
))}
</div>
);
}
```
---
## 🔄 3. 상태 전이 플로우차트 (상태값 명시)
```
┌─────────────────────────────────────────────────────────────────┐
│ POST /api/train/status/{uuid} API 호출 │
└────────────────────────────┬────────────────────────────────────┘
┌────────────────────┐
│ UUID → ModelID │
│ 조회 및 Job 조회 │
└────────┬───────────┘
┌────────────────────┐
│ Docker Inspect 실행 │
│ (containerName) │
└────────┬───────────┘
┌──────────────┴──────────────┐
│ │
[exists=false] [exists=true]
컨테이너 없음 컨테이너 존재
↓ ↓
┌─────────────────────┐ ┌──────────────────────┐
│ TrainUtilService │ │ jobType 확인 │
│ .probeOutputs() │ │ (paramsJson) │
│ │ └──────────┬───────────┘
│ 1. total_epoch 추출 │ │
│ 2. valInterval 추출 │ ┌──────────┴──────────┐
│ 3. val.csv 존재확인 │ │ │
│ 4. 라인수 검증 │ [TRAIN] [EVAL]
└─────────┬───────────┘ │ │
│ ↓ ↓
┌─────────┴─────────┐ ┌──────────────┐ ┌──────────────┐
│ │ │ Step1 진행중 │ │ Step2 진행중 │
[completed=true] [completed=false] └──────────────┘ └──────────────┘
│ │ │ │
│ │ ┌────▼─────────────────────▼────────┐
│ │ │ ✅ tb_model_train_job │
│ │ │ status_cd = "RUNNING" │
│ │ │ │
│ │ │ ✅ tb_model_master │
│ │ │ status_cd = "IN_PROGRESS" │
│ │ │ step1_state = "IN_PROGRESS" │ [TRAIN]
│ │ │ step1_strt_dttm = now() │
│ │ │ OR │
│ │ │ step2_state = "IN_PROGRESS" │ [EVAL]
│ │ │ step2_strt_dttm = now() │
│ │ │ current_attempt_id = jobId │
│ │ └──────────────────────────────────┘
│ │ 【프론트 표시】
│ │ 🔄 진행중 - 학습 중... / 테스트 중...
│ │
│ ↓
│ ┌─────────────────────┐
│ │ ⚠️ 산출물 부족 │
│ │ (val.csv 부족 등) │
│ └─────────┬───────────┘
│ │
│ ┌─────────▼────────────────────────────────┐
│ │ ⚠️ tb_model_train_job │
│ │ status_cd = "STOPPED" │
│ │ exit_code = -1 │
│ │ error_message = "SERVER_RESTART_..." │
│ │ │
│ │ ⚠️ tb_model_master │
│ │ status_cd = "STOPPED" │
│ │ step1_state = "STOPPED" [TRAIN] │
│ │ OR │
│ │ step2_state = "STOPPED" [EVAL] │
│ │ last_error = "컨테이너 없음, 산출물 부족" │
│ └──────────────────────────────────────────┘
│ 【프론트 표시】
│ ⚠️ 중단됨 - 산출물 부족으로 중단됨
│ [재시작] [이어하기] 버튼 활성화
┌──────────────────┐
│ existsZipFile() │
│ ZIP 파일 존재? │
└────┬────────┬────┘
│ │
[YES] [NO]
│ │
│ ↓
│ ┌──────────────────────────────────────────────┐
│ │ 📁 학습 완료 (Step1만) │
│ └─────────┬────────────────────────────────────┘
│ │
│ ┌─────────▼──────────────────────────────────┐
│ │ ✅ tb_model_train_job │
│ │ status_cd = "SUCCESS" │
│ │ exit_code = 0 │
│ │ finished_dttm = now() │
│ │ │
│ │ ✅ tb_model_master (Step1 미완료 시) │
│ │ status_cd = "COMPLETED" │
│ │ step1_state = "COMPLETED" │
│ │ step1_end_dttm = now() │
│ │ step1_metric_save_yn = true │
│ │ │
│ │ 📊 Metrics 저장 │
│ │ - train.csv → tb_model_metrics_train │
│ │ - val.csv → tb_model_metrics_validation │
│ └────────────────────────────────────────────┘
│ 【프론트 표시】
│ ✅ 완료 - 학습 완료 (테스트 대기)
│ [테스트 실행] 버튼 활성화
┌──────────────────────────────────────────────┐
│ 📦 학습+테스트 완료 (Step1 + Step2) │
└─────────┬────────────────────────────────────┘
┌─────────▼──────────────────────────────────┐
│ ✅ tb_model_train_job │
│ status_cd = "SUCCESS" │
│ exit_code = 0 │
│ finished_dttm = now() │
│ │
│ ✅ tb_model_master (Step1 미완료 시) │
│ status_cd = "COMPLETED" │
│ step1_state = "COMPLETED" │
│ step1_end_dttm = now() │
│ step1_metric_save_yn = true │
│ │
│ ✅ tb_model_master (Step2 미완료 시) │
│ step2_state = "COMPLETED" │
│ step2_end_dttm = now() │
│ step2_metric_save_yn = true │
│ best_epoch = 최적값 │
│ │
│ 📊 Metrics 저장 │
│ - train.csv → tb_model_metrics_train │
│ - val.csv → tb_model_metrics_validation │
│ - test.csv → 테스트 메트릭 테이블 │
│ - *.zip → 테스트 결과 파일 생성 │
└────────────────────────────────────────────┘
【프론트 표시】
✅ 완료 - 모든 학습 및 테스트 완료
[결과 보기] [다운로드] 버튼 활성화
```
---
## 🛠️ 4. 상태 제어 API 목록
### 4.1 학습 실행 제어 API
| API | HTTP | 엔드포인트 | 설명 | 상태 전환 | 프론트 버튼 표시 조건 |
|-----|------|-----------|------|----------|---------------------|
| **학습 실행** | POST | `/api/train/run/{uuid}` | 최초 학습 시작 | `READY``IN_PROGRESS` | `statusCd == 'READY'` |
| **학습 재실행** | POST | `/api/train/restart/{uuid}` | 중단/오류 후 처음부터 재실행 | `STOPPED/ERROR``IN_PROGRESS` | `statusCd == 'STOPPED' \|\| statusCd == 'ERROR'` |
| **학습 이어하기** | POST | `/api/train/resume/{uuid}` | 중단된 지점부터 계속 실행 | `STOPPED``IN_PROGRESS` | `statusCd == 'STOPPED'` |
| **학습 취소** | POST | `/api/train/cancel/{uuid}` | 실행 중인 학습 중단 | `IN_PROGRESS``STOPPED` | `statusCd == 'IN_PROGRESS' && step1Status == 'IN_PROGRESS'` |
| **학습 상태 확인** | POST | `/api/train/status/{uuid}` | 현재 상태 동기화 | 현재 상태 유지/갱신 | 주기적 호출 (폴링) |
### 4.2 테스트 실행 제어 API
| API | HTTP | 엔드포인트 | 설명 | 상태 전환 | 프론트 버튼 표시 조건 |
|-----|------|-----------|------|----------|---------------------|
| **테스트 실행** | POST | `/api/train/test/run/{epoch}/{uuid}` | 특정 에폭으로 테스트 실행 | `step2_state: READY``IN_PROGRESS` | `step1Status == 'COMPLETED' && step2Status != 'IN_PROGRESS'` |
| **테스트 취소** | POST | `/api/train/test/cancel/{uuid}` | 실행 중인 테스트 중단 | `step2_state: IN_PROGRESS``STOPPED` | `step2Status == 'IN_PROGRESS'` |
### 4.3 기타 API
| API | HTTP | 엔드포인트 | 설명 |
|-----|------|-----------|------|
| **데이터셋 임시 파일 생성** | POST | `/api/train/create-tmp/{uuid}` | 학습용 임시 데이터셋 생성 |
| **데이터셋 카운트 조회** | GET | `/api/train/counts/{uuid}` | 데이터셋 통계 정보 조회 |
---
## 📋 5. 상태별 프론트엔드 액션 매트릭스
### 5.1 전체 상태 (`statusCd`) 기준
| 상태 코드 | 상태명 | 활성화 버튼 | 비활성화 버튼 | 표시 메시지 | UI 색상 |
|-----------|-------|------------|--------------|------------|---------|
| `READY` | 대기 | [학습 실행] | [취소] [재실행] [이어하기] | "학습 준비 완료" | 파란색 |
| `IN_PROGRESS` | 진행중 | [취소] | [학습 실행] [재실행] [이어하기] | "학습 진행 중..." | 녹색 |
| `COMPLETED` | 완료 | [결과 보기] [다운로드] | [학습 실행] [취소] | "학습 완료" | 연두색 |
| `STOPPED` | 중단됨 | [재실행] [이어하기] | [취소] | "학습 중단됨 - 재시작 가능" | 주황색 |
| `ERROR` | 오류 | [재실행] | [취소] [이어하기] | "오류 발생 - 재시작 필요" | 빨간색 |
### 5.2 Step1 상태 (`step1Status`) 기준
| 상태 코드 | 버튼/액션 | 조건 | 설명 |
|-----------|----------|------|------|
| `READY` | [학습 실행] | `statusCd == 'READY'` | 최초 학습 시작 |
| `IN_PROGRESS` | [학습 취소] | `statusCd == 'IN_PROGRESS'` | 진행 중인 학습 중단 |
| `COMPLETED` | [테스트 실행] | `step2Status == 'READY'` | 학습 완료 후 테스트 가능 |
| `STOPPED` | [재실행] [이어하기] | `statusCd == 'STOPPED'` | 중단된 학습 복구 |
| `ERROR` | [재실행] | `statusCd == 'ERROR'` | 오류 발생 후 재시도 |
### 5.3 Step2 상태 (`step2Status`) 기준
| 상태 코드 | 버튼/액션 | 조건 | 설명 |
|-----------|----------|------|------|
| `READY` | [테스트 실행] | `step1Status == 'COMPLETED'` | 학습 완료 후 테스트 가능 |
| `IN_PROGRESS` | [테스트 취소] | `statusCd == 'IN_PROGRESS'` | 진행 중인 테스트 중단 |
| `COMPLETED` | [결과 보기] [다운로드] | 항상 | 테스트 완료 후 결과 확인 |
| `STOPPED` | [테스트 재실행] | `step1Status == 'COMPLETED'` | 중단된 테스트 재시작 |
---
## 💻 6. 프론트엔드 구현 예시
### 6.1 상태별 버튼 렌더링 (React)
```javascript
function ModelActionButtons({ model }) {
const { uuid, statusCd, step1Status, step2Status } = model;
// 학습 실행 버튼
const canRun = statusCd === 'READY';
// 학습 취소 버튼
const canCancel = statusCd === 'IN_PROGRESS' && step1Status === 'IN_PROGRESS';
// 재실행 버튼
const canRestart = ['STOPPED', 'ERROR'].includes(statusCd);
// 이어하기 버튼
const canResume = statusCd === 'STOPPED';
// 테스트 실행 버튼
const canTest = step1Status === 'COMPLETED' &&
step2Status !== 'IN_PROGRESS' &&
step2Status !== 'COMPLETED';
// 테스트 취소 버튼
const canCancelTest = step2Status === 'IN_PROGRESS';
// 결과 보기 버튼
const canViewResult = statusCd === 'COMPLETED' &&
step1Status === 'COMPLETED' &&
step2Status === 'COMPLETED';
return (
<div className="action-buttons">
{canRun && (
<button onClick={() => runTrain(uuid)} className="btn-primary">
🚀 학습 실행
</button>
)}
{canCancel && (
<button onClick={() => cancelTrain(uuid)} className="btn-danger">
학습 취소
</button>
)}
{canRestart && (
<button onClick={() => restartTrain(uuid)} className="btn-warning">
🔄 재실행
</button>
)}
{canResume && (
<button onClick={() => resumeTrain(uuid)} className="btn-info">
이어하기
</button>
)}
{canTest && (
<button onClick={() => runTest(uuid, model.bestEpoch)} className="btn-success">
🧪 테스트 실행
</button>
)}
{canCancelTest && (
<button onClick={() => cancelTest(uuid)} className="btn-danger">
테스트 취소
</button>
)}
{canViewResult && (
<button onClick={() => viewResult(uuid)} className="btn-primary">
📊 결과 보기
</button>
)}
</div>
);
}
```
### 6.2 API 호출 함수
```javascript
import axios from 'axios';
const API_BASE = '/api/train';
// 학습 실행
async function runTrain(uuid) {
try {
const response = await axios.post(`${API_BASE}/run/${uuid}`);
if (response.data.success) {
alert('학습이 시작되었습니다.');
refreshModelList(); // 목록 갱신
}
} catch (error) {
alert('학습 실행 실패: ' + error.message);
}
}
// 학습 취소
async function cancelTrain(uuid) {
if (!confirm('학습을 취소하시겠습니까?')) return;
try {
const response = await axios.post(`${API_BASE}/cancel/${uuid}`);
if (response.data.success) {
alert('학습이 취소되었습니다.');
refreshModelList();
}
} catch (error) {
alert('학습 취소 실패: ' + error.message);
}
}
// 학습 재실행
async function restartTrain(uuid) {
if (!confirm('처음부터 다시 학습을 시작하시겠습니까?')) return;
try {
const response = await axios.post(`${API_BASE}/restart/${uuid}`);
if (response.data.success) {
alert('학습이 재시작되었습니다.');
refreshModelList();
}
} catch (error) {
alert('학습 재시작 실패: ' + error.message);
}
}
// 학습 이어하기
async function resumeTrain(uuid) {
if (!confirm('중단된 지점부터 학습을 이어가시겠습니까?')) return;
try {
const response = await axios.post(`${API_BASE}/resume/${uuid}`);
if (response.data.success) {
alert('학습이 재개되었습니다.');
refreshModelList();
}
} catch (error) {
alert('학습 이어하기 실패: ' + error.message);
}
}
// 테스트 실행
async function runTest(uuid, epoch) {
if (!confirm(`Epoch ${epoch}으로 테스트를 실행하시겠습니까?`)) return;
try {
const response = await axios.post(`${API_BASE}/test/run/${epoch}/${uuid}`);
if (response.data.success) {
alert('테스트가 시작되었습니다.');
refreshModelList();
}
} catch (error) {
alert('테스트 실행 실패: ' + error.message);
}
}
// 테스트 취소
async function cancelTest(uuid) {
if (!confirm('테스트를 취소하시겠습니까?')) return;
try {
const response = await axios.post(`${API_BASE}/test/cancel/${uuid}`);
if (response.data.success) {
alert('테스트가 취소되었습니다.');
refreshModelList();
}
} catch (error) {
alert('테스트 취소 실패: ' + error.message);
}
}
// 학습 상태 확인 (폴링용)
async function checkTrainStatus(uuid) {
try {
const response = await axios.post(`${API_BASE}/status/${uuid}`);
return response.data.success;
} catch (error) {
console.error('상태 확인 실패:', error);
return false;
}
}
```
### 6.3 주기적 상태 업데이트 (폴링)
```javascript
import { useEffect, useState } from 'react';
function ModelMonitor({ uuid }) {
const [isPolling, setIsPolling] = useState(false);
useEffect(() => {
let intervalId;
// 진행 중인 모델만 폴링
if (isPolling) {
intervalId = setInterval(async () => {
const success = await checkTrainStatus(uuid);
if (success) {
refreshModelList(); // 상태 업데이트 후 목록 갱신
}
}, 10000); // 10초마다 상태 확인
}
return () => {
if (intervalId) clearInterval(intervalId);
};
}, [uuid, isPolling]);
// 모델 상태에 따라 폴링 활성화/비활성화
useEffect(() => {
const shouldPoll = model.statusCd === 'IN_PROGRESS';
setIsPolling(shouldPoll);
}, [model.statusCd]);
return null; // 백그라운드 작업
}
```
---
## 🎯 7. 상태 수정 시나리오별 가이드
### 시나리오 1: 학습 중단 후 재시작
**현재 상태**:
```json
{
"statusCd": "STOPPED",
"step1Status": "STOPPED",
"lastError": "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE"
}
```
**프론트 표시**:
- ⚠️ 중단됨 - 산출물 부족으로 중단됨
- 버튼: [재실행] [이어하기]
**액션**:
**옵션 A) 재실행** (`POST /api/train/restart/{uuid}`):
```javascript
// 처음부터 다시 시작
await axios.post(`/api/train/restart/${uuid}`);
// 결과 상태
{
"statusCd": "IN_PROGRESS",
"step1Status": "IN_PROGRESS",
"currentAttemptId": 새로운JobId
}
```
**옵션 B) 이어하기** (`POST /api/train/resume/{uuid}`):
```javascript
// 중단된 지점부터 계속
await axios.post(`/api/train/resume/${uuid}`);
// 결과 상태
{
"statusCd": "IN_PROGRESS",
"step1Status": "IN_PROGRESS",
"currentAttemptId": 새로운JobId,
// paramsJson에 resumeFrom 설정됨
}
```
---
### 시나리오 2: 학습 완료 후 테스트 실행
**현재 상태**:
```json
{
"statusCd": "COMPLETED",
"step1Status": "COMPLETED",
"step2Status": "READY",
"bestEpoch": 45
}
```
**프론트 표시**:
- ✅ 완료 - 학습 완료 (테스트 대기)
- 버튼: [테스트 실행]
**액션**:
```javascript
// 테스트 실행 (bestEpoch 사용)
await axios.post(`/api/train/test/run/45/${uuid}`);
// 결과 상태
{
"statusCd": "IN_PROGRESS",
"step1Status": "COMPLETED",
"step2Status": "IN_PROGRESS",
"step2StrtDttm": "2026-04-06 14:30:00"
}
```
**프론트 표시 변경**:
- 🔄 진행중 - 테스트 진행 중...
- 버튼: [테스트 취소]
---
### 시나리오 3: 실행 중인 학습 취소
**현재 상태**:
```json
{
"statusCd": "IN_PROGRESS",
"step1Status": "IN_PROGRESS",
"currentAttemptId": 123
}
```
**프론트 표시**:
- 🔄 진행중 - 학습 진행 중...
- 버튼: [학습 취소]
**액션**:
```javascript
// 학습 취소
await axios.post(`/api/train/cancel/${uuid}`);
// 결과 상태
{
"statusCd": "STOPPED",
"step1Status": "STOPPED",
"currentAttemptId": 123
}
```
**프론트 표시 변경**:
- ⚠️ 중단됨 - 사용자가 학습을 취소함
- 버튼: [재실행] [이어하기]
---
### 시나리오 4: 서버 재시작 후 자동 상태 복구
**서버 재시작 전**:
```json
{
"statusCd": "IN_PROGRESS",
"step1Status": "IN_PROGRESS"
}
```
**서버 재시작 후 API 호출**:
```javascript
// 주기적 폴링 또는 수동 호출
await axios.post(`/api/train/status/${uuid}`);
```
**케이스 A) 학습 완료된 경우**:
```json
{
"statusCd": "COMPLETED",
"step1Status": "COMPLETED",
"step1EndDttm": "2026-04-06 15:00:00",
"step1MetricSaveYn": true
}
```
- ✅ 완료 - 학습 완료
- 버튼: [테스트 실행] [결과 보기]
**케이스 B) 산출물 부족한 경우**:
```json
{
"statusCd": "STOPPED",
"step1Status": "STOPPED",
"lastError": "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE: val.csv-lines-mismatch"
}
```
- ⚠️ 중단됨 - 산출물 부족으로 중단됨
- 버튼: [재실행] [이어하기]
**케이스 C) 여전히 실행 중인 경우**:
```json
{
"statusCd": "IN_PROGRESS",
"step1Status": "IN_PROGRESS"
}
```
- 🔄 진행중 - 학습 진행 중...
- 버튼: [학습 취소]
---
## 📊 8. 에러 메시지 처리
### 8.1 `last_error` 필드 해석
| 에러 메시지 | 의미 | 프론트 표시 | 권장 액션 |
|------------|------|-----------|----------|
| `SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE` | 서버 재시작 후 컨테이너 없음 + 산출물 부족 | "서버 재시작으로 인한 중단 - 산출물 확인 필요" | [재실행] |
| `val.csv-lines-mismatch` | val.csv 라인 수 부족 | "검증 데이터 부족 - 학습이 완료되지 않음" | [재실행] [이어하기] |
| `val.csv-missing` | val.csv 파일 없음 | "검증 파일 없음 - 학습 실패" | [재실행] |
| `total-epoch-missing` | paramsJson에 total_epoch 없음 | "설정 오류 - 에폭 정보 없음" | [재실행] |
| `output-dir-missing` | 산출물 디렉토리 없음 | "산출물 디렉토리 없음 - 학습 실패" | [재실행] |
### 8.2 에러 표시 컴포넌트
```javascript
function ErrorMessage({ lastError }) {
if (!lastError) return null;
const errorMessages = {
'SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE': {
icon: '⚠️',
title: '서버 재시작으로 인한 중단',
message: '서버가 재시작되면서 학습이 중단되었습니다. 산출물을 확인하여 학습 상태를 복구합니다.',
severity: 'warning'
},
'val.csv-lines-mismatch': {
icon: '📊',
title: '검증 데이터 부족',
message: '검증 데이터 라인 수가 예상보다 적습니다. 학습이 완료되지 않았을 가능성이 있습니다.',
severity: 'warning'
},
'val.csv-missing': {
icon: '❌',
title: '검증 파일 없음',
message: 'val.csv 파일을 찾을 수 없습니다. 학습이 실패했을 가능성이 높습니다.',
severity: 'error'
}
};
// 에러 메시지 파싱
const errorKey = Object.keys(errorMessages).find(key => lastError.includes(key));
const errorInfo = errorMessages[errorKey] || {
icon: '⚠️',
title: '오류 발생',
message: lastError,
severity: 'error'
};
return (
<div className={`error-message severity-${errorInfo.severity}`}>
<div className="error-header">
<span className="error-icon">{errorInfo.icon}</span>
<span className="error-title">{errorInfo.title}</span>
</div>
<p className="error-description">{errorInfo.message}</p>
</div>
);
}
```
---
## 🔍 9. 상태 일관성 체크리스트
### 프론트엔드 개발 시 확인사항
#### ✅ 상태 표시
- [ ] `statusCd`를 UI에 정확히 매핑 (READY, IN_PROGRESS, COMPLETED, STOPPED, ERROR)
- [ ] `step1Status`, `step2Status` 개별 표시
- [ ] 한글 상태명 표시 (statusName, step1StatusName, step2StatusName 활용)
- [ ] 상태별 적절한 색상/아이콘 사용
#### ✅ 버튼 활성화/비활성화
- [ ] `statusCd`에 따른 버튼 조건 확인
- [ ] `step1Status`, `step2Status` 조합 고려
- [ ] 중복 실행 방지 (disabled 속성)
#### ✅ 시간 정보 표시
- [ ] `step1StrtDttm`, `step1EndDttm` 표시
- [ ] `step2StrtDttm`, `step2EndDttm` 표시
- [ ] `step1Duration`, `step2Duration` 계산 표시
#### ✅ 에러 처리
- [ ] `lastError` 메시지 파싱 및 표시
- [ ] 사용자 친화적 에러 메시지 변환
- [ ] 에러 발생 시 복구 방법 안내
#### ✅ 주기적 업데이트
- [ ] 진행 중인 모델 폴링 (10초 간격 권장)
- [ ] `POST /api/train/status/{uuid}` 주기 호출
- [ ] 목록 자동 갱신
---
## 💡 10. 베스트 프랙티스
### 10.1 상태 동기화
```javascript
// ❌ 나쁜 예: 프론트에서 임의로 상태 변경
function handleCancel() {
model.statusCd = 'STOPPED'; // 직접 변경 X
updateUI();
}
// ✅ 좋은 예: API 호출 후 서버 응답 기준으로 업데이트
async function handleCancel() {
await axios.post(`/api/train/cancel/${uuid}`);
const updated = await axios.get(`/api/models/list`);
setModels(updated.data.content);
}
```
### 10.2 낙관적 UI 업데이트
```javascript
// ✅ 사용자 경험 향상: 즉시 UI 업데이트 + 백그라운드 검증
async function handleRun() {
// 1. 즉시 UI 업데이트 (낙관적)
setModel(prev => ({ ...prev, statusCd: 'IN_PROGRESS' }));
try {
// 2. API 호출
await axios.post(`/api/train/run/${uuid}`);
// 3. 실제 상태 확인
setTimeout(() => checkTrainStatus(uuid), 2000);
} catch (error) {
// 4. 실패 시 롤백
setModel(prev => ({ ...prev, statusCd: 'READY' }));
alert('실행 실패: ' + error.message);
}
}
```
### 10.3 상태별 UI 일관성
```css
/* 상태별 일관된 색상 스타일 */
.status-badge.ready { background: #e3f2fd; color: #1976d2; }
.status-badge.in-progress { background: #e8f5e9; color: #388e3c; }
.status-badge.completed { background: #f1f8e9; color: #689f38; }
.status-badge.stopped { background: #fff3e0; color: #f57c00; }
.status-badge.error { background: #ffebee; color: #d32f2f; }
/* 버튼 스타일 */
.btn-primary { background: #1976d2; color: white; }
.btn-success { background: #388e3c; color: white; }
.btn-warning { background: #f57c00; color: white; }
.btn-danger { background: #d32f2f; color: white; }
.btn-info { background: #0288d1; color: white; }
```
---
## 📝 요약
### 상태 확인 방법
1. **API 호출**: `POST /api/train/status/{uuid}`
2. **응답 확인**: `statusCd`, `step1Status`, `step2Status`
3. **UI 반영**: 상태별 배지/아이콘 표시
### 상태 변경 방법
1. **적절한 제어 API 호출**:
- 실행: `POST /api/train/run/{uuid}`
- 취소: `POST /api/train/cancel/{uuid}`
- 재실행: `POST /api/train/restart/{uuid}`
- 이어하기: `POST /api/train/resume/{uuid}`
2. **버튼 조건부 표시**:
- `statusCd`, `step1Status`, `step2Status` 조합 확인
3. **주기적 폴링**:
- 진행 중(`IN_PROGRESS`) 상태일 때만 10초 간격 폴링
---