Compare commits
214 Commits
265813e6f7
...
feat/train
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e858c8896 | |||
| b546e053b6 | |||
| bc67753b99 | |||
| 8043e1a41a | |||
| d48e96ba82 | |||
| 01a1211e55 | |||
| a0f4d0b8e2 | |||
| 38906a5795 | |||
| 051082665d | |||
| 13d9d9176b | |||
| 62398846d3 | |||
| 260569225c | |||
|
|
acdffd99ec | ||
| bd6fe924de | |||
| d7458e3c8b | |||
| 92492ca879 | |||
| a5d79b2504 | |||
| b8c53aae64 | |||
| 348d3d0052 | |||
| b85ead36b4 | |||
| e77eae8f8b | |||
| 570952df7e | |||
| 26d34d88eb | |||
| 46a5d4c2d3 | |||
| 91f022889b | |||
|
|
f00296cf2c | ||
| f98f6cb038 | |||
| d1593e57c3 | |||
| 732dccf2e4 | |||
| f6cd553af8 | |||
| 618dbe4047 | |||
| 5546e8ef89 | |||
| b952ec7b47 | |||
| e93f533c59 | |||
| a5267d8065 | |||
| 71d9835b03 | |||
| 39f39a4f0c | |||
| 1df7142544 | |||
| d99e18b38c | |||
| d6aa612494 | |||
| 8def356323 | |||
|
|
6cc9b54ba9 | ||
|
|
50ad05b53b | ||
|
|
822dbb252f | ||
|
|
5e04df73af | ||
| 650b1695f0 | |||
| 960e4215e0 | |||
| 08a220db4d | |||
| a9b49faa6c | |||
| b760e9874c | |||
| 8698bf61d1 | |||
| 680e137284 | |||
| f4a81a34d6 | |||
| 479ad710e0 | |||
| 3cb9840248 | |||
| fc9543f195 | |||
| 73d0e03b08 | |||
| 50c965cb79 | |||
|
|
abca9467d8 | ||
|
|
4ed03f6e94 | ||
| 04eddfce54 | |||
| f49b7cc850 | |||
| 888c0e314b | |||
| 6c043b0031 | |||
| 531da09c5f | |||
| 4da2a1f0d7 | |||
| 50b3f1ba62 | |||
| f1f88c83e1 | |||
| ff478452a6 | |||
| bf77725ef8 | |||
| dec0f26999 | |||
| dfd4a42379 | |||
| 79272137ab | |||
| 73ea6176b4 | |||
| 3d2a4049d3 | |||
| 26caf505b9 | |||
| 0cbaf53e86 | |||
| bd54854bc6 | |||
| 80fd2bda3e | |||
| ca3d115d0e | |||
| fb647e5991 | |||
| 831ba3e616 | |||
| 87575a62f7 | |||
| a4b5e20db2 | |||
| 246c11f8b0 | |||
| da260f35ea | |||
| 2c1f9bdf5c | |||
| 6cf81bf60f | |||
| 5799f7dfb2 | |||
| ed95829a34 | |||
| 9f428e9572 | |||
| 52ffe53815 | |||
| 904968a1be | |||
| 4b44be6a29 | |||
| 5887a954ea | |||
| f9f0662f8e | |||
|
|
72bc2fd47b | ||
| 7416327cc3 | |||
| da31bd9d99 | |||
| f3e5347335 | |||
| 7d5581f60c | |||
| b4428217ea | |||
| 8a63fdacdd | |||
| cb2e42143a | |||
| 997e85c0cc | |||
| 731ca59475 | |||
| fe6d37456d | |||
| 6c98a48a5d | |||
| 81b69caa99 | |||
| 7fce070686 | |||
| 8d83505ee7 | |||
| 0ff38b24d4 | |||
| 5c082f7c9d | |||
| 43d0e55cb7 | |||
| df3bedfbda | |||
| c26a48d07d | |||
| 1c7c213977 | |||
| 6583a45abd | |||
| b15f77d894 | |||
| 3bcd99f0db | |||
| 5513cd60a0 | |||
| 7b35d26a13 | |||
| d92ff88ef7 | |||
| bfcddd0327 | |||
| e193330f99 | |||
| 6c0184597d | |||
| 1e8a8d8dad | |||
| eb7680b952 | |||
| 2c357ebf27 | |||
| 0daaa1c8cb | |||
| 96383595df | |||
| c5e03f7ca8 | |||
| df2acc4dfb | |||
| 693de354d2 | |||
| 62cdc5015e | |||
| 5c11263d55 | |||
| dd5031ae3a | |||
| c369e01ada | |||
| 54991622f1 | |||
| 17d69486ec | |||
| 948f1061da | |||
| 42438b3cd5 | |||
| 524ae200b0 | |||
| 4f763d3c2e | |||
| 9ebf525387 | |||
| 4ab672a96e | |||
| 7d2a367e3f | |||
| 67a67749c3 | |||
| 251307b5c9 | |||
| 8423a03d31 | |||
| d6cdf6b690 | |||
| 9cfa299e58 | |||
| a137e71420 | |||
| f08f80622f | |||
| e565fd7a34 | |||
| 8c45b39dcc | |||
| b119f333ac | |||
| bbe04ee458 | |||
| fab3c83a69 | |||
| fb87a0f32f | |||
| 63794ec4ec | |||
| bf6dc9740f | |||
| a23bc8dd67 | |||
| 13023a06cc | |||
| 28b50bd949 | |||
| 78ab928459 | |||
| ae3601cff5 | |||
| 5f62f4a209 | |||
| 29bf155b4f | |||
| da03f8b749 | |||
| 6a2deff93b | |||
| b0a99afcd3 | |||
| eedf72d7aa | |||
| 25e9941464 | |||
| a0da0392cf | |||
| a3ebee12b5 | |||
| c5b14ca09d | |||
| 44b3b857b1 | |||
| 63124455fd | |||
| e75ea8d8a5 | |||
| 31ac4209c3 | |||
| df09935789 | |||
| bb15b1b0f2 | |||
| f4d491ed94 | |||
| 96cb7d2f23 | |||
| cc6305b0df | |||
| 3916b13876 | |||
| ee4a06df30 | |||
| bb5ff7c3cd | |||
| 312a96dda1 | |||
| e38231e06d | |||
| bf6e45d706 | |||
| 7fa8921a25 | |||
| 7c940351d9 | |||
| 6b834da912 | |||
| 25aaa97d65 | |||
| da9d47ae4a | |||
| 7d6a77bf2a | |||
| 26828d0968 | |||
| e2dbae15c0 | |||
| b246034632 | |||
| 687ea82d78 | |||
| 4ac0f19908 | |||
| 9e5e7595eb | |||
| 9cd9274e99 | |||
| 5d82f3ecfe | |||
| 2ce249ab33 | |||
| e34bf68de0 | |||
| 862bda0cb9 | |||
| 90f7b17d07 | |||
| 2128baa46a | |||
| 875c30f467 | |||
| 2b29cd1ac6 | |||
| 9206fff5d0 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -72,3 +72,9 @@ docker-compose.override.yml
|
||||
*.swo
|
||||
*~
|
||||
!/CLAUDE.md
|
||||
|
||||
### SSL Certificates ###
|
||||
nginx/ssl/
|
||||
*.crt
|
||||
*.key
|
||||
*.pem
|
||||
|
||||
415
DEPLOY.md
Normal file
415
DEPLOY.md
Normal file
@@ -0,0 +1,415 @@
|
||||
# KAMCO Training API 배포 가이드 (RedHat 9.6)
|
||||
|
||||
## 빠른 배포 (Quick Start)
|
||||
|
||||
이 문서는 RedHat 9.6 환경에서 HTTPS로 KAMCO Training API를 배포하는 방법을 설명합니다.
|
||||
|
||||
**접속 URL**:
|
||||
- `https://api.train-kamco.com`
|
||||
- `https://train-kamco.com`
|
||||
|
||||
## 사전 요구사항
|
||||
|
||||
- [x] Docker & Docker Compose 설치
|
||||
- [x] Git 설치
|
||||
- [x] sudo 권한
|
||||
- [x] 포트 80, 443 사용 가능
|
||||
|
||||
## 1단계: /etc/hosts 설정
|
||||
|
||||
```bash
|
||||
# root 권한으로 도메인 추가
|
||||
echo "127.0.0.1 api.train-kamco.com train-kamco.com" | sudo tee -a /etc/hosts
|
||||
|
||||
# 확인
|
||||
cat /etc/hosts | grep train-kamco
|
||||
```
|
||||
|
||||
**예상 결과**:
|
||||
```
|
||||
127.0.0.1 api.train-kamco.com train-kamco.com
|
||||
```
|
||||
|
||||
## 2단계: 방화벽 설정 (필요시)
|
||||
|
||||
```bash
|
||||
# 방화벽 상태 확인
|
||||
sudo firewall-cmd --state
|
||||
|
||||
# HTTP/HTTPS 포트 개방
|
||||
sudo firewall-cmd --permanent --add-port=80/tcp
|
||||
sudo firewall-cmd --permanent --add-port=443/tcp
|
||||
|
||||
# 방화벽 재로드
|
||||
sudo firewall-cmd --reload
|
||||
|
||||
# 확인
|
||||
sudo firewall-cmd --list-ports
|
||||
```
|
||||
|
||||
**예상 결과**: `80/tcp 443/tcp`
|
||||
|
||||
## 3단계: 프로젝트 디렉토리로 이동
|
||||
|
||||
```bash
|
||||
cd /path/to/kamco-train-api
|
||||
|
||||
# 현재 위치 확인
|
||||
pwd
|
||||
# 예상: /home/username/kamco-train-api
|
||||
```
|
||||
|
||||
## 4단계: 파일 구조 확인
|
||||
|
||||
배포 전 필수 파일이 모두 있는지 확인하세요:
|
||||
|
||||
```bash
|
||||
# SSL 인증서 확인
|
||||
ls -la nginx/ssl/
|
||||
|
||||
# 예상 결과:
|
||||
# train-kamco.com.crt (인증서)
|
||||
# train-kamco.com.key (개인 키)
|
||||
# openssl.cnf (설정 파일)
|
||||
```
|
||||
|
||||
```bash
|
||||
# Docker Compose 파일 확인
|
||||
ls -la docker-compose-prod.yml nginx/nginx.conf
|
||||
|
||||
# 예상: 두 파일 모두 존재
|
||||
```
|
||||
|
||||
## 5단계: Docker 네트워크 생성 (최초 1회)
|
||||
|
||||
```bash
|
||||
# kamco-cds 네트워크가 있는지 확인
|
||||
docker network ls | grep kamco-cds
|
||||
|
||||
# 없으면 생성
|
||||
docker network create kamco-cds
|
||||
```
|
||||
|
||||
## 6단계: Docker Compose 배포
|
||||
|
||||
```bash
|
||||
# 기존 컨테이너 중지 (있는 경우)
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
|
||||
# 새로운 이미지 빌드 및 실행
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
|
||||
# 컨테이너 상태 확인
|
||||
docker-compose -f docker-compose-prod.yml ps
|
||||
```
|
||||
|
||||
**예상 결과**:
|
||||
```
|
||||
NAME STATUS
|
||||
kamco-cd-nginx Up (healthy)
|
||||
kamco-cd-training-api Up (healthy)
|
||||
```
|
||||
|
||||
## 7단계: 배포 확인
|
||||
|
||||
### 컨테이너 로그 확인
|
||||
|
||||
```bash
|
||||
# Nginx 로그
|
||||
docker logs kamco-cd-nginx --tail 50
|
||||
|
||||
# API 로그
|
||||
docker logs kamco-cd-training-api --tail 50
|
||||
|
||||
# 실시간 로그 (Ctrl+C로 종료)
|
||||
docker-compose -f docker-compose-prod.yml logs -f
|
||||
```
|
||||
|
||||
### HTTP → HTTPS 리다이렉트 테스트
|
||||
|
||||
```bash
|
||||
# HTTP 접속 시 HTTPS로 리다이렉트되는지 확인
|
||||
curl -I http://api.train-kamco.com
|
||||
curl -I http://train-kamco.com
|
||||
|
||||
# 예상 결과: 301 Moved Permanently
|
||||
# Location: https://api.train-kamco.com/ 또는 https://train-kamco.com/
|
||||
```
|
||||
|
||||
### HTTPS 헬스체크
|
||||
|
||||
```bash
|
||||
# -k 플래그: 사설 인증서 경고 무시
|
||||
curl -k https://api.train-kamco.com/monitor/health
|
||||
curl -k https://train-kamco.com/monitor/health
|
||||
|
||||
# 예상 결과: {"status":"UP","components":{...}}
|
||||
```
|
||||
|
||||
### 브라우저 테스트
|
||||
|
||||
브라우저에서 다음 URL에 접속:
|
||||
|
||||
- `https://api.train-kamco.com/monitor/health`
|
||||
- `https://train-kamco.com/monitor/health`
|
||||
|
||||
**사설 인증서 경고**:
|
||||
- "안전하지 않음" 경고가 표시되면 **"고급"** → **"계속 진행"** 클릭
|
||||
|
||||
## 8단계: SSL 인증서 확인 (선택사항)
|
||||
|
||||
```bash
|
||||
# 인증서 정보 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -text -noout | head -30
|
||||
|
||||
# 유효 기간 확인 (100년)
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -noout -dates
|
||||
|
||||
# SAN (멀티 도메인) 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -text -noout | grep -A1 "Subject Alternative Name"
|
||||
|
||||
# 예상 결과:
|
||||
# X509v3 Subject Alternative Name:
|
||||
# DNS:api.train-kamco.com, DNS:train-kamco.com
|
||||
```
|
||||
|
||||
## 트러블슈팅
|
||||
|
||||
### 문제 1: "Connection refused"
|
||||
|
||||
**원인**: 컨테이너가 실행되지 않음
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# 컨테이너 상태 확인
|
||||
docker ps -a | grep kamco-cd
|
||||
|
||||
# 컨테이너 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
|
||||
# 로그 확인
|
||||
docker logs kamco-cd-nginx
|
||||
docker logs kamco-cd-training-api
|
||||
```
|
||||
|
||||
### 문제 2: "502 Bad Gateway"
|
||||
|
||||
**원인**: Nginx는 실행 중이지만 API 컨테이너가 준비되지 않음
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# API 컨테이너 상태 확인
|
||||
docker logs kamco-cd-training-api
|
||||
|
||||
# API 헬스체크 (컨테이너 내부에서)
|
||||
docker exec kamco-cd-nginx wget -qO- http://kamco-changedetection-api:8080/monitor/health
|
||||
|
||||
# API 컨테이너 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart kamco-changedetection-api
|
||||
```
|
||||
|
||||
### 문제 3: "Name or service not known"
|
||||
|
||||
**원인**: /etc/hosts에 도메인이 설정되지 않음
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# /etc/hosts 확인
|
||||
cat /etc/hosts | grep train-kamco
|
||||
|
||||
# 없으면 추가
|
||||
echo "127.0.0.1 api.train-kamco.com train-kamco.com" | sudo tee -a /etc/hosts
|
||||
```
|
||||
|
||||
### 문제 4: 포트 80 또는 443이 이미 사용 중
|
||||
|
||||
**원인**: 다른 프로세스가 포트를 사용 중
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# 포트 사용 확인
|
||||
sudo lsof -i :80
|
||||
sudo lsof -i :443
|
||||
|
||||
# 사용 중인 프로세스 종료 (예: httpd, nginx)
|
||||
sudo systemctl stop httpd
|
||||
sudo systemctl stop nginx
|
||||
|
||||
# Docker Compose 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
```
|
||||
|
||||
### 문제 5: SELinux 권한 오류
|
||||
|
||||
**원인**: SELinux가 Docker 볼륨 마운트를 차단
|
||||
|
||||
**해결**:
|
||||
```bash
|
||||
# SELinux 상태 확인
|
||||
getenforce
|
||||
|
||||
# Permissive 모드로 임시 변경 (재부팅 시 초기화됨)
|
||||
sudo setenforce 0
|
||||
|
||||
# 영구 변경 (권장하지 않음)
|
||||
sudo vi /etc/selinux/config
|
||||
# SELINUX=permissive 또는 SELINUX=disabled로 변경
|
||||
```
|
||||
|
||||
## 컨테이너 관리 명령어
|
||||
|
||||
### 시작/중지/재시작
|
||||
|
||||
```bash
|
||||
# 시작
|
||||
docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 중지
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
|
||||
# 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
|
||||
# 특정 서비스만 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart nginx
|
||||
docker-compose -f docker-compose-prod.yml restart kamco-changedetection-api
|
||||
```
|
||||
|
||||
### 로그 확인
|
||||
|
||||
```bash
|
||||
# 전체 로그
|
||||
docker-compose -f docker-compose-prod.yml logs
|
||||
|
||||
# 특정 서비스 로그
|
||||
docker-compose -f docker-compose-prod.yml logs nginx
|
||||
docker-compose -f docker-compose-prod.yml logs kamco-changedetection-api
|
||||
|
||||
# 실시간 로그
|
||||
docker-compose -f docker-compose-prod.yml logs -f
|
||||
|
||||
# 마지막 N줄만 보기
|
||||
docker logs kamco-cd-nginx --tail 100
|
||||
```
|
||||
|
||||
### 컨테이너 상태 확인
|
||||
|
||||
```bash
|
||||
# 실행 중인 컨테이너
|
||||
docker-compose -f docker-compose-prod.yml ps
|
||||
|
||||
# 상세 정보
|
||||
docker inspect kamco-cd-nginx
|
||||
docker inspect kamco-cd-training-api
|
||||
|
||||
# 리소스 사용량
|
||||
docker stats kamco-cd-nginx kamco-cd-training-api
|
||||
```
|
||||
|
||||
### 컨테이너 내부 접속
|
||||
|
||||
```bash
|
||||
# Nginx 컨테이너 내부 접속
|
||||
docker exec -it kamco-cd-nginx sh
|
||||
|
||||
# API 컨테이너 내부 접속
|
||||
docker exec -it kamco-cd-training-api sh
|
||||
|
||||
# 내부에서 빠져나오기
|
||||
exit
|
||||
```
|
||||
|
||||
## 업데이트 및 재배포
|
||||
|
||||
### 코드 업데이트 후 재배포
|
||||
|
||||
```bash
|
||||
# 1. Git pull (코드 업데이트)
|
||||
git pull origin develop
|
||||
|
||||
# 2. JAR 파일 빌드 (Jenkins에서 수행하는 경우 생략)
|
||||
./gradlew clean build -x test
|
||||
|
||||
# 3. 컨테이너 재빌드 및 재시작
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
|
||||
# 4. 로그 확인
|
||||
docker-compose -f docker-compose-prod.yml logs -f
|
||||
```
|
||||
|
||||
### 설정 파일만 변경한 경우
|
||||
|
||||
```bash
|
||||
# nginx.conf 또는 docker-compose-prod.yml 변경 시
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 또는
|
||||
docker-compose -f docker-compose-prod.yml restart nginx
|
||||
```
|
||||
|
||||
## 모니터링
|
||||
|
||||
### 헬스체크 엔드포인트
|
||||
|
||||
```bash
|
||||
# API 헬스체크
|
||||
curl -k https://api.train-kamco.com/monitor/health
|
||||
|
||||
# 예상 결과:
|
||||
# {
|
||||
# "status": "UP",
|
||||
# "components": {
|
||||
# "db": {"status": "UP"},
|
||||
# "diskSpace": {"status": "UP"}
|
||||
# }
|
||||
# }
|
||||
```
|
||||
|
||||
### 시스템 리소스
|
||||
|
||||
```bash
|
||||
# 디스크 사용량
|
||||
df -h
|
||||
|
||||
# 메모리 사용량
|
||||
free -h
|
||||
|
||||
# Docker 이미지 및 컨테이너 용량
|
||||
docker system df
|
||||
```
|
||||
|
||||
## 보안 권장 사항
|
||||
|
||||
1. **사설 인증서**: 현재 사설 인증서를 사용 중입니다. 프로덕션 환경에서는 **Let's Encrypt** 또는 **GlobalSign** 같은 공인 인증서 사용을 권장합니다.
|
||||
|
||||
2. **방화벽**: 필요한 포트(80, 443)만 개방하고, 불필요한 포트는 차단하세요.
|
||||
|
||||
3. **정기 업데이트**: Docker 이미지와 시스템 패키지를 정기적으로 업데이트하세요.
|
||||
|
||||
4. **로그 모니터링**: 정기적으로 로그를 확인하여 비정상적인 활동을 감지하세요.
|
||||
|
||||
5. **백업**: SSL 인증서 키 파일(`train-kamco.com.key`)과 데이터베이스를 정기적으로 백업하세요.
|
||||
|
||||
## 참고 문서
|
||||
|
||||
- **SSL 인증서 설정**: [nginx/SSL_SETUP.md](nginx/SSL_SETUP.md)
|
||||
- **프로젝트 개요**: [README.md](README.md)
|
||||
- **CLAUDE.md**: [CLAUDE.md](CLAUDE.md)
|
||||
|
||||
## 지원
|
||||
|
||||
문제가 발생하면 다음을 확인하세요:
|
||||
1. 컨테이너 로그: `docker-compose -f docker-compose-prod.yml logs`
|
||||
2. 컨테이너 상태: `docker-compose -f docker-compose-prod.yml ps`
|
||||
3. /etc/hosts 설정: `cat /etc/hosts | grep train-kamco`
|
||||
4. 방화벽 상태: `sudo firewall-cmd --list-ports`
|
||||
|
||||
---
|
||||
|
||||
**배포 완료!** 🎉
|
||||
|
||||
접속 URL:
|
||||
- `https://api.train-kamco.com`
|
||||
- `https://train-kamco.com`
|
||||
443
DEPLOYMENT.md
Normal file
443
DEPLOYMENT.md
Normal file
@@ -0,0 +1,443 @@
|
||||
# KAMCO Train API - Production Deployment Guide
|
||||
|
||||
프로덕션 환경 배포 가이드
|
||||
|
||||
## 목차
|
||||
- [사전 요구사항](#사전-요구사항)
|
||||
- [초기 설정](#초기-설정)
|
||||
- [배포 순서](#배포-순서)
|
||||
- [개별 서비스 관리](#개별-서비스-관리)
|
||||
- [롤백 절차](#롤백-절차)
|
||||
- [모니터링 및 헬스체크](#모니터링-및-헬스체크)
|
||||
- [트러블슈팅](#트러블슈팅)
|
||||
|
||||
---
|
||||
|
||||
## 사전 요구사항
|
||||
|
||||
### 시스템 요구사항
|
||||
- Docker Engine 20.10+
|
||||
- Docker Compose 2.0+
|
||||
- 최소 메모리: 4GB
|
||||
- 디스크 공간: 20GB 이상
|
||||
|
||||
### 네트워크 요구사항
|
||||
- 도메인 설정:
|
||||
- `train-kamco.com` → 서버 IP (Web UI)
|
||||
- `api.train-kamco.com` → 서버 IP (API)
|
||||
- 포트:
|
||||
- 80 (HTTP)
|
||||
- 443 (HTTPS)
|
||||
- 8080 (API - internal)
|
||||
- 3002 (Web - internal)
|
||||
|
||||
### 필수 파일
|
||||
- SSL 인증서:
|
||||
- `nginx/ssl/train-kamco.com.crt`
|
||||
- `nginx/ssl/train-kamco.com.key`
|
||||
- 환경 설정:
|
||||
- `application-prod.yml` (API 설정)
|
||||
- `.env` 파일 (IMAGE_TAG 등)
|
||||
|
||||
---
|
||||
|
||||
## 초기 설정
|
||||
|
||||
### 1. Docker 네트워크 생성
|
||||
|
||||
```bash
|
||||
# kamco-cds 네트워크 생성 (최초 1회만)
|
||||
docker network create kamco-cds
|
||||
|
||||
# 네트워크 확인
|
||||
docker network ls | grep kamco-cds
|
||||
```
|
||||
|
||||
### 2. SSL 인증서 배치
|
||||
|
||||
```bash
|
||||
# 인증서 디렉토리 생성
|
||||
mkdir -p nginx/ssl
|
||||
|
||||
# 인증서 파일 복사
|
||||
cp /path/to/train-kamco.com.crt nginx/ssl/
|
||||
cp /path/to/train-kamco.com.key nginx/ssl/
|
||||
|
||||
# 권한 설정
|
||||
chmod 600 nginx/ssl/train-kamco.com.key
|
||||
chmod 644 nginx/ssl/train-kamco.com.crt
|
||||
```
|
||||
|
||||
### 3. 환경 변수 설정
|
||||
|
||||
```bash
|
||||
# .env 파일 생성
|
||||
cat > .env << EOF
|
||||
IMAGE_TAG=latest
|
||||
SPRING_PROFILES_ACTIVE=prod
|
||||
TZ=Asia/Seoul
|
||||
EOF
|
||||
```
|
||||
|
||||
### 4. 볼륨 디렉토리 생성
|
||||
|
||||
```bash
|
||||
# 데이터 디렉토리 생성
|
||||
mkdir -p ./app/model_output
|
||||
mkdir -p ./app/train_dataset
|
||||
|
||||
# 권한 설정
|
||||
chmod -R 755 ./app
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 배포 순서
|
||||
|
||||
### 전체 스택 초기 배포
|
||||
|
||||
**중요**: 반드시 아래 순서대로 실행해야 합니다.
|
||||
|
||||
```bash
|
||||
# 1. Nginx 시작
|
||||
docker-compose -f docker-compose-nginx.yml up -d
|
||||
|
||||
# 2. Nginx 상태 확인
|
||||
docker ps | grep kamco-train-nginx
|
||||
|
||||
# 3. API 서비스 시작
|
||||
docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 4. API 헬스체크 대기 (최대 40초)
|
||||
sleep 40
|
||||
curl -f http://localhost:8080/monitor/health
|
||||
|
||||
# 5. Web 서비스 시작 (kamco-train-web 프로젝트에서)
|
||||
# cd ../kamco-train-web
|
||||
# docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 6. 전체 상태 확인
|
||||
docker ps -a | grep kamco
|
||||
```
|
||||
|
||||
### 배포 검증
|
||||
|
||||
```bash
|
||||
# 서비스별 헬스체크
|
||||
curl -f http://localhost:8080/monitor/health # API (internal)
|
||||
curl -kf https://api.train-kamco.com/monitor/health # API (external)
|
||||
curl -kf https://train-kamco.com # Web (external)
|
||||
|
||||
# Nginx 설정 검증
|
||||
docker exec kamco-train-nginx nginx -t
|
||||
|
||||
# 로그 확인
|
||||
docker-compose -f docker-compose-nginx.yml logs --tail=50
|
||||
docker-compose -f docker-compose-prod.yml logs --tail=50
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 개별 서비스 관리
|
||||
|
||||
### Nginx 관리
|
||||
|
||||
```bash
|
||||
# 설정 변경 후 리로드 (다운타임 없음)
|
||||
docker exec kamco-train-nginx nginx -s reload
|
||||
|
||||
# 재시작
|
||||
docker-compose -f docker-compose-nginx.yml restart
|
||||
|
||||
# 로그 확인
|
||||
docker-compose -f docker-compose-nginx.yml logs -f
|
||||
|
||||
# 컨테이너 내부 접근
|
||||
docker exec -it kamco-train-nginx sh
|
||||
```
|
||||
|
||||
### API 서비스 관리
|
||||
|
||||
```bash
|
||||
# 재배포 (새 이미지 빌드)
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
|
||||
# 재시작 (이미지 변경 없이)
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
|
||||
# 중지
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
|
||||
# 로그 확인
|
||||
docker-compose -f docker-compose-prod.yml logs -f kamco-train-api
|
||||
|
||||
# 컨테이너 내부 접근
|
||||
docker exec -it kamco-train-api bash
|
||||
```
|
||||
|
||||
### Web 서비스 관리
|
||||
|
||||
```bash
|
||||
# kamco-train-web 프로젝트에서 실행
|
||||
cd ../kamco-train-web
|
||||
|
||||
# 재배포
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
|
||||
# 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
|
||||
# 로그 확인
|
||||
docker-compose -f docker-compose-prod.yml logs -f
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 롤백 절차
|
||||
|
||||
### 이미지 기반 롤백
|
||||
|
||||
```bash
|
||||
# 1. 사용 가능한 이미지 확인
|
||||
docker images | grep kamco-train-api
|
||||
|
||||
# 2. 이전 이미지 태그로 롤백
|
||||
export IMAGE_TAG=previous-commit-hash
|
||||
docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 3. 헬스체크 확인
|
||||
curl -f http://localhost:8080/monitor/health
|
||||
```
|
||||
|
||||
### Git 기반 롤백
|
||||
|
||||
```bash
|
||||
# 1. 이전 커밋으로 체크아웃
|
||||
git log --oneline -10
|
||||
git checkout <previous-commit-hash>
|
||||
|
||||
# 2. 재빌드 및 배포
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
|
||||
# 3. 검증 후 브랜치 업데이트 (필요시)
|
||||
# git checkout develop
|
||||
# git reset --hard <previous-commit-hash>
|
||||
# git push -f origin develop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 모니터링 및 헬스체크
|
||||
|
||||
### 헬스체크 엔드포인트
|
||||
|
||||
```bash
|
||||
# API 헬스체크
|
||||
curl http://localhost:8080/monitor/health
|
||||
curl http://localhost:8080/monitor/health/readiness
|
||||
curl http://localhost:8080/monitor/health/liveness
|
||||
|
||||
# Nginx를 통한 헬스체크
|
||||
curl -k https://api.train-kamco.com/monitor/health
|
||||
```
|
||||
|
||||
### 컨테이너 상태 모니터링
|
||||
|
||||
```bash
|
||||
# 모든 컨테이너 상태
|
||||
docker ps -a | grep kamco
|
||||
|
||||
# 리소스 사용량 실시간 모니터링
|
||||
docker stats kamco-train-nginx kamco-train-api
|
||||
|
||||
# 헬스체크 상태
|
||||
docker inspect kamco-train-api | grep -A 10 Health
|
||||
```
|
||||
|
||||
### 로그 모니터링
|
||||
|
||||
```bash
|
||||
# 실시간 로그 (모든 서비스)
|
||||
docker-compose -f docker-compose-nginx.yml logs -f &
|
||||
docker-compose -f docker-compose-prod.yml logs -f &
|
||||
|
||||
# 에러 로그만 필터링
|
||||
docker-compose -f docker-compose-prod.yml logs | grep -i error
|
||||
|
||||
# 최근 100줄
|
||||
docker-compose -f docker-compose-prod.yml logs --tail=100
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 트러블슈팅
|
||||
|
||||
### 1. Nginx 502 Bad Gateway
|
||||
|
||||
**원인**: API 서비스가 준비되지 않음
|
||||
|
||||
```bash
|
||||
# API 컨테이너 상태 확인
|
||||
docker ps | grep kamco-train-api
|
||||
|
||||
# API 로그 확인
|
||||
docker logs kamco-train-api --tail=100
|
||||
|
||||
# 네트워크 연결 확인
|
||||
docker network inspect kamco-cds | grep kamco-train-api
|
||||
|
||||
# 해결: API 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart
|
||||
```
|
||||
|
||||
### 2. SSL 인증서 오류
|
||||
|
||||
**원인**: 인증서 파일 누락 또는 권한 문제
|
||||
|
||||
```bash
|
||||
# 인증서 파일 확인
|
||||
ls -la nginx/ssl/
|
||||
|
||||
# Nginx 설정 검증
|
||||
docker exec kamco-train-nginx nginx -t
|
||||
|
||||
# 해결: 인증서 재배치 및 권한 설정
|
||||
chmod 600 nginx/ssl/train-kamco.com.key
|
||||
chmod 644 nginx/ssl/train-kamco.com.crt
|
||||
docker-compose -f docker-compose-nginx.yml restart
|
||||
```
|
||||
|
||||
### 3. 컨테이너 시작 실패
|
||||
|
||||
**원인**: 포트 충돌, 볼륨 권한, 메모리 부족
|
||||
|
||||
```bash
|
||||
# 포트 사용 확인
|
||||
netstat -tulpn | grep -E '80|443|8080'
|
||||
|
||||
# 볼륨 권한 확인
|
||||
ls -la ./app/
|
||||
|
||||
# 메모리 사용량 확인
|
||||
free -h
|
||||
docker system df
|
||||
|
||||
# 해결: 충돌 프로세스 종료 또는 포트 변경
|
||||
# 메모리 정리
|
||||
docker system prune -a
|
||||
```
|
||||
|
||||
### 4. 네트워크 연결 문제
|
||||
|
||||
**원인**: kamco-cds 네트워크 미생성 또는 컨테이너 미연결
|
||||
|
||||
```bash
|
||||
# 네트워크 확인
|
||||
docker network ls | grep kamco-cds
|
||||
|
||||
# 네트워크 상세 정보
|
||||
docker network inspect kamco-cds
|
||||
|
||||
# 해결: 네트워크 생성
|
||||
docker network create kamco-cds
|
||||
|
||||
# 컨테이너를 네트워크에 연결
|
||||
docker network connect kamco-cds kamco-train-api
|
||||
docker network connect kamco-cds kamco-train-nginx
|
||||
```
|
||||
|
||||
### 5. 데이터베이스 연결 실패
|
||||
|
||||
**원인**: application-prod.yml의 DB 설정 오류
|
||||
|
||||
```bash
|
||||
# API 로그에서 DB 연결 에러 확인
|
||||
docker logs kamco-train-api | grep -i "connection"
|
||||
|
||||
# DB 호스트 연결 테스트
|
||||
docker exec kamco-train-api ping <db-host>
|
||||
|
||||
# 해결: application-prod.yml 수정 후 재배포
|
||||
vim src/main/resources/application-prod.yml
|
||||
docker-compose -f docker-compose-prod.yml up -d --build
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Jenkins CI/CD 연동
|
||||
|
||||
현재 프로젝트는 Jenkins 파이프라인으로 자동 배포됩니다.
|
||||
|
||||
### Jenkinsfile-dev 주요 단계
|
||||
|
||||
1. **Checkout**: develop 브랜치 체크아웃
|
||||
2. **Build**: `./gradlew clean build -x test`
|
||||
3. **Extract Commit**: IMAGE_TAG로 사용
|
||||
4. **Transfer**: 배포 서버로 파일 전송
|
||||
5. **Deploy**: Docker Compose 빌드 및 배포
|
||||
6. **Health Check**: 30초 대기 후 헬스체크
|
||||
7. **Cleanup**: 오래된 이미지 정리 (최신 5개 유지)
|
||||
|
||||
### 배포 서버 정보
|
||||
|
||||
- **서버**: 192.168.2.109
|
||||
- **사용자**: space
|
||||
- **배포 경로**: `/home/space/kamco-training-api`
|
||||
- **헬스체크**: `http://localhost:7200/monitor/health`
|
||||
|
||||
---
|
||||
|
||||
## 백업 및 복구
|
||||
|
||||
### 데이터 백업
|
||||
|
||||
```bash
|
||||
# 볼륨 데이터 백업
|
||||
tar -czf backup-$(date +%Y%m%d).tar.gz ./app/model_output ./app/train_dataset
|
||||
|
||||
# 설정 파일 백업
|
||||
tar -czf config-backup-$(date +%Y%m%d).tar.gz \
|
||||
nginx/nginx.conf \
|
||||
nginx/ssl/ \
|
||||
src/main/resources/application-prod.yml
|
||||
```
|
||||
|
||||
### 이미지 백업
|
||||
|
||||
```bash
|
||||
# 현재 이미지 저장
|
||||
docker save kamco-train-api:latest | gzip > kamco-train-api-latest.tar.gz
|
||||
|
||||
# 이미지 복구
|
||||
gunzip -c kamco-train-api-latest.tar.gz | docker load
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 보안 체크리스트
|
||||
|
||||
- [ ] SSL 인증서 유효기간 확인
|
||||
- [ ] nginx/ssl/ 디렉토리 권한 600
|
||||
- [ ] application-prod.yml에 DB 비밀번호 암호화
|
||||
- [ ] JWT secret key 환경변수로 관리
|
||||
- [ ] Docker 소켓 권한 최소화
|
||||
- [ ] 방화벽 규칙 설정 (80, 443만 외부 노출)
|
||||
- [ ] 정기 보안 업데이트 (docker images)
|
||||
|
||||
---
|
||||
|
||||
## 참고 문서
|
||||
|
||||
- [CLAUDE.md](./CLAUDE.md) - 프로젝트 개발 가이드
|
||||
- [README.md](./README.md) - 프로젝트 개요
|
||||
- [Jenkinsfile-dev](./Jenkinsfile-dev) - CI/CD 파이프라인
|
||||
- [nginx/nginx.conf](./nginx/nginx.conf) - Nginx 설정
|
||||
|
||||
---
|
||||
|
||||
## 연락처
|
||||
|
||||
문제 발생 시:
|
||||
1. 로그 수집: `docker-compose logs` 출력
|
||||
2. 시스템 정보: `docker ps -a`, `docker network ls`
|
||||
3. 이슈 리포트: GitHub Issues 또는 내부 이슈 트래커
|
||||
20
Dockerfile
Normal file
20
Dockerfile
Normal file
@@ -0,0 +1,20 @@
|
||||
# Stage 1: Build stage (gradle build는 Jenkins에서 이미 수행)
|
||||
FROM eclipse-temurin:21-jre-jammy
|
||||
|
||||
# docker CLI 설치 (컨테이너에서 호스트 Docker 제어용) 260212 추가
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends docker.io ca-certificates && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 작업 디렉토리 설정
|
||||
WORKDIR /app
|
||||
|
||||
# JAR 파일 복사 (Jenkins에서 빌드된 ROOT.jar)
|
||||
COPY build/libs/ROOT.jar app.jar
|
||||
|
||||
# 포트 노출
|
||||
EXPOSE 8080
|
||||
|
||||
# 애플리케이션 실행
|
||||
# dev 프로파일로 실행
|
||||
ENTRYPOINT ["java", "-jar", "-Dspring.profiles.active=prod", "app.jar"]
|
||||
@@ -5,6 +5,13 @@ services:
|
||||
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:
|
||||
|
||||
28
docker-compose-nginx.yml
Normal file
28
docker-compose-nginx.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: kamco-train-nginx
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./nginx/ssl:/etc/nginx/ssl:ro
|
||||
- nginx-logs:/var/log/nginx
|
||||
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
|
||||
|
||||
volumes:
|
||||
nginx-logs:
|
||||
driver: local
|
||||
36
docker-compose-prod.yml
Normal file
36
docker-compose-prod.yml
Normal file
@@ -0,0 +1,36 @@
|
||||
services:
|
||||
kamco-train-api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: kamco-train-api:${IMAGE_TAG:-latest}
|
||||
container_name: kamco-train-api
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
expose:
|
||||
- "8080"
|
||||
environment:
|
||||
- SPRING_PROFILES_ACTIVE=prod
|
||||
- TZ=Asia/Seoul
|
||||
volumes:
|
||||
- ./app/model_output:/app/model-outputs
|
||||
- ./app/train_dataset:/app/train-dataset
|
||||
- /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
|
||||
414
nginx/SSL_SETUP.md
Normal file
414
nginx/SSL_SETUP.md
Normal file
@@ -0,0 +1,414 @@
|
||||
# SSL 사설 인증서 설정 가이드 (RedHat 9.6)
|
||||
|
||||
## 개요
|
||||
|
||||
이 문서는 RedHat 9.6 환경에서 `https://api.train-kamco.com` 및 `https://train-kamco.com` 도메인을 위한 100년 유효한 사설 SSL 인증서 설정 방법을 설명합니다.
|
||||
|
||||
## 디렉토리 구조
|
||||
|
||||
```
|
||||
nginx/
|
||||
├── nginx.conf # Nginx 설정 파일
|
||||
├── ssl/
|
||||
│ ├── openssl.cnf # OpenSSL 설정 파일 (SAN 포함)
|
||||
│ ├── train-kamco.com.crt # 사설 SSL 인증서 (멀티 도메인)
|
||||
│ └── train-kamco.com.key # 개인 키 (비공개)
|
||||
└── SSL_SETUP.md # 이 문서
|
||||
```
|
||||
|
||||
## 인증서 정보
|
||||
|
||||
- **도메인**: api.train-kamco.com, train-kamco.com (멀티 도메인)
|
||||
- **유효 기간**: 100년 (36500일)
|
||||
- **알고리즘**: RSA 4096-bit
|
||||
- **CN (Common Name)**: api.train-kamco.com
|
||||
- **SAN (Subject Alternative Names)**: api.train-kamco.com, train-kamco.com
|
||||
|
||||
## 사설 SSL 인증서 생성 (이미 생성됨)
|
||||
|
||||
인증서가 이미 생성되어 있습니다. 재생성이 필요한 경우 아래 단계를 따르세요.
|
||||
|
||||
### 1. OpenSSL 설정 파일 생성
|
||||
|
||||
```bash
|
||||
cd /path/to/kamco-train-api
|
||||
|
||||
cat > nginx/ssl/openssl.cnf << 'EOF'
|
||||
[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
|
||||
EOF
|
||||
```
|
||||
|
||||
### 2. SSL 인증서 및 개인 키 생성
|
||||
|
||||
```bash
|
||||
# nginx/ssl 디렉토리 생성 (없는 경우)
|
||||
mkdir -p nginx/ssl
|
||||
chmod 700 nginx/ssl
|
||||
|
||||
# 인증서 및 개인 키 생성 (100년 유효)
|
||||
openssl req -new -x509 -newkey rsa:4096 -sha256 -nodes \
|
||||
-keyout nginx/ssl/train-kamco.com.key \
|
||||
-out nginx/ssl/train-kamco.com.crt \
|
||||
-days 36500 \
|
||||
-config nginx/ssl/openssl.cnf \
|
||||
-extensions v3_req
|
||||
|
||||
# 파일 권한 설정
|
||||
chmod 600 nginx/ssl/train-kamco.com.key
|
||||
chmod 644 nginx/ssl/train-kamco.com.crt
|
||||
```
|
||||
|
||||
### 3. 인증서 검증
|
||||
|
||||
```bash
|
||||
# 인증서 정보 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -text -noout
|
||||
|
||||
# 유효 기간 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -text -noout | grep -A2 "Validity"
|
||||
|
||||
# SAN (멀티 도메인) 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -text -noout | grep -A1 "Subject Alternative Name"
|
||||
|
||||
# CN 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -noout -subject
|
||||
|
||||
# 개인 키 확인
|
||||
openssl rsa -in nginx/ssl/train-kamco.com.key -check
|
||||
```
|
||||
|
||||
**예상 결과**:
|
||||
```
|
||||
X509v3 Subject Alternative Name:
|
||||
DNS:api.train-kamco.com, DNS:train-kamco.com
|
||||
|
||||
Validity
|
||||
Not Before: Mar 2 23:39:XX 2026 GMT
|
||||
Not After : Feb 6 23:39:XX 2126 GMT
|
||||
```
|
||||
|
||||
## /etc/hosts 설정 (RedHat 9.6)
|
||||
|
||||
### 1. hosts 파일에 도메인 추가
|
||||
|
||||
```bash
|
||||
# root 권한으로 실행
|
||||
echo "127.0.0.1 api.train-kamco.com train-kamco.com" | sudo tee -a /etc/hosts
|
||||
|
||||
# 확인
|
||||
cat /etc/hosts | grep train-kamco
|
||||
```
|
||||
|
||||
**예상 결과**:
|
||||
```
|
||||
127.0.0.1 api.train-kamco.com train-kamco.com
|
||||
```
|
||||
|
||||
### 2. 도메인 확인
|
||||
|
||||
```bash
|
||||
# ping 테스트
|
||||
ping -c 2 api.train-kamco.com
|
||||
ping -c 2 train-kamco.com
|
||||
```
|
||||
|
||||
## Docker Compose 배포
|
||||
|
||||
### 1. 기존 컨테이너 중지 (실행 중인 경우)
|
||||
|
||||
```bash
|
||||
cd /path/to/kamco-train-api
|
||||
docker-compose -f docker-compose-prod.yml down
|
||||
```
|
||||
|
||||
### 2. Production 환경 실행
|
||||
|
||||
```bash
|
||||
# IMAGE_TAG 환경 변수 설정 (선택사항)
|
||||
export IMAGE_TAG=latest
|
||||
|
||||
# Docker Compose 실행
|
||||
docker-compose -f docker-compose-prod.yml up -d
|
||||
|
||||
# 컨테이너 상태 확인
|
||||
docker-compose -f docker-compose-prod.yml ps
|
||||
```
|
||||
|
||||
### 3. 로그 확인
|
||||
|
||||
```bash
|
||||
# Nginx 로그
|
||||
docker logs kamco-cd-nginx
|
||||
|
||||
# API 로그
|
||||
docker logs kamco-cd-training-api
|
||||
|
||||
# 실시간 로그 확인
|
||||
docker-compose -f docker-compose-prod.yml logs -f
|
||||
```
|
||||
|
||||
## HTTPS 접속 테스트
|
||||
|
||||
### 1. HTTP → HTTPS 리다이렉트 테스트
|
||||
|
||||
```bash
|
||||
# api.train-kamco.com
|
||||
curl -I http://api.train-kamco.com
|
||||
|
||||
# train-kamco.com
|
||||
curl -I http://train-kamco.com
|
||||
|
||||
# 예상 결과: 301 Moved Permanently
|
||||
# Location: https://api.train-kamco.com/ 또는 https://train-kamco.com/
|
||||
```
|
||||
|
||||
### 2. HTTPS 헬스체크 (-k: 사설 인증서 경고 무시)
|
||||
|
||||
```bash
|
||||
# api.train-kamco.com
|
||||
curl -k https://api.train-kamco.com/monitor/health
|
||||
|
||||
# train-kamco.com
|
||||
curl -k https://train-kamco.com/monitor/health
|
||||
|
||||
# 예상 결과: {"status":"UP","components":{...}}
|
||||
```
|
||||
|
||||
### 3. SSL 인증서 확인
|
||||
|
||||
```bash
|
||||
# api.train-kamco.com
|
||||
openssl s_client -connect api.train-kamco.com:443 -showcerts
|
||||
|
||||
# train-kamco.com
|
||||
openssl s_client -connect train-kamco.com:443 -showcerts
|
||||
|
||||
# CN 및 SAN 확인
|
||||
```
|
||||
|
||||
### 4. 브라우저 테스트
|
||||
|
||||
브라우저에서 다음 URL에 접속:
|
||||
|
||||
- `https://api.train-kamco.com/monitor/health`
|
||||
- `https://train-kamco.com/monitor/health`
|
||||
|
||||
**주의**: 사설 인증서이므로 "안전하지 않음" 경고가 표시됩니다.
|
||||
- **Chrome/Edge**: "고급" → "계속 진행" 클릭
|
||||
- **Firefox**: "위험 감수 및 계속" 클릭
|
||||
|
||||
## 브라우저에서 사설 인증서 신뢰 설정 (선택사항)
|
||||
|
||||
사설 인증서를 브라우저에 등록하면 경고 없이 접속 가능합니다.
|
||||
|
||||
### Chrome/Edge (RedHat Desktop)
|
||||
|
||||
1. `chrome://settings/certificates` 접속
|
||||
2. **Authorities** 탭 선택
|
||||
3. **Import** 클릭
|
||||
4. `nginx/ssl/train-kamco.com.crt` 선택
|
||||
5. **Trust this certificate for identifying websites** 체크
|
||||
6. **OK** 클릭
|
||||
|
||||
### Firefox
|
||||
|
||||
1. `about:preferences#privacy` 접속
|
||||
2. **Certificates** → **View Certificates** 클릭
|
||||
3. **Authorities** 탭 선택
|
||||
4. **Import** 클릭
|
||||
5. `nginx/ssl/train-kamco.com.crt` 선택
|
||||
6. **Trust this CA to identify websites** 체크
|
||||
7. **OK** 클릭
|
||||
|
||||
## 방화벽 설정 (RedHat 9.6)
|
||||
|
||||
### 1. 방화벽 상태 확인
|
||||
|
||||
```bash
|
||||
sudo firewall-cmd --state
|
||||
```
|
||||
|
||||
### 2. HTTP (80) 및 HTTPS (443) 포트 개방
|
||||
|
||||
```bash
|
||||
# HTTP 포트 개방
|
||||
sudo firewall-cmd --permanent --add-port=80/tcp
|
||||
|
||||
# HTTPS 포트 개방
|
||||
sudo firewall-cmd --permanent --add-port=443/tcp
|
||||
|
||||
# 방화벽 재로드
|
||||
sudo firewall-cmd --reload
|
||||
|
||||
# 확인
|
||||
sudo firewall-cmd --list-ports
|
||||
```
|
||||
|
||||
**예상 결과**:
|
||||
```
|
||||
80/tcp 443/tcp
|
||||
```
|
||||
|
||||
## 보안 체크리스트
|
||||
|
||||
- [x] `train-kamco.com.key` 파일 권한이 600으로 설정됨
|
||||
- [x] ssl 디렉토리가 버전 관리에서 제외됨 (.gitignore 확인)
|
||||
- [x] 두 도메인(api.train-kamco.com, train-kamco.com) 모두 SAN에 포함됨
|
||||
- [ ] 방화벽에서 80, 443 포트 개방 확인
|
||||
- [x] HSTS 헤더 활성화 확인
|
||||
- [x] TLS 1.2 이상만 허용 확인
|
||||
- [ ] /etc/hosts에 도메인 매핑 확인
|
||||
|
||||
## 트러블슈팅
|
||||
|
||||
### 인증서 관련 오류
|
||||
|
||||
**"certificate verify failed"**
|
||||
```bash
|
||||
# 해결: -k 플래그 사용 (사설 인증서 경고 무시)
|
||||
curl -k https://api.train-kamco.com/monitor/health
|
||||
```
|
||||
|
||||
**"NET::ERR_CERT_AUTHORITY_INVALID" (브라우저)**
|
||||
- 정상 동작: 사설 인증서이므로 브라우저 경고는 예상된 동작입니다
|
||||
- 해결: 브라우저에 인증서 등록 (위 "브라우저에서 사설 인증서 신뢰 설정" 참조)
|
||||
|
||||
### 연결 오류
|
||||
|
||||
**"Connection refused"**
|
||||
```bash
|
||||
# 컨테이너 상태 확인
|
||||
docker ps | grep kamco-cd
|
||||
|
||||
# 포트 바인딩 확인
|
||||
docker port kamco-cd-nginx
|
||||
|
||||
# 예상 결과:
|
||||
# 80/tcp -> 0.0.0.0:80
|
||||
# 443/tcp -> 0.0.0.0:443
|
||||
```
|
||||
|
||||
**"502 Bad Gateway"**
|
||||
```bash
|
||||
# API 컨테이너 상태 확인
|
||||
docker logs kamco-cd-training-api
|
||||
|
||||
# nginx → API 연결 확인
|
||||
docker exec kamco-cd-nginx wget -qO- http://kamco-changedetection-api:8080/monitor/health
|
||||
```
|
||||
|
||||
**"Name or service not known" (도메인 해석 실패)**
|
||||
```bash
|
||||
# /etc/hosts 확인
|
||||
cat /etc/hosts | grep train-kamco
|
||||
|
||||
# 없으면 추가
|
||||
echo "127.0.0.1 api.train-kamco.com train-kamco.com" | sudo tee -a /etc/hosts
|
||||
```
|
||||
|
||||
### 방화벽 관련 오류
|
||||
|
||||
**외부에서 접속 안 됨**
|
||||
```bash
|
||||
# 방화벽 확인
|
||||
sudo firewall-cmd --list-ports
|
||||
|
||||
# 포트 개방
|
||||
sudo firewall-cmd --permanent --add-port=80/tcp
|
||||
sudo firewall-cmd --permanent --add-port=443/tcp
|
||||
sudo firewall-cmd --reload
|
||||
```
|
||||
|
||||
## 인증서 만료 및 갱신
|
||||
|
||||
### 만료 확인
|
||||
|
||||
```bash
|
||||
# 인증서 만료일 확인
|
||||
openssl x509 -in nginx/ssl/train-kamco.com.crt -noout -enddate
|
||||
|
||||
# 예상 결과: notAfter=Feb 6 23:39:XX 2126 GMT (100년 후)
|
||||
```
|
||||
|
||||
### 갱신 방법 (필요시)
|
||||
|
||||
100년 유효한 인증서이므로 갱신이 필요하지 않지만, 재생성이 필요한 경우:
|
||||
|
||||
```bash
|
||||
# 기존 인증서 백업
|
||||
cp nginx/ssl/train-kamco.com.crt nginx/ssl/train-kamco.com.crt.bak
|
||||
cp nginx/ssl/train-kamco.com.key nginx/ssl/train-kamco.com.key.bak
|
||||
|
||||
# 위의 "사설 SSL 인증서 생성" 단계 재실행
|
||||
|
||||
# nginx 재시작
|
||||
docker-compose -f docker-compose-prod.yml restart nginx
|
||||
```
|
||||
|
||||
## 주의사항
|
||||
|
||||
1. **사설 인증서 경고**: 브라우저에서 "안전하지 않음" 경고가 표시됩니다. 프로덕션 환경에서는 **공인 인증서(Let's Encrypt, GlobalSign 등) 사용을 권장**합니다.
|
||||
|
||||
2. **포트 80/443**: Docker가 자동으로 처리하지만, 이미 사용 중인 프로세스가 있으면 충돌할 수 있습니다.
|
||||
```bash
|
||||
# 포트 사용 확인
|
||||
sudo lsof -i :80
|
||||
sudo lsof -i :443
|
||||
```
|
||||
|
||||
3. **대용량 파일 업로드**: `client_max_body_size`를 10GB로 설정했으므로, 서버 메모리 및 디스크 용량을 충분히 확보하세요.
|
||||
|
||||
4. **인증서 백업**: `train-kamco.com.key` 파일은 매우 중요합니다. 안전한 곳에 백업하세요.
|
||||
|
||||
5. **SELinux**: RedHat 9.6에서 SELinux가 활성화된 경우, Docker 볼륨 마운트 권한 문제가 발생할 수 있습니다.
|
||||
```bash
|
||||
# SELinux 상태 확인
|
||||
getenforce
|
||||
|
||||
# 필요시 permissive 모드로 변경
|
||||
sudo setenforce 0
|
||||
```
|
||||
|
||||
|
||||
### 2단계: 시스템 신뢰 폴더로 복사
|
||||
터미널을 열고 관리자 권한(sudo)을 사용해 인증서를 시스템 폴더로 복사합니다.
|
||||
|
||||
```
|
||||
sudo cp mycert.crt /etc/pki/ca-trust/source/anchors/
|
||||
```
|
||||
|
||||
### 3단계: 시스템 신뢰 목록 업데이트
|
||||
아래 명령어를 입력해 추가한 인증서를 시스템에 갱신시킵니다.
|
||||
|
||||
```
|
||||
sudo update-ca-trust
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 참고 자료
|
||||
|
||||
- [OpenSSL Documentation](https://www.openssl.org/docs/)
|
||||
- [Nginx SSL Configuration](https://nginx.org/en/docs/http/configuring_https_servers.html)
|
||||
- [Docker Compose Documentation](https://docs.docker.com/compose/)
|
||||
- [Let's Encrypt (공인 인증서)](https://letsencrypt.org/)
|
||||
179
nginx/nginx.conf
Normal file
179
nginx/nginx.conf
Normal file
@@ -0,0 +1,179 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +125,7 @@ public class CommonCodeService {
|
||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 공통코드 이름 조회
|
||||
*
|
||||
@@ -136,6 +137,8 @@ public class CommonCodeService {
|
||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
public List<CodeDto> getTypeCode(String type) {
|
||||
return Enums.getCodes(type);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.common.download;
|
||||
|
||||
import com.kamco.cd.training.common.download.dto.DownloadSpec;
|
||||
@@ -46,3 +47,4 @@ public class DownloadExecutor {
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.common.download;
|
||||
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
@@ -17,3 +18,4 @@ public final class DownloadPaths {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.kamco.cd.training.common.dto;
|
||||
|
||||
public class MonitorDto {
|
||||
|
||||
public int cpu; // CPU 사용률 (%)
|
||||
public long[] memory; // "사용/전체"
|
||||
public int gpu; // 🔥 전체 GPU 평균 (%)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.common.enums;
|
||||
|
||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||
@@ -17,3 +18,4 @@ public enum DeployTargetType implements EnumType {
|
||||
private final String id;
|
||||
private final String text;
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.common.enums;
|
||||
|
||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||
@@ -25,3 +26,4 @@ public enum ModelMngStatusType implements EnumType {
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.common.enums;
|
||||
|
||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||
@@ -18,3 +19,4 @@ public enum ProcessStepType implements EnumType {
|
||||
private final String id;
|
||||
private final String text;
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.kamco.cd.training.common.service;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Log4j2
|
||||
public class GpuDmonReader {
|
||||
|
||||
// =========================
|
||||
// GPU 사용률 저장소
|
||||
// key: GPU index (0,1,2...)
|
||||
// value: 현재 GPU 사용률 (%)
|
||||
// ConcurrentHashMap → 멀티스레드 안전
|
||||
// =========================
|
||||
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
||||
|
||||
// =========================
|
||||
// 외부 조회용
|
||||
// SystemMonitorService에서 호출
|
||||
// =========================
|
||||
public Map<Integer, Integer> getGpuUtilMap() {
|
||||
return gpuUtilMap;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Bean 초기화 시 실행
|
||||
// - 별도 스레드에서 GPU 모니터링 시작
|
||||
// - 메인 스레드 block 방지
|
||||
// =========================
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
|
||||
// nvidia-smi 없는 환경이면 GPU 모니터링 비활성화
|
||||
if (!isNvidiaAvailable()) {
|
||||
log.warn("nvidia-smi not found. GPU monitoring disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 데몬 스레드로 실행 (서버 종료 시 자동 종료)
|
||||
Thread t = new Thread(this::runLoop, "gpu-dmon-thread");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 무한 루프
|
||||
// - dmon 실행
|
||||
// - 죽으면 자동 재시작
|
||||
// =========================
|
||||
private void runLoop() {
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
runDmon(); // GPU 사용률 수집 시작
|
||||
} catch (Exception e) {
|
||||
// dmon 프로세스 종료되면 여기로 들어옴
|
||||
log.warn("dmon restart: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 5초 대기 후 재시작
|
||||
sleep(5000);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi dmon 실행
|
||||
// - GPU 사용률 스트리밍으로 계속 수신
|
||||
// =========================
|
||||
private void runDmon() throws Exception {
|
||||
|
||||
// -s u → GPU utilization만 출력
|
||||
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
||||
|
||||
// 프로세스 실행 후 stdout 읽기
|
||||
try (BufferedReader br =
|
||||
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
||||
|
||||
String line;
|
||||
|
||||
// dmon은 계속 출력됨 (스트리밍)
|
||||
while ((line = br.readLine()) != null) {
|
||||
|
||||
// 헤더 제거 (#로 시작)
|
||||
if (line.startsWith("#")) continue;
|
||||
|
||||
line = line.trim();
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
// 공백 기준 분리
|
||||
String[] parts = line.split("\\s+");
|
||||
|
||||
// 첫 번째 값이 GPU index인지 확인
|
||||
if (!parts[0].matches("\\d+")) continue;
|
||||
|
||||
int index = Integer.parseInt(parts[0]);
|
||||
|
||||
try {
|
||||
// 두 번째 값이 GPU 사용률 (sm)
|
||||
int util = Integer.parseInt(parts[1]);
|
||||
|
||||
// 최신 값 갱신
|
||||
gpuUtilMap.put(index, util);
|
||||
|
||||
} catch (Exception ignored) {
|
||||
// 파싱 실패 시 무시
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||
// → runLoop에서 재시작하도록 예외 발생
|
||||
throw new IllegalStateException("dmon stopped");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi 존재 여부 확인
|
||||
// =========================
|
||||
private boolean isNvidiaAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder("which", "nvidia-smi").start();
|
||||
return p.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// sleep 유틸
|
||||
// =========================
|
||||
private void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.kamco.cd.training.common.service;
|
||||
|
||||
import com.kamco.cd.training.common.dto.MonitorDto;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Log4j2
|
||||
public class SystemMonitorService {
|
||||
|
||||
// =========================
|
||||
// CPU 이전값 (delta 계산용)
|
||||
// - /proc/stat은 누적값이기 때문에
|
||||
// - 이전 값과 비교해서 사용률 계산
|
||||
// =========================
|
||||
private long prevIdle = 0;
|
||||
private long prevTotal = 0;
|
||||
|
||||
// =========================
|
||||
// 최근 30초 히스토리
|
||||
// - CPU: 30개 (1초 * 30)
|
||||
// - GPU: GPU별 30개
|
||||
// =========================
|
||||
private final Deque<Double> cpuHistory = new ArrayDeque<>();
|
||||
|
||||
// key: GPU index
|
||||
// value: 최근 30개 사용률
|
||||
private final Map<Integer, Deque<Integer>> gpuHistory = new ConcurrentHashMap<>();
|
||||
|
||||
// =========================
|
||||
// GPU 데이터 제공 (dmon reader)
|
||||
// =========================
|
||||
private final GpuDmonReader gpuReader;
|
||||
|
||||
// =========================
|
||||
// 캐시 (API 응답용)
|
||||
// - 매 요청마다 계산하지 않기 위해 사용
|
||||
// - volatile → 멀티스레드 안전하게 최신값 유지
|
||||
// =========================
|
||||
private volatile MonitorDto cached = new MonitorDto();
|
||||
|
||||
// =========================
|
||||
// 1초마다 수집
|
||||
// =========================
|
||||
@Scheduled(fixedRate = 1000)
|
||||
public void collect() {
|
||||
try {
|
||||
|
||||
// =====================
|
||||
// 1. CPU 수집
|
||||
// =====================
|
||||
double cpu = readCpu();
|
||||
|
||||
cpuHistory.add(cpu);
|
||||
|
||||
// 30개 유지 (rolling window)
|
||||
if (cpuHistory.size() > 30) cpuHistory.poll();
|
||||
|
||||
// =====================
|
||||
// 2. GPU 수집
|
||||
// =====================
|
||||
Map<Integer, Integer> gpuMap = gpuReader.getGpuUtilMap();
|
||||
|
||||
for (Map.Entry<Integer, Integer> entry : gpuMap.entrySet()) {
|
||||
|
||||
int index = entry.getKey();
|
||||
int util = entry.getValue();
|
||||
|
||||
// GPU별 히스토리 생성 및 추가
|
||||
gpuHistory.computeIfAbsent(index, k -> new ArrayDeque<>()).add(util);
|
||||
|
||||
// 30개 유지
|
||||
Deque<Integer> q = gpuHistory.get(index);
|
||||
if (q.size() > 30) q.poll();
|
||||
}
|
||||
|
||||
// =====================
|
||||
// 3. 캐시 업데이트
|
||||
// =====================
|
||||
updateCache();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("collect error", e);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// CPU 사용률 계산
|
||||
// - /proc/stat 사용
|
||||
// - 이전값과의 차이로 계산 (delta 방식)
|
||||
// =========================
|
||||
private double readCpu() throws Exception {
|
||||
|
||||
if (!isLinux()) return 0;
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("/proc/stat"))) {
|
||||
|
||||
String[] p = br.readLine().split("\\s+");
|
||||
|
||||
long user = Long.parseLong(p[1]);
|
||||
long nice = Long.parseLong(p[2]);
|
||||
long system = Long.parseLong(p[3]);
|
||||
long idle = Long.parseLong(p[4]);
|
||||
long iowait = Long.parseLong(p[5]);
|
||||
long irq = Long.parseLong(p[6]);
|
||||
long softirq = Long.parseLong(p[7]);
|
||||
|
||||
long total = user + nice + system + idle + iowait + irq + softirq;
|
||||
long idleAll = idle + iowait;
|
||||
|
||||
// 최초 실행 시 기준값만 저장
|
||||
if (prevTotal == 0) {
|
||||
prevTotal = total;
|
||||
prevIdle = idleAll;
|
||||
return 0;
|
||||
}
|
||||
|
||||
long totalDiff = total - prevTotal;
|
||||
long idleDiff = idleAll - prevIdle;
|
||||
|
||||
prevTotal = total;
|
||||
prevIdle = idleAll;
|
||||
|
||||
if (totalDiff == 0) return 0;
|
||||
|
||||
// CPU 사용률 (%)
|
||||
return (1.0 - (double) idleDiff / totalDiff) * 100;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Linux 환경 체크
|
||||
// =========================
|
||||
private boolean isLinux() {
|
||||
return System.getProperty("os.name").toLowerCase().contains("linux");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Memory 조회 (/proc/meminfo)
|
||||
// - OS 값 그대로 사용 (kB)
|
||||
// - [사용량, 전체]
|
||||
// =========================
|
||||
private long[] readMemory() throws Exception {
|
||||
|
||||
if (!isLinux()) return new long[] {0, 0};
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("/proc/meminfo"))) {
|
||||
|
||||
long total = 0;
|
||||
long available = 0;
|
||||
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (line.startsWith("MemTotal")) {
|
||||
total = Long.parseLong(line.replaceAll("\\D+", ""));
|
||||
} else if (line.startsWith("MemAvailable")) {
|
||||
available = Long.parseLong(line.replaceAll("\\D+", ""));
|
||||
}
|
||||
}
|
||||
|
||||
long used = total - available;
|
||||
|
||||
return new long[] {used, total};
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 캐시 업데이트
|
||||
// - CPU: 30초 평균
|
||||
// - GPU: 전체 샘플 평균
|
||||
// - Memory: 현재값
|
||||
// =========================
|
||||
private void updateCache() throws Exception {
|
||||
|
||||
MonitorDto dto = new MonitorDto();
|
||||
|
||||
// =====================
|
||||
// CPU 평균 (30초)
|
||||
// =====================
|
||||
dto.cpu = (int) cpuHistory.stream().mapToDouble(Double::doubleValue).average().orElse(0);
|
||||
|
||||
// =====================
|
||||
// Memory (kB 그대로)
|
||||
// =====================
|
||||
dto.memory = readMemory();
|
||||
|
||||
// =====================
|
||||
// GPU 평균 (🔥 전체 샘플 기준)
|
||||
// =====================
|
||||
int sum = 0;
|
||||
int count = 0;
|
||||
|
||||
for (Deque<Integer> q : gpuHistory.values()) {
|
||||
for (int v : q) {
|
||||
sum += v;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
dto.gpu = (count == 0) ? 0 : sum / count;
|
||||
|
||||
// =====================
|
||||
// 캐시 교체 (atomic)
|
||||
// =====================
|
||||
this.cached = dto;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 외부 조회
|
||||
// - Controller에서 호출
|
||||
// =========================
|
||||
public MonitorDto get() {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
@@ -20,4 +20,18 @@ public class AsyncConfig {
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Bean("datasetExecutor")
|
||||
public Executor datasetExecutor() {
|
||||
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
|
||||
executor.setCorePoolSize(5);
|
||||
executor.setMaxPoolSize(10);
|
||||
executor.setQueueCapacity(100);
|
||||
executor.setThreadNamePrefix("dataset-");
|
||||
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ public class OpenApiConfig {
|
||||
@Value("${swagger.dev-url:https://kamco.training-dev-api.gs.dabeeo.com}")
|
||||
private String devUrl;
|
||||
|
||||
@Value("${swagger.prod-url:https://api.training-kamco.com}")
|
||||
@Value("${swagger.prod-url:https://api.train-kamco.com}")
|
||||
private String prodUrl;
|
||||
|
||||
@Bean
|
||||
@@ -53,10 +53,10 @@ public class OpenApiConfig {
|
||||
} else if ("prod".equals(profile)) {
|
||||
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
||||
servers.add(new Server().url(devUrl).description("개발 서버"));
|
||||
servers.add(new Server().url(prodUrl).description("개발 서버"));
|
||||
} else {
|
||||
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
||||
servers.add(new Server().url(devUrl).description("개발 서버"));
|
||||
servers.add(new Server().url(devUrl).description("운영 서버"));
|
||||
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||
}
|
||||
|
||||
|
||||
@@ -104,15 +104,19 @@ public class SecurityConfig {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
/** CORS 설정 */
|
||||
/** CORS 설정 - application.yml에서 환경별로 관리 */
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration(); // CORS 객체 생성
|
||||
|
||||
// application.yml에서 환경별로 설정된 도메인 사용
|
||||
config.setAllowedOriginPatterns(List.of("*")); // 도메인 허용
|
||||
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*")); // 헤더요청 Authorization, Content-Type, X-Custom-Header
|
||||
config.setAllowCredentials(true); // 쿠키, Authorization 헤더, Bearer Token 등 자격증명 포함 요청을 허용할지 설정
|
||||
config.setExposedHeaders(List.of("Content-Disposition"));
|
||||
config.setExposedHeaders(List.of("Content-Disposition", "Authorization"));
|
||||
config.setMaxAge(3600L); // Preflight 요청 캐시 (1시간)
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
/** "/**" → 모든 API 경로에 대해 이 CORS 규칙을 적용 /api/** 같이 특정 경로만 지정 가능. */
|
||||
@@ -133,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/**");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ public class StartupLogger {
|
||||
"""
|
||||
|
||||
╔════════════════════════════════════════════════════════════════════════════════╗
|
||||
║ 🚀 APPLICATION STARTUP INFORMATION ║
|
||||
║ 🚀 APPLICATION STARTUP INFORMATION 3 ║
|
||||
╠════════════════════════════════════════════════════════════════════════════════╣
|
||||
║ PROFILE CONFIGURATION ║
|
||||
╠────────────────────────────────────────────────────────────────────────────────╣
|
||||
|
||||
@@ -16,6 +16,12 @@ public class ApiLogFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri.contains("/download/")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
|
||||
|
||||
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
|
||||
|
||||
@@ -2,10 +2,14 @@ package com.kamco.cd.training.dataset;
|
||||
|
||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
||||
import com.kamco.cd.training.dataset.service.DatasetAsyncService;
|
||||
import com.kamco.cd.training.dataset.service.DatasetService;
|
||||
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
||||
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -33,6 +37,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
public class DatasetApiController {
|
||||
|
||||
private final DatasetService datasetService;
|
||||
private final DatasetAsyncService datasetAsyncService;
|
||||
|
||||
@Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
|
||||
@ApiResponses(
|
||||
@@ -248,4 +253,48 @@ public class DatasetApiController {
|
||||
String path = datasetService.getFilePathByUUIDPathType(uuid, pathType);
|
||||
return datasetService.getFilePathByFile(path);
|
||||
}
|
||||
|
||||
@Operation(summary = "납품 폴더 조회", description = "납품 폴더 조회 API")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "조회 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = FoldersDto.class))),
|
||||
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@PostMapping("/folder-list")
|
||||
public ApiResponseDto<FoldersDto> getDir(@RequestBody SrchFoldersDto srchDto) throws IOException {
|
||||
|
||||
return ApiResponseDto.createOK(datasetService.getFolderAll(srchDto));
|
||||
}
|
||||
|
||||
@Operation(summary = "납품 학습데이터셋 등록", description = "납품 학습데이터셋 등록 API")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "등록 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = String.class))),
|
||||
@ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@PostMapping("/deliveries")
|
||||
public ApiResponseDto<String> insertDeliveriesDataset(@RequestBody AddDeliveriesReq req) {
|
||||
|
||||
// 폴더 구조 검증
|
||||
DatasetService.validateTrainValTestDirs(req.getFilePath());
|
||||
// 파일 개수 검증
|
||||
DatasetService.validateDirFileCount(req.getFilePath());
|
||||
|
||||
datasetAsyncService.insertDeliveriesDatasetAsync(req);
|
||||
return ApiResponseDto.createOK("ok");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ public class DatasetDto {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Schema(name = "DatasetDetailReq", description = "데이터셋 상세 조회 요청")
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -157,6 +158,8 @@ public class DatasetDto {
|
||||
private Long datasetId;
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Schema(name = "DatasetRegisterReq", description = "데이터셋 등록 요청")
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -245,12 +248,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,
|
||||
@@ -263,6 +267,7 @@ public class DatasetDto {
|
||||
Integer targetYyyy,
|
||||
String memo,
|
||||
Long classCount) {
|
||||
this.modelNo = modelNo;
|
||||
this.datasetId = datasetId;
|
||||
this.uuid = uuid;
|
||||
this.dataType = dataType;
|
||||
@@ -277,6 +282,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,8 +297,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;
|
||||
@@ -532,4 +540,28 @@ public class DatasetDto {
|
||||
private Long totalObjectCount;
|
||||
private String datasetPath;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class AddDeliveriesReq {
|
||||
@Schema(description = "경로", example = "/")
|
||||
private String filePath;
|
||||
|
||||
@Schema(description = "제목", example = "")
|
||||
private String title;
|
||||
|
||||
@Schema(description = "메모", example = "")
|
||||
private String memo;
|
||||
|
||||
@Schema(description = "비교년도", example = "")
|
||||
private Integer compareYyyy;
|
||||
|
||||
@Schema(description = "기준년도", example = "")
|
||||
private Integer targetYyyy;
|
||||
|
||||
@Schema(description = "회차", example = "")
|
||||
private Long roundNo;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.dataset.dto;
|
||||
|
||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||
@@ -72,6 +73,7 @@ public class MapSheetDto {
|
||||
private List<Long> itemIds;
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Schema(name = "MapSheetCheckReq", description = "도엽 번호 유효성 검증 요청")
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -101,3 +103,4 @@ public class MapSheetDto {
|
||||
private boolean duplicate;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.kamco.cd.training.dataset.service;
|
||||
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
@RequiredArgsConstructor
|
||||
public class DatasetAsyncService {
|
||||
|
||||
private final DatasetService datasetService;
|
||||
private final DatasetCoreService datasetCoreService;
|
||||
|
||||
private static final String LOG_PREFIX = "[납품 데이터셋]";
|
||||
|
||||
/**
|
||||
* 납품 데이터셋 등록 비동기 업로드 처리 1) 데이터셋 구조/파일 검증 2) UID 생성 및 마스터 데이터 저장 3) 상태를 UPLOADING으로 변경 4) 실제
|
||||
* 데이터(train/val/test) 등록 5) 완료 시 COMPLETED 상태로 변경 6) 실패 시 상태를 UPLOAD_FAILED로 변경 후 데이터 정리(삭제)
|
||||
*
|
||||
* @param req
|
||||
*/
|
||||
@Async("datasetExecutor")
|
||||
public void insertDeliveriesDatasetAsync(AddDeliveriesReq req) {
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
log.info("{} 업로드 시작 ==========", LOG_PREFIX);
|
||||
log.info(
|
||||
"{} filePath={}, targetYyyy={}, compareYyyy={}, roundNo={}",
|
||||
LOG_PREFIX,
|
||||
req.getFilePath(),
|
||||
req.getTargetYyyy(),
|
||||
req.getCompareYyyy(),
|
||||
req.getRoundNo());
|
||||
|
||||
Long datasetUid = null;
|
||||
|
||||
try {
|
||||
|
||||
// ===== 1. UID 생성 =====
|
||||
String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
|
||||
log.info("{} 생성된 UID: {}", LOG_PREFIX, uid);
|
||||
|
||||
// ===== 2. 마스터 데이터 생성 =====
|
||||
String title = req.getTitle();
|
||||
|
||||
if (title == null || title.isBlank()) {
|
||||
Integer compareYyyy = req.getCompareYyyy();
|
||||
Integer targetYyyy = req.getTargetYyyy();
|
||||
|
||||
if (compareYyyy != null && targetYyyy != null) {
|
||||
title = compareYyyy + "-" + targetYyyy;
|
||||
} else {
|
||||
title = null;
|
||||
}
|
||||
}
|
||||
|
||||
DatasetMngRegDto datasetMngRegDto = new DatasetMngRegDto();
|
||||
datasetMngRegDto.setUid(uid);
|
||||
datasetMngRegDto.setDataType("DELIVER");
|
||||
datasetMngRegDto.setCompareYyyy(req.getCompareYyyy() == null ? 0 : req.getCompareYyyy());
|
||||
datasetMngRegDto.setTargetYyyy(req.getTargetYyyy() == null ? 0 : req.getTargetYyyy());
|
||||
datasetMngRegDto.setRoundNo(req.getRoundNo());
|
||||
datasetMngRegDto.setTitle(title);
|
||||
datasetMngRegDto.setMemo(req.getMemo());
|
||||
datasetMngRegDto.setDatasetPath(req.getFilePath());
|
||||
|
||||
// 마스터 저장
|
||||
datasetUid = datasetCoreService.insertDatasetMngData(datasetMngRegDto);
|
||||
|
||||
log.info("{} 마스터 저장 완료. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||
|
||||
// ===== 3. 상태 변경 (업로드중) =====
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.UPLOADING);
|
||||
log.info("{} 상태 변경 → UPLOADING. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||
|
||||
// ===== 4. 데이터 등록 =====
|
||||
long insertStart = System.currentTimeMillis();
|
||||
|
||||
// 납품 데이터 obj 등록
|
||||
datasetService.insertDeliveriesDataset(req, datasetUid);
|
||||
|
||||
log.info(
|
||||
"{} 데이터 등록 완료. datasetUid={}, 소요시간={} ms",
|
||||
LOG_PREFIX,
|
||||
datasetUid,
|
||||
System.currentTimeMillis() - insertStart);
|
||||
|
||||
// ===== 5. 상태 변경 (완료) =====
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||
log.info("{} 상태 변경 → COMPLETED. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||
|
||||
log.info(
|
||||
"{} 업로드 완료. 총 소요시간={} ms ==========", LOG_PREFIX, System.currentTimeMillis() - startTime);
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
log.error(
|
||||
"{} 업로드 실패. datasetUid={}, filePath={}", LOG_PREFIX, datasetUid, req.getFilePath(), e);
|
||||
|
||||
if (datasetUid != null) {
|
||||
try {
|
||||
// ===== 실패 처리 =====
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.UPLOAD_FAILED);
|
||||
log.error("{} 상태 변경 → 업로드 실패. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||
|
||||
// 실패 시 데이터 정리
|
||||
datasetCoreService.deleteAllDatasetObj(datasetUid);
|
||||
log.error("{} 데이터 정리 완료. datasetUid={}", LOG_PREFIX, datasetUid);
|
||||
|
||||
} catch (Exception ex) {
|
||||
log.error("{} 실패 후 정리 작업 중 오류. datasetUid={}", LOG_PREFIX, datasetUid, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package com.kamco.cd.training.dataset.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetObjRegDto;
|
||||
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
@RequiredArgsConstructor
|
||||
public class DatasetBatchService {
|
||||
|
||||
private final DatasetCoreService datasetCoreService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
/**
|
||||
* 배치 단위 데이터 저장
|
||||
*
|
||||
* <p>- 전달받은 데이터 목록을 순회하며 개별 insert 처리 - batch 단위로 트랜잭션 관리
|
||||
*/
|
||||
@Transactional
|
||||
public void saveBatch(List<Map<String, Object>> batch, Long datasetUid, String type) {
|
||||
for (Map<String, Object> map : batch) {
|
||||
try {
|
||||
insertTrainTestData(map, datasetUid, type);
|
||||
} catch (Exception e) {
|
||||
log.error("파일 단위 실패. skip. file={}", batch, e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 데이터 처리 및 insert DTO 생성
|
||||
*
|
||||
* <p>처리 흐름: 1) 경로/JSON 데이터 추출 2) 파일명에서 연도 및 도엽번호 파싱 3) label JSON → feature 단위 분리 4) feature별 DTO
|
||||
* 생성 후 DB insert
|
||||
*/
|
||||
private void insertTrainTestData(Map<String, Object> map, Long datasetUid, String subDir) {
|
||||
|
||||
String comparePath = (String) map.get("input1");
|
||||
String targetPath = (String) map.get("input2");
|
||||
String labelPath = (String) map.get("label");
|
||||
String geojsonPath = (String) map.get("geojson_path");
|
||||
Object labelJson = map.get("label-json");
|
||||
|
||||
// JSON 파싱
|
||||
JsonNode json;
|
||||
try {
|
||||
json = parseJson(labelJson);
|
||||
if (json == null) {
|
||||
log.warn("json null. skip. file={}", labelJson);
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 실패하면 skip, 다음 진행
|
||||
log.error("GeoJSON 파싱 실패. skip. file={}", geojsonPath, e);
|
||||
return;
|
||||
}
|
||||
|
||||
// 파일명 파싱
|
||||
String fileName = Paths.get(comparePath).getFileName().toString();
|
||||
String[] fileNameStr = fileName.split("_");
|
||||
|
||||
if (fileNameStr.length < 4) {
|
||||
log.error("파일명 파싱 실패: {}", fileName);
|
||||
return;
|
||||
// throw new IllegalArgumentException("잘못된 파일명 형식: " + fileName);
|
||||
}
|
||||
|
||||
int compareYyyy = 0;
|
||||
int targetYyyy = 0;
|
||||
try {
|
||||
compareYyyy = parseInt(fileNameStr[1], "compareYyyy", fileName);
|
||||
targetYyyy = parseInt(fileNameStr[2], "targetYyyy", fileName);
|
||||
} catch (Exception e) {
|
||||
log.error("기준년도 파싱 실패: {}", fileName);
|
||||
return;
|
||||
}
|
||||
|
||||
String mapSheetNum = fileNameStr[3];
|
||||
|
||||
// JSON 유효성 체크
|
||||
JsonNode featuresNode = json.path("features");
|
||||
|
||||
// 2. 비어있는지 확인
|
||||
if (featuresNode.isEmpty()) {
|
||||
log.warn("features empty. skip. file={}", geojsonPath);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!featuresNode.isArray()) {
|
||||
log.warn("features array 아님. skip. file={}", geojsonPath);
|
||||
return; // skip
|
||||
}
|
||||
|
||||
if (featuresNode.isMissingNode() || !featuresNode.isArray() || featuresNode.isEmpty()) {
|
||||
return; // skip
|
||||
}
|
||||
|
||||
ObjectNode base = mapper.createObjectNode();
|
||||
base.put("type", "FeatureCollection");
|
||||
|
||||
for (JsonNode feature : featuresNode) {
|
||||
|
||||
try {
|
||||
JsonNode prop = feature.path("properties");
|
||||
|
||||
String compareClassCd = prop.path("before").asText(null);
|
||||
String targetClassCd = prop.path("after").asText(null);
|
||||
|
||||
// null 방어
|
||||
if (compareClassCd == null || targetClassCd == null) {
|
||||
log.warn("class 값 없음. skip. file={}", fileName);
|
||||
continue;
|
||||
}
|
||||
|
||||
ArrayNode arr = mapper.createArrayNode();
|
||||
arr.add(feature);
|
||||
|
||||
ObjectNode root = base.deepCopy();
|
||||
root.set("features", arr);
|
||||
|
||||
DatasetObjRegDto objRegDto =
|
||||
DatasetObjRegDto.builder()
|
||||
.datasetUid(datasetUid)
|
||||
.compareYyyy(compareYyyy)
|
||||
.compareClassCd(compareClassCd)
|
||||
.targetYyyy(targetYyyy)
|
||||
.targetClassCd(targetClassCd)
|
||||
.comparePath(comparePath)
|
||||
.targetPath(targetPath)
|
||||
.labelPath(labelPath)
|
||||
.mapSheetNum(mapSheetNum)
|
||||
.geojson(root)
|
||||
.geojsonPath(geojsonPath)
|
||||
.fileName(fileName)
|
||||
.build();
|
||||
|
||||
// 데이터 타입별 insert
|
||||
insertByType(subDir, objRegDto);
|
||||
} catch (Exception e) {
|
||||
// 개별 feature skip
|
||||
log.error("feature 처리 실패. skip. file={}", fileName, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 데이터 타입별 insert 처리 - type 값에 따라 대상 테이블 분기 - 잘못된 타입 입력 시 예외 발생 */
|
||||
private void insertByType(String type, DatasetObjRegDto dto) {
|
||||
|
||||
switch (type) {
|
||||
case "train" -> datasetCoreService.insertDatasetObj(dto);
|
||||
case "val" -> datasetCoreService.insertDatasetValObj(dto);
|
||||
case "test" -> datasetCoreService.insertDatasetTestObj(dto);
|
||||
default -> throw new IllegalArgumentException("잘못된 타입: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* label_json → JsonNode 변환
|
||||
*
|
||||
* <p>- JsonNode면 그대로 사용 - 문자열이면 파싱 수행 - 실패 시 로그 후 예외 발생
|
||||
*/
|
||||
private JsonNode parseJson(Object labelJson) {
|
||||
try {
|
||||
if (labelJson instanceof JsonNode jn) {
|
||||
return jn;
|
||||
}
|
||||
return mapper.readTree(labelJson.toString());
|
||||
} catch (Exception e) {
|
||||
log.error("label_json parse error: {}", labelJson, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 → 정수 변환
|
||||
*
|
||||
* <p>- 파싱 실패 시 어떤 필드/파일에서 발생했는지 로그 기록 - 잘못된 데이터는 즉시 예외 처리
|
||||
*/
|
||||
private int parseInt(String value, String field, String fileName) {
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
log.error("{} 파싱 실패. fileName={}, value={}", field, fileName, value);
|
||||
throw new IllegalArgumentException(field + " 파싱 실패: " + fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||
import com.kamco.cd.training.common.service.FormatStorage;
|
||||
@@ -11,6 +12,7 @@ import com.kamco.cd.training.common.utils.FIleChecker;
|
||||
import com.kamco.cd.training.config.api.ApiResponseDto.ApiResponseCode;
|
||||
import com.kamco.cd.training.config.api.ApiResponseDto.ResponseObj;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.AddReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||
@@ -18,8 +20,11 @@ import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetObjRegDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.SearchReq;
|
||||
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
|
||||
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
|
||||
import com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
@@ -27,6 +32,8 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -37,7 +44,6 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -51,13 +57,10 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional
|
||||
public class DatasetService {
|
||||
|
||||
private final DatasetCoreService datasetCoreService;
|
||||
|
||||
@Value("${file.dataset-dir}")
|
||||
private String datasetDir;
|
||||
private final DatasetBatchService datasetBatchService;
|
||||
|
||||
private static final List<String> LABEL_DIRS = List.of("label-json", "label", "input1", "input2");
|
||||
private static final List<String> REQUIRED_DIRS = Arrays.asList("train", "val", "test");
|
||||
@@ -84,6 +87,7 @@ public class DatasetService {
|
||||
return datasetCoreService.getOneByUuid(id);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 데이터셋 등록
|
||||
*
|
||||
@@ -98,6 +102,7 @@ public class DatasetService {
|
||||
return saved.getId();
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
/**
|
||||
* 데이터셋 수정
|
||||
*
|
||||
@@ -231,7 +236,7 @@ public class DatasetService {
|
||||
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid);
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
||||
}
|
||||
|
||||
@@ -365,7 +370,12 @@ public class DatasetService {
|
||||
// 폴더별 처리
|
||||
if ("label-json".equals(dirName)) {
|
||||
// json 파일이면 파싱
|
||||
data.put("label-json", readJson(path));
|
||||
try {
|
||||
data.put("label-json", readJson(path));
|
||||
} catch (Exception e) {
|
||||
log.error("파일 JSON 읽기 실패. skip. file={}", path, e);
|
||||
return; // skip
|
||||
}
|
||||
data.put("geojson_path", path.toAbsolutePath().toString());
|
||||
} else {
|
||||
data.put(dirName, path.toAbsolutePath().toString());
|
||||
@@ -398,24 +408,6 @@ public class DatasetService {
|
||||
return datasetCoreService.getFilePathByUUIDPathType(uuid, pathType);
|
||||
}
|
||||
|
||||
private String readRemoteFileAsString(String remoteFilePath) {
|
||||
|
||||
String command = "cat " + escape(remoteFilePath);
|
||||
|
||||
List<String> lines = FIleChecker.execCommandAndReadLines(command);
|
||||
|
||||
return String.join("\n", lines);
|
||||
}
|
||||
|
||||
private JsonNode parseJson(String json) {
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
return mapper.readTree(json);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("JSON 파싱 실패", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String escape(String path) {
|
||||
// 쉘 커맨드에서 안전하게 사용할 수 있도록 문자열을 작은따옴표로 감싸면서, 내부의 작은따옴표를 이스케이프 처리
|
||||
return "'" + path.replace("'", "'\"'\"'") + "'";
|
||||
@@ -524,4 +516,164 @@ public class DatasetService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 폴더 조회
|
||||
*
|
||||
* @param srchDto 폴더 경로
|
||||
* @return 폴더 리스트
|
||||
* @throws IOException
|
||||
*/
|
||||
public FoldersDto getFolderAll(SrchFoldersDto srchDto) throws IOException {
|
||||
|
||||
File dir = new File(srchDto.getDirPath() == null ? "/" : srchDto.getDirPath());
|
||||
|
||||
// 존재 + 디렉토리 체크
|
||||
if (!dir.exists() || !dir.isDirectory()) {
|
||||
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST, "잘못된 경로입니다.");
|
||||
}
|
||||
|
||||
// 권한 없을때
|
||||
if (!dir.canRead()) {
|
||||
throw new CustomApiException(
|
||||
ApiResponseCode.FORBIDDEN.getId(), HttpStatus.FORBIDDEN, "디렉토리에 접근할 권한이 없습니다.");
|
||||
}
|
||||
|
||||
String canonicalPath = dir.getCanonicalPath();
|
||||
|
||||
File[] files = dir.listFiles();
|
||||
|
||||
if (files == null) {
|
||||
return new FoldersDto(canonicalPath, 0, 0, Collections.emptyList());
|
||||
}
|
||||
|
||||
List<FIleChecker.Folder> folders = new ArrayList<>();
|
||||
|
||||
int folderTotCnt = 0;
|
||||
int folderErrTotCnt = 0;
|
||||
|
||||
for (File f : files) {
|
||||
|
||||
// 숨김 제외
|
||||
if (f.isHidden()) continue;
|
||||
|
||||
if (f.isDirectory()) {
|
||||
|
||||
// 폴더 개수 증가
|
||||
folderTotCnt++;
|
||||
|
||||
// 폴더 유효성 여부 (기본 true, 이후 검증 로직으로 변경 가능)
|
||||
boolean isValid = true;
|
||||
|
||||
// 유효하지 않은 폴더 카운트 증가
|
||||
if (!isValid) folderErrTotCnt++;
|
||||
|
||||
// 현재 폴더 이름 (ex: train, images 등)
|
||||
String folderNm = f.getName();
|
||||
|
||||
// 부모 경로 (ex: /data/datasets)
|
||||
String parentPath = f.getParent();
|
||||
|
||||
// 부모 폴더 이름 (ex: datasets)
|
||||
String parentFolderNm = new File(parentPath).getName();
|
||||
|
||||
// 전체 절대 경로 (ex: /data/datasets/train)
|
||||
String fullPath = f.getAbsolutePath();
|
||||
|
||||
// 폴더 깊이 (경로 기준 depth)
|
||||
// ex: /a/b/c → depth = 3
|
||||
int depth = f.toPath().getNameCount();
|
||||
|
||||
// 하위 폴더 개수
|
||||
long childCnt = FIleChecker.getChildFolderCount(f);
|
||||
|
||||
// 마지막 수정 시간 (문자열 포맷)
|
||||
String lastModified = FIleChecker.getLastModified(f);
|
||||
|
||||
// Folder DTO 생성 및 리스트에 추가
|
||||
folders.add(
|
||||
new FIleChecker.Folder(
|
||||
folderNm, // 폴더명
|
||||
parentFolderNm, // 부모 폴더명
|
||||
parentPath, // 부모 경로
|
||||
fullPath, // 전체 경로
|
||||
depth, // 깊이
|
||||
childCnt, // 하위 폴더 개수
|
||||
lastModified, // 수정일시
|
||||
isValid // 유효성 여부
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 폴더 정렬
|
||||
folders.sort(
|
||||
Comparator.comparing(FIleChecker.Folder::getFolderNm, String.CASE_INSENSITIVE_ORDER));
|
||||
|
||||
return new FoldersDto(canonicalPath, folderTotCnt, folderErrTotCnt, folders);
|
||||
}
|
||||
|
||||
/**
|
||||
* 납품 데이터 등록
|
||||
*
|
||||
* @param req 폴더경로, 메모
|
||||
* @return 성공/실패 여부0
|
||||
*/
|
||||
public void insertDeliveriesDataset(AddDeliveriesReq req, Long datasetUid) {
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 처리
|
||||
processType(req.getFilePath(), datasetUid, "train");
|
||||
processType(req.getFilePath(), datasetUid, "val");
|
||||
processType(req.getFilePath(), datasetUid, "test");
|
||||
|
||||
log.info("========== 전체 완료. 총 소요시간: {} ms ==========", System.currentTimeMillis() - startTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 납품 데이터 등록 처리
|
||||
*
|
||||
* @param path
|
||||
* @param datasetUid
|
||||
* @param type
|
||||
*/
|
||||
private void processType(String path, Long datasetUid, String type) {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
log.info("[납품 데이터 등록 처리][{}] 시작", type.toUpperCase());
|
||||
|
||||
List<Map<String, Object>> list = getUnzipDatasetFiles(path, type);
|
||||
|
||||
int batchSize = 1000;
|
||||
int total = list.size();
|
||||
int processed = 0;
|
||||
|
||||
for (int i = 0; i < total; i += batchSize) {
|
||||
|
||||
List<Map<String, Object>> batch = list.subList(i, Math.min(i + batchSize, total));
|
||||
|
||||
try {
|
||||
log.info("[납품 데이터 등록 처리][{}] batch 시작: {} ~ {}", type, i, i + batch.size());
|
||||
|
||||
datasetBatchService.saveBatch(batch, datasetUid, type);
|
||||
|
||||
processed += batch.size();
|
||||
} catch (Exception e) {
|
||||
log.error("batch 실패 row 데이터: {}", batch);
|
||||
log.error(
|
||||
"[납품 데이터 등록 처리][{}] batch 실패. range: {} ~ {}, datasetUid={}",
|
||||
type,
|
||||
i,
|
||||
i + batch.size(),
|
||||
datasetUid,
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info(
|
||||
"[납품 데이터 등록 처리][{}] 완료. 총 {}건, 소요시간: {} ms",
|
||||
type,
|
||||
total,
|
||||
System.currentTimeMillis() - start);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.dataset.service;
|
||||
|
||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||
@@ -39,3 +40,4 @@ public class MapSheetService {
|
||||
log.info("도엽 삭제 완료 - 개수: {}", deleteReq.getItemIds().size());
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package com.kamco.cd.training.filemanager.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.time.LocalDateTime;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
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.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));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장공간 정보 조회 (남은 공간 포함) 고정 경로: /home/kcomu/data
|
||||
*
|
||||
* @return 저장공간 정보 (사용량, 남은 공간, 디스크 용량)
|
||||
*/
|
||||
public FileManagerDto.StorageSpaceRes getStorageSpaceInfo() {
|
||||
// 고정 경로: /home/kcomu/data
|
||||
String directoryPath = "/home/kcomu/data";
|
||||
|
||||
Path directory = Paths.get(directoryPath);
|
||||
if (!Files.exists(directory)) {
|
||||
log.debug("디렉토리가 존재하지 않습니다: {}", 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.debug("디렉토리 경로가 아닙니다: {}", 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();
|
||||
}
|
||||
|
||||
// 디렉토리 사용량 계산 (재귀적으로 모든 파일 크기 합산)
|
||||
final long[] usedSize = {0};
|
||||
final int[] fileCount = {0};
|
||||
final int[] directoryCount = {0};
|
||||
|
||||
try {
|
||||
Files.walkFileTree(
|
||||
directory,
|
||||
new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||
usedSize[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.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();
|
||||
}
|
||||
|
||||
// 디스크 공간 정보 조회 (FileStore 사용)
|
||||
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(); // 남은 저장공간 (할당되지 않은 공간)
|
||||
usableSpace = fileStore.getUsableSpace(); // 사용 가능한 공간 (실제 사용 가능)
|
||||
|
||||
// 디스크 사용률 계산
|
||||
if (totalDiskSpace > 0) {
|
||||
long usedDiskSpace = totalDiskSpace - freeSpace;
|
||||
usagePercentage = (usedDiskSpace * 100.0) / totalDiskSpace;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.debug("디스크 공간 정보 조회 중 오류 발생: {}", directoryPath, e);
|
||||
// 디스크 정보 조회 실패 시에도 디렉토리 용량은 반환
|
||||
}
|
||||
|
||||
return FileManagerDto.StorageSpaceRes.builder()
|
||||
.directoryPath(directoryPath)
|
||||
.fileCount(fileCount[0])
|
||||
.directoryCount(directoryCount[0])
|
||||
.usedSize(usedSize[0])
|
||||
.usedSizeFormatted(formatFileSize(usedSize[0]))
|
||||
.totalDiskSpace(totalDiskSpace)
|
||||
.totalDiskSpaceFormatted(formatFileSize(totalDiskSpace))
|
||||
.freeSpace(freeSpace)
|
||||
.freeSpaceFormatted(formatFileSize(freeSpace))
|
||||
.usableSpace(usableSpace)
|
||||
.usableSpaceFormatted(formatFileSize(usableSpace))
|
||||
.usagePercentage(Math.round(usagePercentage * 100.0) / 100.0)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -11,9 +11,9 @@ 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.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.model.service.ModelTrainDetailService;
|
||||
import com.kamco.cd.training.model.service.ModelTrainMngService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
@@ -34,6 +34,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.apache.coyote.BadRequestException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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.RequestMapping;
|
||||
@@ -45,10 +46,9 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RequestMapping("/api/models")
|
||||
public class ModelTrainDetailApiController {
|
||||
private final ModelTrainDetailService modelTrainDetailService;
|
||||
private final ModelTrainMngService modelTrainMngService;
|
||||
private final RangeDownloadResponder rangeDownloadResponder;
|
||||
|
||||
@Value("${train.docker.responseDir}")
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
||||
@@ -326,4 +326,44 @@ public class ModelTrainDetailApiController {
|
||||
UUID uuid) {
|
||||
return ApiResponseDto.ok(modelTrainDetailService.findModelTrainProgressInfo(uuid));
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "모델관리 > 모델 상세 > best epoch 제외 삭제 될 파일 미리보기",
|
||||
description = "best epoch 제외 삭제 될 파일 미리보기 API")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "조회 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = CleanupResult.class))),
|
||||
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/{uuid}/cleanup/preview")
|
||||
public ApiResponseDto<CleanupResult> previewCleanup(
|
||||
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
||||
return ApiResponseDto.ok(modelTrainDetailService.previewCleanup(uuid));
|
||||
}
|
||||
|
||||
@Operation(summary = "모델관리 > 모델 상세 > best epoch 제외 삭제", description = "best epoch 제외 파일 삭제 API")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "삭제 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = CleanupResult.class))),
|
||||
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@DeleteMapping("/{uuid}/cleanup")
|
||||
public ApiResponseDto<CleanupResult> cleanup(
|
||||
@Parameter(description = "모델 uuid") @PathVariable UUID uuid) {
|
||||
return ApiResponseDto.ok(modelTrainDetailService.cleanup(uuid));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
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;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
@@ -40,6 +43,7 @@ public class ModelTrainMngApiController {
|
||||
private final ModelTrainMngService modelTrainMngService;
|
||||
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||
private final ModelTestMetricsJobService modelTestMetricsJobService;
|
||||
private final SystemMonitorService systemMonitorService;
|
||||
|
||||
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
|
||||
@ApiResponses(
|
||||
@@ -65,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,
|
||||
@@ -140,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 = "",
|
||||
@@ -150,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));
|
||||
}
|
||||
@@ -214,4 +218,22 @@ public class ModelTrainMngApiController {
|
||||
modelTestMetricsJobService.findTestValidMetricCsvFiles();
|
||||
return ApiResponseDto.ok(null);
|
||||
}
|
||||
|
||||
@Operation(summary = "학습서버 시스템 사용율 조회", description = "cpu, gpu, memory 사용율 조회")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "검색 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = Long.class))),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/monitor")
|
||||
public ApiResponseDto<MonitorDto> getSystem() throws IOException {
|
||||
return ApiResponseDto.ok(systemMonitorService.get());
|
||||
}
|
||||
}
|
||||
|
||||
160
src/main/java/com/kamco/cd/training/model/dto/FileDto.java
Normal file
160
src/main/java/com/kamco/cd/training/model/dto/FileDto.java
Normal file
@@ -0,0 +1,160 @@
|
||||
package com.kamco.cd.training.model.dto;
|
||||
|
||||
import com.kamco.cd.training.common.utils.FIleChecker;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
public class FileDto {
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class SrchFoldersDto {
|
||||
@Schema(description = "디렉토리경로(ROOT:/)", example = "")
|
||||
@NotNull
|
||||
private String dirPath = "/";
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class SrchFilesDto {
|
||||
@Schema(description = "디렉토리경로", example = "D:\\kamco\\2022\\캠코_2021_2022_34602060_D1")
|
||||
@NotNull
|
||||
private String dirPath;
|
||||
|
||||
@Schema(description = "전체(*), cpg,dbf,geojson등", example = "*")
|
||||
@NotNull
|
||||
private String extension;
|
||||
|
||||
@Schema(description = "파일명(name), 최종수정일(date)", example = "name")
|
||||
@NotNull
|
||||
private String sortType;
|
||||
|
||||
@Schema(description = "파일시작위치", example = "1")
|
||||
@NotNull
|
||||
private Integer startPos;
|
||||
|
||||
@Schema(description = "파일종료위치", example = "100")
|
||||
@NotNull
|
||||
private Integer endPos;
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class SrchFilesDepthDto extends SrchFilesDto {
|
||||
@Schema(description = "최대폴더Depth", example = "5")
|
||||
@NotNull
|
||||
private Integer maxDepth;
|
||||
}
|
||||
|
||||
@Schema(name = "FolderDto", description = "폴더 정보")
|
||||
@Getter
|
||||
public static class FolderDto {
|
||||
private final String folderNm;
|
||||
private final String parentFolderNm;
|
||||
private final String parentPath;
|
||||
private final String fullPath;
|
||||
private final int depth;
|
||||
private final long childCnt;
|
||||
private final String lastModified;
|
||||
private final Boolean isValid;
|
||||
|
||||
public FolderDto(
|
||||
String folderNm,
|
||||
String parentFolderNm,
|
||||
String parentPath,
|
||||
String fullPath,
|
||||
int depth,
|
||||
long childCnt,
|
||||
String lastModified,
|
||||
Boolean isValid) {
|
||||
this.folderNm = folderNm;
|
||||
this.parentFolderNm = parentFolderNm;
|
||||
this.parentPath = parentPath;
|
||||
this.fullPath = fullPath;
|
||||
this.depth = depth;
|
||||
this.childCnt = childCnt;
|
||||
this.lastModified = lastModified;
|
||||
this.isValid = isValid;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Schema(name = "FoldersDto", description = "폴더목록 정보")
|
||||
@Getter
|
||||
public static class FoldersDto {
|
||||
private final String dirPath;
|
||||
private final int folderTotCnt;
|
||||
private final int folderErrTotCnt;
|
||||
private final List<FIleChecker.Folder> folders;
|
||||
|
||||
public FoldersDto(
|
||||
String dirPath, int folderTotCnt, int folderErrTotCnt, List<FIleChecker.Folder> folders) {
|
||||
|
||||
this.dirPath = dirPath;
|
||||
this.folderTotCnt = folderTotCnt;
|
||||
this.folderErrTotCnt = folderErrTotCnt;
|
||||
this.folders = folders;
|
||||
}
|
||||
}
|
||||
|
||||
@Schema(name = "File Basic", description = "파일 기본 정보")
|
||||
@Getter
|
||||
public static class Basic {
|
||||
|
||||
private final String fileNm;
|
||||
private final String parentFolderNm;
|
||||
private final String parentPath;
|
||||
private final String fullPath;
|
||||
private final String extension;
|
||||
private final long fileSize;
|
||||
private final String lastModified;
|
||||
|
||||
public Basic(
|
||||
String fileNm,
|
||||
String parentFolderNm,
|
||||
String parentPath,
|
||||
String fullPath,
|
||||
String extension,
|
||||
long fileSize,
|
||||
String lastModified) {
|
||||
this.fileNm = fileNm;
|
||||
this.parentFolderNm = parentFolderNm;
|
||||
this.parentPath = parentPath;
|
||||
this.fullPath = fullPath;
|
||||
this.extension = extension;
|
||||
this.fileSize = fileSize;
|
||||
this.lastModified = lastModified;
|
||||
}
|
||||
}
|
||||
|
||||
@Schema(name = "FilesDto", description = "파일 목록 정보")
|
||||
@Getter
|
||||
public static class FilesDto {
|
||||
private final String dirPath;
|
||||
private final int fileTotCnt;
|
||||
private final long fileTotSize;
|
||||
private final List<FIleChecker.Basic> files;
|
||||
|
||||
public FilesDto(
|
||||
String dirPath, int fileTotCnt, long fileTotSize, List<FIleChecker.Basic> files) {
|
||||
|
||||
this.dirPath = dirPath;
|
||||
this.fileTotCnt = fileTotCnt;
|
||||
this.fileTotSize = fileTotSize;
|
||||
this.files = files;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,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,17 +155,20 @@ 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);
|
||||
}
|
||||
|
||||
@@ -172,6 +178,10 @@ public class ModelTrainDetailDto {
|
||||
}
|
||||
}
|
||||
|
||||
private static Long toNullIfZero(Long value) {
|
||||
return (value == null || value == 0L) ? null : value;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
|
||||
@@ -48,6 +48,7 @@ public class ModelTrainMngDto {
|
||||
private ZonedDateTime packingEndDttm;
|
||||
|
||||
private Long beforeModelId;
|
||||
private Integer bestEpoch;
|
||||
|
||||
public String getStatusName() {
|
||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||
@@ -138,7 +139,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
|
||||
@@ -196,10 +197,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
|
||||
@@ -327,4 +329,26 @@ public class ModelTrainMngDto {
|
||||
@JsonFormatDttm private ZonedDateTime endTime;
|
||||
private boolean isError;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class CleanupResult {
|
||||
// cleanup 대상 전체 파일 수 (삭제 대상 + 유지 파일 포함)
|
||||
private int totalCount;
|
||||
|
||||
// 실제로 삭제된 파일 개수
|
||||
private int deletedCount;
|
||||
|
||||
// 삭제 실패한 파일 개수
|
||||
private int failedCount;
|
||||
|
||||
// 삭제 실패한 파일명 목록
|
||||
private List<String> failedFiles;
|
||||
|
||||
// 유지된 파일명 (best epoch 기준)
|
||||
private String keptFile;
|
||||
|
||||
// 삭제 될 파일
|
||||
private List<String> deleteTargets;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.kamco.cd.training.model.service;
|
||||
|
||||
import com.kamco.cd.training.common.enums.ModelType;
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||
@@ -14,15 +16,31 @@ 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.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 java.io.IOException;
|
||||
import java.nio.file.AccessDeniedException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
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.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -35,6 +53,9 @@ public class ModelTrainDetailService {
|
||||
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
||||
private final ModelTrainMngCoreService mngCoreService;
|
||||
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
/**
|
||||
* 모델 상세정보 요약
|
||||
*
|
||||
@@ -63,6 +84,7 @@ public class ModelTrainDetailService {
|
||||
return modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 전이학습 모델선택 정보
|
||||
*
|
||||
@@ -129,6 +151,8 @@ public class ModelTrainDetailService {
|
||||
return transferDetailDto;
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||
return modelTrainDetailCoreService.getModelTrainMetricResult(uuid);
|
||||
}
|
||||
@@ -152,4 +176,262 @@ public class ModelTrainDetailService {
|
||||
public List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid) {
|
||||
return modelTrainDetailCoreService.findModelTrainProgressInfo(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 삭제될 파일목록 및 유지될 파일 목록
|
||||
*
|
||||
* @param uuid
|
||||
* @return
|
||||
*/
|
||||
public CleanupResult previewCleanup(UUID uuid) {
|
||||
|
||||
CleanupResult result = new CleanupResult();
|
||||
|
||||
// ===== 모델 조회 =====
|
||||
ModelTrainMngDto.Basic model = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||
|
||||
if (model == null) {
|
||||
throw new CustomApiException(
|
||||
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다. UUID: " + uuid);
|
||||
}
|
||||
|
||||
Path dir = Paths.get(responseDir, model.getUuid().toString()).toAbsolutePath().normalize();
|
||||
|
||||
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "디렉토리가 없습니다.");
|
||||
}
|
||||
|
||||
if (!Files.isReadable(dir)) {
|
||||
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 읽기 권한이 없습니다.");
|
||||
}
|
||||
|
||||
try (Stream<Path> stream = Files.list(dir)) {
|
||||
|
||||
List<Path> files = stream.toList();
|
||||
|
||||
if (files.isEmpty()) {
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "파일이 없습니다.");
|
||||
}
|
||||
|
||||
// ===== keep 파일 찾기 =====
|
||||
Path keep =
|
||||
files.stream()
|
||||
.filter(
|
||||
p -> {
|
||||
String name = p.getFileName().toString();
|
||||
return name.endsWith(".zip") && name.contains(model.getUuid().toString());
|
||||
})
|
||||
.findFirst()
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new CustomApiException(
|
||||
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "zip 파일이 없습니다."));
|
||||
|
||||
log.info("유지 파일: {}", keep.getFileName());
|
||||
|
||||
// ===== 결과 세팅 =====
|
||||
result.setTotalCount(files.size());
|
||||
result.setKeptFile(keep.getFileName().toString());
|
||||
|
||||
// ===== 삭제 대상 =====
|
||||
List<String> deleteTargets =
|
||||
files.stream()
|
||||
.filter(
|
||||
p -> !p.toAbsolutePath().normalize().equals(keep.toAbsolutePath().normalize()))
|
||||
.map(p -> p.getFileName().toString())
|
||||
.toList();
|
||||
|
||||
result.setDeleteTargets(deleteTargets);
|
||||
|
||||
log.info(
|
||||
"previewCleanup 완료. total={}, deleteTargets={}",
|
||||
result.getTotalCount(),
|
||||
deleteTargets.size());
|
||||
|
||||
return result;
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("파일 목록 조회 실패: {}", dir, e);
|
||||
throw new CustomApiException(
|
||||
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "파일 목록 조회 실패");
|
||||
}
|
||||
}
|
||||
|
||||
public CleanupResult cleanup(UUID uuid) {
|
||||
// ===== 모델 조회 =====
|
||||
ModelTrainMngDto.Basic model = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||
|
||||
if (model == null) {
|
||||
throw new CustomApiException(
|
||||
"NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "모델을 찾을 수 없습니다. UUID: " + uuid);
|
||||
}
|
||||
|
||||
if (!TrainStatusType.COMPLETED.getId().equals(model.getStep2Status())) {
|
||||
throw new CustomApiException("CONFLICT", HttpStatus.CONFLICT, "테스트가 완료되지 않았습니다.");
|
||||
}
|
||||
|
||||
// ===== 경로 =====
|
||||
Path dir = Paths.get(responseDir, model.getUuid().toString()).toAbsolutePath().normalize();
|
||||
|
||||
return executeCleanup(model, dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 베스트 에폭 제외 파일 삭제, 베스트 에폭 zip 파일만 남김
|
||||
*
|
||||
* @param model model 정보
|
||||
* @param dir response 폴더 경로
|
||||
* @return 삭제 정보
|
||||
*/
|
||||
public CleanupResult executeCleanup(ModelTrainMngDto.Basic model, Path dir) {
|
||||
CleanupResult result = new CleanupResult();
|
||||
|
||||
if (!Files.exists(dir) || !Files.isDirectory(dir)) {
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "디렉토리가 없습니다.");
|
||||
}
|
||||
|
||||
if (!Files.isReadable(dir)) {
|
||||
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 읽기 권한이 없습니다.");
|
||||
}
|
||||
|
||||
if (!Files.isWritable(dir)) {
|
||||
throw new CustomApiException("FORBIDDEN", HttpStatus.FORBIDDEN, "디렉토리 삭제 권한이 없습니다.");
|
||||
}
|
||||
|
||||
int bestEpoch = model.getBestEpoch();
|
||||
|
||||
if (bestEpoch <= 0) {
|
||||
throw new CustomApiException(
|
||||
"BAD_REQUEST", HttpStatus.BAD_REQUEST, "잘못된 bestEpoch 값 입니다. : " + bestEpoch);
|
||||
}
|
||||
|
||||
log.info("cleanup 시작. dir={}, bestEpoch={}", dir, bestEpoch);
|
||||
|
||||
try (Stream<Path> stream = Files.list(dir)) {
|
||||
|
||||
List<Path> files = stream.toList();
|
||||
|
||||
if (files.isEmpty()) {
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "파일이 없습니다.");
|
||||
}
|
||||
|
||||
// ===== keep 파일 찾기 =====
|
||||
Path keep = null;
|
||||
|
||||
for (Path p : files) {
|
||||
String name = p.getFileName().toString();
|
||||
if (name.endsWith(".zip") && name.contains(model.getUuid().toString())) {
|
||||
keep = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (keep == null) {
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "zip 파일이 없습니다.");
|
||||
}
|
||||
|
||||
log.info("유지 파일: {}", keep.getFileName());
|
||||
|
||||
result.setTotalCount(files.size());
|
||||
result.setKeptFile(keep.getFileName().toString());
|
||||
|
||||
int deletedCount = 0;
|
||||
List<String> failed = new ArrayList<>();
|
||||
|
||||
// ===== 삭제 =====
|
||||
for (Path p : files) {
|
||||
|
||||
if (p.equals(keep)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// 심볼릭 링크 → 링크만 삭제
|
||||
if (Files.isSymbolicLink(p)) {
|
||||
Files.deleteIfExists(p);
|
||||
log.info("심볼릭 링크 삭제: {}", p.getFileName());
|
||||
}
|
||||
|
||||
// 디렉토리 → 재귀 삭제
|
||||
else if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
|
||||
log.info("디렉토리 재귀 삭제: {}", p.getFileName());
|
||||
deleteDirectory(p);
|
||||
}
|
||||
|
||||
// 일반 파일
|
||||
else {
|
||||
Files.deleteIfExists(p);
|
||||
log.info("파일 삭제: {}", p.getFileName());
|
||||
}
|
||||
|
||||
deletedCount++;
|
||||
|
||||
} catch (AccessDeniedException e) {
|
||||
failed.add(p.getFileName().toString());
|
||||
log.error("권한 없음: {}", p.getFileName(), e);
|
||||
|
||||
} catch (IOException e) {
|
||||
failed.add(p.getFileName().toString());
|
||||
log.error("삭제 실패: {}", p.getFileName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
result.setDeletedCount(deletedCount);
|
||||
result.setFailedCount(failed.size());
|
||||
result.setFailedFiles(failed);
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("파일 목록 조회 실패: {}", dir, e);
|
||||
throw new CustomApiException(
|
||||
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "파일 목록 조회 실패");
|
||||
}
|
||||
|
||||
log.info(
|
||||
"cleanup 완료. total={}, deleted={}, failed={}",
|
||||
result.getTotalCount(),
|
||||
result.getDeletedCount(),
|
||||
result.getFailedCount());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 디렉토리 재귀 삭제
|
||||
private void deleteDirectory(Path dir) throws IOException {
|
||||
|
||||
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// dir 자체가 심볼릭 링크면 링크만 삭제
|
||||
if (Files.isSymbolicLink(dir)) {
|
||||
Files.delete(dir);
|
||||
return;
|
||||
}
|
||||
|
||||
Files.walkFileTree(
|
||||
dir,
|
||||
EnumSet.noneOf(FileVisitOption.class), // NOFOLLOW_LINKS
|
||||
Integer.MAX_VALUE,
|
||||
new SimpleFileVisitor<>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
|
||||
Files.delete(file); // 링크면 링크만 삭제됨
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||
throws IOException {
|
||||
|
||||
if (exc != null) throw exc;
|
||||
|
||||
Files.delete(directory);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.kamco.cd.training.model.service;
|
||||
import com.kamco.cd.training.common.dto.HyperParam;
|
||||
import com.kamco.cd.training.common.enums.HyperParamSelectType;
|
||||
import com.kamco.cd.training.common.enums.ModelType;
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.common.enums.TrainType;
|
||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
@@ -14,10 +15,21 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
|
||||
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import com.kamco.cd.training.train.service.TrainJobService;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitOption;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -32,6 +44,16 @@ public class ModelTrainMngService {
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
private final HyperParamCoreService hyperParamCoreService;
|
||||
private final TrainJobService trainJobService;
|
||||
private final ModelTrainDetailService modelTrainDetailService;
|
||||
|
||||
@Value("${train.docker.base_path}")
|
||||
private String basePath;
|
||||
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
@Value("${train.docker.symbolic_link_dir}")
|
||||
private String symbolicDir;
|
||||
|
||||
/**
|
||||
* 모델학습 조회
|
||||
@@ -46,11 +68,199 @@ public class ModelTrainMngService {
|
||||
/**
|
||||
* 모델학습 삭제
|
||||
*
|
||||
* @param uuid
|
||||
* <p>순서: 1. tmp 구조 검증 (예외 발생 가능) 2. DB 삭제 (트랜잭션) 3. 파일 삭제 (실패해도 로그만)
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteModelTrain(UUID uuid) {
|
||||
|
||||
log.info("deleteModelTrain 시작. uuid={}", uuid);
|
||||
|
||||
// ===== 1. 모델 조회 =====
|
||||
ModelTrainMngDto.Basic model = modelTrainMngCoreService.findModelByUuid(uuid);
|
||||
|
||||
if (model == null) {
|
||||
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();
|
||||
|
||||
Path responseBase = Paths.get(responseDir).toAbsolutePath().normalize();
|
||||
Path response = responseBase.resolve(model.getUuid().toString()).normalize();
|
||||
|
||||
// ===== 3. 경로 탈출 방지 =====
|
||||
if (!tmp.startsWith(tmpBase)) {
|
||||
throw new CustomApiException("INVALID_PATH", HttpStatus.BAD_REQUEST, "잘못된 tmp 경로");
|
||||
}
|
||||
|
||||
if (!response.startsWith(responseBase)) {
|
||||
throw new CustomApiException("INVALID_PATH", HttpStatus.BAD_REQUEST, "잘못된 response 경로");
|
||||
}
|
||||
|
||||
// ===== 4. 상태 로그 =====
|
||||
log.info(
|
||||
"tmp 상태: exists={}, isDir={}, isSymlink={}",
|
||||
Files.exists(tmp, LinkOption.NOFOLLOW_LINKS),
|
||||
Files.isDirectory(tmp, LinkOption.NOFOLLOW_LINKS),
|
||||
Files.isSymbolicLink(tmp));
|
||||
|
||||
log.info(
|
||||
"response 상태: exists={}, isDir={}, isSymlink={}",
|
||||
Files.exists(response, LinkOption.NOFOLLOW_LINKS),
|
||||
Files.isDirectory(response, LinkOption.NOFOLLOW_LINKS),
|
||||
Files.isSymbolicLink(response));
|
||||
|
||||
// ===== 5. tmp 구조 검증 =====
|
||||
validateTmpStructure(tmp);
|
||||
|
||||
// ===== 6. DB 삭제 =====
|
||||
modelTrainMngCoreService.deleteModel(uuid);
|
||||
log.info("DB 삭제 완료. uuid={}", uuid);
|
||||
|
||||
// ===== 7. tmp 삭제 =====
|
||||
log.info("tmp 삭제 시작: {}", tmp);
|
||||
try {
|
||||
deleteTmpDirectory(tmp);
|
||||
log.info("tmp 삭제 완료: {}", tmp);
|
||||
} catch (Exception e) {
|
||||
log.error("tmp 삭제 실패 (DB는 이미 삭제됨): {}", tmp, e);
|
||||
}
|
||||
|
||||
// ===== 8. response 삭제 =====
|
||||
log.info("response 삭제 시작: {}", response);
|
||||
try {
|
||||
// 테스트 완료되었으면 베스트 에폭은 삭제안함
|
||||
if (TrainStatusType.COMPLETED.getId().equals(model.getStep2Status())) {
|
||||
modelTrainDetailService.executeCleanup(model, response);
|
||||
} else {
|
||||
deleteResponseDirectory(response);
|
||||
}
|
||||
|
||||
log.info("response 삭제 완료: {}", response);
|
||||
} catch (Exception e) {
|
||||
log.error("response 삭제 실패 (DB는 이미 삭제됨): {}", response, e);
|
||||
}
|
||||
|
||||
log.info("deleteModelTrain 완료. uuid={}", uuid);
|
||||
}
|
||||
|
||||
/** tmp 디렉토리 삭제 */
|
||||
private void deleteTmpDirectory(Path dir) throws IOException {
|
||||
|
||||
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||
log.warn("삭제 대상 없음: {}", dir);
|
||||
return;
|
||||
}
|
||||
|
||||
Files.walkFileTree(
|
||||
dir,
|
||||
EnumSet.noneOf(FileVisitOption.class),
|
||||
Integer.MAX_VALUE,
|
||||
new SimpleFileVisitor<>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
|
||||
Files.delete(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||
throws IOException {
|
||||
|
||||
if (exc != null) {
|
||||
throw exc;
|
||||
}
|
||||
|
||||
Files.delete(directory);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** response 디렉토리 삭제 */
|
||||
private void deleteResponseDirectory(Path dir) throws IOException {
|
||||
|
||||
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||
log.warn("삭제 대상 없음: {}", dir);
|
||||
return;
|
||||
}
|
||||
|
||||
Files.walkFileTree(
|
||||
dir,
|
||||
EnumSet.noneOf(FileVisitOption.class),
|
||||
Integer.MAX_VALUE,
|
||||
new SimpleFileVisitor<>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
|
||||
Files.delete(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
|
||||
throws IOException {
|
||||
|
||||
if (exc != null) {
|
||||
throw exc;
|
||||
}
|
||||
|
||||
Files.delete(directory);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** tmp 내부 구조 검증 - 내부는 반드시 symlink만 허용 */
|
||||
private void validateTmpStructure(Path dir) {
|
||||
|
||||
if (!Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Files.walkFileTree(
|
||||
dir,
|
||||
EnumSet.noneOf(FileVisitOption.class),
|
||||
Integer.MAX_VALUE,
|
||||
new SimpleFileVisitor<>() {
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
|
||||
// 파일은 전부 허용 (일반 + symlink)
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
|
||||
throws IOException {
|
||||
|
||||
// 루트 제외 + symlink 디렉토리 금지
|
||||
if (!directory.equals(dir) && Files.isSymbolicLink(directory)) {
|
||||
log.error("tmp 내부에 symlink 디렉토리 존재: {}", directory);
|
||||
throw new CustomApiException(
|
||||
"BAD_REQUEST", HttpStatus.BAD_REQUEST, "tmp 내부에 symlink 디렉토리는 허용되지 않습니다.");
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new CustomApiException(
|
||||
"INTERNAL_SERVER_ERROR", HttpStatus.INTERNAL_SERVER_ERROR, "tmp 구조 검증 실패");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,6 +328,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);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.kamco.cd.training.postgres.core;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||
@@ -30,9 +29,9 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
public class DatasetCoreService
|
||||
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
||||
|
||||
private final DatasetRepository datasetRepository;
|
||||
private final DatasetObjRepository datasetObjRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 학습 데이터 삭제
|
||||
@@ -96,6 +95,7 @@ public class DatasetCoreService
|
||||
return search(searchReq);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 학습데이터 등록
|
||||
*
|
||||
@@ -130,6 +130,7 @@ public class DatasetCoreService
|
||||
return savedEntity.toDto();
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
/**
|
||||
* 학습 데이터 수정
|
||||
*
|
||||
@@ -221,7 +222,6 @@ public class DatasetCoreService
|
||||
return datasetRepository.insertDatasetMngData(mngRegDto);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||
datasetObjRepository.insertDatasetObj(objRegDto);
|
||||
}
|
||||
@@ -234,13 +234,20 @@ public class DatasetCoreService
|
||||
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
||||
}
|
||||
|
||||
public void updateDatasetUploadStatus(Long datasetUid) {
|
||||
/**
|
||||
* 학습데이터셋 마스터 상태 변경
|
||||
*
|
||||
* @param datasetUid 학습데이터셋 마스터 id
|
||||
* @param register 상태
|
||||
*/
|
||||
@Transactional
|
||||
public void updateDatasetUploadStatus(Long datasetUid, LearnDataRegister register) {
|
||||
DatasetEntity entity =
|
||||
datasetRepository
|
||||
.findById(datasetUid)
|
||||
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
||||
|
||||
entity.setStatus(LearnDataRegister.COMPLETED.getId());
|
||||
entity.setStatus(register.getId());
|
||||
}
|
||||
|
||||
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||
@@ -250,4 +257,15 @@ public class DatasetCoreService
|
||||
public Long findDatasetByUidExistsCnt(String uid) {
|
||||
return datasetRepository.findDatasetByUidExistsCnt(uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터셋 등록 실패시 Obj 데이터 정리
|
||||
*
|
||||
* @param datasetUid 모델 마스터 id
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteAllDatasetObj(Long datasetUid) {
|
||||
int cnt = datasetObjRepository.deleteAllDatasetObj(datasetUid);
|
||||
log.info("datasetUid={} 데이터셋 실패 - 전체 삭제 완료. 총 {}건", datasetUid, cnt);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.core;
|
||||
|
||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||
@@ -70,3 +71,4 @@ public class MapSheetCoreService
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -26,6 +26,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);
|
||||
}
|
||||
|
||||
@@ -67,10 +67,13 @@ public class ModelTrainDetailCoreService {
|
||||
return modelDetailRepository.getByModelHyperParamSummary(uuid);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
public TransferHyperSummary getTransferHyperSummary(UUID uuid) {
|
||||
return modelDetailRepository.getByModelTransferHyperParamSummary(uuid);
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
public List<MappingDataset> getByModelMappingDataset(UUID uuid) {
|
||||
return modelDetailRepository.getByModelMappingDataset(uuid);
|
||||
}
|
||||
@@ -80,6 +83,7 @@ public class ModelTrainDetailCoreService {
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 모델 학습별 config 정보 조회
|
||||
*
|
||||
@@ -90,6 +94,7 @@ public class ModelTrainDetailCoreService {
|
||||
return modelConfigRepository.findModelConfigByModelId(modelId).orElse(null);
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||
return modelDetailRepository.getModelTrainMetricResult(uuid);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 성공 처리
|
||||
*
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
@@ -219,6 +222,7 @@ public class ModelTrainMngCoreService {
|
||||
modelConfigRepository.save(entity);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 데이터셋 매핑 생성
|
||||
*
|
||||
@@ -235,6 +239,8 @@ public class ModelTrainMngCoreService {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* UUID로 모델 조회
|
||||
*
|
||||
@@ -278,6 +284,7 @@ public class ModelTrainMngCoreService {
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
public ModelConfigDto.TransferBasic findModelTransferConfigByModelId(UUID uuid) {
|
||||
ModelMasterEntity modelEntity = findByUuid(uuid);
|
||||
return modelConfigRepository
|
||||
@@ -285,6 +292,8 @@ public class ModelTrainMngCoreService {
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 데이터셋 G1 목록
|
||||
*
|
||||
@@ -295,6 +304,7 @@ public class ModelTrainMngCoreService {
|
||||
return datasetRepository.getDatasetSelectG1List(req);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 전이학습 데이터셋 G1 목록
|
||||
*
|
||||
@@ -305,6 +315,8 @@ public class ModelTrainMngCoreService {
|
||||
return datasetRepository.getDatasetTransferSelectG1List(modelId);
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 데이터셋 G2, G3 목록
|
||||
*
|
||||
@@ -315,6 +327,7 @@ public class ModelTrainMngCoreService {
|
||||
return datasetRepository.getDatasetSelectG2G3List(req);
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 전이학습 데이터셋 G2, G3 목록
|
||||
*
|
||||
@@ -327,6 +340,18 @@ public class ModelTrainMngCoreService {
|
||||
return datasetRepository.getDatasetTransferSelectG2G3List(modelId, modelNo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 데이터셋 G4 목록
|
||||
*
|
||||
* @param req
|
||||
* @return
|
||||
*/
|
||||
public List<SelectDataSet> getDatasetSelectG4List(DatasetReq req) {
|
||||
return datasetRepository.getDatasetSelectG4List(req);
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 모델관리 조회
|
||||
*
|
||||
@@ -341,6 +366,20 @@ public class ModelTrainMngCoreService {
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델관리 조회
|
||||
*
|
||||
* @param uuid
|
||||
* @return
|
||||
*/
|
||||
public ModelTrainMngDto.Basic findModelByUuid(UUID uuid) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + uuid));
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
/** 마스터를 IN_PROGRESS로 전환하고, 현재 실행 jobId를 연결 - UI/중단/상태조회 모두 currentAttemptId를 기준으로 동작 */
|
||||
@Transactional
|
||||
public void markInProgress(Long modelId, Long jobId) {
|
||||
@@ -430,6 +469,44 @@ public class ModelTrainMngCoreService {
|
||||
master.setUpdatedDttm(ZonedDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* step1 정지 처리
|
||||
*
|
||||
* @param modelId
|
||||
* @param errorMessage
|
||||
*/
|
||||
public void markStep1Stop(Long modelId, String errorMessage) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||
master.setStep1State(TrainStatusType.STOPPED.getId());
|
||||
master.setLastError(errorMessage);
|
||||
master.setUpdatedUid(userUtil.getId());
|
||||
master.setUpdatedDttm(ZonedDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* step2 정지 처리
|
||||
*
|
||||
* @param modelId
|
||||
* @param errorMessage
|
||||
*/
|
||||
public void markStep2Stop(Long modelId, String errorMessage) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||
master.setStep2State(TrainStatusType.STOPPED.getId());
|
||||
master.setLastError(errorMessage);
|
||||
master.setUpdatedUid(userUtil.getId());
|
||||
master.setUpdatedDttm(ZonedDateTime.now());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void markSuccess(Long modelId) {
|
||||
ModelMasterEntity master =
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.core;
|
||||
|
||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
||||
@@ -64,3 +65,4 @@ public class SystemMetricsCoreService {
|
||||
return isAvailable;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -117,10 +117,12 @@ public class DatasetEntity {
|
||||
@Column(name = "dataset_path", length = 1000)
|
||||
private String datasetPath;
|
||||
|
||||
// TODO 미사용시작
|
||||
@Column(name = "class_counts")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private Map<String, Integer> classCounts;
|
||||
|
||||
// TODO 미사용 끝
|
||||
@Size(max = 32)
|
||||
@Column(name = "uid")
|
||||
private String uid;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.entity;
|
||||
|
||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||
@@ -103,3 +104,4 @@ public class MapSheetEntity {
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -32,10 +32,13 @@ public class ModelDatasetMappEntity {
|
||||
@Column(name = "dataset_uid", nullable = false)
|
||||
private Long datasetUid;
|
||||
|
||||
// TODO 미사용시작
|
||||
@Size(max = 20)
|
||||
@Column(name = "dataset_type", length = 20)
|
||||
private String datasetType;
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
|
||||
@@ -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 */
|
||||
|
||||
@@ -141,6 +141,7 @@ public class ModelMasterEntity {
|
||||
this.packingState,
|
||||
this.packingStrtDttm,
|
||||
this.packingEndDttm,
|
||||
this.beforeModelId);
|
||||
this.beforeModelId,
|
||||
this.bestEpoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
@@ -92,3 +93,4 @@ public class ModelMngEntity {
|
||||
return this.uuid != null ? this.uuid.toString() : null;
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
@@ -53,3 +54,4 @@ public class SystemMetricsEntity {
|
||||
@Column(name = "memused")
|
||||
private Float memused;
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.repository;
|
||||
|
||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
||||
@@ -17,3 +18,4 @@ public interface SystemMetricsRepository extends JpaRepository<SystemMetricsEnti
|
||||
@Query("SELECT s FROM SystemMetricsEntity s ORDER BY s.timestamp DESC LIMIT 1")
|
||||
Optional<SystemMetricsEntity> findLatestMetrics();
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -24,4 +24,12 @@ public interface DatasetObjRepositoryCustom {
|
||||
void insertDatasetTestObj(DatasetObjRegDto objRegDto);
|
||||
|
||||
void insertDatasetValObj(DatasetObjRegDto objRegDto);
|
||||
|
||||
/**
|
||||
* 데이터셋 등록 실패시 Obj 데이터 정리
|
||||
*
|
||||
* @param datasetUid
|
||||
* @return
|
||||
*/
|
||||
int deleteAllDatasetObj(Long datasetUid);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
private final QDatasetEntity dataset = datasetEntity;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@PersistenceContext EntityManager em;
|
||||
|
||||
@@ -55,7 +56,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
||||
|
||||
@Override
|
||||
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String json;
|
||||
Geometry geometry;
|
||||
String geometryJson;
|
||||
@@ -99,7 +99,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
||||
|
||||
@Override
|
||||
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String json;
|
||||
String geometryJson;
|
||||
try {
|
||||
@@ -219,7 +218,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
||||
|
||||
@Override
|
||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String json;
|
||||
String geometryJson;
|
||||
try {
|
||||
@@ -276,4 +274,38 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
||||
.where(datasetObjEntity.uuid.eq(uuid))
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllDatasetObj(Long datasetUid) {
|
||||
int cnt = 0;
|
||||
cnt =
|
||||
em.createNativeQuery(
|
||||
"""
|
||||
delete from tb_dataset_obj
|
||||
where dataset_uid = ?
|
||||
""")
|
||||
.setParameter(1, datasetUid)
|
||||
.executeUpdate();
|
||||
|
||||
cnt +=
|
||||
em.createNativeQuery(
|
||||
"""
|
||||
delete from tb_dataset_val_obj
|
||||
where dataset_uid = ?
|
||||
""")
|
||||
.setParameter(1, datasetUid)
|
||||
.executeUpdate();
|
||||
|
||||
cnt +=
|
||||
em.createNativeQuery(
|
||||
"""
|
||||
delete from tb_dataset_test_obj
|
||||
where dataset_uid = ?
|
||||
""")
|
||||
.setParameter(1, datasetUid)
|
||||
.executeUpdate();
|
||||
|
||||
em.clear();
|
||||
return cnt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface DatasetRepository
|
||||
extends JpaRepository<DatasetEntity, Long>, DatasetRepositoryCustom {
|
||||
|
||||
// TODO 미사용시작
|
||||
List<DatasetEntity> findByDeletedOrderByCreatedDttmDesc(Boolean deleted);
|
||||
// TODO 미사용 끝
|
||||
}
|
||||
|
||||
@@ -18,12 +18,17 @@ public interface DatasetRepositoryCustom {
|
||||
|
||||
List<SelectDataSet> getDatasetSelectG1List(DatasetReq req);
|
||||
|
||||
// TODO 미사용시작
|
||||
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId);
|
||||
|
||||
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(Long modelId, String modelNo);
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req);
|
||||
|
||||
List<SelectDataSet> getDatasetSelectG4List(DatasetReq req);
|
||||
|
||||
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
||||
|
||||
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
||||
|
||||
@@ -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;
|
||||
@@ -98,9 +99,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||
}
|
||||
builder.and(dataset.deleted.isFalse());
|
||||
|
||||
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||
@@ -124,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)
|
||||
@@ -148,6 +150,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
.fetch();
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
||||
|
||||
@@ -245,28 +248,41 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
.fetch();
|
||||
}
|
||||
|
||||
// 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())) {
|
||||
@@ -308,6 +324,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
.fetch();
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
||||
Long modelId, String modelNo) {
|
||||
@@ -418,6 +435,8 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
.fetch();
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Override
|
||||
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
||||
return queryFactory
|
||||
@@ -473,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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.repository.dataset;
|
||||
|
||||
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
|
||||
@@ -11,3 +12,4 @@ public interface MapSheetRepository
|
||||
|
||||
long countByDatasetIdAndDeletedFalse(Long datasetId);
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.repository.dataset;
|
||||
|
||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||
@@ -7,3 +8,4 @@ import org.springframework.data.domain.Page;
|
||||
public interface MapSheetRepositoryCustom {
|
||||
Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq);
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO 미사용시작
|
||||
package com.kamco.cd.training.postgres.repository.dataset;
|
||||
|
||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||
@@ -52,3 +53,4 @@ public class MapSheetRepositoryImpl implements MapSheetRepositoryCustom {
|
||||
return new PageImpl<>(content, pageable, total);
|
||||
}
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
|
||||
@@ -8,5 +8,7 @@ import org.springframework.stereotype.Repository;
|
||||
@Repository
|
||||
public interface HyperParamRepository
|
||||
extends JpaRepository<ModelHyperParamEntity, Long>, HyperParamRepositoryCustom {
|
||||
// TODO 미사용시작
|
||||
Optional<ModelHyperParamEntity> findByHyperVer(String hyperVer);
|
||||
// TODO 미사용 끝
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.springframework.data.domain.Page;
|
||||
|
||||
public interface HyperParamRepositoryCustom {
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 마지막 버전 조회
|
||||
*
|
||||
@@ -19,6 +20,8 @@ public interface HyperParamRepositoryCustom {
|
||||
@Deprecated
|
||||
Optional<ModelHyperParamEntity> findHyperParamVer();
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 모델 타입별 마지막 버전 조회
|
||||
*
|
||||
@@ -27,8 +30,11 @@ public interface HyperParamRepositoryCustom {
|
||||
*/
|
||||
Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType);
|
||||
|
||||
// TODO 미사용시작
|
||||
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 하이퍼 파라미터 상세조회
|
||||
*
|
||||
|
||||
@@ -29,6 +29,7 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
||||
|
||||
@@ -42,6 +43,8 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
.fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Override
|
||||
public Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType) {
|
||||
|
||||
@@ -59,6 +62,7 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
.fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
||||
|
||||
@@ -75,6 +79,8 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
.fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Override
|
||||
public Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid) {
|
||||
return Optional.ofNullable(
|
||||
|
||||
@@ -7,14 +7,18 @@ import java.util.UUID;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public interface MembersRepositoryCustom {
|
||||
// TODO 미사용시작
|
||||
boolean existsByUserId(String userId);
|
||||
|
||||
// TODO 미사용 끝
|
||||
boolean existsByEmployeeNo(String employeeNo);
|
||||
|
||||
Optional<MemberEntity> findByEmployeeNo(String employeeNo);
|
||||
|
||||
// TODO 미사용시작
|
||||
Optional<MemberEntity> findByUserId(String userId);
|
||||
|
||||
// TODO 미사용 끝
|
||||
Optional<MemberEntity> findByUUID(UUID uuid);
|
||||
|
||||
Page<MemberEntity> findByMembers(MembersDto.SearchReq searchReq);
|
||||
|
||||
@@ -27,6 +27,7 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
||||
this.queryFactory = queryFactory;
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 사용자 ID 조회
|
||||
*
|
||||
@@ -43,6 +44,8 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
||||
!= null;
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 사용자 사번 조회
|
||||
*
|
||||
@@ -59,6 +62,7 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
||||
!= null;
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* 사용자 조회 user id
|
||||
*
|
||||
@@ -71,6 +75,8 @@ public class MembersRepositoryImpl extends QuerydslRepositorySupport
|
||||
queryFactory.selectFrom(memberEntity).where(memberEntity.userId.eq(userId)).fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
/**
|
||||
* 사용자 조회 employeed no
|
||||
*
|
||||
|
||||
@@ -6,5 +6,7 @@ import java.util.Optional;
|
||||
public interface ModelConfigRepositoryCustom {
|
||||
Optional<ModelConfigDto.Basic> findModelConfigByModelId(Long modelId);
|
||||
|
||||
// TODO 미사용시작
|
||||
Optional<ModelConfigDto.TransferBasic> findModelTransferConfigByModelId(Long modelId);
|
||||
// TODO 미사용 끝
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ public class ModelConfigRepositoryImpl implements ModelConfigRepositoryCustom {
|
||||
.fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public Optional<TransferBasic> findModelTransferConfigByModelId(Long modelId) {
|
||||
QModelConfigEntity beforeConfig = new QModelConfigEntity("beforeConfig");
|
||||
@@ -78,4 +79,5 @@ public class ModelConfigRepositoryImpl implements ModelConfigRepositoryCustom {
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.fetchOne());
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -23,8 +23,11 @@ public interface ModelDetailRepositoryCustom {
|
||||
|
||||
HyperSummary getByModelHyperParamSummary(UUID uuid);
|
||||
|
||||
// TODO 미사용시작
|
||||
TransferHyperSummary getByModelTransferHyperParamSummary(UUID uuid);
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
List<MappingDataset> getByModelMappingDataset(UUID uuid);
|
||||
|
||||
ModelMasterEntity findByModelByUUID(UUID uuid);
|
||||
|
||||
@@ -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;
|
||||
@@ -154,10 +158,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 +237,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -20,9 +21,22 @@ public interface ModelMngRepositoryCustom {
|
||||
|
||||
Optional<ModelMasterEntity> findByUuid(UUID uuid);
|
||||
|
||||
// TODO 미사용시작
|
||||
Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn);
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
TrainRunRequest findTrainRunRequest(Long modelId);
|
||||
|
||||
Long findModelStep1InProgressCnt();
|
||||
|
||||
/**
|
||||
* 모델 번호와 삭제 여부로 모델 조회 (최신순)
|
||||
*
|
||||
* @param modelNo 모델 번호 (G1, G2, G3, G4)
|
||||
* @param delYn 삭제 여부
|
||||
* @return 모델 목록
|
||||
*/
|
||||
List<ModelMasterEntity> findByModelNoAndDelYnOrderByCreatedDttmDesc(
|
||||
String modelNo, Boolean delYn);
|
||||
}
|
||||
|
||||
@@ -133,11 +133,14 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
||||
.fetchOne());
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Override
|
||||
public Optional<ModelMasterEntity> findFirstByStatusCdAndDelYn(String statusCd, Boolean delYn) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Override
|
||||
public TrainRunRequest findTrainRunRequest(Long modelId) {
|
||||
return queryFactory
|
||||
@@ -208,4 +211,14 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ public interface ModelTestMetricsJobRepositoryCustom {
|
||||
|
||||
List<ResponsePathDto> getTestMetricSaveNotYetModelIds();
|
||||
|
||||
ResponsePathDto getTestMetricSaveNotYetModelId(Long modelId);
|
||||
|
||||
void insertModelMetricsTest(List<Object[]> batchArgs);
|
||||
|
||||
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
||||
|
||||
@@ -63,6 +63,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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -213,4 +213,27 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,11 @@ import org.springframework.stereotype.Service;
|
||||
public class DataSetCountersService {
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
|
||||
@Value("${train.docker.requestDir}")
|
||||
@Value("${train.docker.request_dir}")
|
||||
private String requestDir;
|
||||
|
||||
@Value("${train.docker.basePath}")
|
||||
private String trainBaseDir;
|
||||
@Value("${train.docker.symbolic_link_dir}")
|
||||
private String symbolicDir;
|
||||
|
||||
public String getCount(Long modelId) {
|
||||
ModelTrainMngDto.Basic basic = modelTrainMngCoreService.findModelById(modelId);
|
||||
@@ -45,7 +45,7 @@ public class DataSetCountersService {
|
||||
}
|
||||
|
||||
// tmp
|
||||
Path tmpPath = Path.of(trainBaseDir, "tmp", basic.getRequestPath());
|
||||
Path tmpPath = Path.of(symbolicDir, basic.getRequestPath());
|
||||
|
||||
// 차이나는거
|
||||
diffMergedRequestsVsTmp(uids, tmpPath);
|
||||
@@ -222,7 +222,9 @@ public class DataSetCountersService {
|
||||
log.info("missing = {}", missing.size());
|
||||
log.info("extra = {}", extra.size());
|
||||
|
||||
log.info("[MISSING] total = {}", missing.size());
|
||||
missing.stream().sorted().limit(50).forEach(f -> log.warn("[MISSING] {}", f));
|
||||
log.info("[EXTRA] total = {}", extra.size());
|
||||
extra.stream().sorted().limit(50).forEach(f -> log.warn("[EXTRA] {}", f));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,25 +31,40 @@ public class DockerTrainService {
|
||||
private String image;
|
||||
|
||||
// 학습 요청 데이터가 위치한 호스트 디렉토리
|
||||
@Value("${train.docker.requestDir}")
|
||||
@Value("${train.docker.request_dir}")
|
||||
private String requestDir;
|
||||
|
||||
// 학습 결과가 저장될 호스트 디렉토리
|
||||
@Value("${train.docker.responseDir}")
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
// 컨테이너 이름 prefix
|
||||
@Value("${train.docker.containerPrefix}")
|
||||
private String containerPrefix;
|
||||
|
||||
// 공유메모리 사이즈 설정 (대용량 학습시 필요)
|
||||
@Value("${train.docker.shmSize:16g}")
|
||||
@Value("${train.docker.shm_size:16g}")
|
||||
private String shmSize;
|
||||
|
||||
// data 경로 request,response 상위 폴더
|
||||
@Value("${train.docker.base_path}")
|
||||
private String basePath;
|
||||
|
||||
@Value("${train.docker.symbolic_link_dir}")
|
||||
private String symbolicDir;
|
||||
|
||||
// IPC host 사용 여부
|
||||
@Value("${train.docker.ipcHost:true}")
|
||||
@Value("${train.docker.ipc_host:true}")
|
||||
private boolean ipcHost;
|
||||
|
||||
@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;
|
||||
|
||||
/**
|
||||
@@ -254,9 +269,11 @@ public class DockerTrainService {
|
||||
|
||||
// 요청/결과 디렉토리 볼륨 마운트
|
||||
c.add("-v");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
c.add(symbolicDir + ":/data"); // 요청할경로
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints"); // 저장될경로
|
||||
|
||||
// 표준입력 유지 (-it 대신 -i만 사용)
|
||||
c.add("-i");
|
||||
@@ -273,8 +290,17 @@ public class DockerTrainService {
|
||||
addArg(c, "--output-folder", req.getOutputFolder());
|
||||
addArg(c, "--input-size", req.getInputSize());
|
||||
addArg(c, "--crop-size", req.getCropSize());
|
||||
addArg(c, "--batch-size", req.getBatchSize());
|
||||
addArg(c, "--gpu-ids", req.getGpuIds()); // null
|
||||
// addArg(c, "--batch-size", req.getBatchSize());
|
||||
// addArg(c, "--gpu-ids", req.getGpuIds()); // null
|
||||
if ("prod".equals(profile)) {
|
||||
addArg(c, "--batch-size", 2); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
|
||||
|
||||
} else {
|
||||
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());
|
||||
@@ -440,11 +466,14 @@ public class DockerTrainService {
|
||||
c.add("--rm");
|
||||
c.add("--gpus");
|
||||
c.add("all");
|
||||
|
||||
c.add("--ipc=host");
|
||||
c.add("--shm-size=" + shmSize);
|
||||
|
||||
c.add("-v");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||
c.add("-v");
|
||||
c.add(basePath + "/tmp:/data");
|
||||
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
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;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -41,14 +34,8 @@ public class JobRecoveryOnStartupService {
|
||||
|
||||
private final ModelTrainJobCoreService modelTrainJobCoreService;
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
|
||||
/**
|
||||
* Docker 컨테이너가 쓰는 response(산출물) 디렉토리의 "호스트 측" 베이스 경로. 예) /data/train/response
|
||||
*
|
||||
* <p>컨테이너가 --rm 으로 삭제된 경우에도 이 경로에 val.csv / *.pth 등이 남아있으면 정상 종료 여부를 "파일 기반"으로 판정합니다.
|
||||
*/
|
||||
@Value("${train.docker.responseDir}")
|
||||
private String responseDir;
|
||||
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||
private final TrainUtilService trainUtilService;
|
||||
|
||||
/**
|
||||
* 스프링 부팅 완료 시점(빈 생성/초기화 모두 끝난 뒤)에 복구 로직 실행.
|
||||
@@ -56,7 +43,7 @@ public class JobRecoveryOnStartupService {
|
||||
* <p>@Transactional: - recover() 메서드 전체가 하나의 트랜잭션으로 감싸집니다. - Job 하나씩 처리하다가 예외가 발생하면 전체 롤백이 될 수
|
||||
* 있으므로 "잡 단위로 확실히 커밋"이 필요하면 (권장) 잡 단위로 분리 트랜잭션(REQUIRES_NEW) 고려하세요.
|
||||
*/
|
||||
// @EventListener(ApplicationReadyEvent.class)
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional
|
||||
public void recover() {
|
||||
|
||||
@@ -74,7 +61,7 @@ public class JobRecoveryOnStartupService {
|
||||
|
||||
try {
|
||||
// 2-1) docker inspect로 컨테이너 상태 조회
|
||||
DockerInspectState state = inspectContainer(containerName);
|
||||
DockerInspectState state = trainUtilService.inspectContainer(containerName);
|
||||
|
||||
// 3) 컨테이너가 "없음"
|
||||
// - docker run --rm 로 실행한 컨테이너는 정상 종료 시 바로 삭제될 수 있음
|
||||
@@ -85,63 +72,94 @@ public class JobRecoveryOnStartupService {
|
||||
containerName);
|
||||
|
||||
// 3-1) 컨테이너가 없을 때는 산출물(responseDir)을 보고 완료 여부를 "추정"
|
||||
OutputResult out = probeOutputs(job);
|
||||
OutputResult out = trainUtilService.probeOutputs(job);
|
||||
|
||||
// 3-2) 산출물이 충분하면 성공 처리
|
||||
if (out.completed()) {
|
||||
log.info("[RECOVERY] outputs look completed. mark SUCCESS. jobId={}", job.getId());
|
||||
modelTrainJobCoreService.markSuccess(job.getId(), 0);
|
||||
// model 상태 변경
|
||||
markStepSuccessByJobType(job);
|
||||
// 결과 csv 파일 정보 등록
|
||||
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
||||
|
||||
} else {
|
||||
// 3-3) 산출물이 부족하면 실패 처리(운영 정책에 따라 "유예"도 가능)
|
||||
|
||||
// 3-3) 산출물이 부족하면 중단처리
|
||||
// 산출물이 부족하면 "중단/보류"로 처리
|
||||
// 운영자가 재시작 할 수 있게 한다.
|
||||
log.warn(
|
||||
"[RECOVERY] outputs incomplete. mark FAILED. jobId={} reason={}",
|
||||
"[RECOVERY] outputs incomplete. mark PAUSED/STOP for restart. jobId={} reason={}",
|
||||
job.getId(),
|
||||
out.reason());
|
||||
|
||||
modelTrainJobCoreService.markFailed(
|
||||
// PAUSED/STOP
|
||||
modelTrainJobCoreService.markPaused(
|
||||
job.getId(), -1, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE");
|
||||
|
||||
markStepErrorByJobType(job, out.reason());
|
||||
// 모델도 에러가 아니라 STOP으로
|
||||
markStepStopByJobType(
|
||||
job, "SERVER_RESTART_CONTAINER_MISSING_OUTPUT_INCOMPLETE: " + out.reason());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 4) 컨테이너는 존재하고, 아직 running=true
|
||||
// - 서버만 재기동됐고 컨테이너는 그대로 살아있는 케이스
|
||||
// - 이 경우 DB를 건드리면 오히려 꼬일 수 있으니 RUNNING 유지
|
||||
// - 실행중 docker 를 kill 하고 이어하기를 한다,
|
||||
if (state.running()) {
|
||||
log.info("[RECOVERY] container still running. container={}", containerName);
|
||||
log.warn("[RECOVERY] container still running. force kill. container={}", containerName);
|
||||
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder("docker", "stop", "-t", "20", containerName);
|
||||
// ============================================================
|
||||
// 1) docker kill (SIGKILL) 바로 전송
|
||||
// - kill은 즉시 종료
|
||||
// ============================================================
|
||||
ProcessBuilder pb = new ProcessBuilder("docker", "kill", containerName);
|
||||
pb.redirectErrorStream(true);
|
||||
|
||||
Process p = pb.start();
|
||||
|
||||
boolean finished = p.waitFor(30, TimeUnit.SECONDS);
|
||||
boolean finished = p.waitFor(20, TimeUnit.SECONDS);
|
||||
if (!finished) {
|
||||
p.destroyForcibly();
|
||||
throw new IOException("docker stop timeout");
|
||||
throw new IOException("docker kill timeout");
|
||||
}
|
||||
|
||||
int code = p.exitValue();
|
||||
if (code != 0) {
|
||||
throw new IOException("docker stop failed. exit=" + code);
|
||||
throw new IOException("docker kill failed. exit=" + code);
|
||||
}
|
||||
|
||||
log.info(
|
||||
"[RECOVERY] container stopped (will be auto removed by --rm). container={}",
|
||||
containerName);
|
||||
// ============================================================
|
||||
// 2) kill 후 실제로 죽었는지 확인
|
||||
// ============================================================
|
||||
DockerInspectState after = trainUtilService.inspectContainer(containerName);
|
||||
if (after.exists() && after.running()) {
|
||||
throw new IOException("docker kill returned 0 but container still running");
|
||||
}
|
||||
|
||||
// 여기서 상태를 PAUSED로 바꿔도 되고
|
||||
modelTrainJobCoreService.markPaused(job.getId(), -1, "AUTO_STOP_FAILED_ON_RESTART");
|
||||
log.info("[RECOVERY] container killed successfully. container={}", containerName);
|
||||
|
||||
// ============================================================
|
||||
// 3) job 상태를 PAUSED로 변경 (서버 재기동으로 강제 중단)
|
||||
// ============================================================
|
||||
|
||||
modelTrainJobCoreService.markPaused(job.getId(), -1, "AUTO_KILLED_ON_SERVER_RESTART");
|
||||
|
||||
log.info("job = {}", job);
|
||||
markStepStopByJobType(job, "AUTO_KILLED_ON_SERVER_RESTART");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("[RECOVERY] docker stop failed. container={}", containerName, e);
|
||||
|
||||
modelTrainJobCoreService.markFailed(job.getId(), -1, "AUTO_STOP_FAILED_ON_RESTART");
|
||||
log.error("[RECOVERY] docker kill failed. container={}", containerName, e);
|
||||
|
||||
modelTrainJobCoreService.markFailed(
|
||||
job.getId(), -1, "AUTO_KILL_FAILED_ON_SERVER_RESTART");
|
||||
|
||||
markStepErrorByJobType(job, "AUTO_KILL_FAILED_ON_SERVER_RESTART");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -154,7 +172,10 @@ public class JobRecoveryOnStartupService {
|
||||
if (exitCode != null && exitCode == 0) {
|
||||
log.info("[RECOVERY] container exited(0). mark SUCCESS. container={}", containerName);
|
||||
modelTrainJobCoreService.markSuccess(job.getId(), 0);
|
||||
// model 상태 변경
|
||||
markStepSuccessByJobType(job);
|
||||
// 결과 csv 파일 정보 등록
|
||||
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
||||
|
||||
} else {
|
||||
// 5-2) exitCode != 0 이거나 null이면 실패로 간주 → FAILED 처리
|
||||
@@ -166,7 +187,7 @@ public class JobRecoveryOnStartupService {
|
||||
|
||||
modelTrainJobCoreService.markFailed(
|
||||
job.getId(), exitCode, "SERVER_RESTART_CONTAINER_EXIT_NONZERO");
|
||||
|
||||
// model 상태 변경
|
||||
markStepErrorByJobType(job, "exit=" + exitCode + " status=" + status);
|
||||
}
|
||||
|
||||
@@ -178,7 +199,7 @@ public class JobRecoveryOnStartupService {
|
||||
|
||||
modelTrainJobCoreService.markFailed(
|
||||
job.getId(), -1, "SERVER_RESTART_CONTAINER_INSPECT_ERROR");
|
||||
|
||||
// model 상태 변경
|
||||
markStepErrorByJobType(job, "inspect-error");
|
||||
}
|
||||
}
|
||||
@@ -204,6 +225,16 @@ public class JobRecoveryOnStartupService {
|
||||
*
|
||||
* <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);
|
||||
}
|
||||
}
|
||||
|
||||
private void markStepErrorByJobType(ModelTrainJobDto job, String msg) {
|
||||
Map<String, Object> params = job.getParamsJson();
|
||||
boolean isEval = params != null && "EVAL".equals(String.valueOf(params.get("jobType")));
|
||||
@@ -213,237 +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 {
|
||||
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");
|
||||
}
|
||||
|
||||
Path valCsv = outDir.resolve("val.csv");
|
||||
if (!Files.exists(valCsv)) {
|
||||
return new OutputResult(false, "val.csv-missing");
|
||||
}
|
||||
|
||||
long lines = countNonHeaderLines(valCsv);
|
||||
|
||||
// “같아야 완료” 정책
|
||||
if (lines == totalEpoch) {
|
||||
return new OutputResult(true, "ok");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class ModelTestMetricsJobService {
|
||||
private String profile;
|
||||
|
||||
// 학습 결과가 저장될 호스트 디렉토리
|
||||
@Value("${train.docker.responseDir}")
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
@Value("${file.pt-path}")
|
||||
@@ -59,119 +59,133 @@ 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
|
||||
*/
|
||||
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 =
|
||||
ModelMetricJsonDto jsonDto =
|
||||
modelTestMetricsJobCoreService.getTestMetricPackingInfo(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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
|
||||
|
||||
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);
|
||||
}
|
||||
ModelTestFileName fileInfo =
|
||||
modelTestMetricsJobCoreService.findModelTestFileNames(modelInfo.getModelId());
|
||||
|
||||
try {
|
||||
zipFiles(files, zipPath);
|
||||
Path zipPath =
|
||||
Paths.get(
|
||||
responseDir + "/" + modelInfo.getUuid() + "/" + fileInfo.getModelVersion() + ".zip");
|
||||
Set<String> targetNames =
|
||||
Set.of(
|
||||
"model_config.py",
|
||||
fileInfo.getBestEpochFileName() + ".pth",
|
||||
fileInfo.getModelVersion() + ".json");
|
||||
|
||||
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);
|
||||
}
|
||||
List<Path> files = new ArrayList<>();
|
||||
try (Stream<Path> s = Files.list(responsePath)) {
|
||||
files.addAll(
|
||||
s.filter(Files::isRegularFile)
|
||||
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
||||
.collect(Collectors.toList()));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try (Stream<Path> s = Files.list(Path.of(ptPathDir))) {
|
||||
files.addAll(
|
||||
s.filter(Files::isRegularFile)
|
||||
.limit(1) // yolov8_6th-6m.pt 파일 1개만
|
||||
.collect(Collectors.toList()));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
zipFiles(files, zipPath);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ public class ModelTrainMetricsJobService {
|
||||
private String profile;
|
||||
|
||||
// 학습 결과가 저장될 호스트 디렉토리
|
||||
@Value("${train.docker.responseDir}")
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
/** 결과 csv 파일 정보 등록 */
|
||||
@@ -48,109 +48,151 @@ 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); ) {
|
||||
createFile(modelInfo);
|
||||
}
|
||||
}
|
||||
|
||||
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
||||
/** 단건 결과 csv 파일 정보 등록 */
|
||||
public void trainValidMetricCsvFile(Long modelId) {
|
||||
|
||||
List<Object[]> batchArgs = new ArrayList<>();
|
||||
ResponsePathDto modelInfo =
|
||||
modelTrainMetricsJobCoreService.getTrainMetricSaveNotYetModelId(modelId);
|
||||
|
||||
for (CSVRecord record : parser) {
|
||||
if (modelInfo == null) {
|
||||
return;
|
||||
}
|
||||
createFile(modelInfo);
|
||||
}
|
||||
|
||||
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"));
|
||||
/**
|
||||
* 학습 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); ) {
|
||||
|
||||
batchArgs.add(new Object[] {modelInfo.getModelId(), epoch, iteration, Loss, LR, time});
|
||||
}
|
||||
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
||||
|
||||
modelTrainMetricsJobCoreService.insertModelMetricsTrain(batchArgs);
|
||||
List<Object[]> batchArgs = new ArrayList<>();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
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});
|
||||
}
|
||||
|
||||
String validationPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/val.csv";
|
||||
try (BufferedReader reader =
|
||||
Files.newBufferedReader(Paths.get(validationPath), StandardCharsets.UTF_8); ) {
|
||||
modelTrainMetricsJobCoreService.insertModelMetricsTrain(batchArgs);
|
||||
|
||||
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
List<Object[]> batchArgs = new ArrayList<>();
|
||||
String validationPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/val.csv";
|
||||
try (BufferedReader reader =
|
||||
Files.newBufferedReader(Paths.get(validationPath), StandardCharsets.UTF_8); ) {
|
||||
|
||||
for (CSVRecord record : parser) {
|
||||
CSVParser parser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
|
||||
|
||||
int epoch = Integer.parseInt(record.get("Epoch"));
|
||||
float aAcc = Float.parseFloat(record.get("aAcc"));
|
||||
float mFscore = Float.parseFloat(record.get("mFscore"));
|
||||
float mPrecision = Float.parseFloat(record.get("mPrecision"));
|
||||
float mRecall = Float.parseFloat(record.get("mRecall"));
|
||||
float mIoU = Float.parseFloat(record.get("mIoU"));
|
||||
float mAcc = Float.parseFloat(record.get("mAcc"));
|
||||
float changed_fscore = Float.parseFloat(record.get("changed_fscore"));
|
||||
float changed_precision = Float.parseFloat(record.get("changed_precision"));
|
||||
float changed_recall = Float.parseFloat(record.get("changed_recall"));
|
||||
float unchanged_fscore = Float.parseFloat(record.get("unchanged_fscore"));
|
||||
float unchanged_precision = Float.parseFloat(record.get("unchanged_precision"));
|
||||
float unchanged_recall = Float.parseFloat(record.get("unchanged_recall"));
|
||||
List<Object[]> batchArgs = new ArrayList<>();
|
||||
|
||||
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
|
||||
});
|
||||
}
|
||||
for (CSVRecord record : parser) {
|
||||
|
||||
modelTrainMetricsJobCoreService.insertModelMetricsValidation(batchArgs);
|
||||
int epoch = Integer.parseInt(record.get("Epoch"));
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
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
|
||||
});
|
||||
}
|
||||
|
||||
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
|
||||
Integer epoch = null;
|
||||
boolean exists;
|
||||
Pattern pattern = Pattern.compile("best_changed_fscore_epoch_(\\d+)\\.pth");
|
||||
modelTrainMetricsJobCoreService.insertModelMetricsValidation(batchArgs);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
} 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");
|
||||
|
||||
// best_changed_fscore_epoch_숫자.pth -> 숫자 값 가지고 와서 베스트 에폭에 업데이트 하기
|
||||
modelTrainMetricsJobCoreService.updateModelSelectedBestEpoch(modelInfo.getModelId(), epoch);
|
||||
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);
|
||||
|
||||
modelTrainMetricsJobCoreService.updateModelMetricsTrainSaveYn(
|
||||
modelInfo.getModelId(), "step1");
|
||||
} 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;
|
||||
|
||||
value = value.trim();
|
||||
|
||||
if (value.isEmpty()) return null;
|
||||
|
||||
if (value.equalsIgnoreCase("nan")) return null;
|
||||
|
||||
float f = Float.parseFloat(value);
|
||||
|
||||
return Float.isNaN(f) ? null : f;
|
||||
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,11 +14,11 @@ import org.springframework.stereotype.Service;
|
||||
@RequiredArgsConstructor
|
||||
public class TmpDatasetService {
|
||||
|
||||
@Value("${train.docker.requestDir}")
|
||||
@Value("${train.docker.request_dir}")
|
||||
private String requestDir;
|
||||
|
||||
@Value("${train.docker.basePath}")
|
||||
private String trainBaseDir;
|
||||
@Value("${train.docker.symbolic_link_dir}")
|
||||
private String symbolicDir;
|
||||
|
||||
/**
|
||||
* train, val, test 폴더별로 link
|
||||
@@ -36,9 +36,9 @@ public class TmpDatasetService {
|
||||
throw new IOException("links is empty");
|
||||
}
|
||||
|
||||
Path tmp = Path.of(trainBaseDir, "tmp", uid);
|
||||
Path tmp = Path.of(symbolicDir, uid);
|
||||
|
||||
long hardlinksMade = 0;
|
||||
long linksMade = 0;
|
||||
|
||||
for (ModelTrainLinkDto dto : links) {
|
||||
|
||||
@@ -54,27 +54,26 @@ public class TmpDatasetService {
|
||||
Files.createDirectories(tmp.resolve(type).resolve("label-json"));
|
||||
|
||||
// comparePath → input1
|
||||
hardlinksMade += link(tmp, type, "input1", dto.getComparePath());
|
||||
linksMade += link(tmp, type, "input1", dto.getComparePath());
|
||||
|
||||
// targetPath → input2
|
||||
hardlinksMade += link(tmp, type, "input2", dto.getTargetPath());
|
||||
linksMade += link(tmp, type, "input2", dto.getTargetPath());
|
||||
|
||||
// labelPath → label
|
||||
hardlinksMade += link(tmp, type, "label", dto.getLabelPath());
|
||||
linksMade += link(tmp, type, "label", dto.getLabelPath());
|
||||
|
||||
// geoJsonPath -> label-json
|
||||
hardlinksMade += link(tmp, type, "label-json", dto.getGeoJsonPath());
|
||||
linksMade += link(tmp, type, "label-json", dto.getGeoJsonPath());
|
||||
}
|
||||
|
||||
if (hardlinksMade == 0) {
|
||||
throw new IOException("No hardlinks created.");
|
||||
if (linksMade == 0) {
|
||||
throw new IOException("No symlinks created.");
|
||||
}
|
||||
|
||||
log.info("tmp dataset created: {}, hardlinksMade={}", tmp, hardlinksMade);
|
||||
log.info("tmp dataset created: {}, linksMade={}", tmp, linksMade);
|
||||
}
|
||||
|
||||
private long link(Path tmp, String type, String part, String fullPath) throws IOException {
|
||||
|
||||
if (fullPath == null || fullPath.isBlank()) return 0;
|
||||
|
||||
Path src = Path.of(fullPath);
|
||||
@@ -87,20 +86,19 @@ public class TmpDatasetService {
|
||||
String fileName = src.getFileName().toString();
|
||||
Path dst = tmp.resolve(type).resolve(part).resolve(fileName);
|
||||
|
||||
// 충돌 시 덮어쓰기
|
||||
if (Files.exists(dst)) {
|
||||
Files.createDirectories(dst.getParent());
|
||||
|
||||
if (Files.exists(dst) || Files.isSymbolicLink(dst)) {
|
||||
Files.delete(dst);
|
||||
}
|
||||
|
||||
Files.createLink(dst, src);
|
||||
Files.createSymbolicLink(dst, src);
|
||||
log.info("symlink created: {} -> {}", dst, src);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private String safe(String s) {
|
||||
return (s == null || s.isBlank()) ? null : s.trim();
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
/**
|
||||
* request 전체 폴더 link
|
||||
*
|
||||
@@ -111,19 +109,19 @@ public class TmpDatasetService {
|
||||
*/
|
||||
public String buildTmpDatasetSymlink(String uid, List<String> datasetUids) throws IOException {
|
||||
|
||||
log.info("========== buildTmpDatasetHardlink START ==========");
|
||||
log.info("========== buildTmpDatasetSymlink START ==========");
|
||||
log.info("uid={}", uid);
|
||||
log.info("datasetUids={}", datasetUids);
|
||||
log.info("requestDir(raw)={}", requestDir);
|
||||
|
||||
Path BASE = toPath(requestDir);
|
||||
Path tmp = Path.of(trainBaseDir, "tmp", uid);
|
||||
Path tmp = Path.of(symbolicDir, uid);
|
||||
|
||||
log.info("BASE={}", BASE);
|
||||
log.info("BASE exists? {}", Files.isDirectory(BASE));
|
||||
log.info("tmp={}", tmp);
|
||||
|
||||
long noDir = 0, scannedDirs = 0, regularFiles = 0, hardlinksMade = 0;
|
||||
long noDir = 0, scannedDirs = 0, regularFiles = 0, symlinksMade = 0;
|
||||
|
||||
// tmp 디렉토리 준비
|
||||
for (String type : List.of("train", "val", "test")) {
|
||||
@@ -134,26 +132,7 @@ public class TmpDatasetService {
|
||||
}
|
||||
}
|
||||
|
||||
// 하드링크는 "같은 파일시스템"에서만 가능하므로 BASE/tmp가 같은 FS인지 미리 확인(권장)
|
||||
try {
|
||||
var baseStore = Files.getFileStore(BASE);
|
||||
var tmpStore = Files.getFileStore(tmp.getParent()); // BASE/tmp
|
||||
if (!baseStore.name().equals(tmpStore.name()) || !baseStore.type().equals(tmpStore.type())) {
|
||||
throw new IOException(
|
||||
"Hardlink requires same filesystem. baseStore="
|
||||
+ baseStore.name()
|
||||
+ "("
|
||||
+ baseStore.type()
|
||||
+ "), tmpStore="
|
||||
+ tmpStore.name()
|
||||
+ "("
|
||||
+ tmpStore.type()
|
||||
+ ")");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// FileStore 비교가 환경마다 애매할 수 있어서, 여기서는 경고만 주고 실제 createLink에서 최종 판단하게 둘 수도 있음.
|
||||
log.warn("FileStore check skipped/failed (will rely on createLink): {}", e.toString());
|
||||
}
|
||||
// 심볼릭 링크는 파일시스템이 달라도 작동하므로 FileStore 체크 불필요
|
||||
|
||||
for (String id : datasetUids) {
|
||||
Path srcRoot = BASE.resolve(id);
|
||||
@@ -191,13 +170,12 @@ public class TmpDatasetService {
|
||||
}
|
||||
|
||||
try {
|
||||
// 하드링크 생성 (dst가 새 파일로 생기지만 inode는 f와 동일)
|
||||
Files.createLink(dst, f);
|
||||
hardlinksMade++;
|
||||
log.debug("created hardlink: {} => {}", dst, f);
|
||||
// 심볼릭 링크 생성 (파일시스템이 달라도 작동)
|
||||
Files.createSymbolicLink(dst, f);
|
||||
symlinksMade++;
|
||||
log.debug("created symlink: {} => {}", dst, f);
|
||||
} catch (IOException e) {
|
||||
// 여기서 바로 실패시키면 “tmp는 만들었는데 내용은 0개” 같은 상태를 방지할 수 있음
|
||||
log.error("FAILED create hardlink: {} => {}", dst, f, e);
|
||||
log.error("FAILED create symlink: {} => {}", dst, f, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -206,9 +184,9 @@ public class TmpDatasetService {
|
||||
}
|
||||
}
|
||||
|
||||
if (hardlinksMade == 0) {
|
||||
if (symlinksMade == 0) {
|
||||
throw new IOException(
|
||||
"No hardlinks created. regularFiles="
|
||||
"No symlinks created. regularFiles="
|
||||
+ regularFiles
|
||||
+ ", scannedDirs="
|
||||
+ scannedDirs
|
||||
@@ -218,11 +196,11 @@ public class TmpDatasetService {
|
||||
|
||||
log.info("tmp dataset created: {}", tmp);
|
||||
log.info(
|
||||
"summary: scannedDirs={}, noDir={}, regularFiles={}, hardlinksMade={}",
|
||||
"summary: scannedDirs={}, noDir={}, regularFiles={}, symlinksMade={}",
|
||||
scannedDirs,
|
||||
noDir,
|
||||
regularFiles,
|
||||
hardlinksMade);
|
||||
symlinksMade);
|
||||
|
||||
return uid;
|
||||
}
|
||||
@@ -233,4 +211,5 @@ public class TmpDatasetService {
|
||||
}
|
||||
return Paths.get(p).toAbsolutePath().normalize();
|
||||
}
|
||||
// TODO 미사용 끝
|
||||
}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
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 java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -16,6 +20,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,14 +38,17 @@ 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.responseDir}")
|
||||
@Value("${train.docker.response_dir}")
|
||||
private String responseDir;
|
||||
|
||||
public Long getModelIdByUuid(UUID uuid) {
|
||||
@@ -268,13 +276,19 @@ public class TrainJobService {
|
||||
try {
|
||||
// 데이터셋 심볼링크 생성
|
||||
// String pathUid = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
|
||||
// train path
|
||||
// train path 모델 클래스별 조회
|
||||
List<ModelTrainLinkDto> trainList = modelTrainMngCoreService.findDatasetTrainPath(modelId);
|
||||
// validation path
|
||||
// validation path 모델 클래스별 조회
|
||||
List<ModelTrainLinkDto> valList = modelTrainMngCoreService.findDatasetValPath(modelId);
|
||||
// test path
|
||||
// test path 모델 클래스별 조회
|
||||
List<ModelTrainLinkDto> testList = modelTrainMngCoreService.findDatasetTestPath(modelId);
|
||||
|
||||
log.info(
|
||||
"createTmpFile class list trainList = {} valList = {} testList = {}",
|
||||
trainList.size(),
|
||||
valList.size(),
|
||||
testList.size());
|
||||
|
||||
// train 데이터셋 심볼링크 생성
|
||||
tmpDatasetService.buildTmpDatasetHardlink(raw, "train", trainList);
|
||||
// val 데이터셋 심볼링크 생성
|
||||
@@ -303,4 +317,133 @@ public class TrainJobService {
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,10 @@ public class TrainJobWorker {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* 0 정상 종료 SUCCESS 1~125 학습 코드 에러 FAILED 137 OOMKill FAILED 143 SIGTERM (stop) STOP -1 우리 내부
|
||||
* 강제 중단 STOP
|
||||
*/
|
||||
if (result.getExitCode() == 0) {
|
||||
// 성공 처리
|
||||
modelTrainJobCoreService.markSuccess(jobId, result.getExitCode());
|
||||
@@ -124,17 +128,36 @@ public class TrainJobWorker {
|
||||
}
|
||||
|
||||
} else {
|
||||
String failMsg = result.getStatus() + "\n" + result.getLogs();
|
||||
// 실패 처리
|
||||
modelTrainJobCoreService.markFailed(
|
||||
jobId, result.getExitCode(), result.getStatus() + "\n" + result.getLogs());
|
||||
|
||||
if (isEval) {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markStep2Error(modelId, "exit=" + result.getExitCode());
|
||||
String failMsg = result.getStatus() + "\n" + result.getLogs();
|
||||
log.info("training fail exitCode={} Msg ={}", result.getExitCode(), failMsg);
|
||||
|
||||
if (result.getExitCode() == -1
|
||||
|| result.getExitCode() == 143
|
||||
|| result.getExitCode() == 137) {
|
||||
// 실패 처리
|
||||
modelTrainJobCoreService.markPaused(
|
||||
jobId, result.getExitCode(), result.getStatus() + "\n" + result.getLogs());
|
||||
|
||||
if (isEval) {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markStep2Stop(modelId, "exit=" + result.getExitCode());
|
||||
} else {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markStep1Stop(modelId, "exit=" + result.getExitCode());
|
||||
}
|
||||
} else {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markError(modelId, "exit=" + result.getExitCode());
|
||||
// 실패 처리
|
||||
modelTrainJobCoreService.markFailed(
|
||||
jobId, result.getExitCode(), result.getStatus() + "\n" + result.getLogs());
|
||||
|
||||
if (isEval) {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markStep2Error(modelId, "exit=" + result.getExitCode());
|
||||
} else {
|
||||
// 오류 정보 등록
|
||||
modelTrainMngCoreService.markError(modelId, "exit=" + result.getExitCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,7 @@ public class UploadDto {
|
||||
private UUID uuid;
|
||||
}
|
||||
|
||||
// TODO 미사용시작
|
||||
@Schema(name = "UploadCompleteReq", description = "업로드 완료 요청")
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -126,12 +127,15 @@ public class UploadDto {
|
||||
@Schema(description = "상태", example = "UPLOADING")
|
||||
private String status;
|
||||
|
||||
// TODO 미사용시작
|
||||
@Schema(description = "총 청크 수", example = "100")
|
||||
private Integer totalChunks;
|
||||
|
||||
@Schema(description = "업로드된 청크 수", example = "50")
|
||||
private Integer uploadedChunks;
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Schema(description = "진행률 (%)", example = "50.0")
|
||||
private Double progress;
|
||||
|
||||
@@ -139,6 +143,8 @@ public class UploadDto {
|
||||
private String errorMessage;
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Schema(name = "UploadAddReq", description = "업로드 요청")
|
||||
@Getter
|
||||
@Setter
|
||||
|
||||
@@ -26,27 +26,21 @@ public class UploadService {
|
||||
|
||||
private final UploadSessionCoreService uploadSessionCoreService;
|
||||
|
||||
@Value("${file.sync-root-dir}")
|
||||
private String syncRootDir;
|
||||
|
||||
@Value("${file.sync-tmp-dir}")
|
||||
private String syncTmpDir;
|
||||
|
||||
@Value("${file.sync-file-extention}")
|
||||
private String syncFileExtention;
|
||||
|
||||
@Value("${file.dataset-dir}")
|
||||
private String datasetDir;
|
||||
|
||||
@Value("${file.dataset-tmp-dir}")
|
||||
private String datasetTmpDir;
|
||||
|
||||
// TODO 미사용시작
|
||||
@Transactional
|
||||
public DmlReturn initUpload(UploadDto.InitReq initReq) {
|
||||
|
||||
return new DmlReturn("success", "UPLOAD CHUNK INIT");
|
||||
}
|
||||
|
||||
// TODO 미사용 끝
|
||||
|
||||
@Transactional
|
||||
public UploadDto.UploadRes uploadChunk(UploadDto.UploadAddReq upAddReqDto, MultipartFile file) {
|
||||
|
||||
|
||||
@@ -1,72 +1,49 @@
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
on-profile: dev
|
||||
|
||||
jpa:
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate:
|
||||
default_batch_fetch_size: 100 # ✅ 성능 - N+1 쿼리 방지
|
||||
order_updates: true # ✅ 성능 - 업데이트 순서 정렬로 데드락 방지
|
||||
use_sql_comments: true # ⚠️ 선택 - SQL에 주석 추가 (디버깅용)
|
||||
format_sql: true # ⚠️ 선택 - SQL 포맷팅 (가독성)
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://192.168.2.127:15432/kamco_training_db
|
||||
# url: jdbc:postgresql://localhost:15432/kamco_training_db
|
||||
username: kamco_training_user
|
||||
password: kamco_training_user_2025_!@#
|
||||
hikari:
|
||||
minimum-idle: 10
|
||||
maximum-pool-size: 20
|
||||
connection-timeout: 60000 # 60초 연결 타임아웃
|
||||
idle-timeout: 300000 # 5분 유휴 타임아웃
|
||||
max-lifetime: 1800000 # 30분 최대 수명
|
||||
leak-detection-threshold: 60000 # 연결 누수 감지
|
||||
|
||||
transaction:
|
||||
default-timeout: 300 # 5분 트랜잭션 타임아웃
|
||||
|
||||
|
||||
jwt:
|
||||
secret: "kamco_token_dev_dfc6446d-68fc-4eba-a2ff-c80a14a0bf3a"
|
||||
access-token-validity-in-ms: 86400000 # 1일
|
||||
refresh-token-validity-in-ms: 604800000 # 7일
|
||||
|
||||
token:
|
||||
refresh-cookie-name: kamco-dev # 개발용 쿠키 이름
|
||||
refresh-cookie-secure: false # 로컬 http 테스트면 false
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
persist-authorization: true # 스웨거 새로고침해도 토큰 유지, 로컬스토리지에 저장
|
||||
|
||||
member:
|
||||
init_password: kamco1234!
|
||||
|
||||
swagger:
|
||||
local-port: 9080
|
||||
|
||||
file:
|
||||
sync-root-dir: /app/original-images/
|
||||
sync-tmp-dir: ${file.sync-root-dir}tmp/
|
||||
sync-file-extention: tfw,tif
|
||||
|
||||
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
|
||||
requestDir: /home/kcomu/data/request
|
||||
responseDir: /home/kcomu/data/response
|
||||
basePath: /home/kcomu/data
|
||||
containerPrefix: kamco-cd-train
|
||||
shmSize: 16g
|
||||
ipcHost: true
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
on-profile: dev
|
||||
|
||||
jpa:
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
use_sql_comments: true # ⚠️ 선택 - SQL에 주석 추가 (디버깅용)
|
||||
format_sql: true # ⚠️ 선택 - SQL 포맷팅 (가독성)
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://192.168.2.127:15432/kamco_training_db
|
||||
username: kamco_training_user
|
||||
password: kamco_training_user_2025_!@#
|
||||
hikari:
|
||||
minimum-idle: 10
|
||||
maximum-pool-size: 20
|
||||
|
||||
jwt:
|
||||
secret: "kamco_token_dev_dfc6446d-68fc-4eba-a2ff-c80a14a0bf3a"
|
||||
access-token-validity-in-ms: 86400000 # 1일
|
||||
refresh-token-validity-in-ms: 604800000 # 7일
|
||||
|
||||
token:
|
||||
refresh-cookie-name: kamco-dev # 개발용 쿠키 이름
|
||||
refresh-cookie-secure: false # 로컬 http 테스트면 false
|
||||
|
||||
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
|
||||
|
||||
@@ -1,72 +1,48 @@
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
on-profile: prod
|
||||
|
||||
jpa:
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate:
|
||||
default_batch_fetch_size: 100 # ✅ 성능 - N+1 쿼리 방지
|
||||
order_updates: true # ✅ 성능 - 업데이트 순서 정렬로 데드락 방지
|
||||
use_sql_comments: true # ⚠️ 선택 - SQL에 주석 추가 (디버깅용)
|
||||
format_sql: true # ⚠️ 선택 - SQL 포맷팅 (가독성)
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://127.0.01:15432/kamco_training_db
|
||||
# url: jdbc:postgresql://localhost:15432/kamco_training_db
|
||||
username: kamco_training_user
|
||||
password: kamco_training_user_2025_!@#
|
||||
hikari:
|
||||
minimum-idle: 10
|
||||
maximum-pool-size: 20
|
||||
connection-timeout: 60000 # 60초 연결 타임아웃
|
||||
idle-timeout: 300000 # 5분 유휴 타임아웃
|
||||
max-lifetime: 1800000 # 30분 최대 수명
|
||||
leak-detection-threshold: 60000 # 연결 누수 감지
|
||||
|
||||
transaction:
|
||||
default-timeout: 300 # 5분 트랜잭션 타임아웃
|
||||
|
||||
jwt:
|
||||
secret: "kamco_token_dev_dfc6446d-68fc-4eba-a2ff-c80a14a0bf3a"
|
||||
access-token-validity-in-ms: 86400000 # 1일
|
||||
refresh-token-validity-in-ms: 604800000 # 7일
|
||||
|
||||
token:
|
||||
refresh-cookie-name: kamco # 개발용 쿠키 이름
|
||||
refresh-cookie-secure: false # 로컬 http 테스트면 false
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
persist-authorization: true # 스웨거 새로고침해도 토큰 유지, 로컬스토리지에 저장
|
||||
|
||||
member:
|
||||
init_password: kamco1234!
|
||||
|
||||
swagger:
|
||||
local-port: 9080
|
||||
|
||||
file:
|
||||
sync-root-dir: /app/original-images/
|
||||
sync-tmp-dir: ${file.sync-root-dir}tmp/
|
||||
sync-file-extention: tfw,tif
|
||||
|
||||
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
|
||||
requestDir: /home/kcomu/data/request
|
||||
responseDir: /home/kcomu/data/response
|
||||
basePath: /home/kcomu/data
|
||||
containerPrefix: kamco-cd-train
|
||||
shmSize: 16g
|
||||
ipcHost: true
|
||||
|
||||
spring:
|
||||
config:
|
||||
activate:
|
||||
on-profile: prod
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://kamco-cd-train-db:5432/kamco_training_db
|
||||
username: kamco_training_user
|
||||
password: kamco_training_user_2025_!@#
|
||||
hikari:
|
||||
minimum-idle: 10
|
||||
maximum-pool-size: 20
|
||||
|
||||
jwt:
|
||||
# ⚠️ 운영 환경에서는 반드시 별도의 강력한 시크릿 키를 사용하세요
|
||||
secret: "kamco_token_prod_CHANGE_THIS_TO_SECURE_SECRET_KEY"
|
||||
access-token-validity-in-ms: 86400000 # 1일
|
||||
refresh-token-validity-in-ms: 604800000 # 7일
|
||||
|
||||
token:
|
||||
refresh-cookie-name: kamco
|
||||
refresh-cookie-secure: true # HTTPS 환경에서 필수
|
||||
|
||||
swagger:
|
||||
local-port: 9080
|
||||
|
||||
file:
|
||||
dataset-dir: /data/training/request/
|
||||
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||
|
||||
pt-path: /data/training/response/v6-cls-checkpoints/
|
||||
pt-FileName: yolov8_6th-6m.pt
|
||||
|
||||
train:
|
||||
docker:
|
||||
image: kamco-cd-train:latest
|
||||
base_path: /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: 4
|
||||
gpu-ids: 0,1,2,3
|
||||
batch-size: 30
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user