Compare commits
390 Commits
29e1d0ec7e
...
feat/train
| Author | SHA1 | Date | |
|---|---|---|---|
| 960e4215e0 | |||
| 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 | |||
| 265813e6f7 | |||
| 8190a6e9c8 | |||
| 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 | |||
| e9f8bb37fa | |||
| 17d69486ec | |||
| f3c822587f | |||
| 948f1061da | |||
| 335f0dbb9b | |||
| 42438b3cd5 | |||
| 69eaba1a83 | |||
| 524ae200b0 | |||
| 4f763d3c2e | |||
| 9ebf525387 | |||
| 4ab672a96e | |||
| 7d2a367e3f | |||
| 365ad81cad | |||
| 67a67749c3 | |||
| 9dfa54fbf9 | |||
| 251307b5c9 | |||
| 12f6bb7154 | |||
| 8423a03d31 | |||
| aa3af4e9d0 | |||
| d6cdf6b690 | |||
| 7ca37bf1e4 | |||
| 9cfa299e58 | |||
| 901dde066d | |||
| cb0a38274a | |||
| b8194df9ae | |||
| a137e71420 | |||
| 7c5f07683e | |||
| 159fb281d4 | |||
| 97192ff811 | |||
| 4f3fb675be | |||
| e6caea05b3 | |||
| f08f80622f | |||
| fd63824edc | |||
| 8a44df26b8 | |||
| cb97c5e59e | |||
| 8f75b16dc6 | |||
| e565fd7a34 | |||
| c2978e41c2 | |||
| 8c45b39dcc | |||
| 07429dbe8e | |||
| 83859bb9fe | |||
| b119f333ac | |||
| 564a99448c | |||
| bbe04ee458 | |||
| 38ae6e5575 | |||
| fab3c83a69 | |||
| 40fe98ae0c | |||
| fb87a0f32f | |||
| 255ff10a56 | |||
| f674f73330 | |||
| 63794ec4ec | |||
| db2bc32e7d | |||
| 37786a1e44 | |||
| 901ea83fb7 | |||
| bf6dc9740f | |||
| 832e1b5681 | |||
| a23bc8dd67 | |||
| 4f16355cda | |||
| 13023a06cc | |||
| df46a8f79f | |||
| fcd48831c5 | |||
| 28b50bd949 | |||
| 62c9d73b94 | |||
| 78ab928459 | |||
| 68c0e634c5 | |||
| ae3601cff5 | |||
| ad421e3c74 | |||
| 5f62f4a209 | |||
| 46db1512a6 | |||
| 29bf155b4f | |||
| 2034a8fcb2 | |||
| da03f8b749 | |||
| bf212842d8 | |||
| 6a2deff93b | |||
| d2ca94ea55 | |||
| b0a99afcd3 | |||
| 5ddf6dfeeb | |||
| eedf72d7aa | |||
| 5e13c0b396 | |||
| 25e9941464 | |||
| 435f60dcac | |||
| a0da0392cf | |||
| 5f5eabca19 | |||
| a3ebee12b5 | |||
| 413631840f | |||
| c7f63d1ad1 | |||
| c5b14ca09d | |||
| 7529d23488 | |||
| 44b3b857b1 | |||
| cb3e51d712 | |||
| 99a4597b5f | |||
| 63124455fd | |||
| d9da0d4610 | |||
| e75ea8d8a5 | |||
| 22c481556c | |||
| 31ac4209c3 | |||
| 0798b352c7 | |||
| df09935789 | |||
| 5b074bdb81 | |||
| bb15b1b0f2 | |||
| 28919345c2 | |||
| f4d491ed94 | |||
| aa0552aaa7 | |||
| 96cb7d2f23 | |||
| 5d0aca14a6 | |||
| cc6305b0df | |||
| af8d59ddfa | |||
| 3916b13876 | |||
| 4f24e09c57 | |||
| ee4a06df30 | |||
| 4da477706f | |||
| bb5ff7c3cd | |||
| a070566048 | |||
| 312a96dda1 | |||
| a5b3ae613f | |||
| e38231e06d | |||
| 979af088be | |||
| bf6e45d706 | |||
| e5a1cab36b | |||
| bb67996742 | |||
| 1981d6d1ce | |||
| 47f4ffd4db | |||
| 7fa8921a25 | |||
| 195856b846 | |||
| 7c940351d9 | |||
| 124da48e51 | |||
| 6b834da912 | |||
| 02724e9508 | |||
| 7ed91ccab9 | |||
| a7c13b985d | |||
| 25aaa97d65 | |||
| 352a28b87f | |||
| da9d47ae4a | |||
| bf8515163c | |||
| 7d6a77bf2a | |||
| 26828d0968 | |||
| 2691f6ce16 | |||
| e2dbae15c0 | |||
| b246034632 | |||
| 7e5aa5e713 | |||
| 060a815e1c | |||
| 687ea82d78 | |||
| 1eb4d04779 | |||
| f30c0c6d45 | |||
| 12994aab60 | |||
| 4ac0f19908 | |||
| 11d3afe295 | |||
| 9e5e7595eb | |||
| 1e62a8b097 | |||
| 9cd9274e99 | |||
| 26a4623aa8 | |||
| 5d82f3ecfe | |||
| ce6e4f5aea | |||
| 2ce249ab33 | |||
| c2215836c0 | |||
| e34bf68de0 | |||
| 8c19c996f7 | |||
| 862bda0cb9 | |||
| b5ce3ab1fb | |||
| 90f7b17d07 | |||
| e1ceb769dd | |||
| 2128baa46a | |||
| 4219b88fb3 | |||
| 4f94c99b64 | |||
| 875c30f467 | |||
| d42e1afbd4 | |||
| b3b8016673 | |||
| 2b29cd1ac6 | |||
| 79e8259f28 | |||
| 9206fff5d0 | |||
| 032c82c2f0 | |||
| 6204a6e5fa | |||
| 4d9c9a86b4 | |||
| 83204abfe9 | |||
| 5b682c1386 | |||
| 452494d44d | |||
| 8ada26448b | |||
| e442f105bc | |||
| 5e0a771848 | |||
| b4c2685059 | |||
| e238f3ca88 | |||
| 97b06eb3b3 | |||
| ad32ca18ca | |||
| 98a1283ebe | |||
| a10fccaae3 | |||
| c3c9191d9d | |||
| 9fd5a15a72 | |||
| 12f9de7367 | |||
| 5455da1e96 | |||
| 9e803661cd | |||
| b0cf9e77ec | |||
| c92426aefc | |||
| d5b2b8ecec | |||
| 6185a18a7c | |||
| 49d3e37458 | |||
| 1fb10830b9 | |||
| d7766edd24 | |||
| 0bc4453c9c | |||
| ae0d30e5da | |||
| 37d776dd2c | |||
| 0c34ea7dcb | |||
| 3106d36431 | |||
| ed48f697a4 | |||
| da92b28d97 | |||
| 6c865d26fd | |||
| e3f00876f1 | |||
| 16e156b5b4 | |||
| 60962bbc75 | |||
| 6a939118ff | |||
| 64d37dcc08 | |||
| 0c0ae16c2b | |||
| a2490f30e6 | |||
| 953f95aed6 | |||
| bd04e1f4e8 | |||
| 85633c8bab | |||
| 5fc15937c0 | |||
| 8b3940b446 | |||
| 201cfefb6b | |||
| 9958b0999a | |||
| 3547c28361 | |||
| 6c70bfed18 | |||
| 95a75e63f4 | |||
| 2a1dbee290 | |||
| 384a321bf3 | |||
| f4e97d389b | |||
| 590810ff0a | |||
| a01c872982 | |||
| 905a245070 | |||
| 860ce35a8f | |||
| 7f3f5dca40 | |||
| 4a0a4e35ed | |||
| ae055dca1e | |||
| 26e8e1492f | |||
| 8fa722011c | |||
| 17d47d6200 | |||
| e178f58fe2 | |||
| cd0cf5726d | |||
| 8e4bea53da | |||
| 7a22d8ba73 | |||
| 2df4a7a80b | |||
| b451f697bc | |||
| 7e9c867f34 | |||
| 130e85f8a1 | |||
| 9e713cb49d | |||
| 51dfa97900 | |||
| 87c6b599b4 | |||
| f50855a822 | |||
| 8d416317a8 | |||
| 22aa071476 | |||
| a83bd09f8f | |||
| 96035f864a | |||
| fd7dfd7e7f | |||
| 190b93bee8 | |||
| c5f19cc961 | |||
| c56c0ca605 | |||
| c6e721aa37 | |||
| 6572e17f00 | |||
| be6365807c | |||
| d2fff7dfde | |||
| f66bc22c95 | |||
| 3367d0e7be | |||
| 352ec6ccb0 | |||
| 6a989255a3 | |||
| 878b21573f | |||
| 0602db1436 | |||
| 2f8bd1f98c | |||
| 75231ccbba | |||
| 1249a80da5 | |||
| 00c78eb42f | |||
| 35767adba1 | |||
| 47a2a159ef | |||
| 95548223cd | |||
| 2debdc5312 | |||
| 207cc47f1b | |||
| b6338bce8e | |||
| 2cfa2adcf5 | |||
| d7e19abfc9 | |||
| c843703ee7 | |||
| 133ea6b1ba | |||
| 0df977ae81 | |||
| 3e39006822 | |||
| 3ec1a71406 | |||
| 16009f1623 | |||
| 41911014c9 | |||
| 8ea32ce675 | |||
| a4ac80c787 | |||
| 3a5d136d34 | |||
| 2f63b9ddcd | |||
| 92de48b55e | |||
| 224ddae68b | |||
| 885b72a0c6 | |||
| 9ac00d37c5 | |||
| fbb5a34867 | |||
| e25fc01b25 | |||
| 6b3f22dd66 | |||
| abc2c8e806 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -72,3 +72,9 @@ docker-compose.override.yml
|
|||||||
*.swo
|
*.swo
|
||||||
*~
|
*~
|
||||||
!/CLAUDE.md
|
!/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"]
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
# Stage 1: Build stage (gradle build는 Jenkins에서 이미 수행)
|
# Stage 1: Build stage (gradle build는 Jenkins에서 이미 수행)
|
||||||
FROM eclipse-temurin:21-jre-jammy
|
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
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
45
build.gradle
45
build.gradle
@@ -3,6 +3,7 @@ plugins {
|
|||||||
id 'org.springframework.boot' version '3.5.7'
|
id 'org.springframework.boot' version '3.5.7'
|
||||||
id 'io.spring.dependency-management' version '1.1.7'
|
id 'io.spring.dependency-management' version '1.1.7'
|
||||||
id 'com.diffplug.spotless' version '6.25.0'
|
id 'com.diffplug.spotless' version '6.25.0'
|
||||||
|
id 'idea'
|
||||||
}
|
}
|
||||||
|
|
||||||
group = 'com.kamco.cd'
|
group = 'com.kamco.cd'
|
||||||
@@ -21,11 +22,23 @@ configurations {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// QueryDSL 생성된 소스 디렉토리 정의
|
||||||
|
def generatedSourcesDir = file("$buildDir/generated/sources/annotationProcessor/java/main")
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
maven { url "https://repo.osgeo.org/repository/release/" }
|
maven { url "https://repo.osgeo.org/repository/release/" }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gradle이 생성된 소스를 컴파일 경로에 포함하도록 설정
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
srcDirs += generatedSourcesDir
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
@@ -83,6 +96,23 @@ dependencies {
|
|||||||
implementation 'io.hypersistence:hypersistence-utils-hibernate-63:3.7.0'
|
implementation 'io.hypersistence:hypersistence-utils-hibernate-63:3.7.0'
|
||||||
implementation 'org.reflections:reflections:0.10.2'
|
implementation 'org.reflections:reflections:0.10.2'
|
||||||
|
|
||||||
|
implementation 'com.jcraft:jsch:0.1.55'
|
||||||
|
implementation 'org.apache.commons:commons-csv:1.10.0'
|
||||||
|
}
|
||||||
|
|
||||||
|
// IntelliJ가 생성된 소스를 인식하도록 설정
|
||||||
|
idea {
|
||||||
|
module {
|
||||||
|
// 소스 디렉토리로 인식
|
||||||
|
sourceDirs += generatedSourcesDir
|
||||||
|
|
||||||
|
// Generated Sources Root로 마킹 (IntelliJ에서 특별 처리)
|
||||||
|
generatedSourceDirs += generatedSourcesDir
|
||||||
|
|
||||||
|
// 소스 및 Javadoc 다운로드
|
||||||
|
downloadJavadoc = true
|
||||||
|
downloadSources = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
configurations.configureEach {
|
configurations.configureEach {
|
||||||
@@ -93,6 +123,21 @@ tasks.named('test') {
|
|||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 컴파일 전 생성된 소스 디렉토리 생성 보장
|
||||||
|
tasks.named('compileJava') {
|
||||||
|
doFirst {
|
||||||
|
generatedSourcesDir.mkdirs()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 생성된 소스 정리 태스크
|
||||||
|
tasks.register('cleanGeneratedSources', Delete) {
|
||||||
|
delete generatedSourcesDir
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('clean') {
|
||||||
|
dependsOn 'cleanGeneratedSources'
|
||||||
|
}
|
||||||
|
|
||||||
bootJar {
|
bootJar {
|
||||||
archiveFileName = 'ROOT.jar'
|
archiveFileName = 'ROOT.jar'
|
||||||
|
|||||||
@@ -5,6 +5,13 @@ services:
|
|||||||
dockerfile: Dockerfile-dev
|
dockerfile: Dockerfile-dev
|
||||||
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
||||||
container_name: kamco-cd-training-api
|
container_name: kamco-cd-training-api
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
reservations:
|
||||||
|
devices:
|
||||||
|
- driver: nvidia
|
||||||
|
count: all
|
||||||
|
capabilities: [gpu]
|
||||||
ports:
|
ports:
|
||||||
- "7200:8080"
|
- "7200:8080"
|
||||||
environment:
|
environment:
|
||||||
@@ -14,6 +21,8 @@ services:
|
|||||||
- /mnt/nfs_share/images:/app/original-images
|
- /mnt/nfs_share/images:/app/original-images
|
||||||
- /mnt/nfs_share/model_output:/app/model-outputs
|
- /mnt/nfs_share/model_output:/app/model-outputs
|
||||||
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
||||||
|
- /home/kcomu/data:/home/kcomu/data
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- kamco-cds
|
- kamco-cds
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|||||||
private final UserDetailsService userDetailsService;
|
private final UserDetailsService userDetailsService;
|
||||||
private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
|
private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
|
||||||
private static final String[] EXCLUDE_PATHS = {
|
private static final String[] EXCLUDE_PATHS = {
|
||||||
"/api/auth/signin", "/api/auth/refresh", "/api/auth/logout", "/api/members/*/password"
|
// "/api/auth/signin", "/api/auth/refresh", "/api/auth/logout", "/api/members/*/password"
|
||||||
|
"/api/auth/signin", "/api/auth/refresh", "/api/auth/logout"
|
||||||
};
|
};
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
@Tag(name = "공통코드 관리", description = "공통코드 관리 API")
|
@Tag(name = "공통코드 관리", description = "공통코드 관리 API")
|
||||||
@RestController
|
@RestController
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@RequestMapping("/api/code")
|
@RequestMapping("/api/common-code")
|
||||||
public class CommonCodeApiController {
|
public class CommonCodeApiController {
|
||||||
|
|
||||||
private final CommonCodeService commonCodeService;
|
private final CommonCodeService commonCodeService;
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ public class CommonCodeService {
|
|||||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 공통코드 이름 조회
|
* 공통코드 이름 조회
|
||||||
*
|
*
|
||||||
@@ -136,6 +137,8 @@ public class CommonCodeService {
|
|||||||
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
return commonCodeCoreService.getCode(parentCodeCd, childCodeCd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
public List<CodeDto> getTypeCode(String type) {
|
public List<CodeDto> getTypeCode(String type) {
|
||||||
return Enums.getCodes(type);
|
return Enums.getCodes(type);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
|
package com.kamco.cd.training.common.download;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.download.dto.DownloadSpec;
|
||||||
|
import com.kamco.cd.training.common.utils.UserUtil;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DownloadExecutor {
|
||||||
|
|
||||||
|
private final UserUtil userUtil;
|
||||||
|
|
||||||
|
public ResponseEntity<StreamingResponseBody> stream(DownloadSpec spec) throws IOException {
|
||||||
|
|
||||||
|
if (!Files.isReadable(spec.filePath())) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
StreamingResponseBody body =
|
||||||
|
os -> {
|
||||||
|
try (InputStream in = Files.newInputStream(spec.filePath())) {
|
||||||
|
in.transferTo(os);
|
||||||
|
os.flush();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// 고용량은 중간 끊김 흔하니까 throw 금지
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
String fileName =
|
||||||
|
spec.downloadName() != null
|
||||||
|
? spec.downloadName()
|
||||||
|
: spec.filePath().getFileName().toString();
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(
|
||||||
|
spec.contentType() != null ? spec.contentType() : MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
|
package com.kamco.cd.training.common.download;
|
||||||
|
|
||||||
|
import org.springframework.util.AntPathMatcher;
|
||||||
|
|
||||||
|
public final class DownloadPaths {
|
||||||
|
private DownloadPaths() {}
|
||||||
|
|
||||||
|
public static final String[] PATTERNS = {
|
||||||
|
"/api/inference/download/**", "/api/training-data/stage/download/**"
|
||||||
|
};
|
||||||
|
|
||||||
|
public static boolean matches(String uri) {
|
||||||
|
AntPathMatcher m = new AntPathMatcher();
|
||||||
|
for (String p : PATTERNS) {
|
||||||
|
if (m.match(p, uri)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.kamco.cd.training.common.download;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import org.springframework.core.io.FileSystemResource;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.support.ResourceRegion;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpRange;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class RangeDownloadResponder {
|
||||||
|
|
||||||
|
public ResponseEntity<?> buildZipResponse(
|
||||||
|
Path filePath, String downloadFileName, HttpServletRequest request) throws IOException {
|
||||||
|
|
||||||
|
if (!Files.isRegularFile(filePath)) {
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
long totalSize = Files.size(filePath);
|
||||||
|
Resource resource = new FileSystemResource(filePath);
|
||||||
|
|
||||||
|
String disposition = "attachment; filename=\"" + downloadFileName + "\"";
|
||||||
|
String rangeHeader = request.getHeader(HttpHeaders.RANGE);
|
||||||
|
|
||||||
|
// 🔥 공통 헤더 (여기 고정)
|
||||||
|
ResponseEntity.BodyBuilder base =
|
||||||
|
ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
|
||||||
|
.header(HttpHeaders.ACCEPT_RANGES, "bytes")
|
||||||
|
.header("Access-Control-Expose-Headers", "Content-Disposition")
|
||||||
|
.header("X-Accel-Buffering", "no");
|
||||||
|
|
||||||
|
if (rangeHeader == null || rangeHeader.isBlank()) {
|
||||||
|
return base.contentLength(totalSize).body(resource);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<HttpRange> ranges;
|
||||||
|
try {
|
||||||
|
ranges = HttpRange.parseRanges(rangeHeader);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
return ResponseEntity.status(416)
|
||||||
|
.header(HttpHeaders.CONTENT_RANGE, "bytes */" + totalSize)
|
||||||
|
.header("X-Accel-Buffering", "no")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpRange range = ranges.get(0);
|
||||||
|
|
||||||
|
long start = range.getRangeStart(totalSize);
|
||||||
|
long end = range.getRangeEnd(totalSize);
|
||||||
|
|
||||||
|
if (start >= totalSize) {
|
||||||
|
return ResponseEntity.status(416)
|
||||||
|
.header(HttpHeaders.CONTENT_RANGE, "bytes */" + totalSize)
|
||||||
|
.header("X-Accel-Buffering", "no")
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
long regionLength = end - start + 1;
|
||||||
|
ResourceRegion region = new ResourceRegion(resource, start, regionLength);
|
||||||
|
|
||||||
|
return ResponseEntity.status(206)
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, disposition)
|
||||||
|
.header(HttpHeaders.ACCEPT_RANGES, "bytes")
|
||||||
|
.header("Access-Control-Expose-Headers", "Content-Disposition")
|
||||||
|
.header("X-Accel-Buffering", "no")
|
||||||
|
.header(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + totalSize)
|
||||||
|
.contentLength(regionLength)
|
||||||
|
.body(region);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.kamco.cd.training.common.download.dto;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.UUID;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
|
||||||
|
public record DownloadSpec(
|
||||||
|
UUID uuid, // 다운로드 식별(로그/정책용)
|
||||||
|
Path filePath, // 실제 파일 경로
|
||||||
|
String downloadName, // 사용자에게 보일 파일명
|
||||||
|
MediaType contentType // 보통 OCTET_STREAM
|
||||||
|
) {}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.common.dto;
|
package com.kamco.cd.training.common.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
@@ -11,9 +12,14 @@ import lombok.Setter;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
public class HyperParam {
|
public class HyperParam {
|
||||||
|
|
||||||
|
@Schema(description = "모델", example = "G1")
|
||||||
|
private ModelType model; // G1, G2, G3
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// Important
|
// Important
|
||||||
// -------------------------
|
// -------------------------
|
||||||
|
|
||||||
@Schema(description = "백본 네트워크", example = "large")
|
@Schema(description = "백본 네트워크", example = "large")
|
||||||
private String backbone; // backbone
|
private String backbone; // backbone
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
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 id;
|
||||||
private final String text;
|
private final String text;
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum JobStatusType implements EnumType {
|
||||||
|
QUEUED("대기중"),
|
||||||
|
RUNNING("실행중"),
|
||||||
|
SUCCESS("성공"),
|
||||||
|
FAILED("실패"),
|
||||||
|
CANCELED("취소");
|
||||||
|
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public enum JobType implements EnumType {
|
||||||
|
TRAIN("학습"),
|
||||||
|
TEST("테스트");
|
||||||
|
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getId() {
|
||||||
|
return name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getText() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.enums;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
@@ -25,3 +26,4 @@ public enum ModelMngStatusType implements EnumType {
|
|||||||
return desc;
|
return desc;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.kamco.cd.training.common.enums;
|
|||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
import com.kamco.cd.training.common.utils.enums.EnumType;
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
|
import java.util.Arrays;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
@@ -15,6 +16,13 @@ public enum ModelType implements EnumType {
|
|||||||
|
|
||||||
private String desc;
|
private String desc;
|
||||||
|
|
||||||
|
public static ModelType getValueData(String modelNo) {
|
||||||
|
return Arrays.stream(ModelType.values())
|
||||||
|
.filter(m -> m.getId().equals(modelNo))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(G1);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return name();
|
return name();
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.common.enums;
|
package com.kamco.cd.training.common.enums;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
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 id;
|
||||||
private final String text;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,11 @@ package com.kamco.cd.training.common.utils;
|
|||||||
|
|
||||||
import static java.lang.String.CASE_INSENSITIVE_ORDER;
|
import static java.lang.String.CASE_INSENSITIVE_ORDER;
|
||||||
|
|
||||||
|
import com.jcraft.jsch.ChannelExec;
|
||||||
|
import com.jcraft.jsch.JSch;
|
||||||
|
import com.jcraft.jsch.Session;
|
||||||
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto.ApiResponseCode;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -11,6 +16,7 @@ import java.io.FileReader;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.InputStreamReader;
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
@@ -23,6 +29,7 @@ import java.util.Arrays;
|
|||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@@ -34,6 +41,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.geotools.coverage.grid.GridCoverage2D;
|
import org.geotools.coverage.grid.GridCoverage2D;
|
||||||
import org.geotools.gce.geotiff.GeoTiffReader;
|
import org.geotools.gce.geotiff.GeoTiffReader;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.util.FileSystemUtils;
|
import org.springframework.util.FileSystemUtils;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@@ -501,11 +509,15 @@ public class FIleChecker {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
File dir = new File(targetPath);
|
File dir = new File(targetPath);
|
||||||
|
log.info("targetPath={}", targetPath);
|
||||||
|
log.info("absolute targetPath={}", dir.getAbsolutePath());
|
||||||
|
|
||||||
if (!dir.exists()) {
|
if (!dir.exists()) {
|
||||||
dir.mkdirs();
|
dir.mkdirs();
|
||||||
}
|
}
|
||||||
|
|
||||||
File dest = new File(dir, String.valueOf(chunkIndex));
|
File dest = new File(dir, String.valueOf(chunkIndex));
|
||||||
|
log.info("real save path = {}", dest.getAbsolutePath());
|
||||||
|
|
||||||
log.info("chunkIndex={}, uploadSize={}", chunkIndex, mfile.getSize());
|
log.info("chunkIndex={}, uploadSize={}", chunkIndex, mfile.getSize());
|
||||||
log.info("savedSize={}", dest.length());
|
log.info("savedSize={}", dest.length());
|
||||||
@@ -517,6 +529,9 @@ public class FIleChecker {
|
|||||||
log.info("after delete={}", dest.length());
|
log.info("after delete={}", dest.length());
|
||||||
mfile.transferTo(dest);
|
mfile.transferTo(dest);
|
||||||
|
|
||||||
|
log.info("after transfer size={}", dest.length());
|
||||||
|
log.info("after transfer exists={}", dest.exists());
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("chunk save error", e);
|
log.error("chunk save error", e);
|
||||||
@@ -702,12 +717,30 @@ public class FIleChecker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void unzip(String fileName, String destDirectory) throws IOException {
|
public static void unzip(String fileName, String destDirectory) throws IOException {
|
||||||
File destDir = new File(destDirectory);
|
String zipFilePath = destDirectory + File.separator + fileName;
|
||||||
if (!destDir.exists()) {
|
|
||||||
destDir.mkdirs(); // 대상 폴더가 없으면 생성
|
log.info("fileName : {}", fileName);
|
||||||
|
log.info("destDirectory : {}", destDirectory);
|
||||||
|
log.info("zipFilePath : {}", zipFilePath);
|
||||||
|
// zip 이름으로 폴더 생성 (확장자 제거)
|
||||||
|
String folderName =
|
||||||
|
fileName.endsWith(".zip") ? fileName.substring(0, fileName.length() - 4) : fileName;
|
||||||
|
log.info("folderName : {}", folderName);
|
||||||
|
|
||||||
|
File destDir = new File(destDirectory, folderName);
|
||||||
|
log.info("destDir : {}", destDir);
|
||||||
|
|
||||||
|
// 동일 폴더가 이미 있으면 삭제
|
||||||
|
log.info("111 destDir.exists() : {}", destDir.exists());
|
||||||
|
if (destDir.exists()) {
|
||||||
|
deleteDirectoryRecursively(destDir.toPath());
|
||||||
}
|
}
|
||||||
|
|
||||||
String zipFilePath = destDirectory + "/" + fileName;
|
log.info("222 destDir.exists() : {}", destDir.exists());
|
||||||
|
if (!destDir.exists()) {
|
||||||
|
log.info("mkdirs : {}", destDir.exists());
|
||||||
|
destDir.mkdirs();
|
||||||
|
}
|
||||||
|
|
||||||
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
|
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
|
||||||
ZipEntry zipEntry = zis.getNextEntry();
|
ZipEntry zipEntry = zis.getNextEntry();
|
||||||
@@ -740,6 +773,11 @@ public class FIleChecker {
|
|||||||
zipEntry = zis.getNextEntry();
|
zipEntry = zis.getNextEntry();
|
||||||
}
|
}
|
||||||
zis.closeEntry();
|
zis.closeEntry();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.INTERNAL_SERVER_ERROR.getId(),
|
||||||
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
"압축 해제 중 오류가 발생했습니다: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -755,4 +793,70 @@ public class FIleChecker {
|
|||||||
|
|
||||||
return destFile;
|
return destFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static List<String> execCommandAndReadLines(String command) {
|
||||||
|
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
|
||||||
|
String host = "192.168.2.86";
|
||||||
|
String user = "kcomu";
|
||||||
|
String password = "Kamco2025!";
|
||||||
|
|
||||||
|
Session session = null;
|
||||||
|
ChannelExec channel = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSch jsch = new JSch();
|
||||||
|
|
||||||
|
session = jsch.getSession(user, host, 22);
|
||||||
|
session.setPassword(password);
|
||||||
|
|
||||||
|
Properties config = new Properties();
|
||||||
|
config.put("StrictHostKeyChecking", "no");
|
||||||
|
session.setConfig(config);
|
||||||
|
|
||||||
|
session.connect(10_000);
|
||||||
|
|
||||||
|
channel = (ChannelExec) session.openChannel("exec");
|
||||||
|
channel.setCommand(command);
|
||||||
|
channel.setInputStream(null);
|
||||||
|
|
||||||
|
InputStream in = channel.getInputStream();
|
||||||
|
channel.connect();
|
||||||
|
|
||||||
|
try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
|
||||||
|
String line;
|
||||||
|
while ((line = br.readLine()) != null) {
|
||||||
|
result.add(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("remote command failed : " + command, e);
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (channel != null) channel.disconnect();
|
||||||
|
if (session != null) session.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ✅ 폴더 재귀 삭제 */
|
||||||
|
private static void deleteDirectoryRecursively(Path path) throws IOException {
|
||||||
|
if (!Files.exists(path)) return;
|
||||||
|
|
||||||
|
// 하위부터 지워야 하므로 reverse order
|
||||||
|
Files.walk(path)
|
||||||
|
.sorted(Comparator.reverseOrder())
|
||||||
|
.forEach(
|
||||||
|
p -> {
|
||||||
|
try {
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
} catch (IOException e) {
|
||||||
|
// 여기서 바로 RuntimeException으로 올려서 상위 catch(IOException)로 잡히게 함
|
||||||
|
throw new UncheckedIOException("폴더 삭제 실패: " + p.toAbsolutePath(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.kamco.cd.training.common.utils;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
public final class HeaderUtil {
|
||||||
|
|
||||||
|
private HeaderUtil() {}
|
||||||
|
|
||||||
|
/** 특정 Header 값 조회 */
|
||||||
|
public static String get(HttpServletRequest request, String headerName) {
|
||||||
|
if (request == null || headerName == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String value = request.getHeader(headerName);
|
||||||
|
return (value != null && !value.isBlank()) ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 필수 Header 조회 (없으면 null) */
|
||||||
|
public static String getRequired(HttpServletRequest request, String headerName) {
|
||||||
|
return get(request, headerName);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
src/main/java/com/kamco/cd/training/config/AsyncConfig.java
Normal file
37
src/main/java/com/kamco/cd/training/config/AsyncConfig.java
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
package com.kamco.cd.training.config;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.scheduling.annotation.EnableAsync;
|
||||||
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableAsync
|
||||||
|
public class AsyncConfig {
|
||||||
|
|
||||||
|
@Bean(name = "trainJobExecutor")
|
||||||
|
public Executor trainJobExecutor() {
|
||||||
|
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||||
|
executor.setCorePoolSize(4); // 동시에 4개 실행
|
||||||
|
executor.setMaxPoolSize(8); // 최대 8개
|
||||||
|
executor.setQueueCapacity(200); // 대기 큐
|
||||||
|
executor.setThreadNamePrefix("train-job-");
|
||||||
|
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}")
|
@Value("${swagger.dev-url:https://kamco.training-dev-api.gs.dabeeo.com}")
|
||||||
private String devUrl;
|
private String devUrl;
|
||||||
|
|
||||||
@Value("${swagger.prod-url:https://api.training-kamco.com}")
|
@Value("${swagger.prod-url:https://api.train-kamco.com}")
|
||||||
private String prodUrl;
|
private String prodUrl;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -53,10 +53,10 @@ public class OpenApiConfig {
|
|||||||
} else if ("prod".equals(profile)) {
|
} else if ("prod".equals(profile)) {
|
||||||
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||||
servers.add(new Server().url("http://localhost:" + localPort).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 {
|
} else {
|
||||||
servers.add(new Server().url("http://localhost:" + localPort).description("로컬 서버"));
|
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("운영 서버"));
|
// servers.add(new Server().url(prodUrl).description("운영 서버"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,11 +76,13 @@ public class SecurityConfig {
|
|||||||
"/api/auth/logout",
|
"/api/auth/logout",
|
||||||
"/swagger-ui/**",
|
"/swagger-ui/**",
|
||||||
"/v3/api-docs/**",
|
"/v3/api-docs/**",
|
||||||
"/api/members/*/password",
|
|
||||||
"/api/upload/chunk-upload-dataset",
|
"/api/upload/chunk-upload-dataset",
|
||||||
"/api/upload/chunk-upload-complete")
|
"/api/upload/chunk-upload-complete",
|
||||||
|
"/download_progress_test.html",
|
||||||
|
"/api/models/download/**")
|
||||||
.permitAll()
|
.permitAll()
|
||||||
|
.requestMatchers("/api/members/*/password")
|
||||||
|
.authenticated()
|
||||||
// default
|
// default
|
||||||
.anyRequest()
|
.anyRequest()
|
||||||
.authenticated())
|
.authenticated())
|
||||||
@@ -102,15 +104,19 @@ public class SecurityConfig {
|
|||||||
return new BCryptPasswordEncoder();
|
return new BCryptPasswordEncoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** CORS 설정 */
|
/** CORS 설정 - application.yml에서 환경별로 관리 */
|
||||||
@Bean
|
@Bean
|
||||||
public CorsConfigurationSource corsConfigurationSource() {
|
public CorsConfigurationSource corsConfigurationSource() {
|
||||||
CorsConfiguration config = new CorsConfiguration(); // CORS 객체 생성
|
CorsConfiguration config = new CorsConfiguration(); // CORS 객체 생성
|
||||||
|
|
||||||
|
// application.yml에서 환경별로 설정된 도메인 사용
|
||||||
config.setAllowedOriginPatterns(List.of("*")); // 도메인 허용
|
config.setAllowedOriginPatterns(List.of("*")); // 도메인 허용
|
||||||
|
|
||||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||||
config.setAllowedHeaders(List.of("*")); // 헤더요청 Authorization, Content-Type, X-Custom-Header
|
config.setAllowedHeaders(List.of("*")); // 헤더요청 Authorization, Content-Type, X-Custom-Header
|
||||||
config.setAllowCredentials(true); // 쿠키, Authorization 헤더, Bearer Token 등 자격증명 포함 요청을 허용할지 설정
|
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();
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
/** "/**" → 모든 API 경로에 대해 이 CORS 규칙을 적용 /api/** 같이 특정 경로만 지정 가능. */
|
/** "/**" → 모든 API 경로에 대해 이 CORS 규칙을 적용 /api/** 같이 특정 경로만 지정 가능. */
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ public class StartupLogger {
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
╔════════════════════════════════════════════════════════════════════════════════╗
|
╔════════════════════════════════════════════════════════════════════════════════╗
|
||||||
║ 🚀 APPLICATION STARTUP INFORMATION ║
|
║ 🚀 APPLICATION STARTUP INFORMATION 2 ║
|
||||||
╠════════════════════════════════════════════════════════════════════════════════╣
|
╠════════════════════════════════════════════════════════════════════════════════╣
|
||||||
║ PROFILE CONFIGURATION ║
|
║ PROFILE CONFIGURATION ║
|
||||||
╠────────────────────────────────────────────────────────────────────────────────╣
|
╠────────────────────────────────────────────────────────────────────────────────╣
|
||||||
|
|||||||
@@ -16,6 +16,12 @@ public class ApiLogFilter extends OncePerRequestFilter {
|
|||||||
protected void doFilterInternal(
|
protected void doFilterInternal(
|
||||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||||
throws ServletException, IOException {
|
throws ServletException, IOException {
|
||||||
|
String uri = request.getRequestURI();
|
||||||
|
if (uri.contains("/download/")) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
|
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
|
||||||
|
|
||||||
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
|
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
|
||||||
|
|||||||
@@ -5,11 +5,14 @@ import com.kamco.cd.training.log.dto.EventType;
|
|||||||
import com.kamco.cd.training.menu.dto.MenuDto;
|
import com.kamco.cd.training.menu.dto.MenuDto;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
public class ApiLogFunction {
|
public class ApiLogFunction {
|
||||||
|
|
||||||
// 클라이언트 IP 추출
|
// 클라이언트 IP 추출
|
||||||
@@ -34,6 +37,14 @@ public class ApiLogFunction {
|
|||||||
return ip;
|
return ip;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static String getXFowardedForIp(HttpServletRequest request) {
|
||||||
|
String ip = request.getHeader("X-Forwarded-For");
|
||||||
|
if (ip != null) {
|
||||||
|
ip = ip.split(",")[0].trim();
|
||||||
|
}
|
||||||
|
return ip;
|
||||||
|
}
|
||||||
|
|
||||||
// 사용자 ID 추출 예시 (Spring Security 기준)
|
// 사용자 ID 추출 예시 (Spring Security 기준)
|
||||||
public static String getUserId(HttpServletRequest request) {
|
public static String getUserId(HttpServletRequest request) {
|
||||||
try {
|
try {
|
||||||
@@ -47,20 +58,20 @@ public class ApiLogFunction {
|
|||||||
String method = request.getMethod().toUpperCase();
|
String method = request.getMethod().toUpperCase();
|
||||||
String uri = request.getRequestURI().toLowerCase();
|
String uri = request.getRequestURI().toLowerCase();
|
||||||
|
|
||||||
// URL 기반 DOWNLOAD/PRINT 분류
|
// URL 기반 DOWNLOAD/PRINT 분류 -> /download는 FileDownloadInterceptor로 옮김
|
||||||
if (uri.contains("/download") || uri.contains("/export")) {
|
if (uri.contains("/download") || uri.contains("/export")) {
|
||||||
return EventType.DOWNLOAD;
|
return EventType.DOWNLOAD;
|
||||||
}
|
}
|
||||||
if (uri.contains("/print")) {
|
if (uri.contains("/print")) {
|
||||||
return EventType.PRINT;
|
return EventType.OTHER;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 일반 CRUD
|
// 일반 CRUD
|
||||||
return switch (method) {
|
return switch (method) {
|
||||||
case "POST" -> EventType.CREATE;
|
case "POST" -> EventType.ADDED;
|
||||||
case "GET" -> EventType.READ;
|
case "GET" -> EventType.LIST;
|
||||||
case "DELETE" -> EventType.DELETE;
|
case "DELETE" -> EventType.REMOVE;
|
||||||
case "PUT", "PATCH" -> EventType.UPDATE;
|
case "PUT", "PATCH" -> EventType.MODIFIED;
|
||||||
default -> EventType.OTHER;
|
default -> EventType.OTHER;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -121,12 +132,22 @@ public class ApiLogFunction {
|
|||||||
|
|
||||||
public static String getUriMenuInfo(List<MenuDto.Basic> menuList, String uri) {
|
public static String getUriMenuInfo(List<MenuDto.Basic> menuList, String uri) {
|
||||||
|
|
||||||
MenuDto.Basic m =
|
String normalizedUri = uri.replace("/api", "");
|
||||||
|
MenuDto.Basic basic =
|
||||||
menuList.stream()
|
menuList.stream()
|
||||||
.filter(menu -> menu.getMenuApiUrl() != null && uri.contains(menu.getMenuApiUrl()))
|
.filter(
|
||||||
.findFirst()
|
menu -> menu.getMenuUrl() != null && normalizedUri.startsWith(menu.getMenuUrl()))
|
||||||
|
.max(Comparator.comparingInt(m -> m.getMenuUrl().length()))
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
|
|
||||||
return m != null ? m.getMenuUid() : "SYSTEM";
|
return basic != null ? basic.getMenuUid() : "SYSTEM";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String cutRequestBody(String value) {
|
||||||
|
int MAX_LEN = 255;
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value.length() <= MAX_LEN ? value : value.substring(0, MAX_LEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,17 @@ package com.kamco.cd.training.config.api;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.kamco.cd.training.auth.CustomUserDetails;
|
import com.kamco.cd.training.auth.CustomUserDetails;
|
||||||
|
import com.kamco.cd.training.common.utils.HeaderUtil;
|
||||||
|
import com.kamco.cd.training.log.dto.EventType;
|
||||||
|
import com.kamco.cd.training.menu.dto.MenuDto;
|
||||||
import com.kamco.cd.training.menu.service.MenuService;
|
import com.kamco.cd.training.menu.service.MenuService;
|
||||||
import com.kamco.cd.training.postgres.entity.AuditLogEntity;
|
import com.kamco.cd.training.postgres.entity.AuditLogEntity;
|
||||||
import com.kamco.cd.training.postgres.repository.log.AuditLogRepository;
|
import com.kamco.cd.training.postgres.repository.log.AuditLogRepository;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.core.MethodParameter;
|
import org.springframework.core.MethodParameter;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -23,6 +30,7 @@ import org.springframework.web.util.ContentCachingRequestWrapper;
|
|||||||
*
|
*
|
||||||
* <p>createOK() → 201 CREATED ok() → 200 OK deleteOk() → 204 NO_CONTENT
|
* <p>createOK() → 201 CREATED ok() → 200 OK deleteOk() → 204 NO_CONTENT
|
||||||
*/
|
*/
|
||||||
|
@Slf4j
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||||
|
|
||||||
@@ -61,12 +69,27 @@ public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
|||||||
if (body instanceof ApiResponseDto<?> apiResponse) {
|
if (body instanceof ApiResponseDto<?> apiResponse) {
|
||||||
response.setStatusCode(apiResponse.getHttpStatus());
|
response.setStatusCode(apiResponse.getHttpStatus());
|
||||||
|
|
||||||
String ip = ApiLogFunction.getClientIp(servletRequest);
|
String actionType = HeaderUtil.get(servletRequest, "kamco-action-type");
|
||||||
Long userid = null;
|
// actionType 이 없으면 로그 저장하지 않기 || download 는 FileDownloadInterceptor 에서 하기
|
||||||
|
// (file down URL prefix 추가는 WebConfig.java 에 하기)
|
||||||
|
if (actionType == null || actionType.equalsIgnoreCase("download")) {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
if (servletRequest.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken auth
|
String ip =
|
||||||
&& auth.getPrincipal() instanceof CustomUserDetails customUserDetails) {
|
Optional.ofNullable(HeaderUtil.get(servletRequest, "kamco-user-ip"))
|
||||||
userid = customUserDetails.getMember().getId();
|
.orElseGet(() -> ApiLogFunction.getXFowardedForIp(servletRequest));
|
||||||
|
Long userid = null;
|
||||||
|
String loginAttemptId = null;
|
||||||
|
|
||||||
|
// 로그인 시도할 때
|
||||||
|
if (servletRequest.getRequestURI().contains("/api/auth/signin")) {
|
||||||
|
loginAttemptId = HeaderUtil.get(servletRequest, "kamco-login-attempt-id");
|
||||||
|
} else {
|
||||||
|
if (servletRequest.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken auth
|
||||||
|
&& auth.getPrincipal() instanceof CustomUserDetails customUserDetails) {
|
||||||
|
userid = customUserDetails.getMember().getId();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String requestBody;
|
String requestBody;
|
||||||
@@ -84,17 +107,33 @@ public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
|||||||
requestBody = maskSensitiveFields(requestBody);
|
requestBody = maskSensitiveFields(requestBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<?> list = menuService.getFindAll();
|
||||||
|
List<MenuDto.Basic> result =
|
||||||
|
list.stream()
|
||||||
|
.map(
|
||||||
|
item -> {
|
||||||
|
if (item instanceof LinkedHashMap<?, ?> map) {
|
||||||
|
return objectMapper.convertValue(map, MenuDto.Basic.class);
|
||||||
|
} else if (item instanceof MenuDto.Basic dto) {
|
||||||
|
return dto;
|
||||||
|
} else {
|
||||||
|
throw new IllegalStateException("Unsupported cache type: " + item.getClass());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
|
||||||
AuditLogEntity log =
|
AuditLogEntity log =
|
||||||
new AuditLogEntity(
|
new AuditLogEntity(
|
||||||
userid,
|
userid,
|
||||||
ApiLogFunction.getEventType(servletRequest),
|
EventType.fromName(actionType),
|
||||||
ApiLogFunction.isSuccessFail(apiResponse),
|
ApiLogFunction.isSuccessFail(apiResponse),
|
||||||
ApiLogFunction.getUriMenuInfo(
|
ApiLogFunction.getUriMenuInfo(result, servletRequest.getRequestURI()),
|
||||||
menuService.getFindAll(), servletRequest.getRequestURI()),
|
|
||||||
ip,
|
ip,
|
||||||
servletRequest.getRequestURI(),
|
servletRequest.getRequestURI(),
|
||||||
requestBody,
|
ApiLogFunction.cutRequestBody(requestBody),
|
||||||
apiResponse.getErrorLogUid());
|
apiResponse.getErrorLogUid(),
|
||||||
|
null,
|
||||||
|
loginAttemptId);
|
||||||
auditLogRepository.save(log);
|
auditLogRepository.save(log);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,14 @@ package com.kamco.cd.training.dataset;
|
|||||||
|
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
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;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
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.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.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
@@ -14,15 +18,15 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
|||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.FileStore;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
@@ -33,6 +37,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
public class DatasetApiController {
|
public class DatasetApiController {
|
||||||
|
|
||||||
private final DatasetService datasetService;
|
private final DatasetService datasetService;
|
||||||
|
private final DatasetAsyncService datasetAsyncService;
|
||||||
|
|
||||||
@Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
|
@Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
@@ -212,8 +217,15 @@ public class DatasetApiController {
|
|||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@GetMapping("/usable-bytes")
|
@GetMapping("/usable-bytes")
|
||||||
public ApiResponseDto<DatasetStorage> getUsableBytes() {
|
public ApiResponseDto<DatasetStorage> getUsableBytes() throws IOException {
|
||||||
return ApiResponseDto.ok(datasetService.getUsableBytes());
|
FileStore store = Files.getFileStore(Path.of("."));
|
||||||
|
|
||||||
|
long usable = store.getUsableSpace();
|
||||||
|
DatasetStorage storage = new DatasetStorage();
|
||||||
|
storage.setUsableBytes(String.valueOf(usable));
|
||||||
|
|
||||||
|
// datasetService.getUsableBytes();
|
||||||
|
return ApiResponseDto.ok(storage);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "학습데이터 zip파일 등록", description = "학습데이터 zip파일 등록 합니다.")
|
@Operation(summary = "학습데이터 zip파일 등록", description = "학습데이터 zip파일 등록 합니다.")
|
||||||
@@ -221,7 +233,7 @@ public class DatasetApiController {
|
|||||||
public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
|
public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
|
||||||
@RequestBody @Valid DatasetDto.AddReq addReq) {
|
@RequestBody @Valid DatasetDto.AddReq addReq) {
|
||||||
|
|
||||||
return ApiResponseDto.ok(datasetService.insertDataset(addReq));
|
return ApiResponseDto.okObject(datasetService.insertDataset(addReq));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
|
@Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
|
||||||
@@ -230,10 +242,59 @@ public class DatasetApiController {
|
|||||||
throws Exception {
|
throws Exception {
|
||||||
|
|
||||||
String path = datasetService.getFilePathByUUIDPathType(uuid, pathType);
|
String path = datasetService.getFilePathByUUIDPathType(uuid, pathType);
|
||||||
Path filePath = Paths.get(path);
|
return datasetService.getFilePathByFile(path);
|
||||||
|
}
|
||||||
|
|
||||||
Resource resource = new UrlResource(filePath.toUri());
|
@Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
|
||||||
|
@GetMapping("/files-to86")
|
||||||
|
public ResponseEntity<Resource> getFileTo86(
|
||||||
|
@RequestParam UUID uuid, @RequestParam String pathType) throws Exception {
|
||||||
|
|
||||||
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
|
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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
package com.kamco.cd.training.dataset.dto;
|
package com.kamco.cd.training.dataset.dto;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
import com.kamco.cd.training.common.enums.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
@@ -75,9 +76,16 @@ public class DatasetDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getTotalSize(Long totalSize) {
|
public String getTotalSize(Long totalSize) {
|
||||||
if (totalSize == null) return "0G";
|
if (totalSize == null || totalSize <= 0) return "0M";
|
||||||
|
|
||||||
double giga = totalSize / (1024.0 * 1024 * 1024);
|
double giga = totalSize / (1024.0 * 1024 * 1024);
|
||||||
return String.format("%.2fG", giga);
|
|
||||||
|
if (giga >= 1) {
|
||||||
|
return String.format("%.2fG", giga);
|
||||||
|
} else {
|
||||||
|
double mega = totalSize / (1024.0 * 1024);
|
||||||
|
return String.format("%.2fM", mega);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStatus(String status) {
|
public String getStatus(String status) {
|
||||||
@@ -137,6 +145,7 @@ public class DatasetDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Schema(name = "DatasetDetailReq", description = "데이터셋 상세 조회 요청")
|
@Schema(name = "DatasetDetailReq", description = "데이터셋 상세 조회 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -149,6 +158,8 @@ public class DatasetDto {
|
|||||||
private Long datasetId;
|
private Long datasetId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Schema(name = "DatasetRegisterReq", description = "데이터셋 등록 요청")
|
@Schema(name = "DatasetRegisterReq", description = "데이터셋 등록 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -225,9 +236,9 @@ public class DatasetDto {
|
|||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
|
||||||
public static class SelectDataSet {
|
public static class SelectDataSet {
|
||||||
|
|
||||||
|
private String modelNo; // G1, G2, G3 모델 타입
|
||||||
private Long datasetId;
|
private Long datasetId;
|
||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
private String dataType;
|
private String dataType;
|
||||||
@@ -236,12 +247,16 @@ public class DatasetDto {
|
|||||||
private Integer compareYyyy;
|
private Integer compareYyyy;
|
||||||
private Integer targetYyyy;
|
private Integer targetYyyy;
|
||||||
private String memo;
|
private String memo;
|
||||||
private Long classCount;
|
@JsonIgnore private Long classCount;
|
||||||
private Integer buildingCount;
|
private Integer buildingCnt;
|
||||||
private Integer containerCount;
|
private Integer containerCnt;
|
||||||
private String dataTypeName;
|
private String dataTypeName;
|
||||||
|
|
||||||
|
private Long wasteCnt;
|
||||||
|
private Long landCoverCnt;
|
||||||
|
|
||||||
public SelectDataSet(
|
public SelectDataSet(
|
||||||
|
String modelNo,
|
||||||
Long datasetId,
|
Long datasetId,
|
||||||
UUID uuid,
|
UUID uuid,
|
||||||
String dataType,
|
String dataType,
|
||||||
@@ -254,15 +269,22 @@ public class DatasetDto {
|
|||||||
this.datasetId = datasetId;
|
this.datasetId = datasetId;
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
|
this.dataTypeName = getDataTypeName(dataType);
|
||||||
this.title = title;
|
this.title = title;
|
||||||
this.roundNo = roundNo;
|
this.roundNo = roundNo;
|
||||||
this.compareYyyy = compareYyyy;
|
this.compareYyyy = compareYyyy;
|
||||||
this.targetYyyy = targetYyyy;
|
this.targetYyyy = targetYyyy;
|
||||||
this.memo = memo;
|
this.memo = memo;
|
||||||
this.classCount = classCount;
|
this.classCount = classCount;
|
||||||
|
if (modelNo.equals(ModelType.G2.getId())) {
|
||||||
|
this.wasteCnt = classCount;
|
||||||
|
} else if (modelNo.equals(ModelType.G3.getId())) {
|
||||||
|
this.landCoverCnt = classCount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public SelectDataSet(
|
public SelectDataSet(
|
||||||
|
String modelNo,
|
||||||
Long datasetId,
|
Long datasetId,
|
||||||
UUID uuid,
|
UUID uuid,
|
||||||
String dataType,
|
String dataType,
|
||||||
@@ -271,8 +293,8 @@ public class DatasetDto {
|
|||||||
Integer compareYyyy,
|
Integer compareYyyy,
|
||||||
Integer targetYyyy,
|
Integer targetYyyy,
|
||||||
String memo,
|
String memo,
|
||||||
Integer buildingCount,
|
Integer buildingCnt,
|
||||||
Integer containerCount) {
|
Integer containerCnt) {
|
||||||
this.datasetId = datasetId;
|
this.datasetId = datasetId;
|
||||||
this.uuid = uuid;
|
this.uuid = uuid;
|
||||||
this.dataType = dataType;
|
this.dataType = dataType;
|
||||||
@@ -282,8 +304,8 @@ public class DatasetDto {
|
|||||||
this.compareYyyy = compareYyyy;
|
this.compareYyyy = compareYyyy;
|
||||||
this.targetYyyy = targetYyyy;
|
this.targetYyyy = targetYyyy;
|
||||||
this.memo = memo;
|
this.memo = memo;
|
||||||
this.buildingCount = buildingCount;
|
this.buildingCnt = buildingCnt;
|
||||||
this.containerCount = containerCount;
|
this.containerCnt = containerCnt;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDataTypeName(String groupTitleCd) {
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
@@ -296,6 +318,183 @@ public class DatasetDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Schema(name = "SelectTransferDataSet", description = "전이학습 데이터셋 선택 리스트")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public static class SelectTransferDataSet {
|
||||||
|
|
||||||
|
private String modelNo; // G1, G2, G3 모델 타입
|
||||||
|
private Long datasetId;
|
||||||
|
private UUID uuid;
|
||||||
|
private String dataType;
|
||||||
|
private String title;
|
||||||
|
private Long roundNo;
|
||||||
|
private Integer compareYyyy;
|
||||||
|
private Integer targetYyyy;
|
||||||
|
private String memo;
|
||||||
|
@JsonIgnore private Long classCount;
|
||||||
|
private Integer buildingCnt;
|
||||||
|
private Integer containerCnt;
|
||||||
|
private String dataTypeName;
|
||||||
|
|
||||||
|
private Long wasteCnt;
|
||||||
|
private Long landCoverCnt;
|
||||||
|
|
||||||
|
private String beforeModelNo; // G1, G2, G3 모델 타입
|
||||||
|
private Long beforeDatasetId;
|
||||||
|
private UUID beforeUuid;
|
||||||
|
private String beforeDataType;
|
||||||
|
private String beforeTitle;
|
||||||
|
private Long beforeRoundNo;
|
||||||
|
private Integer beforeCompareYyyy;
|
||||||
|
private Integer beforeTargetYyyy;
|
||||||
|
private String beforeMemo;
|
||||||
|
|
||||||
|
@JsonIgnore private Long beforeClassCount;
|
||||||
|
|
||||||
|
private Integer beforeBuildingCnt;
|
||||||
|
private Integer beforeContainerCnt;
|
||||||
|
private String beforeDataTypeName;
|
||||||
|
|
||||||
|
private Long beforeWasteCnt;
|
||||||
|
private Long beforeLandCoverCnt;
|
||||||
|
|
||||||
|
public SelectTransferDataSet(
|
||||||
|
// 현재
|
||||||
|
String modelNo,
|
||||||
|
Long datasetId,
|
||||||
|
UUID uuid,
|
||||||
|
String dataType,
|
||||||
|
String title,
|
||||||
|
Long roundNo,
|
||||||
|
Integer compareYyyy,
|
||||||
|
Integer targetYyyy,
|
||||||
|
String memo,
|
||||||
|
Long classCount,
|
||||||
|
|
||||||
|
// 이전(before)
|
||||||
|
String beforeModelNo,
|
||||||
|
Long beforeDatasetId,
|
||||||
|
UUID beforeUuid,
|
||||||
|
String beforeDataType,
|
||||||
|
String beforeTitle,
|
||||||
|
Long beforeRoundNo,
|
||||||
|
Integer beforeCompareYyyy,
|
||||||
|
Integer beforeTargetYyyy,
|
||||||
|
String beforeMemo,
|
||||||
|
Long beforeClassCount) {
|
||||||
|
// 현재
|
||||||
|
this.modelNo = modelNo;
|
||||||
|
this.datasetId = datasetId;
|
||||||
|
this.uuid = uuid;
|
||||||
|
this.dataType = dataType;
|
||||||
|
this.dataTypeName = getDataTypeName(dataType);
|
||||||
|
this.title = title;
|
||||||
|
this.roundNo = roundNo;
|
||||||
|
this.compareYyyy = compareYyyy;
|
||||||
|
this.targetYyyy = targetYyyy;
|
||||||
|
this.memo = memo;
|
||||||
|
this.classCount = classCount;
|
||||||
|
|
||||||
|
if (modelNo != null && modelNo.equals(ModelType.G2.getId())) {
|
||||||
|
this.wasteCnt = classCount;
|
||||||
|
} else if (modelNo != null && modelNo.equals(ModelType.G3.getId())) {
|
||||||
|
this.landCoverCnt = classCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 이전(before)
|
||||||
|
this.beforeModelNo = beforeModelNo;
|
||||||
|
this.beforeDatasetId = beforeDatasetId;
|
||||||
|
this.beforeUuid = beforeUuid;
|
||||||
|
this.beforeDataType = beforeDataType;
|
||||||
|
this.beforeDataTypeName = getDataTypeName(beforeDataType);
|
||||||
|
this.beforeTitle = beforeTitle;
|
||||||
|
this.beforeRoundNo = beforeRoundNo;
|
||||||
|
this.beforeCompareYyyy = beforeCompareYyyy;
|
||||||
|
this.beforeTargetYyyy = beforeTargetYyyy;
|
||||||
|
this.beforeMemo = beforeMemo;
|
||||||
|
this.beforeClassCount = beforeClassCount;
|
||||||
|
|
||||||
|
if (beforeModelNo != null && beforeModelNo.equals(ModelType.G2.getId())) {
|
||||||
|
this.beforeWasteCnt = beforeClassCount;
|
||||||
|
} else if (beforeModelNo != null && beforeModelNo.equals(ModelType.G3.getId())) {
|
||||||
|
this.beforeLandCoverCnt = beforeClassCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public SelectTransferDataSet(
|
||||||
|
// 현재
|
||||||
|
String modelNo,
|
||||||
|
Long datasetId,
|
||||||
|
UUID uuid,
|
||||||
|
String dataType,
|
||||||
|
String title,
|
||||||
|
Long roundNo,
|
||||||
|
Integer compareYyyy,
|
||||||
|
Integer targetYyyy,
|
||||||
|
String memo,
|
||||||
|
Integer buildingCnt,
|
||||||
|
Integer containerCnt,
|
||||||
|
|
||||||
|
// 이전(before)
|
||||||
|
String beforeModelNo,
|
||||||
|
Long beforeDatasetId,
|
||||||
|
UUID beforeUuid,
|
||||||
|
String beforeDataType,
|
||||||
|
String beforeTitle,
|
||||||
|
Long beforeRoundNo,
|
||||||
|
Integer beforeCompareYyyy,
|
||||||
|
Integer beforeTargetYyyy,
|
||||||
|
String beforeMemo,
|
||||||
|
Integer beforeBuildingCnt,
|
||||||
|
Integer beforeContainerCnt) {
|
||||||
|
// 현재
|
||||||
|
this.modelNo = modelNo;
|
||||||
|
this.datasetId = datasetId;
|
||||||
|
this.uuid = uuid;
|
||||||
|
this.dataType = dataType;
|
||||||
|
this.dataTypeName = getDataTypeName(dataType);
|
||||||
|
this.title = title;
|
||||||
|
this.roundNo = roundNo;
|
||||||
|
this.compareYyyy = compareYyyy;
|
||||||
|
this.targetYyyy = targetYyyy;
|
||||||
|
this.memo = memo;
|
||||||
|
this.buildingCnt = buildingCnt;
|
||||||
|
this.containerCnt = containerCnt;
|
||||||
|
|
||||||
|
// 이전(before)
|
||||||
|
this.beforeModelNo = beforeModelNo;
|
||||||
|
this.beforeDatasetId = beforeDatasetId;
|
||||||
|
this.beforeUuid = beforeUuid;
|
||||||
|
this.beforeDataType = beforeDataType;
|
||||||
|
this.beforeDataTypeName = getDataTypeName(beforeDataType);
|
||||||
|
this.beforeTitle = beforeTitle;
|
||||||
|
this.beforeRoundNo = beforeRoundNo;
|
||||||
|
this.beforeCompareYyyy = beforeCompareYyyy;
|
||||||
|
this.beforeTargetYyyy = beforeTargetYyyy;
|
||||||
|
this.beforeMemo = beforeMemo;
|
||||||
|
this.beforeBuildingCnt = beforeBuildingCnt;
|
||||||
|
this.beforeContainerCnt = beforeContainerCnt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDataTypeName(String groupTitleCd) {
|
||||||
|
LearnDataType type = Enums.fromId(LearnDataType.class, groupTitleCd);
|
||||||
|
return type == null ? null : type.getText();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getYear() {
|
||||||
|
return this.compareYyyy + "-" + this.targetYyyy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBeforeYear() {
|
||||||
|
if (this.beforeCompareYyyy == null || this.beforeTargetYyyy == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.beforeCompareYyyy + "-" + this.beforeTargetYyyy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@@ -336,4 +535,28 @@ public class DatasetDto {
|
|||||||
private Long totalObjectCount;
|
private Long totalObjectCount;
|
||||||
private String datasetPath;
|
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;
|
package com.kamco.cd.training.dataset.dto;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
@@ -72,6 +73,7 @@ public class MapSheetDto {
|
|||||||
private List<Long> itemIds;
|
private List<Long> itemIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Schema(name = "MapSheetCheckReq", description = "도엽 번호 유효성 검증 요청")
|
@Schema(name = "MapSheetCheckReq", description = "도엽 번호 유효성 검증 요청")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -101,3 +103,4 @@ public class MapSheetDto {
|
|||||||
private boolean duplicate;
|
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.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
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.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
import com.kamco.cd.training.common.service.FormatStorage;
|
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.ApiResponseCode;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto.ResponseObj;
|
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;
|
||||||
|
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.AddReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
|
||||||
@@ -18,38 +20,51 @@ 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.DatasetObjRegDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetObjDto.SearchReq;
|
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 com.kamco.cd.training.postgres.core.DatasetCoreService;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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;
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@Transactional
|
|
||||||
public class DatasetService {
|
public class DatasetService {
|
||||||
|
|
||||||
private final DatasetCoreService datasetCoreService;
|
private final DatasetCoreService datasetCoreService;
|
||||||
|
private final DatasetBatchService datasetBatchService;
|
||||||
@Value("${file.dataset-dir}")
|
|
||||||
private String datasetDir;
|
|
||||||
|
|
||||||
private static final List<String> LABEL_DIRS = List.of("label-json", "label", "input1", "input2");
|
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");
|
||||||
|
private static final List<String> CHECK_DIRS = List.of("label", "input1", "input2");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 데이터셋 목록 조회
|
* 데이터셋 목록 조회
|
||||||
@@ -72,6 +87,7 @@ public class DatasetService {
|
|||||||
return datasetCoreService.getOneByUuid(id);
|
return datasetCoreService.getOneByUuid(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 데이터셋 등록
|
* 데이터셋 등록
|
||||||
*
|
*
|
||||||
@@ -86,6 +102,7 @@ public class DatasetService {
|
|||||||
return saved.getId();
|
return saved.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
/**
|
/**
|
||||||
* 데이터셋 수정
|
* 데이터셋 수정
|
||||||
*
|
*
|
||||||
@@ -164,9 +181,22 @@ public class DatasetService {
|
|||||||
Long datasetUid = null; // master id 값, 등록하면서 가져올 예정
|
Long datasetUid = null; // master id 값, 등록하면서 가져올 예정
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 같은 uid 로 등록한 파일이 있는지 확인
|
||||||
|
Long existsCnt =
|
||||||
|
datasetCoreService.findDatasetByUidExistsCnt(addReq.getFileName().replace(".zip", ""));
|
||||||
|
if (existsCnt > 0) {
|
||||||
|
return new ResponseObj(ApiResponseCode.DUPLICATE_DATA, "이미 등록된 회차 데이터 파일입니다. 확인 부탁드립니다.");
|
||||||
|
}
|
||||||
|
|
||||||
// 압축 해제
|
// 압축 해제
|
||||||
FIleChecker.unzip(addReq.getFileName(), addReq.getFilePath());
|
FIleChecker.unzip(addReq.getFileName(), addReq.getFilePath());
|
||||||
|
|
||||||
|
// 압축 해제한 폴더 하위에 train,val,test 폴더 모두 존재하는지 확인
|
||||||
|
validateTrainValTestDirs(addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||||
|
|
||||||
|
// 압축 해제한 폴더의 갯수 맞는지 log 찍기
|
||||||
|
validateDirFileCount(addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||||
|
|
||||||
// 해제한 폴더 읽어서 데이터 저장
|
// 해제한 폴더 읽어서 데이터 저장
|
||||||
List<Map<String, Object>> list =
|
List<Map<String, Object>> list =
|
||||||
getUnzipDatasetFiles(
|
getUnzipDatasetFiles(
|
||||||
@@ -179,6 +209,17 @@ public class DatasetService {
|
|||||||
idx++;
|
idx++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<Map<String, Object>> valList =
|
||||||
|
getUnzipDatasetFiles(
|
||||||
|
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), "val");
|
||||||
|
|
||||||
|
int valIdx = 0;
|
||||||
|
for (Map<String, Object> valid : valList) {
|
||||||
|
datasetUid =
|
||||||
|
this.insertTrainTestData(valid, addReq, valIdx, datasetUid, "val"); // val 데이터 insert
|
||||||
|
valIdx++;
|
||||||
|
}
|
||||||
|
|
||||||
List<Map<String, Object>> testList =
|
List<Map<String, Object>> testList =
|
||||||
getUnzipDatasetFiles(
|
getUnzipDatasetFiles(
|
||||||
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), "test");
|
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), "test");
|
||||||
@@ -195,7 +236,7 @@ public class DatasetService {
|
|||||||
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
return new ResponseObj(ApiResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
datasetCoreService.updateDatasetUploadStatus(datasetUid);
|
datasetCoreService.updateDatasetUploadStatus(datasetUid, LearnDataRegister.COMPLETED);
|
||||||
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,6 +326,8 @@ public class DatasetService {
|
|||||||
|
|
||||||
if (subDir.equals("train")) {
|
if (subDir.equals("train")) {
|
||||||
datasetCoreService.insertDatasetObj(objRegDto);
|
datasetCoreService.insertDatasetObj(objRegDto);
|
||||||
|
} else if (subDir.equals("val")) {
|
||||||
|
datasetCoreService.insertDatasetValObj(objRegDto);
|
||||||
} else {
|
} else {
|
||||||
datasetCoreService.insertDatasetTestObj(objRegDto);
|
datasetCoreService.insertDatasetTestObj(objRegDto);
|
||||||
}
|
}
|
||||||
@@ -303,7 +346,10 @@ public class DatasetService {
|
|||||||
Path dir = root.resolve(dirName);
|
Path dir = root.resolve(dirName);
|
||||||
|
|
||||||
if (!Files.isDirectory(dir)) {
|
if (!Files.isDirectory(dir)) {
|
||||||
throw new IllegalStateException("폴더가 존재하지 않습니다 : " + dir);
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"폴더가 존재하지 않습니다. 업로드 된 파일을 확인하세요. : " + dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
try (Stream<Path> stream = Files.list(dir)) {
|
try (Stream<Path> stream = Files.list(dir)) {
|
||||||
@@ -324,7 +370,12 @@ public class DatasetService {
|
|||||||
// 폴더별 처리
|
// 폴더별 처리
|
||||||
if ("label-json".equals(dirName)) {
|
if ("label-json".equals(dirName)) {
|
||||||
// json 파일이면 파싱
|
// 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());
|
data.put("geojson_path", path.toAbsolutePath().toString());
|
||||||
} else {
|
} else {
|
||||||
data.put(dirName, path.toAbsolutePath().toString());
|
data.put(dirName, path.toAbsolutePath().toString());
|
||||||
@@ -356,4 +407,273 @@ public class DatasetService {
|
|||||||
public String getFilePathByUUIDPathType(UUID uuid, String pathType) {
|
public String getFilePathByUUIDPathType(UUID uuid, String pathType) {
|
||||||
return datasetCoreService.getFilePathByUUIDPathType(uuid, pathType);
|
return datasetCoreService.getFilePathByUUIDPathType(uuid, pathType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String escape(String path) {
|
||||||
|
// 쉘 커맨드에서 안전하게 사용할 수 있도록 문자열을 작은따옴표로 감싸면서, 내부의 작은따옴표를 이스케이프 처리
|
||||||
|
return "'" + path.replace("'", "'\"'\"'") + "'";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeLinuxPath(String path) {
|
||||||
|
return path.replace("\\", "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Resource> getFilePathByFile(String remoteFilePath) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
Path path = Paths.get(remoteFilePath);
|
||||||
|
InputStream inputStream = Files.newInputStream(path);
|
||||||
|
|
||||||
|
InputStreamResource resource =
|
||||||
|
new InputStreamResource(inputStream) {
|
||||||
|
@Override
|
||||||
|
public long contentLength() {
|
||||||
|
return -1; // 알 수 없으면 -1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
String fileName = Paths.get(remoteFilePath.replace("\\", "/")).getFileName().toString();
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.body(resource);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** unzipRootDir: 압축 해제된 폴더 경로 (ex: /data/xxx/myzipname) */
|
||||||
|
public static void validateTrainValTestDirs(String unzipRootDir) {
|
||||||
|
Path root = Paths.get(unzipRootDir);
|
||||||
|
|
||||||
|
// 루트 폴더 자체 존재 확인
|
||||||
|
if (!Files.exists(root) || !Files.isDirectory(root)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"압축 해제 폴더가 존재하지 않습니다: " + unzipRootDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 필요한 폴더들 존재/디렉토리 여부 확인
|
||||||
|
List<String> missing =
|
||||||
|
REQUIRED_DIRS.stream()
|
||||||
|
.filter(d -> !Files.isDirectory(root.resolve(d)))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (!missing.isEmpty()) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
"데이터 폴더 구조가 올바르지 않습니다. 누락된 폴더: "
|
||||||
|
+ String.join(", ", missing)
|
||||||
|
+ " (필수: train, val, test)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void validateDirFileCount(String unzipRootDir) {
|
||||||
|
Path root = Paths.get(unzipRootDir);
|
||||||
|
|
||||||
|
for (String split : REQUIRED_DIRS) {
|
||||||
|
|
||||||
|
Path splitPath = root.resolve(split);
|
||||||
|
|
||||||
|
Map<String, Long> fileCountMap = new HashMap<>();
|
||||||
|
|
||||||
|
for (String subDir : CHECK_DIRS) { // input1, input2, label 폴더만 수행하기
|
||||||
|
|
||||||
|
Path subDirPath = splitPath.resolve(subDir);
|
||||||
|
|
||||||
|
if (!Files.isDirectory(subDirPath)) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + " 폴더 하위에 " + subDir + " 폴더가 존재하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
long count;
|
||||||
|
try (Stream<Path> files = Files.list(subDirPath)) {
|
||||||
|
count = files.filter(Files::isRegularFile).count();
|
||||||
|
log.info("dir: " + subDirPath + ", count: " + count);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + "/" + subDir + " 파일 개수 확인 중 오류 발생");
|
||||||
|
}
|
||||||
|
|
||||||
|
fileCountMap.put(subDir, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 모든 폴더 파일 개수가 동일한지 확인
|
||||||
|
Set<Long> uniqueCounts = new HashSet<>(fileCountMap.values());
|
||||||
|
|
||||||
|
if (uniqueCounts.size() != 1) {
|
||||||
|
throw new CustomApiException(
|
||||||
|
ApiResponseCode.NOT_FOUND_DATA.getId(),
|
||||||
|
HttpStatus.CONFLICT,
|
||||||
|
split + " 데이터 파일 개수가 일치하지 않습니다. " + fileCountMap.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 폴더 조회
|
||||||
|
*
|
||||||
|
* @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;
|
package com.kamco.cd.training.dataset.service;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -39,3 +40,4 @@ public class MapSheetService {
|
|||||||
log.info("도엽 삭제 완료 - 개수: {}", deleteReq.getItemIds().size());
|
log.info("도엽 삭제 완료 - 개수: {}", deleteReq.getItemIds().size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.kamco.cd.training.hyperparam;
|
package com.kamco.cd.training.hyperparam;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
||||||
@@ -65,7 +66,7 @@ public class HyperParamApiController {
|
|||||||
mediaType = "application/json",
|
mediaType = "application/json",
|
||||||
schema = @Schema(implementation = String.class))),
|
schema = @Schema(implementation = String.class))),
|
||||||
@ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
|
@ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
|
||||||
@ApiResponse(responseCode = "422", description = "HPs_0001 수정 불가", content = @Content),
|
@ApiResponse(responseCode = "422", description = "default는 삭제불가", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@PutMapping("/{uuid}")
|
@PutMapping("/{uuid}")
|
||||||
@@ -96,10 +97,13 @@ public class HyperParamApiController {
|
|||||||
String type,
|
String type,
|
||||||
@Parameter(description = "시작일", example = "2026-02-01") @RequestParam(required = false)
|
@Parameter(description = "시작일", example = "2026-02-01") @RequestParam(required = false)
|
||||||
LocalDate startDate,
|
LocalDate startDate,
|
||||||
@Parameter(description = "종료일", example = "2026-02-28") @RequestParam(required = false)
|
@Parameter(description = "종료일", example = "2026-03-31") @RequestParam(required = false)
|
||||||
LocalDate endDate,
|
LocalDate endDate,
|
||||||
@Parameter(description = "버전명", example = "HPs_0001") @RequestParam(required = false)
|
@Parameter(description = "버전명", example = "G1_000019") @RequestParam(required = false)
|
||||||
String hyperVer,
|
String hyperVer,
|
||||||
|
@Parameter(description = "모델 타입 (G1, G2, G3 중 하나)", example = "G1")
|
||||||
|
@RequestParam(required = false)
|
||||||
|
ModelType model,
|
||||||
@Parameter(
|
@Parameter(
|
||||||
description = "정렬",
|
description = "정렬",
|
||||||
example = "createdDttm desc",
|
example = "createdDttm desc",
|
||||||
@@ -124,7 +128,7 @@ public class HyperParamApiController {
|
|||||||
searchReq.setSort(sort);
|
searchReq.setSort(sort);
|
||||||
searchReq.setPage(page);
|
searchReq.setPage(page);
|
||||||
searchReq.setSize(size);
|
searchReq.setSize(size);
|
||||||
Page<List> list = hyperParamService.getHyperParamList(searchReq);
|
Page<List> list = hyperParamService.getHyperParamList(model, searchReq);
|
||||||
|
|
||||||
return ApiResponseDto.ok(list);
|
return ApiResponseDto.ok(list);
|
||||||
}
|
}
|
||||||
@@ -133,12 +137,12 @@ public class HyperParamApiController {
|
|||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
value = {
|
value = {
|
||||||
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content),
|
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content),
|
||||||
@ApiResponse(responseCode = "422", description = "HPs_0001 삭제 불가", content = @Content),
|
@ApiResponse(responseCode = "422", description = "default 삭제 불가", content = @Content),
|
||||||
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
})
|
})
|
||||||
@DeleteMapping("/{uuid}")
|
@DeleteMapping("/{uuid}")
|
||||||
public ApiResponseDto<Void> deleteHyperParam(
|
public ApiResponseDto<Void> deleteHyperParam(
|
||||||
@Parameter(description = "하이퍼파라미터 uuid", example = "c3b5a285-8f68-42af-84f0-e6d09162deb5")
|
@Parameter(description = "하이퍼파라미터 uuid", example = "57fc9170-64c1-4128-aa7b-0657f08d6d10")
|
||||||
@PathVariable
|
@PathVariable
|
||||||
UUID uuid) {
|
UUID uuid) {
|
||||||
hyperParamService.deleteHyperParam(uuid);
|
hyperParamService.deleteHyperParam(uuid);
|
||||||
@@ -160,7 +164,7 @@ public class HyperParamApiController {
|
|||||||
})
|
})
|
||||||
@GetMapping("/{uuid}")
|
@GetMapping("/{uuid}")
|
||||||
public ApiResponseDto<HyperParamDto.Basic> getHyperParam(
|
public ApiResponseDto<HyperParamDto.Basic> getHyperParam(
|
||||||
@Parameter(description = "하이퍼파라미터 uuid", example = "c3b5a285-8f68-42af-84f0-e6d09162deb5")
|
@Parameter(description = "하이퍼파라미터 uuid", example = "57fc9170-64c1-4128-aa7b-0657f08d6d10")
|
||||||
@PathVariable
|
@PathVariable
|
||||||
UUID uuid) {
|
UUID uuid) {
|
||||||
return ApiResponseDto.ok(hyperParamService.getHyperParam(uuid));
|
return ApiResponseDto.ok(hyperParamService.getHyperParam(uuid));
|
||||||
@@ -179,8 +183,9 @@ public class HyperParamApiController {
|
|||||||
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@GetMapping("/init")
|
@GetMapping("/init/{model}")
|
||||||
public ApiResponseDto<HyperParamDto.Basic> getInitHyperParam() {
|
public ApiResponseDto<HyperParamDto.Basic> getInitHyperParam(@PathVariable ModelType model) {
|
||||||
return ApiResponseDto.ok(hyperParamService.getInitHyperParam());
|
|
||||||
|
return ApiResponseDto.ok(hyperParamService.getInitHyperParam(model));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.hyperparam.dto;
|
package com.kamco.cd.training.hyperparam.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
import com.kamco.cd.training.common.utils.enums.EnumType;
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
@@ -24,9 +25,12 @@ public class HyperParamDto {
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class Basic {
|
public static class Basic {
|
||||||
|
|
||||||
|
private ModelType model; // 20250212 modeltype추가
|
||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
private String hyperVer;
|
private String hyperVer;
|
||||||
@JsonFormatDttm private ZonedDateTime createdDttm;
|
@JsonFormatDttm private ZonedDateTime createdDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
||||||
|
private Integer totalUseCnt;
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// Important
|
// Important
|
||||||
@@ -98,6 +102,8 @@ public class HyperParamDto {
|
|||||||
private Integer gpuCnt;
|
private Integer gpuCnt;
|
||||||
private String gpuIds;
|
private String gpuIds;
|
||||||
private Integer masterPort;
|
private Integer masterPort;
|
||||||
|
|
||||||
|
private Boolean isDefault;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@@ -106,13 +112,12 @@ public class HyperParamDto {
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class List {
|
public static class List {
|
||||||
private UUID uuid;
|
private UUID uuid;
|
||||||
|
private ModelType model;
|
||||||
private String hyperVer;
|
private String hyperVer;
|
||||||
@JsonFormatDttm private ZonedDateTime createDttm;
|
@JsonFormatDttm private ZonedDateTime createDttm;
|
||||||
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
||||||
private Long m1UseCnt;
|
private String memo;
|
||||||
private Long m2UseCnt;
|
private Integer totalUseCnt;
|
||||||
private Long m3UseCnt;
|
|
||||||
private Long totalCnt;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package com.kamco.cd.training.hyperparam.service;
|
package com.kamco.cd.training.hyperparam.service;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.List;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -20,11 +22,12 @@ public class HyperParamService {
|
|||||||
/**
|
/**
|
||||||
* 하이퍼 파라미터 목록 조회
|
* 하이퍼 파라미터 목록 조회
|
||||||
*
|
*
|
||||||
|
* @param model
|
||||||
* @param req
|
* @param req
|
||||||
* @return 목록
|
* @return 목록
|
||||||
*/
|
*/
|
||||||
public Page<List> getHyperParamList(HyperParamDto.SearchReq req) {
|
public Page<List> getHyperParamList(ModelType model, SearchReq req) {
|
||||||
return hyperParamCoreService.findByHyperVerList(req);
|
return hyperParamCoreService.findByHyperVerList(model, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,8 +62,8 @@ public class HyperParamService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 하이퍼파라미터 최적화 설정값 조회 */
|
/** 하이퍼파라미터 최적화 설정값 조회 */
|
||||||
public HyperParamDto.Basic getInitHyperParam() {
|
public HyperParamDto.Basic getInitHyperParam(ModelType model) {
|
||||||
return hyperParamCoreService.getInitHyperParam();
|
return hyperParamCoreService.getInitHyperParam(model);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package com.kamco.cd.training.log;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
|
import com.kamco.cd.training.log.dto.AuditLogDto;
|
||||||
|
import com.kamco.cd.training.log.service.AuditLogService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Tag(name = "감사 로그", description = "감사 로그 관리 API")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/logs/audit")
|
||||||
|
public class AuditLogApiController {
|
||||||
|
|
||||||
|
private final AuditLogService auditLogService;
|
||||||
|
|
||||||
|
@Operation(summary = "일자별 로그 조회")
|
||||||
|
@GetMapping("/daily")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.DailyAuditList>> getDailyLogs(
|
||||||
|
@RequestParam(required = false) LocalDate startDate,
|
||||||
|
@RequestParam(required = false) LocalDate endDate,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
|
||||||
|
Page<AuditLogDto.DailyAuditList> result =
|
||||||
|
auditLogService.getLogByDaily(searchReq, startDate, endDate);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "일자별 로그 상세")
|
||||||
|
@GetMapping("/daily/result")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.DailyDetail>> getDailyResultLogs(
|
||||||
|
@RequestParam LocalDate logDate,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
Page<AuditLogDto.DailyDetail> result = auditLogService.getLogByDailyResult(searchReq, logDate);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "메뉴별 로그 조회")
|
||||||
|
@GetMapping("/menu")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.MenuAuditList>> getMenuLogs(
|
||||||
|
@RequestParam(required = false) String searchValue,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
Page<AuditLogDto.MenuAuditList> result = auditLogService.getLogByMenu(searchReq, searchValue);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "메뉴별 로그 상세")
|
||||||
|
@GetMapping("/menu/result")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.MenuDetail>> getMenuResultLogs(
|
||||||
|
@RequestParam String menuId,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
Page<AuditLogDto.MenuDetail> result = auditLogService.getLogByMenuResult(searchReq, menuId);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "사용자별 로그 조회")
|
||||||
|
@GetMapping("/account")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.UserAuditList>> getAccountLogs(
|
||||||
|
@RequestParam(required = false) String searchValue,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
Page<AuditLogDto.UserAuditList> result =
|
||||||
|
auditLogService.getLogByAccount(searchReq, searchValue);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "사용자별 로그 상세")
|
||||||
|
@GetMapping("/account/result")
|
||||||
|
public ApiResponseDto<Page<AuditLogDto.UserDetail>> getAccountResultLogs(
|
||||||
|
@RequestParam Long userUid,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
AuditLogDto.searchReq searchReq = new AuditLogDto.searchReq(page, size, "created_dttm,desc");
|
||||||
|
Page<AuditLogDto.UserDetail> result = auditLogService.getLogByAccountResult(searchReq, userUid);
|
||||||
|
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.kamco.cd.training.log;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
|
import com.kamco.cd.training.log.dto.ErrorLogDto;
|
||||||
|
import com.kamco.cd.training.log.dto.EventType;
|
||||||
|
import com.kamco.cd.training.log.service.ErrorLogService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@Tag(name = "에러 로그", description = "에러 로그 관리 API")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RestController
|
||||||
|
@RequestMapping({"/api/logs/system"})
|
||||||
|
public class ErrorLogApiController {
|
||||||
|
|
||||||
|
private final ErrorLogService errorLogService;
|
||||||
|
|
||||||
|
@Operation(summary = "에러로그 조회")
|
||||||
|
@GetMapping("/error")
|
||||||
|
public ApiResponseDto<Page<ErrorLogDto.Basic>> getErrorLogs(
|
||||||
|
@RequestParam(required = false) ErrorLogDto.LogErrorLevel logErrorLevel,
|
||||||
|
@RequestParam(required = false) EventType eventType,
|
||||||
|
@RequestParam(required = false) LocalDate startDate,
|
||||||
|
@RequestParam(required = false) LocalDate endDate,
|
||||||
|
@RequestParam int page,
|
||||||
|
@RequestParam(defaultValue = "20") int size) {
|
||||||
|
ErrorLogDto.ErrorSearchReq searchReq =
|
||||||
|
new ErrorLogDto.ErrorSearchReq(
|
||||||
|
logErrorLevel, eventType, startDate, endDate, page, size, "created_dttm,desc");
|
||||||
|
Page<ErrorLogDto.Basic> result = errorLogService.findLogByError(searchReq);
|
||||||
|
return ApiResponseDto.ok(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,9 @@ package com.kamco.cd.training.log.dto;
|
|||||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import java.time.LocalDate;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
@@ -58,6 +60,7 @@ public class AuditLogDto {
|
|||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class AuditCommon {
|
public static class AuditCommon {
|
||||||
|
|
||||||
private int readCount;
|
private int readCount;
|
||||||
private int cudCount;
|
private int cudCount;
|
||||||
private int printCount;
|
private int printCount;
|
||||||
@@ -68,6 +71,7 @@ public class AuditLogDto {
|
|||||||
@Schema(name = "DailyAuditList", description = "일자별 목록")
|
@Schema(name = "DailyAuditList", description = "일자별 목록")
|
||||||
@Getter
|
@Getter
|
||||||
public static class DailyAuditList extends AuditCommon {
|
public static class DailyAuditList extends AuditCommon {
|
||||||
|
|
||||||
private final String baseDate;
|
private final String baseDate;
|
||||||
|
|
||||||
public DailyAuditList(
|
public DailyAuditList(
|
||||||
@@ -85,6 +89,7 @@ public class AuditLogDto {
|
|||||||
@Schema(name = "MenuAuditList", description = "메뉴별 목록")
|
@Schema(name = "MenuAuditList", description = "메뉴별 목록")
|
||||||
@Getter
|
@Getter
|
||||||
public static class MenuAuditList extends AuditCommon {
|
public static class MenuAuditList extends AuditCommon {
|
||||||
|
|
||||||
private final String menuId;
|
private final String menuId;
|
||||||
private final String menuName;
|
private final String menuName;
|
||||||
|
|
||||||
@@ -105,6 +110,7 @@ public class AuditLogDto {
|
|||||||
@Schema(name = "UserAuditList", description = "사용자별 목록")
|
@Schema(name = "UserAuditList", description = "사용자별 목록")
|
||||||
@Getter
|
@Getter
|
||||||
public static class UserAuditList extends AuditCommon {
|
public static class UserAuditList extends AuditCommon {
|
||||||
|
|
||||||
private final Long accountId;
|
private final Long accountId;
|
||||||
private final String loginId;
|
private final String loginId;
|
||||||
private final String username;
|
private final String username;
|
||||||
@@ -129,6 +135,7 @@ public class AuditLogDto {
|
|||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class AuditDetail {
|
public static class AuditDetail {
|
||||||
|
|
||||||
private Long logId;
|
private Long logId;
|
||||||
private EventType eventType;
|
private EventType eventType;
|
||||||
private LogDetail detail;
|
private LogDetail detail;
|
||||||
@@ -137,9 +144,11 @@ public class AuditLogDto {
|
|||||||
@Schema(name = "DailyDetail", description = "일자별 로그 상세")
|
@Schema(name = "DailyDetail", description = "일자별 로그 상세")
|
||||||
@Getter
|
@Getter
|
||||||
public static class DailyDetail extends AuditDetail {
|
public static class DailyDetail extends AuditDetail {
|
||||||
|
|
||||||
private final String userName;
|
private final String userName;
|
||||||
private final String loginId;
|
private final String loginId;
|
||||||
private final String menuName;
|
private final String menuName;
|
||||||
|
private final String logDateTime;
|
||||||
|
|
||||||
public DailyDetail(
|
public DailyDetail(
|
||||||
Long logId,
|
Long logId,
|
||||||
@@ -147,17 +156,20 @@ public class AuditLogDto {
|
|||||||
String loginId,
|
String loginId,
|
||||||
String menuName,
|
String menuName,
|
||||||
EventType eventType,
|
EventType eventType,
|
||||||
|
String logDateTime,
|
||||||
LogDetail detail) {
|
LogDetail detail) {
|
||||||
super(logId, eventType, detail);
|
super(logId, eventType, detail);
|
||||||
this.userName = userName;
|
this.userName = userName;
|
||||||
this.loginId = loginId;
|
this.loginId = loginId;
|
||||||
this.menuName = menuName;
|
this.menuName = menuName;
|
||||||
|
this.logDateTime = logDateTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Schema(name = "MenuDetail", description = "메뉴별 로그 상세")
|
@Schema(name = "MenuDetail", description = "메뉴별 로그 상세")
|
||||||
@Getter
|
@Getter
|
||||||
public static class MenuDetail extends AuditDetail {
|
public static class MenuDetail extends AuditDetail {
|
||||||
|
|
||||||
private final String logDateTime;
|
private final String logDateTime;
|
||||||
private final String userName;
|
private final String userName;
|
||||||
private final String loginId;
|
private final String loginId;
|
||||||
@@ -179,6 +191,7 @@ public class AuditLogDto {
|
|||||||
@Schema(name = "UserDetail", description = "사용자별 로그 상세")
|
@Schema(name = "UserDetail", description = "사용자별 로그 상세")
|
||||||
@Getter
|
@Getter
|
||||||
public static class UserDetail extends AuditDetail {
|
public static class UserDetail extends AuditDetail {
|
||||||
|
|
||||||
private final String logDateTime;
|
private final String logDateTime;
|
||||||
private final String menuNm;
|
private final String menuNm;
|
||||||
|
|
||||||
@@ -194,6 +207,7 @@ public class AuditLogDto {
|
|||||||
@Setter
|
@Setter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class LogDetail {
|
public static class LogDetail {
|
||||||
|
|
||||||
String serviceName;
|
String serviceName;
|
||||||
String parentMenuName;
|
String parentMenuName;
|
||||||
String menuName;
|
String menuName;
|
||||||
@@ -226,4 +240,26 @@ public class AuditLogDto {
|
|||||||
return PageRequest.of(page, size);
|
return PageRequest.of(page, size);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class DownloadReq {
|
||||||
|
|
||||||
|
UUID uuid;
|
||||||
|
LocalDate startDate;
|
||||||
|
LocalDate endDate;
|
||||||
|
String searchValue;
|
||||||
|
String menuId;
|
||||||
|
String requestUri;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class DownloadRes {
|
||||||
|
|
||||||
|
String name;
|
||||||
|
String employeeNo;
|
||||||
|
@JsonFormatDttm ZonedDateTime downloadDttm;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.log.dto;
|
package com.kamco.cd.training.log.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
import com.kamco.cd.training.common.utils.enums.EnumType;
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -77,6 +78,7 @@ public class ErrorLogDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@CodeExpose
|
||||||
public enum LogErrorLevel implements EnumType {
|
public enum LogErrorLevel implements EnumType {
|
||||||
WARNING("Warning"),
|
WARNING("Warning"),
|
||||||
ERROR("Error"),
|
ERROR("Error"),
|
||||||
|
|||||||
@@ -1,22 +1,35 @@
|
|||||||
package com.kamco.cd.training.log.dto;
|
package com.kamco.cd.training.log.dto;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||||
import com.kamco.cd.training.common.utils.enums.EnumType;
|
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@CodeExpose
|
||||||
@Getter
|
@Getter
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public enum EventType implements EnumType {
|
public enum EventType implements EnumType {
|
||||||
CREATE("생성"),
|
LIST("목록"),
|
||||||
READ("조회"),
|
DETAIL("상세"),
|
||||||
UPDATE("수정"),
|
POPUP("팝업"),
|
||||||
DELETE("삭제"),
|
STATUS("상태"),
|
||||||
|
ADDED("추가"),
|
||||||
|
MODIFIED("수정"),
|
||||||
|
REMOVE("삭제"),
|
||||||
DOWNLOAD("다운로드"),
|
DOWNLOAD("다운로드"),
|
||||||
PRINT("출력"),
|
LOGIN("로그인"),
|
||||||
OTHER("기타");
|
OTHER("기타");
|
||||||
|
|
||||||
private final String desc;
|
private final String desc;
|
||||||
|
|
||||||
|
public static EventType fromName(String name) {
|
||||||
|
try {
|
||||||
|
return EventType.valueOf(name.toUpperCase());
|
||||||
|
} catch (Exception e) {
|
||||||
|
return OTHER;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return name();
|
return name();
|
||||||
|
|||||||
@@ -1,22 +1,40 @@
|
|||||||
package com.kamco.cd.training.model;
|
package com.kamco.cd.training.model;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.download.RangeDownloadResponder;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelBestEpoch;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelFileInfo;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTestMetrics;
|
||||||
|
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.TransferDetailDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.CleanupResult;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||||
import com.kamco.cd.training.model.service.ModelTrainDetailService;
|
import com.kamco.cd.training.model.service.ModelTrainDetailService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
import io.swagger.v3.oas.annotations.media.ArraySchema;
|
import io.swagger.v3.oas.annotations.media.ArraySchema;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
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.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -28,6 +46,10 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
@RequestMapping("/api/models")
|
@RequestMapping("/api/models")
|
||||||
public class ModelTrainDetailApiController {
|
public class ModelTrainDetailApiController {
|
||||||
private final ModelTrainDetailService modelTrainDetailService;
|
private final ModelTrainDetailService modelTrainDetailService;
|
||||||
|
private final RangeDownloadResponder rangeDownloadResponder;
|
||||||
|
|
||||||
|
@Value("${train.docker.responseDir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
@@ -112,7 +134,28 @@ public class ModelTrainDetailApiController {
|
|||||||
return ApiResponseDto.ok(modelTrainDetailService.getByModelMappingDataset(uuid));
|
return ApiResponseDto.ok(modelTrainDetailService.getByModelMappingDataset(uuid));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "모델관리 > 전이 학습 실행설정 > 모델선택", description = "모델선택 정보 API")
|
// @Operation(summary = "모델관리 > 전이 학습 실행설정 > 모델선택", description = "모델선택 정보 API")
|
||||||
|
// @ApiResponses(
|
||||||
|
// value = {
|
||||||
|
// @ApiResponse(
|
||||||
|
// responseCode = "200",
|
||||||
|
// description = "조회 성공",
|
||||||
|
// content =
|
||||||
|
// @Content(
|
||||||
|
// mediaType = "application/json",
|
||||||
|
// schema = @Schema(implementation = TransferDetailDto.class))),
|
||||||
|
// @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
// @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
// })
|
||||||
|
// @GetMapping("/transfer/detail/{uuid}")
|
||||||
|
// public ApiResponseDto<TransferDetailDto> getTransferDetail(
|
||||||
|
// @Parameter(description = "모델 uuid", example = "7fbdff54-ea87-4b02-90d1-955fa2a3457e")
|
||||||
|
// @PathVariable
|
||||||
|
// UUID uuid) {
|
||||||
|
// return ApiResponseDto.ok(modelTrainDetailService.getTransferDetail(uuid));
|
||||||
|
// }
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델 상세 > 성능 정보 (Train)", description = "모델 상세 > 성능 정보 (Train) API")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
value = {
|
value = {
|
||||||
@ApiResponse(
|
@ApiResponse(
|
||||||
@@ -125,11 +168,202 @@ public class ModelTrainDetailApiController {
|
|||||||
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@GetMapping("/transfer/detail/{uuid}")
|
@GetMapping("/metrics/train/{uuid}")
|
||||||
public ApiResponseDto<TransferDetailDto> getTransferDetail(
|
public ApiResponseDto<List<ModelTrainMetrics>> getModelTrainMetricResult(
|
||||||
@Parameter(description = "모델 uuid", example = "7fbdff54-ea87-4b02-90d1-955fa2a3457e")
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
@PathVariable
|
@PathVariable
|
||||||
UUID uuid) {
|
UUID uuid) {
|
||||||
return ApiResponseDto.ok(modelTrainDetailService.getTransferDetail(uuid));
|
return ApiResponseDto.ok(modelTrainDetailService.getModelTrainMetricResult(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "모델관리 > 모델 상세 > 성능 정보 (Validation)",
|
||||||
|
description = "모델 상세 > 성능 정보 (Validation) API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = TransferDetailDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/metrics/validation/{uuid}")
|
||||||
|
public ApiResponseDto<List<ModelValidationMetrics>> getModelValidationMetricResult(
|
||||||
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.getModelValidationMetricResult(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델 상세 > 성능 정보 (Test)", description = "모델 상세 > 성능 정보 (Test) API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = TransferDetailDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/metrics/test/{uuid}")
|
||||||
|
public ApiResponseDto<List<ModelTestMetrics>> getModelTestMetricResult(
|
||||||
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.getModelTestMetricResult(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델 상세 > 성능 정보 (Test)", description = "모델 상세 > 성능 정보 (Test) API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = TransferDetailDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/best-epoch/{uuid}")
|
||||||
|
public ApiResponseDto<ModelBestEpoch> getModelTrainBestEpoch(
|
||||||
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.getModelTrainBestEpoch(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "학습데이터 파일 다운로드",
|
||||||
|
description = "학습데이터 파일 다운로드",
|
||||||
|
parameters = {
|
||||||
|
@Parameter(
|
||||||
|
name = "kamco-download-uuid",
|
||||||
|
in = ParameterIn.HEADER,
|
||||||
|
required = true,
|
||||||
|
description = "다운로드 요청 UUID",
|
||||||
|
schema =
|
||||||
|
@Schema(
|
||||||
|
type = "string",
|
||||||
|
format = "uuid",
|
||||||
|
example = "6d8d49dc-0c9d-4124-adc7-b9ca610cc394"))
|
||||||
|
})
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "학습데이터 zip파일 다운로드",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/octet-stream",
|
||||||
|
schema = @Schema(type = "string", format = "binary"))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "파일 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/download/{uuid}")
|
||||||
|
public ResponseEntity<?> download(@PathVariable UUID uuid, HttpServletRequest request)
|
||||||
|
throws IOException {
|
||||||
|
|
||||||
|
Basic info = modelTrainDetailService.findByModelByUUID(uuid);
|
||||||
|
Path zipPath =
|
||||||
|
Paths.get(responseDir)
|
||||||
|
.resolve(String.valueOf(info.getUuid()))
|
||||||
|
.resolve(info.getModelVer() + ".zip");
|
||||||
|
|
||||||
|
if (!Files.isRegularFile(zipPath)) {
|
||||||
|
throw new BadRequestException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return rangeDownloadResponder.buildZipResponse(zipPath, info.getModelVer() + ".zip", request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델 상세 > 파일 정보", description = "모델 상세 > 파일 정보 API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = TransferDetailDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/file-info/{uuid}")
|
||||||
|
public ApiResponseDto<ModelFileInfo> getModelTrainFileInfo(
|
||||||
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
|
@PathVariable
|
||||||
|
UUID uuid) {
|
||||||
|
return ApiResponseDto.ok(modelTrainDetailService.getModelTrainFileInfo(uuid));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "모델관리 > 모델별 진행 상황", description = "모델관리 > 모델별 진행 상황 API")
|
||||||
|
@ApiResponses(
|
||||||
|
value = {
|
||||||
|
@ApiResponse(
|
||||||
|
responseCode = "200",
|
||||||
|
description = "조회 성공",
|
||||||
|
content =
|
||||||
|
@Content(
|
||||||
|
mediaType = "application/json",
|
||||||
|
schema = @Schema(implementation = ModelProgressStepDto.class))),
|
||||||
|
@ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
|
||||||
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
|
})
|
||||||
|
@GetMapping("/progress/{uuid}")
|
||||||
|
public ApiResponseDto<List<ModelProgressStepDto>> findModelTrainProgressInfo(
|
||||||
|
@Parameter(description = "모델 uuid", example = "95cb116c-380a-41c0-98d8-4d1142f15bbf")
|
||||||
|
@PathVariable
|
||||||
|
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,13 +1,17 @@
|
|||||||
package com.kamco.cd.training.model;
|
package com.kamco.cd.training.model;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.dto.MonitorDto;
|
||||||
|
import com.kamco.cd.training.common.service.SystemMonitorService;
|
||||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
||||||
import com.kamco.cd.training.model.service.ModelTrainMngService;
|
import com.kamco.cd.training.model.service.ModelTrainMngService;
|
||||||
|
import com.kamco.cd.training.train.service.ModelTestMetricsJobService;
|
||||||
|
import com.kamco.cd.training.train.service.ModelTrainMetricsJobService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
@@ -16,6 +20,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
|||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -35,6 +40,9 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
@RequestMapping("/api/models")
|
@RequestMapping("/api/models")
|
||||||
public class ModelTrainMngApiController {
|
public class ModelTrainMngApiController {
|
||||||
private final ModelTrainMngService modelTrainMngService;
|
private final ModelTrainMngService modelTrainMngService;
|
||||||
|
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||||
|
private final ModelTestMetricsJobService modelTestMetricsJobService;
|
||||||
|
private final SystemMonitorService systemMonitorService;
|
||||||
|
|
||||||
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
|
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
|
||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
@@ -50,7 +58,7 @@ public class ModelTrainMngApiController {
|
|||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@GetMapping("/list")
|
@GetMapping("/list")
|
||||||
public ApiResponseDto<Page<Basic>> findByModelList(
|
public ApiResponseDto<Page<ListDto>> findByModelList(
|
||||||
@Parameter(
|
@Parameter(
|
||||||
description = "상태코드",
|
description = "상태코드",
|
||||||
example = "IN_PROGRESS",
|
example = "IN_PROGRESS",
|
||||||
@@ -74,7 +82,7 @@ public class ModelTrainMngApiController {
|
|||||||
@ApiResponses(
|
@ApiResponses(
|
||||||
value = {
|
value = {
|
||||||
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content),
|
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content),
|
||||||
@ApiResponse(responseCode = "409", description = "HPs_0001 삭제 불가", content = @Content)
|
@ApiResponse(responseCode = "409", description = "G1_000001 삭제 불가", content = @Content)
|
||||||
})
|
})
|
||||||
@DeleteMapping("/{uuid}")
|
@DeleteMapping("/{uuid}")
|
||||||
public ApiResponseDto<Void> deleteModelTrain(
|
public ApiResponseDto<Void> deleteModelTrain(
|
||||||
@@ -92,9 +100,8 @@ public class ModelTrainMngApiController {
|
|||||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||||
})
|
})
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ApiResponseDto<String> createModelTrain(@Valid @RequestBody ModelTrainMngDto.AddReq req) {
|
public ApiResponseDto<UUID> createModelTrain(@Valid @RequestBody ModelTrainMngDto.AddReq req) {
|
||||||
modelTrainMngService.createModelTrain(req);
|
return ApiResponseDto.ok(modelTrainMngService.createModelTrain(req));
|
||||||
return ApiResponseDto.ok("ok");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "모델학습 config 정보 조회", description = "모델학습 config 정보 조회 API")
|
@Operation(summary = "모델학습 config 정보 조회", description = "모델학습 config 정보 조회 API")
|
||||||
@@ -150,4 +157,82 @@ public class ModelTrainMngApiController {
|
|||||||
req.setDataType(selectType);
|
req.setDataType(selectType);
|
||||||
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
|
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "모델학습 1단계/2단계 실행중인 것이 있는지 count",
|
||||||
|
description = "모델학습 1단계/2단계 실행중인 것이 있는지 count")
|
||||||
|
@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("/ing-training-cnt")
|
||||||
|
public ApiResponseDto<Long> findModelStep1InProgressCnt() {
|
||||||
|
return ApiResponseDto.ok(modelTrainMngService.findModelStep1InProgressCnt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(
|
||||||
|
summary = "스케줄러 findTrainValidMetricCsvFiles",
|
||||||
|
description = "스케줄러 findTrainValidMetricCsvFiles")
|
||||||
|
@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("/schedule-trainvalid")
|
||||||
|
public ApiResponseDto<Long> findTrainValidMetricCsvFiles() {
|
||||||
|
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
||||||
|
return ApiResponseDto.ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "스케줄러 findTestMetricCsvFiles", description = "스케줄러 findTestMetricCsvFiles")
|
||||||
|
@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("/schedule-test")
|
||||||
|
public ApiResponseDto<Long> findTestValidMetricCsvFiles() throws IOException {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,4 +20,25 @@ public class ModelConfigDto {
|
|||||||
private Float testPercent;
|
private Float testPercent;
|
||||||
private String memo;
|
private String memo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class TransferBasic {
|
||||||
|
private Long configId;
|
||||||
|
private Long modelId;
|
||||||
|
private Integer epochCount;
|
||||||
|
private Float trainPercent;
|
||||||
|
private Float validationPercent;
|
||||||
|
private Float testPercent;
|
||||||
|
private String memo;
|
||||||
|
private Long beforeConfigId;
|
||||||
|
private Long beforeModelId;
|
||||||
|
private Integer beforeEpochCount;
|
||||||
|
private Float beforeTrainPercent;
|
||||||
|
private Float beforeValidationPercent;
|
||||||
|
private Float beforeTestPercent;
|
||||||
|
private String beforeMemo;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import com.kamco.cd.training.common.enums.TrainStatusType;
|
|||||||
import com.kamco.cd.training.common.enums.TrainType;
|
import com.kamco.cd.training.common.enums.TrainType;
|
||||||
import com.kamco.cd.training.common.utils.enums.Enums;
|
import com.kamco.cd.training.common.utils.enums.Enums;
|
||||||
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
import com.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -35,6 +35,7 @@ public class ModelTrainDetailDto {
|
|||||||
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
||||||
private String statusCd;
|
private String statusCd;
|
||||||
private String trainType;
|
private String trainType;
|
||||||
|
private UUID beforeUuid;
|
||||||
|
|
||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
@@ -93,6 +94,29 @@ public class ModelTrainDetailDto {
|
|||||||
private Integer batchSize;
|
private Integer batchSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Schema(name = "모델학습관리 전이 하이파라미터", description = "모델학습관리 전이 하이파라미터")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public static class TransferHyperSummary {
|
||||||
|
private UUID uuid;
|
||||||
|
private Long hyperParamId;
|
||||||
|
private String hyperVer;
|
||||||
|
private String backbone;
|
||||||
|
private String inputSize;
|
||||||
|
private String cropSize;
|
||||||
|
private Integer batchSize;
|
||||||
|
private UUID beforeUuid;
|
||||||
|
private Long beforeHyperParamId;
|
||||||
|
private String beforeHyperVer;
|
||||||
|
private String beforeBackbone;
|
||||||
|
private String beforeInputSize;
|
||||||
|
private String beforeCropSize;
|
||||||
|
private Integer beforeBatchSize;
|
||||||
|
}
|
||||||
|
|
||||||
@Schema(name = "선택한 데이터셋 목록", description = "선택한 데이터셋 목록")
|
@Schema(name = "선택한 데이터셋 목록", description = "선택한 데이터셋 목록")
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@@ -153,8 +177,83 @@ public class ModelTrainDetailDto {
|
|||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public static class TransferDetailDto {
|
public static class TransferDetailDto {
|
||||||
private ModelConfigDto.Basic etcConfig;
|
private ModelConfigDto.TransferBasic etcConfig;
|
||||||
private HyperSummary modelTrainHyper;
|
private TransferHyperSummary modelTrainHyper;
|
||||||
private List<SelectDataSet> modelTrainDataset;
|
private List<SelectTransferDataSet> modelTrainDataset;
|
||||||
|
// private List<SelectDataSet> beforeTrainDataset;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelTrainMetrics {
|
||||||
|
private Integer epoch;
|
||||||
|
private Long iteration;
|
||||||
|
private Double loss;
|
||||||
|
private Double lr;
|
||||||
|
private Float durationTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelValidationMetrics {
|
||||||
|
|
||||||
|
private Integer epoch;
|
||||||
|
private Float aAcc;
|
||||||
|
private Float mFscore;
|
||||||
|
private Float mPrecision;
|
||||||
|
private Float mRecall;
|
||||||
|
private Float mIou;
|
||||||
|
private Float mAcc;
|
||||||
|
private Float changedFscore;
|
||||||
|
private Float changedPrecision;
|
||||||
|
private Float changedRecall;
|
||||||
|
private Float unchangedFscore;
|
||||||
|
private Float unchangedPrecision;
|
||||||
|
private Float unchangedRecall;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelTestMetrics {
|
||||||
|
private String model;
|
||||||
|
private Long tp;
|
||||||
|
private Long fp;
|
||||||
|
private Long fn;
|
||||||
|
private Float precision;
|
||||||
|
private Float recall;
|
||||||
|
private Float f1Score;
|
||||||
|
private Float accuracy;
|
||||||
|
private Float iou;
|
||||||
|
private Long detectionCount;
|
||||||
|
private Long gtCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelBestEpoch {
|
||||||
|
private Integer epoch;
|
||||||
|
private Double loss;
|
||||||
|
private Float f1Score;
|
||||||
|
private Float precision;
|
||||||
|
private Float recall;
|
||||||
|
private Float iou;
|
||||||
|
private Float accuracy;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelFileInfo {
|
||||||
|
private Boolean fileExistsYn;
|
||||||
|
private String fileName;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,15 @@ public class ModelTrainMngDto {
|
|||||||
private String statusCd;
|
private String statusCd;
|
||||||
private String trainType;
|
private String trainType;
|
||||||
private String modelNo;
|
private String modelNo;
|
||||||
|
private Long currentAttemptId;
|
||||||
|
private String requestPath;
|
||||||
|
|
||||||
|
private String packingState;
|
||||||
|
private ZonedDateTime packingStrtDttm;
|
||||||
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
|
private Long beforeModelId;
|
||||||
|
private Integer bestEpoch;
|
||||||
|
|
||||||
public String getStatusName() {
|
public String getStatusName() {
|
||||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
@@ -59,7 +68,7 @@ public class ModelTrainMngDto {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStep2StatusNAme() {
|
public String getStep2StatusName() {
|
||||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
try {
|
try {
|
||||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
@@ -98,6 +107,10 @@ public class ModelTrainMngDto {
|
|||||||
public String getStep2Duration() {
|
public String getStep2Duration() {
|
||||||
return formatDuration(this.step2StrtDttm, this.step2EndDttm);
|
return formatDuration(this.step2StrtDttm, this.step2EndDttm);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getPackingDuration() {
|
||||||
|
return formatDuration(this.packingStrtDttm, this.packingEndDttm);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Schema(name = "searchReq", description = "모델학습 관리 목록조회 파라미터")
|
@Schema(name = "searchReq", description = "모델학습 관리 목록조회 파라미터")
|
||||||
@@ -137,6 +150,9 @@ public class ModelTrainMngDto {
|
|||||||
@Schema(description = "학습타입 GENERAL(일반), TRANSFER(전이)", example = "GENERAL")
|
@Schema(description = "학습타입 GENERAL(일반), TRANSFER(전이)", example = "GENERAL")
|
||||||
private String trainType;
|
private String trainType;
|
||||||
|
|
||||||
|
@Schema(description = "전이학습일때 선택한 모델 id")
|
||||||
|
private Long beforeModelId;
|
||||||
|
|
||||||
@NotNull
|
@NotNull
|
||||||
@Schema(
|
@Schema(
|
||||||
description = "하이퍼 파라미터 선택 타입 OPTIMIZED(최적화 파라미터),EXISTING(기존 파라미터),NEW(신규 파라미터)",
|
description = "하이퍼 파라미터 선택 타입 OPTIMIZED(최적화 파라미터),EXISTING(기존 파라미터),NEW(신규 파라미터)",
|
||||||
@@ -151,6 +167,17 @@ public class ModelTrainMngDto {
|
|||||||
ModelConfig modelConfig;
|
ModelConfig modelConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Schema(name = "addReq", description = "모델학습 관리 등록 파라미터")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class UpdateReq {
|
||||||
|
|
||||||
|
private String requestPath;
|
||||||
|
private String responsePath;
|
||||||
|
}
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public static class TrainingDataset {
|
public static class TrainingDataset {
|
||||||
@@ -194,4 +221,133 @@ public class ModelTrainMngDto {
|
|||||||
@Schema(description = "메모", example = "메모 입니다.")
|
@Schema(description = "메모", example = "메모 입니다.")
|
||||||
private String memo;
|
private String memo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Schema(name = "모델학습관리 목록", description = "모델학습관리 목록")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public static class ListDto {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private UUID uuid;
|
||||||
|
private String modelVer;
|
||||||
|
@JsonFormatDttm private ZonedDateTime startDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step1StrtDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step1EndDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step2StrtDttm;
|
||||||
|
@JsonFormatDttm private ZonedDateTime step2EndDttm;
|
||||||
|
private String step1Status;
|
||||||
|
private String step2Status;
|
||||||
|
private String statusCd;
|
||||||
|
private String trainType;
|
||||||
|
private String modelNo;
|
||||||
|
private Long currentAttemptId;
|
||||||
|
private String requestPath;
|
||||||
|
|
||||||
|
private String packingState;
|
||||||
|
private ZonedDateTime packingStrtDttm;
|
||||||
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
|
private String memo;
|
||||||
|
private String userNm;
|
||||||
|
private UUID beforeUuid;
|
||||||
|
|
||||||
|
public String getStatusName() {
|
||||||
|
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
return TrainStatusType.valueOf(this.statusCd).getText(); // 또는 getName()
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return this.statusCd; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStep1StatusName() {
|
||||||
|
if (this.step1Status == null || this.step1Status.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
return TrainStatusType.valueOf(this.step1Status).getText(); // 또는 getName()
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return this.step1Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStep2StatusName() {
|
||||||
|
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return this.step2Status; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTrainTypeName() {
|
||||||
|
if (this.trainType == null || this.trainType.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
return TrainType.valueOf(this.trainType).getText(); // 또는 getName()
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return this.trainType; // 매핑 못하면 코드 그대로 반환(원하면 null 처리)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String formatDuration(ZonedDateTime start, ZonedDateTime end) {
|
||||||
|
if (start == null || end == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
long totalSeconds = Math.abs(Duration.between(start, end).getSeconds());
|
||||||
|
|
||||||
|
long hours = totalSeconds / 3600;
|
||||||
|
long minutes = (totalSeconds % 3600) / 60;
|
||||||
|
long seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
return String.format("%d시간 %d분 %d초", hours, minutes, seconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStep1Duration() {
|
||||||
|
return formatDuration(this.step1StrtDttm, this.step1EndDttm);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStep2Duration() {
|
||||||
|
return formatDuration(this.step2StrtDttm, this.step2EndDttm);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPackingDuration() {
|
||||||
|
return formatDuration(this.packingStrtDttm, this.packingEndDttm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class ModelProgressStepDto {
|
||||||
|
|
||||||
|
private int step;
|
||||||
|
private String status;
|
||||||
|
@JsonFormatDttm private ZonedDateTime startTime;
|
||||||
|
@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,20 +1,46 @@
|
|||||||
package com.kamco.cd.training.model.service;
|
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.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelBestEpoch;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelFileInfo;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTestMetrics;
|
||||||
|
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.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.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.ModelTrainDetailCoreService;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
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.ArrayList;
|
||||||
|
import java.util.EnumSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Stream;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -27,6 +53,9 @@ public class ModelTrainDetailService {
|
|||||||
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
private final ModelTrainDetailCoreService modelTrainDetailCoreService;
|
||||||
private final ModelTrainMngCoreService mngCoreService;
|
private final ModelTrainMngCoreService mngCoreService;
|
||||||
|
|
||||||
|
@Value("${train.docker.responseDir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 상세정보 요약
|
* 모델 상세정보 요약
|
||||||
*
|
*
|
||||||
@@ -55,15 +84,22 @@ public class ModelTrainDetailService {
|
|||||||
return modelTrainDetailCoreService.findByModelByUUID(uuid);
|
return modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 전이학습 모델선택 정보
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
public TransferDetailDto getTransferDetail(UUID uuid) {
|
public TransferDetailDto getTransferDetail(UUID uuid) {
|
||||||
Basic modelInfo = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
Basic modelInfo = modelTrainDetailCoreService.findByModelByUUID(uuid);
|
||||||
|
|
||||||
// config 정보 조회
|
// config 정보 조회
|
||||||
ModelConfigDto.Basic configInfo = mngCoreService.findModelConfigByModelId(uuid);
|
ModelConfigDto.TransferBasic configInfo = mngCoreService.findModelTransferConfigByModelId(uuid);
|
||||||
|
|
||||||
// 하이파라미터 정보 조회
|
// 하이파라미터 정보 조회
|
||||||
HyperSummary hyperSummary = modelTrainDetailCoreService.getByModelHyperParamSummary(uuid);
|
TransferHyperSummary hyperSummary = modelTrainDetailCoreService.getTransferHyperSummary(uuid);
|
||||||
List<SelectDataSet> dataSets = new ArrayList<>();
|
List<SelectTransferDataSet> dataSets = new ArrayList<>();
|
||||||
|
|
||||||
DatasetReq datasetReq = new DatasetReq();
|
DatasetReq datasetReq = new DatasetReq();
|
||||||
List<Long> datasetIds = new ArrayList<>();
|
List<Long> datasetIds = new ArrayList<>();
|
||||||
@@ -74,13 +110,39 @@ public class ModelTrainDetailService {
|
|||||||
datasetIds.add(mappingDataset.getDatasetId());
|
datasetIds.add(mappingDataset.getDatasetId());
|
||||||
}
|
}
|
||||||
datasetReq.setIds(datasetIds);
|
datasetReq.setIds(datasetIds);
|
||||||
|
datasetReq.setModelNo(modelInfo.getModelNo());
|
||||||
|
|
||||||
if (modelInfo.getModelNo().equals("G1")) {
|
if (modelInfo.getModelNo().equals(ModelType.G1.getId())) {
|
||||||
dataSets = mngCoreService.getDatasetSelectG1List(datasetReq);
|
dataSets = mngCoreService.getDatasetTransferSelectG1List(modelInfo.getId());
|
||||||
} else {
|
} else {
|
||||||
dataSets = mngCoreService.getDatasetSelectG2G3List(datasetReq);
|
dataSets =
|
||||||
|
mngCoreService.getDatasetTransferSelectG2G3List(
|
||||||
|
modelInfo.getId(), modelInfo.getModelNo());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DatasetReq beforeDatasetReq = new DatasetReq();
|
||||||
|
// List<Long> beforeDatasetIds = new ArrayList<>();
|
||||||
|
// List<SelectDataSet> beforeDataSets = new ArrayList<>();
|
||||||
|
//
|
||||||
|
// Long beforeModelId = modelInfo.getBeforeModelId();
|
||||||
|
// if (beforeModelId != null) {
|
||||||
|
// Basic beforeInfo = modelTrainDetailCoreService.findByModelBeforeId(beforeModelId);
|
||||||
|
// List<MappingDataset> beforeDatasets =
|
||||||
|
// modelTrainDetailCoreService.getByModelMappingDataset(beforeInfo.getUuid());
|
||||||
|
//
|
||||||
|
// for (MappingDataset before : beforeDatasets) {
|
||||||
|
// beforeDatasetIds.add(before.getDatasetId());
|
||||||
|
// }
|
||||||
|
// beforeDatasetReq.setIds(beforeDatasetIds);
|
||||||
|
// beforeDatasetReq.setModelNo(modelInfo.getModelNo());
|
||||||
|
//
|
||||||
|
// if (beforeInfo.getModelNo().equals(ModelType.G1.getId())) {
|
||||||
|
// beforeDataSets = mngCoreService.getDatasetSelectG1List(beforeDatasetReq);
|
||||||
|
// } else {
|
||||||
|
// beforeDataSets = mngCoreService.getDatasetSelectG2G3List(beforeDatasetReq);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
TransferDetailDto transferDetailDto = new TransferDetailDto();
|
TransferDetailDto transferDetailDto = new TransferDetailDto();
|
||||||
transferDetailDto.setEtcConfig(configInfo);
|
transferDetailDto.setEtcConfig(configInfo);
|
||||||
transferDetailDto.setModelTrainHyper(hyperSummary);
|
transferDetailDto.setModelTrainHyper(hyperSummary);
|
||||||
@@ -88,4 +150,288 @@ public class ModelTrainDetailService {
|
|||||||
|
|
||||||
return transferDetailDto;
|
return transferDetailDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||||
|
return modelTrainDetailCoreService.getModelTrainMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModelValidationMetrics> getModelValidationMetricResult(UUID uuid) {
|
||||||
|
return modelTrainDetailCoreService.getModelValidationMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModelTestMetrics> getModelTestMetricResult(UUID uuid) {
|
||||||
|
return modelTrainDetailCoreService.getModelTestMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelBestEpoch getModelTrainBestEpoch(UUID uuid) {
|
||||||
|
return modelTrainDetailCoreService.getModelTrainBestEpoch(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelFileInfo getModelTrainFileInfo(UUID uuid) {
|
||||||
|
return modelTrainDetailCoreService.getModelTrainFileInfo(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ package com.kamco.cd.training.model.service;
|
|||||||
|
|
||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
import com.kamco.cd.training.common.enums.HyperParamSelectType;
|
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;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
@@ -10,11 +14,24 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
|
||||||
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
||||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
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.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -26,6 +43,14 @@ public class ModelTrainMngService {
|
|||||||
|
|
||||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||||
private final HyperParamCoreService hyperParamCoreService;
|
private final HyperParamCoreService hyperParamCoreService;
|
||||||
|
private final TrainJobService trainJobService;
|
||||||
|
private final ModelTrainDetailService modelTrainDetailService;
|
||||||
|
|
||||||
|
@Value("${train.docker.basePath}")
|
||||||
|
private String basePath;
|
||||||
|
|
||||||
|
@Value("${train.docker.responseDir}")
|
||||||
|
private String responseDir;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델학습 조회
|
* 모델학습 조회
|
||||||
@@ -33,18 +58,202 @@ public class ModelTrainMngService {
|
|||||||
* @param searchReq 검색 조건
|
* @param searchReq 검색 조건
|
||||||
* @return 페이징 처리된 모델 목록
|
* @return 페이징 처리된 모델 목록
|
||||||
*/
|
*/
|
||||||
public Page<ModelTrainMngDto.Basic> getModelList(SearchReq searchReq) {
|
public Page<ModelTrainMngDto.ListDto> getModelList(SearchReq searchReq) {
|
||||||
return modelTrainMngCoreService.findByModelList(searchReq);
|
return modelTrainMngCoreService.findByModelList(searchReq);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델학습 삭제
|
* 모델학습 삭제
|
||||||
*
|
*
|
||||||
* @param uuid
|
* <p>순서: 1. tmp 구조 검증 (예외 발생 가능) 2. DB 삭제 (트랜잭션) 3. 파일 삭제 (실패해도 로그만)
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void deleteModelTrain(UUID uuid) {
|
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, "모델 없음");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 2. 경로 생성 =====
|
||||||
|
Path tmpBase = Path.of(basePath, "tmp").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);
|
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 구조 검증 실패");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,10 +263,17 @@ public class ModelTrainMngService {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@Transactional
|
@Transactional
|
||||||
public void createModelTrain(ModelTrainMngDto.AddReq req) {
|
public UUID createModelTrain(ModelTrainMngDto.AddReq req) {
|
||||||
HyperParam hyperParam = req.getHyperParam();
|
HyperParam hyperParam = req.getHyperParam();
|
||||||
HyperParamDto.Basic hyper = new HyperParamDto.Basic();
|
HyperParamDto.Basic hyper = new HyperParamDto.Basic();
|
||||||
|
|
||||||
|
// 전이 학습은 모델 선택 필수
|
||||||
|
if (TrainType.TRANSFER.getId().equals(req.getTrainType())) {
|
||||||
|
if (req.getBeforeModelId() == null) {
|
||||||
|
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST, "모델을 선택해 주세요.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 하이파라미터 신규저장
|
// 하이파라미터 신규저장
|
||||||
if (HyperParamSelectType.NEW.getId().equals(req.getHyperParamType())) {
|
if (HyperParamSelectType.NEW.getId().equals(req.getHyperParamType())) {
|
||||||
// 하이퍼파라미터 등록
|
// 하이퍼파라미터 등록
|
||||||
@@ -66,7 +282,10 @@ public class ModelTrainMngService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 모델학습 테이블 저장
|
// 모델학습 테이블 저장
|
||||||
Long modelId = modelTrainMngCoreService.saveModel(req);
|
ModelTrainMngDto.Basic modelDto = modelTrainMngCoreService.saveModel(req);
|
||||||
|
|
||||||
|
Long modelId = modelDto.getId();
|
||||||
|
UUID modelUuid = modelDto.getUuid();
|
||||||
|
|
||||||
// 모델학습 데이터셋 저장
|
// 모델학습 데이터셋 저장
|
||||||
modelTrainMngCoreService.saveModelDataset(modelId, req);
|
modelTrainMngCoreService.saveModelDataset(modelId, req);
|
||||||
@@ -77,6 +296,10 @@ public class ModelTrainMngService {
|
|||||||
|
|
||||||
// 모델 config 저장
|
// 모델 config 저장
|
||||||
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
||||||
|
|
||||||
|
// 데이터셋 임시파일 생성
|
||||||
|
trainJobService.createTmpFile(modelUuid);
|
||||||
|
return modelUuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,10 +319,14 @@ public class ModelTrainMngService {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
|
public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
|
||||||
if (req.getModelNo().equals("G1")) {
|
if (req.getModelNo().equals(ModelType.G1.getId())) {
|
||||||
return modelTrainMngCoreService.getDatasetSelectG1List(req);
|
return modelTrainMngCoreService.getDatasetSelectG1List(req);
|
||||||
} else {
|
} else {
|
||||||
return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
|
return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Long findModelStep1InProgressCnt() {
|
||||||
|
return modelTrainMngCoreService.findModelStep1InProgressCnt();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.kamco.cd.training.postgres.core;
|
|||||||
|
|
||||||
import com.kamco.cd.training.common.service.BaseCoreService;
|
import com.kamco.cd.training.common.service.BaseCoreService;
|
||||||
import com.kamco.cd.training.log.dto.AuditLogDto;
|
import com.kamco.cd.training.log.dto.AuditLogDto;
|
||||||
|
import com.kamco.cd.training.log.dto.AuditLogDto.DownloadReq;
|
||||||
import com.kamco.cd.training.postgres.repository.log.AuditLogRepository;
|
import com.kamco.cd.training.postgres.repository.log.AuditLogRepository;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -45,6 +46,11 @@ public class AuditLogCoreService
|
|||||||
return auditLogRepository.findLogByAccount(searchRange, searchValue);
|
return auditLogRepository.findLogByAccount(searchRange, searchValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Page<AuditLogDto.DownloadRes> findLogByAccount(
|
||||||
|
AuditLogDto.searchReq searchReq, DownloadReq downloadReq) {
|
||||||
|
return auditLogRepository.findDownloadLog(searchReq, downloadReq);
|
||||||
|
}
|
||||||
|
|
||||||
public Page<AuditLogDto.DailyDetail> getLogByDailyResult(
|
public Page<AuditLogDto.DailyDetail> getLogByDailyResult(
|
||||||
AuditLogDto.searchReq searchRange, LocalDate logDate) {
|
AuditLogDto.searchReq searchRange, LocalDate logDate) {
|
||||||
return auditLogRepository.findLogByDailyResult(searchRange, logDate);
|
return auditLogRepository.findLogByDailyResult(searchRange, logDate);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.kamco.cd.training.postgres.core;
|
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.LearnDataRegister;
|
||||||
import com.kamco.cd.training.common.enums.LearnDataType;
|
import com.kamco.cd.training.common.enums.LearnDataType;
|
||||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||||
@@ -30,9 +29,9 @@ import org.springframework.stereotype.Service;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
public class DatasetCoreService
|
public class DatasetCoreService
|
||||||
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
implements BaseCoreService<DatasetDto.Basic, Long, DatasetDto.SearchReq> {
|
||||||
|
|
||||||
private final DatasetRepository datasetRepository;
|
private final DatasetRepository datasetRepository;
|
||||||
private final DatasetObjRepository datasetObjRepository;
|
private final DatasetObjRepository datasetObjRepository;
|
||||||
private final ObjectMapper objectMapper;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 학습 데이터 삭제
|
* 학습 데이터 삭제
|
||||||
@@ -96,6 +95,7 @@ public class DatasetCoreService
|
|||||||
return search(searchReq);
|
return search(searchReq);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 학습데이터 등록
|
* 학습데이터 등록
|
||||||
*
|
*
|
||||||
@@ -130,6 +130,7 @@ public class DatasetCoreService
|
|||||||
return savedEntity.toDto();
|
return savedEntity.toDto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
/**
|
/**
|
||||||
* 학습 데이터 수정
|
* 학습 데이터 수정
|
||||||
*
|
*
|
||||||
@@ -221,7 +222,6 @@ public class DatasetCoreService
|
|||||||
return datasetRepository.insertDatasetMngData(mngRegDto);
|
return datasetRepository.insertDatasetMngData(mngRegDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||||
datasetObjRepository.insertDatasetObj(objRegDto);
|
datasetObjRepository.insertDatasetObj(objRegDto);
|
||||||
}
|
}
|
||||||
@@ -234,12 +234,38 @@ public class DatasetCoreService
|
|||||||
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
datasetObjRepository.insertDatasetTestObj(objRegDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateDatasetUploadStatus(Long datasetUid) {
|
/**
|
||||||
|
* 학습데이터셋 마스터 상태 변경
|
||||||
|
*
|
||||||
|
* @param datasetUid 학습데이터셋 마스터 id
|
||||||
|
* @param register 상태
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void updateDatasetUploadStatus(Long datasetUid, LearnDataRegister register) {
|
||||||
DatasetEntity entity =
|
DatasetEntity entity =
|
||||||
datasetRepository
|
datasetRepository
|
||||||
.findById(datasetUid)
|
.findById(datasetUid)
|
||||||
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
.orElseThrow(() -> new NotFoundException("데이터셋을 찾을 수 없습니다. ID: " + datasetUid));
|
||||||
|
|
||||||
entity.setStatus(LearnDataRegister.COMPLETED.getId());
|
entity.setStatus(register.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||||
|
datasetObjRepository.insertDatasetValObj(objRegDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
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,10 +1,12 @@
|
|||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.dto.HyperParam;
|
import com.kamco.cd.training.common.dto.HyperParam;
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
import com.kamco.cd.training.common.utils.UserUtil;
|
import com.kamco.cd.training.common.utils.UserUtil;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.Basic;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.Basic;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
||||||
import com.kamco.cd.training.postgres.repository.hyperparam.HyperParamRepository;
|
import com.kamco.cd.training.postgres.repository.hyperparam.HyperParamRepository;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
@@ -17,6 +19,7 @@ import org.springframework.stereotype.Service;
|
|||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class HyperParamCoreService {
|
public class HyperParamCoreService {
|
||||||
|
|
||||||
private final HyperParamRepository hyperParamRepository;
|
private final HyperParamRepository hyperParamRepository;
|
||||||
private final UserUtil userUtil;
|
private final UserUtil userUtil;
|
||||||
|
|
||||||
@@ -27,11 +30,10 @@ public class HyperParamCoreService {
|
|||||||
* @return 등록된 버전명
|
* @return 등록된 버전명
|
||||||
*/
|
*/
|
||||||
public Basic createHyperParam(HyperParam createReq) {
|
public Basic createHyperParam(HyperParam createReq) {
|
||||||
String firstVersion = getFirstHyperParamVersion();
|
String firstVersion = getFirstHyperParamVersion(createReq.getModel());
|
||||||
|
|
||||||
ModelHyperParamEntity entity = new ModelHyperParamEntity();
|
ModelHyperParamEntity entity = new ModelHyperParamEntity();
|
||||||
entity.setHyperVer(firstVersion);
|
entity.setHyperVer(firstVersion);
|
||||||
|
|
||||||
applyHyperParam(entity, createReq);
|
applyHyperParam(entity, createReq);
|
||||||
|
|
||||||
// user
|
// user
|
||||||
@@ -57,7 +59,7 @@ public class HyperParamCoreService {
|
|||||||
.findHyperParamByUuid(uuid)
|
.findHyperParamByUuid(uuid)
|
||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
if (entity.getHyperVer().equals("HPs_0001")) {
|
if (entity.getIsDefault()) {
|
||||||
throw new CustomApiException("UNPROCESSABLE_ENTITY_UPDATE", HttpStatus.UNPROCESSABLE_ENTITY);
|
throw new CustomApiException("UNPROCESSABLE_ENTITY_UPDATE", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
}
|
}
|
||||||
applyHyperParam(entity, createReq);
|
applyHyperParam(entity, createReq);
|
||||||
@@ -69,11 +71,112 @@ public class HyperParamCoreService {
|
|||||||
return entity.getHyperVer();
|
return entity.getHyperVer();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 삭제
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
*/
|
||||||
|
public void deleteHyperParam(UUID uuid) {
|
||||||
|
ModelHyperParamEntity entity =
|
||||||
|
hyperParamRepository
|
||||||
|
.findHyperParamByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
// if (entity.getHyperVer().equals("HPs_0001")) {
|
||||||
|
// throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// 디폴트면 삭제불가
|
||||||
|
if (entity.getIsDefault()) {
|
||||||
|
throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.setDelYn(true);
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 최적화 설정값 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public HyperParamDto.Basic getInitHyperParam(ModelType model) {
|
||||||
|
ModelHyperParamEntity entity =
|
||||||
|
hyperParamRepository.getHyperParamByType(model).stream()
|
||||||
|
.filter(e -> e.getIsDefault() == Boolean.TRUE)
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 상세 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public HyperParamDto.Basic getHyperParam(UUID uuid) {
|
||||||
|
ModelHyperParamEntity entity =
|
||||||
|
hyperParamRepository
|
||||||
|
.findHyperParamByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 목록 조회
|
||||||
|
*
|
||||||
|
* @param model
|
||||||
|
* @param req
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req) {
|
||||||
|
return hyperParamRepository.findByHyperVerList(model, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼파라미터 버전 조회
|
||||||
|
*
|
||||||
|
* @param model 모델 타입
|
||||||
|
* @return ver
|
||||||
|
*/
|
||||||
|
public String getFirstHyperParamVersion(ModelType model) {
|
||||||
|
return hyperParamRepository
|
||||||
|
.findHyperParamVerByModelType(model)
|
||||||
|
.map(ModelHyperParamEntity::getHyperVer)
|
||||||
|
.map(ver -> increase(ver, model))
|
||||||
|
.orElse(model.name() + "_000001");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터의 버전을 증가시킨다.
|
||||||
|
*
|
||||||
|
* @param hyperVer 현재 버전
|
||||||
|
* @param modelType 모델 타입
|
||||||
|
* @return 증가된 버전
|
||||||
|
*/
|
||||||
|
private String increase(String hyperVer, ModelType modelType) {
|
||||||
|
String prefix = modelType.name() + "_";
|
||||||
|
int num = Integer.parseInt(hyperVer.substring(prefix.length()));
|
||||||
|
return prefix + String.format("%06d", num + 1);
|
||||||
|
}
|
||||||
|
|
||||||
private void applyHyperParam(ModelHyperParamEntity entity, HyperParam src) {
|
private void applyHyperParam(ModelHyperParamEntity entity, HyperParam src) {
|
||||||
|
|
||||||
|
ModelType model = src.getModel();
|
||||||
|
|
||||||
|
// 하드코딩 모델별로 다른경우 250212 bbn 하드코딩
|
||||||
|
if (model == ModelType.G3) {
|
||||||
|
entity.setCropSize("512,512");
|
||||||
|
} else {
|
||||||
|
entity.setCropSize("256,256");
|
||||||
|
}
|
||||||
|
entity.setCropSize(src.getCropSize());
|
||||||
|
|
||||||
// Important
|
// Important
|
||||||
|
entity.setModelType(model); // 20250212 modeltype추가
|
||||||
entity.setBackbone(src.getBackbone());
|
entity.setBackbone(src.getBackbone());
|
||||||
entity.setInputSize(src.getInputSize());
|
entity.setInputSize(src.getInputSize());
|
||||||
entity.setCropSize(src.getCropSize());
|
|
||||||
entity.setBatchSize(src.getBatchSize());
|
entity.setBatchSize(src.getBatchSize());
|
||||||
|
|
||||||
// Data
|
// Data
|
||||||
@@ -110,79 +213,4 @@ public class HyperParamCoreService {
|
|||||||
// memo
|
// memo
|
||||||
entity.setMemo(src.getMemo());
|
entity.setMemo(src.getMemo());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 삭제
|
|
||||||
*
|
|
||||||
* @param uuid
|
|
||||||
*/
|
|
||||||
public void deleteHyperParam(UUID uuid) {
|
|
||||||
ModelHyperParamEntity entity =
|
|
||||||
hyperParamRepository
|
|
||||||
.findHyperParamByUuid(uuid)
|
|
||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
|
||||||
|
|
||||||
if (entity.getHyperVer().equals("HPs_0001")) {
|
|
||||||
throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
|
||||||
}
|
|
||||||
|
|
||||||
entity.setDelYn(true);
|
|
||||||
entity.setUpdatedUid(userUtil.getId());
|
|
||||||
entity.setUpdatedDttm(ZonedDateTime.now());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 최적화 설정값 조회
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public HyperParamDto.Basic getInitHyperParam() {
|
|
||||||
ModelHyperParamEntity entity =
|
|
||||||
hyperParamRepository
|
|
||||||
.findHyperParamByHyperVer("HPs_0001")
|
|
||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
|
||||||
return entity.toDto();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 상세 조회
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public HyperParamDto.Basic getHyperParam(UUID uuid) {
|
|
||||||
ModelHyperParamEntity entity =
|
|
||||||
hyperParamRepository
|
|
||||||
.findHyperParamByUuid(uuid)
|
|
||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
|
||||||
return entity.toDto();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 목록 조회
|
|
||||||
*
|
|
||||||
* @param req
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public Page<HyperParamDto.List> findByHyperVerList(HyperParamDto.SearchReq req) {
|
|
||||||
return hyperParamRepository.findByHyperVerList(req);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 하이퍼파라미터 버전 조회
|
|
||||||
*
|
|
||||||
* @return ver
|
|
||||||
*/
|
|
||||||
public String getFirstHyperParamVersion() {
|
|
||||||
return hyperParamRepository
|
|
||||||
.findHyperParamVer()
|
|
||||||
.map(ModelHyperParamEntity::getHyperVer)
|
|
||||||
.map(this::increase)
|
|
||||||
.orElse("HPs_0001");
|
|
||||||
}
|
|
||||||
|
|
||||||
private String increase(String hyperVer) {
|
|
||||||
String prefix = "HPs_";
|
|
||||||
int num = Integer.parseInt(hyperVer.substring(prefix.length()));
|
|
||||||
return prefix + String.format("%04d", num + 1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.kamco.cd.training.common.exception.NotFoundException;
|
import com.kamco.cd.training.common.exception.NotFoundException;
|
||||||
@@ -70,3 +71,4 @@ public class MapSheetCoreService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.postgres.repository.train.ModelTestMetricsJobRepository;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ModelTestMetricsJobCoreService {
|
||||||
|
|
||||||
|
private final ModelTestMetricsJobRepository modelTestMetricsJobRepository;
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updateModelMetricsTrainSaveYn(Long modelId, String stepNo) {
|
||||||
|
modelTestMetricsJobRepository.updateModelMetricsTrainSaveYn(modelId, stepNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 로직 시작
|
||||||
|
public List<ResponsePathDto> getTestMetricSaveNotYetModelIds() {
|
||||||
|
return modelTestMetricsJobRepository.getTestMetricSaveNotYetModelIds();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
||||||
|
modelTestMetricsJobRepository.insertModelMetricsTest(batchArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelMetricJsonDto getTestMetricPackingInfo(Long modelId) {
|
||||||
|
return modelTestMetricsJobRepository.getTestMetricPackingInfo(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||||
|
return modelTestMetricsJobRepository.findModelTestFileNames(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updatePackingStart(Long modelId, ZonedDateTime now) {
|
||||||
|
modelTestMetricsJobRepository.updatePackingStart(modelId, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
||||||
|
modelTestMetricsJobRepository.updatePackingEnd(modelId, now, failSuccState);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,14 @@ import com.kamco.cd.training.model.dto.ModelConfigDto;
|
|||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.DetailSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.HyperSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.MappingDataset;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelBestEpoch;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelFileInfo;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainDetailDto.ModelTestMetrics;
|
||||||
|
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.TransferHyperSummary;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||||
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||||
import com.kamco.cd.training.postgres.repository.model.ModelConfigRepository;
|
import com.kamco.cd.training.postgres.repository.model.ModelConfigRepository;
|
||||||
import com.kamco.cd.training.postgres.repository.model.ModelDetailRepository;
|
import com.kamco.cd.training.postgres.repository.model.ModelDetailRepository;
|
||||||
@@ -50,10 +57,23 @@ public class ModelTrainDetailCoreService {
|
|||||||
return modelDetailRepository.getModelDetailSummary(uuid);
|
return modelDetailRepository.getModelDetailSummary(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파리미터 요약정보
|
||||||
|
*
|
||||||
|
* @param uuid 모델마스터 uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
public HyperSummary getByModelHyperParamSummary(UUID uuid) {
|
public HyperSummary getByModelHyperParamSummary(UUID uuid) {
|
||||||
return modelDetailRepository.getByModelHyperParamSummary(uuid);
|
return modelDetailRepository.getByModelHyperParamSummary(uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
public TransferHyperSummary getTransferHyperSummary(UUID uuid) {
|
||||||
|
return modelDetailRepository.getByModelTransferHyperParamSummary(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
public List<MappingDataset> getByModelMappingDataset(UUID uuid) {
|
public List<MappingDataset> getByModelMappingDataset(UUID uuid) {
|
||||||
return modelDetailRepository.getByModelMappingDataset(uuid);
|
return modelDetailRepository.getByModelMappingDataset(uuid);
|
||||||
}
|
}
|
||||||
@@ -63,6 +83,7 @@ public class ModelTrainDetailCoreService {
|
|||||||
return entity.toDto();
|
return entity.toDto();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 모델 학습별 config 정보 조회
|
* 모델 학습별 config 정보 조회
|
||||||
*
|
*
|
||||||
@@ -72,4 +93,34 @@ public class ModelTrainDetailCoreService {
|
|||||||
public ModelConfigDto.Basic findModelConfig(Long modelId) {
|
public ModelConfigDto.Basic findModelConfig(Long modelId) {
|
||||||
return modelConfigRepository.findModelConfigByModelId(modelId).orElse(null);
|
return modelConfigRepository.findModelConfigByModelId(modelId).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
public List<ModelTrainMetrics> getModelTrainMetricResult(UUID uuid) {
|
||||||
|
return modelDetailRepository.getModelTrainMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModelValidationMetrics> getModelValidationMetricResult(UUID uuid) {
|
||||||
|
return modelDetailRepository.getModelValidationMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModelTestMetrics> getModelTestMetricResult(UUID uuid) {
|
||||||
|
return modelDetailRepository.getModelTestMetricResult(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelBestEpoch getModelTrainBestEpoch(UUID uuid) {
|
||||||
|
return modelDetailRepository.getModelTrainBestEpoch(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModelFileInfo getModelTrainFileInfo(UUID uuid) {
|
||||||
|
return modelDetailRepository.getModelTrainFileInfo(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid) {
|
||||||
|
return modelDetailRepository.findModelTrainProgressInfo(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Basic findByModelBeforeId(Long beforeModelId) {
|
||||||
|
ModelMasterEntity entity = modelDetailRepository.findByModelBeforeId(beforeModelId);
|
||||||
|
return entity.toDto();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||||
|
import com.kamco.cd.training.postgres.entity.ModelTrainJobEntity;
|
||||||
|
import com.kamco.cd.training.postgres.repository.train.ModelTrainJobRepository;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.log4j.Log4j2;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Log4j2
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public class ModelTrainJobCoreService {
|
||||||
|
|
||||||
|
private final ModelTrainJobRepository modelTrainJobRepository;
|
||||||
|
|
||||||
|
public int findMaxAttemptNo(Long modelId) {
|
||||||
|
return modelTrainJobRepository.findMaxAttemptNo(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<ModelTrainJobDto> findLatestByModelId(Long modelId) {
|
||||||
|
return modelTrainJobRepository.findLatestByModelId(modelId).map(ModelTrainJobEntity::toDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<ModelTrainJobDto> findById(Long jobId) {
|
||||||
|
return modelTrainJobRepository.findById(jobId).map(ModelTrainJobEntity::toDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** QUEUED Job 생성 */
|
||||||
|
@Transactional
|
||||||
|
public Long createQueuedJob(
|
||||||
|
Long modelId, int attemptNo, Map<String, Object> paramsJson, ZonedDateTime queuedDttm) {
|
||||||
|
|
||||||
|
ModelTrainJobEntity job = new ModelTrainJobEntity();
|
||||||
|
job.setModelId(modelId);
|
||||||
|
job.setAttemptNo(attemptNo);
|
||||||
|
job.setStatusCd("QUEUED");
|
||||||
|
job.setParamsJson(paramsJson);
|
||||||
|
job.setQueuedDttm(queuedDttm != null ? queuedDttm : ZonedDateTime.now());
|
||||||
|
|
||||||
|
modelTrainJobRepository.save(job);
|
||||||
|
modelTrainJobRepository.flush();
|
||||||
|
return job.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 실행 시작 처리 */
|
||||||
|
@Transactional
|
||||||
|
public void markRunning(
|
||||||
|
Long jobId,
|
||||||
|
String containerName,
|
||||||
|
String logPath,
|
||||||
|
String lockedBy,
|
||||||
|
Integer totalEpoch,
|
||||||
|
String jobType) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd("RUNNING");
|
||||||
|
job.setContainerName(containerName);
|
||||||
|
job.setLogPath(logPath);
|
||||||
|
job.setStartedDttm(ZonedDateTime.now());
|
||||||
|
job.setLockedDttm(ZonedDateTime.now());
|
||||||
|
job.setLockedBy(lockedBy);
|
||||||
|
job.setJobType(jobType);
|
||||||
|
|
||||||
|
if (totalEpoch != null) {
|
||||||
|
job.setTotalEpoch(totalEpoch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 성공 처리
|
||||||
|
*
|
||||||
|
* @param jobId
|
||||||
|
* @param exitCode
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void markSuccess(Long jobId, int exitCode) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd("SUCCESS");
|
||||||
|
job.setExitCode(exitCode);
|
||||||
|
job.setFinishedDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 실패 처리
|
||||||
|
*
|
||||||
|
* @param jobId
|
||||||
|
* @param exitCode
|
||||||
|
* @param errorMessage
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void markFailed(Long jobId, Integer exitCode, String errorMessage) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd("FAILED");
|
||||||
|
job.setExitCode(exitCode);
|
||||||
|
job.setErrorMessage(errorMessage);
|
||||||
|
job.setFinishedDttm(ZonedDateTime.now());
|
||||||
|
|
||||||
|
log.info("[TRAIN JOB FAIL] jobId={}, modelId={}", jobId, errorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 중단됨 처리
|
||||||
|
*
|
||||||
|
* @param jobId
|
||||||
|
* @param exitCode
|
||||||
|
* @param errorMessage
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void markPaused(Long jobId, Integer exitCode, String errorMessage) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd("STOPPED");
|
||||||
|
job.setExitCode(exitCode);
|
||||||
|
job.setErrorMessage(errorMessage);
|
||||||
|
job.setFinishedDttm(ZonedDateTime.now());
|
||||||
|
|
||||||
|
log.info("[TRAIN JOB FAIL] jobId={}, modelId={}", jobId, errorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 취소 처리 */
|
||||||
|
@Transactional
|
||||||
|
public void markCanceled(Long jobId) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findById(jobId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setStatusCd("STOPPED");
|
||||||
|
job.setFinishedDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updateEpoch(String containerName, Integer epoch) {
|
||||||
|
ModelTrainJobEntity job =
|
||||||
|
modelTrainJobRepository
|
||||||
|
.findByContainerName(containerName)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
|
||||||
|
job.setCurrentEpoch(epoch);
|
||||||
|
|
||||||
|
if (Objects.equals(job.getTotalEpoch(), epoch)) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertModelTestTrainingRun(Long modelId, Long jobId, int epoch) {
|
||||||
|
modelTrainJobRepository.insertModelTestTrainingRun(modelId, jobId, epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 실행중인 학습이 있는지 조회
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<ModelTrainJobDto> findRunningJobs() {
|
||||||
|
List<ModelTrainJobEntity> entity = modelTrainJobRepository.findRunningJobs();
|
||||||
|
|
||||||
|
if (entity == null || entity.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return entity.stream().map(ModelTrainJobEntity::toDto).toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.postgres.repository.train.ModelTrainMetricsJobRepository;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class ModelTrainMetricsJobCoreService {
|
||||||
|
|
||||||
|
private final ModelTrainMetricsJobRepository modelTrainMetricsJobRepository;
|
||||||
|
|
||||||
|
public List<ResponsePathDto> getTrainMetricSaveNotYetModelIds() {
|
||||||
|
return modelTrainMetricsJobRepository.getTrainMetricSaveNotYetModelIds();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertModelMetricsTrain(List<Object[]> batchArgs) {
|
||||||
|
modelTrainMetricsJobRepository.insertModelMetricsTrain(batchArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updateModelMetricsTrainSaveYn(Long modelId, String stepNo) {
|
||||||
|
modelTrainMetricsJobRepository.updateModelMetricsTrainSaveYn(modelId, stepNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertModelMetricsValidation(List<Object[]> batchArgs) {
|
||||||
|
modelTrainMetricsJobRepository.insertModelMetricsValidation(batchArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void updateModelSelectedBestEpoch(Long modelId, Integer epoch) {
|
||||||
|
modelTrainMetricsJobRepository.updateModelSelectedBestEpoch(modelId, epoch);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,9 +8,10 @@ import com.kamco.cd.training.common.exception.CustomApiException;
|
|||||||
import com.kamco.cd.training.common.utils.UserUtil;
|
import com.kamco.cd.training.common.utils.UserUtil;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
||||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.TrainingDataset;
|
import com.kamco.cd.training.model.dto.ModelTrainMngDto.TrainingDataset;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelConfigEntity;
|
import com.kamco.cd.training.postgres.entity.ModelConfigEntity;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelDatasetEntity;
|
import com.kamco.cd.training.postgres.entity.ModelDatasetEntity;
|
||||||
@@ -23,17 +24,23 @@ import com.kamco.cd.training.postgres.repository.model.ModelConfigRepository;
|
|||||||
import com.kamco.cd.training.postgres.repository.model.ModelDatasetMappRepository;
|
import com.kamco.cd.training.postgres.repository.model.ModelDatasetMappRepository;
|
||||||
import com.kamco.cd.training.postgres.repository.model.ModelDatasetRepository;
|
import com.kamco.cd.training.postgres.repository.model.ModelDatasetRepository;
|
||||||
import com.kamco.cd.training.postgres.repository.model.ModelMngRepository;
|
import com.kamco.cd.training.postgres.repository.model.ModelMngRepository;
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||||
|
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Propagation;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ModelTrainMngCoreService {
|
public class ModelTrainMngCoreService {
|
||||||
|
|
||||||
private final ModelMngRepository modelMngRepository;
|
private final ModelMngRepository modelMngRepository;
|
||||||
private final ModelDatasetRepository modelDatasetRepository;
|
private final ModelDatasetRepository modelDatasetRepository;
|
||||||
private final ModelDatasetMappRepository modelDatasetMapRepository;
|
private final ModelDatasetMappRepository modelDatasetMapRepository;
|
||||||
@@ -48,9 +55,10 @@ public class ModelTrainMngCoreService {
|
|||||||
* @param searchReq 검색 조건
|
* @param searchReq 검색 조건
|
||||||
* @return 페이징 처리된 모델 목록
|
* @return 페이징 처리된 모델 목록
|
||||||
*/
|
*/
|
||||||
public Page<Basic> findByModelList(ModelTrainMngDto.SearchReq searchReq) {
|
public Page<ListDto> findByModelList(ModelTrainMngDto.SearchReq searchReq) {
|
||||||
Page<ModelMasterEntity> entityPage = modelMngRepository.findByModels(searchReq);
|
// Page<ModelMasterEntity> entityPage = modelMngRepository.findByModels(searchReq);
|
||||||
return entityPage.map(ModelMasterEntity::toDto);
|
// return entityPage.map(ModelMasterEntity::toDto);
|
||||||
|
return modelMngRepository.findByModels(searchReq);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,13 +82,19 @@ public class ModelTrainMngCoreService {
|
|||||||
* @param addReq
|
* @param addReq
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public Long saveModel(ModelTrainMngDto.AddReq addReq) {
|
public ModelTrainMngDto.Basic saveModel(ModelTrainMngDto.AddReq addReq) {
|
||||||
ModelMasterEntity entity = new ModelMasterEntity();
|
ModelMasterEntity entity = new ModelMasterEntity();
|
||||||
ModelHyperParamEntity hyperParamEntity = new ModelHyperParamEntity();
|
ModelHyperParamEntity hyperParamEntity = new ModelHyperParamEntity();
|
||||||
|
|
||||||
// 최적화 파라미터는 HPs_0001 사용
|
// 최적화 파라미터는 모델 type의 디폴트사용
|
||||||
if (HyperParamSelectType.OPTIMIZED.getId().equals(addReq.getHyperParamType())) {
|
if (HyperParamSelectType.OPTIMIZED.getId().equals(addReq.getHyperParamType())) {
|
||||||
hyperParamEntity = hyperParamRepository.findByHyperVer("HPs_0001").orElse(null);
|
ModelType modelType = ModelType.getValueData(addReq.getModelNo());
|
||||||
|
hyperParamEntity =
|
||||||
|
hyperParamRepository.getHyperParamByType(modelType).stream()
|
||||||
|
.filter(e -> e.getIsDefault() == Boolean.TRUE)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
// hyperParamEntity = hyperParamRepository.findByHyperVer("HPs_0001").orElse(null);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
hyperParamEntity =
|
hyperParamEntity =
|
||||||
@@ -90,6 +104,12 @@ public class ModelTrainMngCoreService {
|
|||||||
if (hyperParamEntity == null || hyperParamEntity.getHyperVer() == null) {
|
if (hyperParamEntity == null || hyperParamEntity.getHyperVer() == null) {
|
||||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND);
|
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND);
|
||||||
}
|
}
|
||||||
|
// 하이퍼 파라미터 사용 횟수 업데이트
|
||||||
|
hyperParamEntity.setTotalUseCnt(
|
||||||
|
hyperParamEntity.getTotalUseCnt() == null ? 1 : hyperParamEntity.getTotalUseCnt() + 1);
|
||||||
|
|
||||||
|
// 최근 사용일시 업데이트
|
||||||
|
hyperParamEntity.setLastUsedDttm(ZonedDateTime.now());
|
||||||
|
|
||||||
String modelVer =
|
String modelVer =
|
||||||
String.join(
|
String.join(
|
||||||
@@ -98,20 +118,19 @@ public class ModelTrainMngCoreService {
|
|||||||
entity.setHyperParamId(hyperParamEntity.getId());
|
entity.setHyperParamId(hyperParamEntity.getId());
|
||||||
entity.setModelNo(addReq.getModelNo());
|
entity.setModelNo(addReq.getModelNo());
|
||||||
entity.setTrainType(addReq.getTrainType()); // 일반, 전이
|
entity.setTrainType(addReq.getTrainType()); // 일반, 전이
|
||||||
|
entity.setBeforeModelId(addReq.getBeforeModelId());
|
||||||
|
|
||||||
if (addReq.getIsStart()) {
|
entity.setStatusCd(TrainStatusType.READY.getId());
|
||||||
entity.setModelStep((short) 1);
|
entity.setStep1State(TrainStatusType.READY.getId());
|
||||||
entity.setStatusCd(TrainStatusType.IN_PROGRESS.getId());
|
|
||||||
entity.setStrtDttm(ZonedDateTime.now());
|
|
||||||
entity.setStep1StrtDttm(ZonedDateTime.now());
|
|
||||||
entity.setStep1State(TrainStatusType.IN_PROGRESS.getId());
|
|
||||||
} else {
|
|
||||||
entity.setStatusCd(TrainStatusType.READY.getId());
|
|
||||||
}
|
|
||||||
|
|
||||||
entity.setCreatedUid(userUtil.getId());
|
entity.setCreatedUid(userUtil.getId());
|
||||||
ModelMasterEntity resultEntity = modelMngRepository.save(entity);
|
ModelMasterEntity resultEntity = modelMngRepository.save(entity);
|
||||||
return resultEntity.getId();
|
|
||||||
|
ModelTrainMngDto.Basic result = new ModelTrainMngDto.Basic();
|
||||||
|
result.setId(resultEntity.getId());
|
||||||
|
result.setUuid(resultEntity.getUuid());
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -143,6 +162,23 @@ public class ModelTrainMngCoreService {
|
|||||||
modelDatasetRepository.save(datasetEntity);
|
modelDatasetRepository.save(datasetEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습모델 수정
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @param req
|
||||||
|
*/
|
||||||
|
public void updateModelMaster(Long modelId, ModelTrainMngDto.UpdateReq req) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
// 임시폴더 UID업데이트
|
||||||
|
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
||||||
|
entity.setRequestPath(req.getRequestPath());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델 데이터셋 mapping 테이블 저장
|
* 모델 데이터셋 mapping 테이블 저장
|
||||||
*
|
*
|
||||||
@@ -171,7 +207,10 @@ public class ModelTrainMngCoreService {
|
|||||||
ModelConfigEntity entity = new ModelConfigEntity();
|
ModelConfigEntity entity = new ModelConfigEntity();
|
||||||
modelMasterEntity.setId(modelId);
|
modelMasterEntity.setId(modelId);
|
||||||
entity.setModel(modelMasterEntity);
|
entity.setModel(modelMasterEntity);
|
||||||
entity.setEpochCount(req.getEpochCnt());
|
entity.setEpochCount(
|
||||||
|
req.getEpochCnt() < 10
|
||||||
|
? 10
|
||||||
|
: req.getEpochCnt()); // 에폭이 10 이하이면 10으로 고정하기. 10 이상 에폭으로 해야 best 에폭 파일이 생성되어 내려옴
|
||||||
entity.setTrainPercent(req.getTrainingCnt());
|
entity.setTrainPercent(req.getTrainingCnt());
|
||||||
entity.setValidationPercent(req.getValidationCnt());
|
entity.setValidationPercent(req.getValidationCnt());
|
||||||
entity.setTestPercent(req.getTestCnt());
|
entity.setTestPercent(req.getTestCnt());
|
||||||
@@ -180,6 +219,7 @@ public class ModelTrainMngCoreService {
|
|||||||
modelConfigRepository.save(entity);
|
modelConfigRepository.save(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 데이터셋 매핑 생성
|
* 데이터셋 매핑 생성
|
||||||
*
|
*
|
||||||
@@ -196,6 +236,8 @@ public class ModelTrainMngCoreService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* UUID로 모델 조회
|
* UUID로 모델 조회
|
||||||
*
|
*
|
||||||
@@ -212,6 +254,20 @@ public class ModelTrainMngCoreService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* uuid로 model id 조회
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Long findModelIdByUuid(UUID uuid) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findByUuid(uuid)
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
return entity.getId();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 모델학습 아이디로 config정보 조회
|
* 모델학습 아이디로 config정보 조회
|
||||||
*
|
*
|
||||||
@@ -225,6 +281,16 @@ public class ModelTrainMngCoreService {
|
|||||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
public ModelConfigDto.TransferBasic findModelTransferConfigByModelId(UUID uuid) {
|
||||||
|
ModelMasterEntity modelEntity = findByUuid(uuid);
|
||||||
|
return modelConfigRepository
|
||||||
|
.findModelTransferConfigByModelId(modelEntity.getId())
|
||||||
|
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 데이터셋 G1 목록
|
* 데이터셋 G1 목록
|
||||||
*
|
*
|
||||||
@@ -235,6 +301,19 @@ public class ModelTrainMngCoreService {
|
|||||||
return datasetRepository.getDatasetSelectG1List(req);
|
return datasetRepository.getDatasetSelectG1List(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 전이학습 데이터셋 G1 목록
|
||||||
|
*
|
||||||
|
* @param modelId 모델 Id
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
||||||
|
return datasetRepository.getDatasetTransferSelectG1List(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 데이터셋 G2, G3 목록
|
* 데이터셋 G2, G3 목록
|
||||||
*
|
*
|
||||||
@@ -244,4 +323,341 @@ public class ModelTrainMngCoreService {
|
|||||||
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
||||||
return datasetRepository.getDatasetSelectG2G3List(req);
|
return datasetRepository.getDatasetSelectG2G3List(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
/**
|
||||||
|
* 전이학습 데이터셋 G2, G3 목록
|
||||||
|
*
|
||||||
|
* @param modelId 모델 Id
|
||||||
|
* @param modelNo G2, G3
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
||||||
|
Long modelId, String modelNo) {
|
||||||
|
return datasetRepository.getDatasetTransferSelectG2G3List(modelId, modelNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델관리 조회
|
||||||
|
*
|
||||||
|
* @param id
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public ModelTrainMngDto.Basic findModelById(Long id) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(id)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + id));
|
||||||
|
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) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setStatusCd(TrainStatusType.IN_PROGRESS.getId());
|
||||||
|
master.setCurrentAttemptId(jobId);
|
||||||
|
|
||||||
|
// 필요하면 시작시간도 여기서 찍어줌
|
||||||
|
modelMngRepository.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 마지막 에러 메시지 초기화 - 재시작/새 실행 때 이전 에러 흔적 제거 */
|
||||||
|
@Transactional
|
||||||
|
public void clearLastError(Long modelId) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setLastError(null);
|
||||||
|
modelMngRepository.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 중단 처리(옵션) - cancel에서 쓰려고 하면 같이 구현 */
|
||||||
|
@Transactional
|
||||||
|
public void markStopped(Long modelId) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
||||||
|
@Transactional
|
||||||
|
public void markCompleted(Long modelId) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step 1오류 처리(옵션) - Worker가 실패 시 호출
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @param errorMessage
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void markError(Long modelId, String errorMessage) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setStatusCd(TrainStatusType.ERROR.getId());
|
||||||
|
master.setStep1State(TrainStatusType.ERROR.getId());
|
||||||
|
master.setLastError(errorMessage);
|
||||||
|
master.setUpdatedUid(userUtil.getId());
|
||||||
|
master.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step 2오류 처리(옵션) - Worker가 실패 시 호출
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @param errorMessage
|
||||||
|
*/
|
||||||
|
@Transactional
|
||||||
|
public void markStep2Error(Long modelId, String errorMessage) {
|
||||||
|
ModelMasterEntity master =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
master.setStatusCd(TrainStatusType.ERROR.getId());
|
||||||
|
master.setStep2State(TrainStatusType.ERROR.getId());
|
||||||
|
master.setLastError(errorMessage);
|
||||||
|
master.setUpdatedUid(userUtil.getId());
|
||||||
|
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 =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
// 모델 상태 완료 처리
|
||||||
|
master.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||||
|
|
||||||
|
// (선택) 마지막 에러 메시지 비우기
|
||||||
|
master.setLastError(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 학습 실행에 필요한 파라미터 조회
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public TrainRunRequest findTrainRunRequest(Long modelId) {
|
||||||
|
return modelMngRepository.findTrainRunRequest(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step1 진행중 처리
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @param jobId
|
||||||
|
*/
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void markStep1InProgress(Long modelId, Long jobId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
entity.setStatusCd(TrainStatusType.IN_PROGRESS.getId());
|
||||||
|
entity.setStrtDttm(ZonedDateTime.now());
|
||||||
|
entity.setStep1StrtDttm(ZonedDateTime.now());
|
||||||
|
entity.setStep1State(TrainStatusType.IN_PROGRESS.getId());
|
||||||
|
entity.setCurrentAttemptId(jobId);
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step2 진행중 처리
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
*/
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void markStep2InProgress(Long modelId, Long jobId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
entity.setStatusCd(TrainStatusType.IN_PROGRESS.getId());
|
||||||
|
entity.setStep2StrtDttm(ZonedDateTime.now());
|
||||||
|
entity.setStep2State(TrainStatusType.IN_PROGRESS.getId());
|
||||||
|
entity.setCurrentAttemptId(jobId);
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step1 완료처리
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
*/
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void markStep1Success(Long modelId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
entity.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||||
|
entity.setStep1State(TrainStatusType.COMPLETED.getId());
|
||||||
|
entity.setStep1EndDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* step2 완료처리
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
*/
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void markStep2Success(Long modelId) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
entity.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||||
|
entity.setStep2State(TrainStatusType.COMPLETED.getId());
|
||||||
|
entity.setStep2EndDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||||
|
entity.setUpdatedUid(userUtil.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void updateModelMasterBestEpoch(Long modelId, int epoch) {
|
||||||
|
ModelMasterEntity entity =
|
||||||
|
modelMngRepository
|
||||||
|
.findById(modelId)
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||||
|
|
||||||
|
entity.setBestEpoch(epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 데이터셋 uid 조회
|
||||||
|
*
|
||||||
|
* @param datasetIds
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<String> findDatasetUid(List<Long> datasetIds) {
|
||||||
|
return datasetRepository.findDatasetUid(datasetIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Long> findModelDatasetMapp(Long modelId) {
|
||||||
|
List<Long> datasetUids = new ArrayList<>();
|
||||||
|
List<ModelDatasetMappEntity> entities = modelDatasetMapRepository.findByModelUid(modelId);
|
||||||
|
for (ModelDatasetMappEntity entity : entities) {
|
||||||
|
datasetUids.add(entity.getDatasetUid());
|
||||||
|
}
|
||||||
|
|
||||||
|
return datasetUids;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long findModelStep1InProgressCnt() {
|
||||||
|
return modelMngRepository.findModelStep1InProgressCnt();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* train 링크할 파일 경로
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId) {
|
||||||
|
return modelDatasetMapRepository.findDatasetTrainPath(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* validation 링크할 파일 경로
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<ModelTrainLinkDto> findDatasetValPath(Long modelId) {
|
||||||
|
return modelDatasetMapRepository.findDatasetValPath(modelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* test 링크할 파일 경로
|
||||||
|
*
|
||||||
|
* @param modelId
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
||||||
|
return modelDatasetMapRepository.findDatasetTestPath(modelId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.core;
|
package com.kamco.cd.training.postgres.core;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
||||||
@@ -64,3 +65,4 @@ public class SystemMetricsCoreService {
|
|||||||
return isAvailable;
|
return isAvailable;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.kamco.cd.training.log.dto.EventStatus;
|
|||||||
import com.kamco.cd.training.log.dto.EventType;
|
import com.kamco.cd.training.log.dto.EventType;
|
||||||
import com.kamco.cd.training.postgres.CommonCreateEntity;
|
import com.kamco.cd.training.postgres.CommonCreateEntity;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
|
import java.util.UUID;
|
||||||
import lombok.AccessLevel;
|
import lombok.AccessLevel;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
@@ -14,6 +15,7 @@ import lombok.NoArgsConstructor;
|
|||||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||||
@Table(name = "tb_audit_log")
|
@Table(name = "tb_audit_log")
|
||||||
public class AuditLogEntity extends CommonCreateEntity {
|
public class AuditLogEntity extends CommonCreateEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@Column(name = "audit_log_uid", nullable = false)
|
@Column(name = "audit_log_uid", nullable = false)
|
||||||
@@ -43,6 +45,12 @@ public class AuditLogEntity extends CommonCreateEntity {
|
|||||||
@Column(name = "error_log_uid")
|
@Column(name = "error_log_uid")
|
||||||
private Long errorLogUid;
|
private Long errorLogUid;
|
||||||
|
|
||||||
|
@Column(name = "download_uuid")
|
||||||
|
private UUID downloadUuid;
|
||||||
|
|
||||||
|
@Column(name = "login_attempt_id")
|
||||||
|
private String loginAttemptId;
|
||||||
|
|
||||||
public AuditLogEntity(
|
public AuditLogEntity(
|
||||||
Long userUid,
|
Long userUid,
|
||||||
EventType eventType,
|
EventType eventType,
|
||||||
@@ -51,7 +59,9 @@ public class AuditLogEntity extends CommonCreateEntity {
|
|||||||
String ipAddress,
|
String ipAddress,
|
||||||
String requestUri,
|
String requestUri,
|
||||||
String requestBody,
|
String requestBody,
|
||||||
Long errorLogUid) {
|
Long errorLogUid,
|
||||||
|
UUID downloadUuid,
|
||||||
|
String loginAttemptId) {
|
||||||
this.userUid = userUid;
|
this.userUid = userUid;
|
||||||
this.eventType = eventType;
|
this.eventType = eventType;
|
||||||
this.eventStatus = eventStatus;
|
this.eventStatus = eventStatus;
|
||||||
@@ -60,6 +70,31 @@ public class AuditLogEntity extends CommonCreateEntity {
|
|||||||
this.requestUri = requestUri;
|
this.requestUri = requestUri;
|
||||||
this.requestBody = requestBody;
|
this.requestBody = requestBody;
|
||||||
this.errorLogUid = errorLogUid;
|
this.errorLogUid = errorLogUid;
|
||||||
|
this.downloadUuid = downloadUuid;
|
||||||
|
this.loginAttemptId = loginAttemptId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 파일 다운로드 이력 생성 */
|
||||||
|
public static AuditLogEntity forFileDownload(
|
||||||
|
Long userId,
|
||||||
|
String requestUri,
|
||||||
|
String menuUid,
|
||||||
|
String ip,
|
||||||
|
int httpStatus,
|
||||||
|
UUID downloadUuid) {
|
||||||
|
|
||||||
|
return new AuditLogEntity(
|
||||||
|
userId,
|
||||||
|
EventType.DOWNLOAD, // 이벤트 타입 고정
|
||||||
|
httpStatus < 400 ? EventStatus.SUCCESS : EventStatus.FAILED, // 성공 여부
|
||||||
|
menuUid,
|
||||||
|
ip,
|
||||||
|
requestUri,
|
||||||
|
null, // requestBody 없음
|
||||||
|
null, // errorLogUid 없음
|
||||||
|
downloadUuid,
|
||||||
|
null // loginAttemptId 없음
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuditLogDto.Basic toDto() {
|
public AuditLogDto.Basic toDto() {
|
||||||
|
|||||||
@@ -117,10 +117,12 @@ public class DatasetEntity {
|
|||||||
@Column(name = "dataset_path", length = 1000)
|
@Column(name = "dataset_path", length = 1000)
|
||||||
private String datasetPath;
|
private String datasetPath;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Column(name = "class_counts")
|
@Column(name = "class_counts")
|
||||||
@JdbcTypeCode(SqlTypes.JSON)
|
@JdbcTypeCode(SqlTypes.JSON)
|
||||||
private Map<String, Integer> classCounts;
|
private Map<String, Integer> classCounts;
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
@Size(max = 32)
|
@Size(max = 32)
|
||||||
@Column(name = "uid")
|
@Column(name = "uid")
|
||||||
private String uid;
|
private String uid;
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetObjDto.Basic;
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
import org.hibernate.annotations.JdbcTypeCode;
|
||||||
|
import org.hibernate.type.SqlTypes;
|
||||||
|
import org.locationtech.jts.geom.Geometry;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Entity
|
||||||
|
@Table(name = "tb_dataset_val_obj")
|
||||||
|
public class DatasetValObjEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "obj_id", nullable = false)
|
||||||
|
private Long objId;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "dataset_uid", nullable = false)
|
||||||
|
private Long datasetUid;
|
||||||
|
|
||||||
|
@Column(name = "target_yyyy")
|
||||||
|
private Integer targetYyyy;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "target_class_cd")
|
||||||
|
private String targetClassCd;
|
||||||
|
|
||||||
|
@Column(name = "compare_yyyy")
|
||||||
|
private Integer compareYyyy;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "compare_class_cd")
|
||||||
|
private String compareClassCd;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "target_path")
|
||||||
|
private String targetPath;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "compare_path")
|
||||||
|
private String comparePath;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "label_path")
|
||||||
|
private String labelPath;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "geojson_path")
|
||||||
|
private String geojsonPath;
|
||||||
|
|
||||||
|
@Size(max = 255)
|
||||||
|
@Column(name = "map_sheet_num")
|
||||||
|
private String mapSheetNum;
|
||||||
|
|
||||||
|
@ColumnDefault("now()")
|
||||||
|
@Column(name = "created_dttm")
|
||||||
|
private ZonedDateTime createdDttm;
|
||||||
|
|
||||||
|
@Column(name = "created_uid")
|
||||||
|
private Long createdUid;
|
||||||
|
|
||||||
|
@ColumnDefault("false")
|
||||||
|
@Column(name = "deleted")
|
||||||
|
private Boolean deleted;
|
||||||
|
|
||||||
|
@Column(name = "uuid")
|
||||||
|
private UUID uuid;
|
||||||
|
|
||||||
|
@Size(max = 32)
|
||||||
|
@Column(name = "uid")
|
||||||
|
private String uid;
|
||||||
|
|
||||||
|
@JdbcTypeCode(SqlTypes.JSON)
|
||||||
|
@Column(name = "geo_jsonb", columnDefinition = "jsonb")
|
||||||
|
private String geoJsonb;
|
||||||
|
|
||||||
|
@Column(name = "file_name")
|
||||||
|
private String fileName;
|
||||||
|
|
||||||
|
@Column(name = "geom", columnDefinition = "geometry")
|
||||||
|
private Geometry geom;
|
||||||
|
|
||||||
|
public Basic toDto() {
|
||||||
|
return new Basic(
|
||||||
|
this.objId,
|
||||||
|
this.datasetUid,
|
||||||
|
this.targetYyyy,
|
||||||
|
this.targetClassCd,
|
||||||
|
this.compareYyyy,
|
||||||
|
this.compareClassCd,
|
||||||
|
this.targetPath,
|
||||||
|
this.comparePath,
|
||||||
|
this.labelPath,
|
||||||
|
this.geojsonPath,
|
||||||
|
this.mapSheetNum,
|
||||||
|
this.createdDttm,
|
||||||
|
this.createdUid,
|
||||||
|
this.deleted,
|
||||||
|
this.uuid,
|
||||||
|
this.geoJsonb);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -103,3 +104,4 @@ public class MapSheetEntity {
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -32,10 +32,13 @@ public class ModelDatasetMappEntity {
|
|||||||
@Column(name = "dataset_uid", nullable = false)
|
@Column(name = "dataset_uid", nullable = false)
|
||||||
private Long datasetUid;
|
private Long datasetUid;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Size(max = 20)
|
@Size(max = 20)
|
||||||
@Column(name = "dataset_type", length = 20)
|
@Column(name = "dataset_type", length = 20)
|
||||||
private String datasetType;
|
private String datasetType;
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
@@ -191,10 +192,10 @@ public class ModelHyperParamEntity {
|
|||||||
@Column(name = "save_best_rule", nullable = false, length = 10)
|
@Column(name = "save_best_rule", nullable = false, length = 10)
|
||||||
private String saveBestRule = "greater";
|
private String saveBestRule = "greater";
|
||||||
|
|
||||||
/** Default: 10 */
|
/** Default: 1 */
|
||||||
@NotNull
|
@NotNull
|
||||||
@Column(name = "val_interval", nullable = false)
|
@Column(name = "val_interval", nullable = false)
|
||||||
private Integer valInterval = 10;
|
private Integer valInterval = 1;
|
||||||
|
|
||||||
/** Default: 400 */
|
/** Default: 400 */
|
||||||
@NotNull
|
@NotNull
|
||||||
@@ -302,20 +303,24 @@ public class ModelHyperParamEntity {
|
|||||||
@Column(name = "last_used_dttm")
|
@Column(name = "last_used_dttm")
|
||||||
private ZonedDateTime lastUsedDttm;
|
private ZonedDateTime lastUsedDttm;
|
||||||
|
|
||||||
@Column(name = "m1_use_cnt")
|
@Column(name = "model_type")
|
||||||
private Long m1UseCnt = 0L;
|
@Enumerated(EnumType.STRING)
|
||||||
|
private ModelType modelType;
|
||||||
|
|
||||||
@Column(name = "m2_use_cnt")
|
@Column(name = "default_param")
|
||||||
private Long m2UseCnt = 0L;
|
private Boolean isDefault = false;
|
||||||
|
|
||||||
@Column(name = "m3_use_cnt")
|
@Column(name = "total_use_cnt")
|
||||||
private Long m3UseCnt = 0L;
|
private Integer totalUseCnt = 0;
|
||||||
|
|
||||||
public HyperParamDto.Basic toDto() {
|
public HyperParamDto.Basic toDto() {
|
||||||
return new HyperParamDto.Basic(
|
return new HyperParamDto.Basic(
|
||||||
|
this.modelType,
|
||||||
this.uuid,
|
this.uuid,
|
||||||
this.hyperVer,
|
this.hyperVer,
|
||||||
this.createdDttm,
|
this.createdDttm,
|
||||||
|
this.lastUsedDttm,
|
||||||
|
this.totalUseCnt,
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// Important
|
// Important
|
||||||
// -------------------------
|
// -------------------------
|
||||||
@@ -385,6 +390,7 @@ public class ModelHyperParamEntity {
|
|||||||
// -------------------------
|
// -------------------------
|
||||||
this.gpuCnt,
|
this.gpuCnt,
|
||||||
this.gpuIds,
|
this.gpuIds,
|
||||||
this.masterPort);
|
this.masterPort,
|
||||||
|
this.isDefault);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,6 +88,39 @@ public class ModelMasterEntity {
|
|||||||
@Column(name = "train_type")
|
@Column(name = "train_type")
|
||||||
private String trainType;
|
private String trainType;
|
||||||
|
|
||||||
|
@Column(name = "before_model_id")
|
||||||
|
private Long beforeModelId;
|
||||||
|
|
||||||
|
@Column(name = "step1_metric_save_yn")
|
||||||
|
private Boolean step1MetricSaveYn;
|
||||||
|
|
||||||
|
@Column(name = "step2_metric_save_yn")
|
||||||
|
private Boolean step2MetricSaveYn;
|
||||||
|
|
||||||
|
@Column(name = "current_attempt_id")
|
||||||
|
private Long currentAttemptId;
|
||||||
|
|
||||||
|
@Column(name = "last_error")
|
||||||
|
private String lastError;
|
||||||
|
|
||||||
|
@Column(name = "best_epoch")
|
||||||
|
private Integer bestEpoch;
|
||||||
|
|
||||||
|
@Column(name = "request_path")
|
||||||
|
private String requestPath;
|
||||||
|
|
||||||
|
@Column(name = "response_path")
|
||||||
|
private String responsePath;
|
||||||
|
|
||||||
|
@Column(name = "packing_state")
|
||||||
|
private String packingState;
|
||||||
|
|
||||||
|
@Column(name = "packing_strt_dttm")
|
||||||
|
private ZonedDateTime packingStrtDttm;
|
||||||
|
|
||||||
|
@Column(name = "packing_end_dttm")
|
||||||
|
private ZonedDateTime packingEndDttm;
|
||||||
|
|
||||||
public ModelTrainMngDto.Basic toDto() {
|
public ModelTrainMngDto.Basic toDto() {
|
||||||
return new ModelTrainMngDto.Basic(
|
return new ModelTrainMngDto.Basic(
|
||||||
this.id,
|
this.id,
|
||||||
@@ -102,6 +135,13 @@ public class ModelMasterEntity {
|
|||||||
this.step2State,
|
this.step2State,
|
||||||
this.statusCd,
|
this.statusCd,
|
||||||
this.trainType,
|
this.trainType,
|
||||||
this.modelNo);
|
this.modelNo,
|
||||||
|
this.currentAttemptId,
|
||||||
|
this.requestPath,
|
||||||
|
this.packingState,
|
||||||
|
this.packingStrtDttm,
|
||||||
|
this.packingEndDttm,
|
||||||
|
this.beforeModelId,
|
||||||
|
this.bestEpoch);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ import org.hibernate.annotations.ColumnDefault;
|
|||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "tb_model_matrics_test")
|
@Table(name = "tb_model_metrics_test")
|
||||||
public class ModelMatricsTestEntity {
|
public class ModelMetricsTestEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@@ -45,9 +45,6 @@ public class ModelMatricsTestEntity {
|
|||||||
@Column(name = "fn")
|
@Column(name = "fn")
|
||||||
private Long fn;
|
private Long fn;
|
||||||
|
|
||||||
@Column(name = "tn")
|
|
||||||
private Long tn;
|
|
||||||
|
|
||||||
@Column(name = "precisions")
|
@Column(name = "precisions")
|
||||||
private Float precisions;
|
private Float precisions;
|
||||||
|
|
||||||
@@ -63,8 +60,11 @@ public class ModelMatricsTestEntity {
|
|||||||
@Column(name = "iou")
|
@Column(name = "iou")
|
||||||
private Float iou;
|
private Float iou;
|
||||||
|
|
||||||
@Column(name = "processed_images")
|
@Column(name = "detection_count")
|
||||||
private Long processedImages;
|
private Long detectionCount;
|
||||||
|
|
||||||
|
@Column(name = "gt_count")
|
||||||
|
private Long gtCount;
|
||||||
|
|
||||||
@ColumnDefault("now()")
|
@ColumnDefault("now()")
|
||||||
@Column(name = "created_dttm")
|
@Column(name = "created_dttm")
|
||||||
@@ -18,8 +18,8 @@ import org.hibernate.annotations.ColumnDefault;
|
|||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "tb_model_matrics_train")
|
@Table(name = "tb_model_metrics_train")
|
||||||
public class ModelMatricsTrainEntity {
|
public class ModelMetricsTrainEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@@ -18,8 +18,8 @@ import org.hibernate.annotations.ColumnDefault;
|
|||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "tb_model_matrics_validation")
|
@Table(name = "tb_model_metrics_validation")
|
||||||
public class ModelMatricsValidationEntity {
|
public class ModelMetricsValidationEntity {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
@@ -92,3 +93,4 @@ public class ModelMngEntity {
|
|||||||
return this.uuid != null ? this.uuid.toString() : null;
|
return this.uuid != null ? this.uuid.toString() : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Entity
|
||||||
|
@Table(name = "tb_model_test_training_run")
|
||||||
|
public class ModelTestTrainingRunEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "tsr_id", nullable = false)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "model_id", nullable = false)
|
||||||
|
private Long modelId;
|
||||||
|
|
||||||
|
@Column(name = "attempt_no")
|
||||||
|
private Integer attemptNo;
|
||||||
|
|
||||||
|
@Column(name = "job_id")
|
||||||
|
private Long jobId;
|
||||||
|
|
||||||
|
@Column(name = "epoch")
|
||||||
|
private Integer epoch;
|
||||||
|
|
||||||
|
@ColumnDefault("now()")
|
||||||
|
@Column(name = "created_dttm")
|
||||||
|
private OffsetDateTime createdDttm;
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.GeneratedValue;
|
||||||
|
import jakarta.persistence.GenerationType;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
import org.hibernate.annotations.ColumnDefault;
|
||||||
|
import org.hibernate.annotations.JdbcTypeCode;
|
||||||
|
import org.hibernate.type.SqlTypes;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Entity
|
||||||
|
@Table(name = "tb_model_train_job")
|
||||||
|
public class ModelTrainJobEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
@Column(name = "id", nullable = false)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "model_id", nullable = false)
|
||||||
|
private Long modelId;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "attempt_no", nullable = false)
|
||||||
|
private Integer attemptNo;
|
||||||
|
|
||||||
|
@Size(max = 30)
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "status_cd", nullable = false, length = 30)
|
||||||
|
private String statusCd;
|
||||||
|
|
||||||
|
@NotNull
|
||||||
|
@Column(name = "params_json", nullable = false)
|
||||||
|
@JdbcTypeCode(SqlTypes.JSON)
|
||||||
|
private Map<String, Object> paramsJson;
|
||||||
|
|
||||||
|
@Size(max = 200)
|
||||||
|
@Column(name = "container_name", length = 200)
|
||||||
|
private String containerName;
|
||||||
|
|
||||||
|
@Size(max = 500)
|
||||||
|
@Column(name = "log_path", length = 500)
|
||||||
|
private String logPath;
|
||||||
|
|
||||||
|
@Column(name = "exit_code")
|
||||||
|
private Integer exitCode;
|
||||||
|
|
||||||
|
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
@ColumnDefault("now()")
|
||||||
|
@Column(name = "queued_dttm")
|
||||||
|
private ZonedDateTime queuedDttm;
|
||||||
|
|
||||||
|
@Column(name = "started_dttm")
|
||||||
|
private ZonedDateTime startedDttm;
|
||||||
|
|
||||||
|
@Column(name = "finished_dttm")
|
||||||
|
private ZonedDateTime finishedDttm;
|
||||||
|
|
||||||
|
@Column(name = "locked_dttm")
|
||||||
|
private ZonedDateTime lockedDttm;
|
||||||
|
|
||||||
|
@Size(max = 100)
|
||||||
|
@Column(name = "locked_by", length = 100)
|
||||||
|
private String lockedBy;
|
||||||
|
|
||||||
|
@Column(name = "total_epoch")
|
||||||
|
private Integer totalEpoch;
|
||||||
|
|
||||||
|
@Column(name = "current_epoch")
|
||||||
|
private Integer currentEpoch;
|
||||||
|
|
||||||
|
@Column(name = "job_type")
|
||||||
|
private String jobType;
|
||||||
|
|
||||||
|
public ModelTrainJobDto toDto() {
|
||||||
|
return new ModelTrainJobDto(
|
||||||
|
this.id,
|
||||||
|
this.modelId,
|
||||||
|
this.attemptNo,
|
||||||
|
this.statusCd,
|
||||||
|
this.exitCode,
|
||||||
|
this.errorMessage,
|
||||||
|
this.containerName,
|
||||||
|
this.paramsJson,
|
||||||
|
this.queuedDttm,
|
||||||
|
this.startedDttm,
|
||||||
|
this.finishedDttm,
|
||||||
|
this.totalEpoch,
|
||||||
|
this.currentEpoch);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.entity;
|
package com.kamco.cd.training.postgres.entity;
|
||||||
|
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
@@ -53,3 +54,4 @@ public class SystemMetricsEntity {
|
|||||||
@Column(name = "memused")
|
@Column(name = "memused")
|
||||||
private Float memused;
|
private Float memused;
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository;
|
package com.kamco.cd.training.postgres.repository;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.SystemMetricsEntity;
|
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")
|
@Query("SELECT s FROM SystemMetricsEntity s ORDER BY s.timestamp DESC LIMIT 1")
|
||||||
Optional<SystemMetricsEntity> findLatestMetrics();
|
Optional<SystemMetricsEntity> findLatestMetrics();
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -22,4 +22,14 @@ public interface DatasetObjRepositoryCustom {
|
|||||||
String getFilePathByUUIDPathType(UUID uuid, String pathType);
|
String getFilePathByUUIDPathType(UUID uuid, String pathType);
|
||||||
|
|
||||||
void insertDatasetTestObj(DatasetObjRegDto objRegDto);
|
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 JPAQueryFactory queryFactory;
|
||||||
private final QDatasetEntity dataset = datasetEntity;
|
private final QDatasetEntity dataset = datasetEntity;
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
@PersistenceContext EntityManager em;
|
@PersistenceContext EntityManager em;
|
||||||
|
|
||||||
@@ -55,7 +56,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetTestObj(DatasetObjRegDto objRegDto) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
String json;
|
String json;
|
||||||
Geometry geometry;
|
Geometry geometry;
|
||||||
String geometryJson;
|
String geometryJson;
|
||||||
@@ -97,6 +97,48 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||||
|
String json;
|
||||||
|
String geometryJson;
|
||||||
|
try {
|
||||||
|
json = objectMapper.writeValueAsString(objRegDto.getGeojson());
|
||||||
|
geometryJson =
|
||||||
|
objectMapper.writeValueAsString(
|
||||||
|
objRegDto.getGeojson().path("features").get(0).path("geometry"));
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
em.createNativeQuery(
|
||||||
|
"""
|
||||||
|
insert into tb_dataset_val_obj
|
||||||
|
(dataset_uid, target_yyyy, target_class_cd,
|
||||||
|
compare_yyyy, compare_class_cd,
|
||||||
|
target_path, compare_path, label_path, geo_jsonb, map_sheet_num, file_name, geom, geojson_path)
|
||||||
|
values
|
||||||
|
(?, ?, ?, ?, ?, ?, ?, ?, cast(? as jsonb), ?, ?, ST_SetSRID(ST_GeomFromGeoJSON(?), 5186), ?)
|
||||||
|
""")
|
||||||
|
.setParameter(1, objRegDto.getDatasetUid())
|
||||||
|
.setParameter(2, objRegDto.getTargetYyyy())
|
||||||
|
.setParameter(3, objRegDto.getTargetClassCd())
|
||||||
|
.setParameter(4, objRegDto.getCompareYyyy())
|
||||||
|
.setParameter(5, objRegDto.getCompareClassCd())
|
||||||
|
.setParameter(6, objRegDto.getTargetPath())
|
||||||
|
.setParameter(7, objRegDto.getComparePath())
|
||||||
|
.setParameter(8, objRegDto.getLabelPath())
|
||||||
|
.setParameter(9, json)
|
||||||
|
.setParameter(10, objRegDto.getMapSheetNum())
|
||||||
|
.setParameter(11, objRegDto.getFileName())
|
||||||
|
.setParameter(12, geometryJson)
|
||||||
|
.setParameter(13, objRegDto.getGeojsonPath())
|
||||||
|
.executeUpdate();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<DatasetObjEntity> searchDatasetObjectList(SearchReq searchReq) {
|
public Page<DatasetObjEntity> searchDatasetObjectList(SearchReq searchReq) {
|
||||||
Pageable pageable = searchReq.toPageable();
|
Pageable pageable = searchReq.toPageable();
|
||||||
@@ -176,7 +218,6 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
public void insertDatasetObj(DatasetObjRegDto objRegDto) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
String json;
|
String json;
|
||||||
String geometryJson;
|
String geometryJson;
|
||||||
try {
|
try {
|
||||||
@@ -233,4 +274,38 @@ public class DatasetObjRepositoryImpl implements DatasetObjRepositoryCustom {
|
|||||||
.where(datasetObjEntity.uuid.eq(uuid))
|
.where(datasetObjEntity.uuid.eq(uuid))
|
||||||
.fetchOne();
|
.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
|
public interface DatasetRepository
|
||||||
extends JpaRepository<DatasetEntity, Long>, DatasetRepositoryCustom {
|
extends JpaRepository<DatasetEntity, Long>, DatasetRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
List<DatasetEntity> findByDeletedOrderByCreatedDttmDesc(Boolean deleted);
|
List<DatasetEntity> findByDeletedOrderByCreatedDttmDesc(Boolean deleted);
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.kamco.cd.training.dataset.dto.DatasetDto;
|
|||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetMngRegDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -17,9 +18,20 @@ public interface DatasetRepositoryCustom {
|
|||||||
|
|
||||||
List<SelectDataSet> getDatasetSelectG1List(DatasetReq req);
|
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> getDatasetSelectG2G3List(DatasetReq req);
|
||||||
|
|
||||||
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
Long getDatasetMaxStage(int compareYyyy, int targetYyyy);
|
||||||
|
|
||||||
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
||||||
|
|
||||||
|
List<String> findDatasetUid(List<Long> datasetIds);
|
||||||
|
|
||||||
|
Long findDatasetByUidExistsCnt(String uid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,24 @@
|
|||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import static com.kamco.cd.training.postgres.entity.QDatasetObjEntity.datasetObjEntity;
|
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.ModelType;
|
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.DatasetMngRegDto;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SearchReq;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SearchReq;
|
||||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||||
|
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectTransferDataSet;
|
||||||
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
import com.kamco.cd.training.postgres.entity.DatasetEntity;
|
||||||
import com.kamco.cd.training.postgres.entity.QDatasetEntity;
|
import com.kamco.cd.training.postgres.entity.QDatasetEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.QDatasetObjEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.QModelDatasetMappEntity;
|
||||||
|
import com.kamco.cd.training.postgres.entity.QModelMasterEntity;
|
||||||
import com.querydsl.core.BooleanBuilder;
|
import com.querydsl.core.BooleanBuilder;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.core.types.dsl.CaseBuilder;
|
import com.querydsl.core.types.dsl.CaseBuilder;
|
||||||
|
import com.querydsl.core.types.dsl.Expressions;
|
||||||
import com.querydsl.core.types.dsl.NumberExpression;
|
import com.querydsl.core.types.dsl.NumberExpression;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -66,7 +73,11 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
// Count 쿼리 별도 실행 (null safe handling)
|
// Count 쿼리 별도 실행 (null safe handling)
|
||||||
long total =
|
long total =
|
||||||
Optional.ofNullable(
|
Optional.ofNullable(
|
||||||
queryFactory.select(dataset.count()).from(dataset).where(builder).fetchOne())
|
queryFactory
|
||||||
|
.select(dataset.count())
|
||||||
|
.from(dataset)
|
||||||
|
.where(builder.and(dataset.deleted.isFalse()))
|
||||||
|
.fetchOne())
|
||||||
.orElse(0L);
|
.orElse(0L);
|
||||||
|
|
||||||
return new PageImpl<>(content, pageable, total);
|
return new PageImpl<>(content, pageable, total);
|
||||||
@@ -87,6 +98,8 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
|
|
||||||
BooleanBuilder builder = new BooleanBuilder();
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||||
}
|
}
|
||||||
@@ -103,6 +116,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
SelectDataSet.class,
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
dataset.id,
|
dataset.id,
|
||||||
dataset.uuid,
|
dataset.uuid,
|
||||||
dataset.dataType,
|
dataset.dataType,
|
||||||
@@ -136,10 +150,110 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG1List(Long modelId) {
|
||||||
|
|
||||||
|
QModelMasterEntity beforeMaster = new QModelMasterEntity("beforeMaster");
|
||||||
|
QModelDatasetMappEntity beforeMapp = new QModelDatasetMappEntity("beforeMapp");
|
||||||
|
QDatasetEntity beforeDataset = new QDatasetEntity("beforeDataset");
|
||||||
|
QDatasetObjEntity beforeObj = new QDatasetObjEntity("beforeObj");
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectTransferDataSet.class,
|
||||||
|
|
||||||
|
// ===== 현재 =====
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq("building"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.eq("container"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
|
||||||
|
// ===== before (join으로) =====
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo,
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.eq("building"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum(),
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.eq("container"))
|
||||||
|
.then(1)
|
||||||
|
.otherwise(0)
|
||||||
|
.sum()))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
|
||||||
|
// ===== 현재 dataset join =====
|
||||||
|
.leftJoin(modelDatasetMappEntity)
|
||||||
|
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(dataset)
|
||||||
|
.on(modelDatasetMappEntity.datasetUid.eq(dataset.id))
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
|
||||||
|
// ===== before 모델 join =====
|
||||||
|
.leftJoin(beforeMaster)
|
||||||
|
.on(beforeMaster.id.eq(modelMasterEntity.beforeModelId))
|
||||||
|
.leftJoin(beforeMapp)
|
||||||
|
.on(beforeMapp.modelUid.eq(beforeMaster.id))
|
||||||
|
.leftJoin(beforeDataset)
|
||||||
|
.on(beforeMapp.datasetUid.eq(beforeDataset.id))
|
||||||
|
.leftJoin(beforeObj)
|
||||||
|
.on(beforeDataset.id.eq(beforeObj.datasetUid))
|
||||||
|
.where(modelMasterEntity.id.eq(modelId))
|
||||||
|
.groupBy(
|
||||||
|
modelMasterEntity.modelNo,
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
@Override
|
@Override
|
||||||
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
||||||
|
|
||||||
BooleanBuilder builder = new BooleanBuilder();
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
builder.and(dataset.deleted.isFalse());
|
||||||
|
|
||||||
NumberExpression<Long> selectedCnt = null;
|
NumberExpression<Long> selectedCnt = null;
|
||||||
NumberExpression<Long> wasteCnt =
|
NumberExpression<Long> wasteCnt =
|
||||||
@@ -174,6 +288,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
SelectDataSet.class,
|
SelectDataSet.class,
|
||||||
|
Expressions.constant(req.getModelNo()),
|
||||||
dataset.id,
|
dataset.id,
|
||||||
dataset.uuid,
|
dataset.uuid,
|
||||||
dataset.dataType,
|
dataset.dataType,
|
||||||
@@ -198,6 +313,119 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
.fetch();
|
.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
|
@Override
|
||||||
|
public List<SelectTransferDataSet> getDatasetTransferSelectG2G3List(
|
||||||
|
Long modelId, String modelNo) {
|
||||||
|
|
||||||
|
// before join용
|
||||||
|
QModelMasterEntity beforeMaster = new QModelMasterEntity("beforeMaster");
|
||||||
|
QModelDatasetMappEntity beforeMapp = new QModelDatasetMappEntity("beforeMapp");
|
||||||
|
QDatasetEntity beforeDataset = new QDatasetEntity("beforeDataset");
|
||||||
|
QDatasetObjEntity beforeObj = new QDatasetObjEntity("beforeObj");
|
||||||
|
|
||||||
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
|
NumberExpression<Long> wasteCnt =
|
||||||
|
datasetObjEntity.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> elseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(datasetObjEntity.targetClassCd.notIn("building", "container", "waste"))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> selectedCnt = ModelType.G2.getId().equals(modelNo) ? wasteCnt : elseCnt;
|
||||||
|
|
||||||
|
// before도 동일 로직으로 cnt 계산
|
||||||
|
NumberExpression<Long> beforeWasteCnt =
|
||||||
|
beforeObj.targetClassCd.when("waste").then(1L).otherwise(0L).sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> beforeElseCnt =
|
||||||
|
new CaseBuilder()
|
||||||
|
.when(beforeObj.targetClassCd.notIn("building", "container", "waste"))
|
||||||
|
.then(1L)
|
||||||
|
.otherwise(0L)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
NumberExpression<Long> beforeSelectedCnt =
|
||||||
|
ModelType.G2.getId().equals(modelNo) ? beforeWasteCnt : beforeElseCnt;
|
||||||
|
|
||||||
|
return queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
SelectTransferDataSet.class,
|
||||||
|
|
||||||
|
// ===== 현재 =====
|
||||||
|
modelMasterEntity.modelNo, // modelNo 파라미터 사용 (req.getModelNo() 제거)
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
selectedCnt, // classCount 자리에 들어가는 cnt (Long)
|
||||||
|
|
||||||
|
// ===== before =====
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo,
|
||||||
|
beforeSelectedCnt))
|
||||||
|
.from(modelMasterEntity)
|
||||||
|
|
||||||
|
// ===== 현재 dataset =====
|
||||||
|
.leftJoin(modelDatasetMappEntity)
|
||||||
|
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||||
|
.leftJoin(dataset)
|
||||||
|
.on(modelDatasetMappEntity.datasetUid.eq(dataset.id))
|
||||||
|
.leftJoin(datasetObjEntity)
|
||||||
|
.on(dataset.id.eq(datasetObjEntity.datasetUid))
|
||||||
|
|
||||||
|
// ===== before dataset =====
|
||||||
|
.leftJoin(beforeMaster)
|
||||||
|
.on(beforeMaster.id.eq(modelMasterEntity.beforeModelId))
|
||||||
|
.leftJoin(beforeMapp)
|
||||||
|
.on(beforeMapp.modelUid.eq(beforeMaster.id))
|
||||||
|
.leftJoin(beforeDataset)
|
||||||
|
.on(beforeMapp.datasetUid.eq(beforeDataset.id))
|
||||||
|
.leftJoin(beforeObj)
|
||||||
|
.on(beforeDataset.id.eq(beforeObj.datasetUid))
|
||||||
|
.where(modelMasterEntity.id.eq(modelId).and(builder))
|
||||||
|
|
||||||
|
// sum() 때문에 groupBy 필요
|
||||||
|
.groupBy(
|
||||||
|
dataset.id,
|
||||||
|
dataset.uuid,
|
||||||
|
dataset.dataType,
|
||||||
|
dataset.title,
|
||||||
|
dataset.roundNo,
|
||||||
|
dataset.compareYyyy,
|
||||||
|
dataset.targetYyyy,
|
||||||
|
dataset.memo,
|
||||||
|
beforeMaster.modelNo,
|
||||||
|
beforeDataset.id,
|
||||||
|
beforeDataset.uuid,
|
||||||
|
beforeDataset.dataType,
|
||||||
|
beforeDataset.title,
|
||||||
|
beforeDataset.roundNo,
|
||||||
|
beforeDataset.compareYyyy,
|
||||||
|
beforeDataset.targetYyyy,
|
||||||
|
beforeDataset.memo)
|
||||||
|
.orderBy(dataset.createdDttm.desc())
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
public Long getDatasetMaxStage(int compareYyyy, int targetYyyy) {
|
||||||
return queryFactory
|
return queryFactory
|
||||||
@@ -236,7 +464,21 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
|||||||
return queryFactory
|
return queryFactory
|
||||||
.select(dataset.id)
|
.select(dataset.id)
|
||||||
.from(dataset)
|
.from(dataset)
|
||||||
.where(dataset.uid.eq(mngRegDto.getUid()))
|
.where(dataset.uid.eq(mngRegDto.getUid()), dataset.deleted.isFalse())
|
||||||
|
.fetchOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> findDatasetUid(List<Long> datasetIds) {
|
||||||
|
return queryFactory.select(dataset.uid).from(dataset).where(dataset.id.in(datasetIds)).fetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Long findDatasetByUidExistsCnt(String uid) {
|
||||||
|
return queryFactory
|
||||||
|
.select(dataset.id.count())
|
||||||
|
.from(dataset)
|
||||||
|
.where(dataset.uid.eq(uid), dataset.deleted.isFalse())
|
||||||
.fetchOne();
|
.fetchOne();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
|
import com.kamco.cd.training.postgres.entity.MapSheetEntity;
|
||||||
@@ -11,3 +12,4 @@ public interface MapSheetRepository
|
|||||||
|
|
||||||
long countByDatasetIdAndDeletedFalse(Long datasetId);
|
long countByDatasetIdAndDeletedFalse(Long datasetId);
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -7,3 +8,4 @@ import org.springframework.data.domain.Page;
|
|||||||
public interface MapSheetRepositoryCustom {
|
public interface MapSheetRepositoryCustom {
|
||||||
Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq);
|
Page<MapSheetEntity> findMapSheetList(MapSheetDto.SearchReq searchReq);
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// TODO 미사용시작
|
||||||
package com.kamco.cd.training.postgres.repository.dataset;
|
package com.kamco.cd.training.postgres.repository.dataset;
|
||||||
|
|
||||||
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
import com.kamco.cd.training.dataset.dto.MapSheetDto;
|
||||||
@@ -52,3 +53,4 @@ public class MapSheetRepositoryImpl implements MapSheetRepositoryCustom {
|
|||||||
return new PageImpl<>(content, pageable, total);
|
return new PageImpl<>(content, pageable, total);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|||||||
@@ -8,5 +8,7 @@ import org.springframework.stereotype.Repository;
|
|||||||
@Repository
|
@Repository
|
||||||
public interface HyperParamRepository
|
public interface HyperParamRepository
|
||||||
extends JpaRepository<ModelHyperParamEntity, Long>, HyperParamRepositoryCustom {
|
extends JpaRepository<ModelHyperParamEntity, Long>, HyperParamRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelHyperParamEntity> findByHyperVer(String hyperVer);
|
Optional<ModelHyperParamEntity> findByHyperVer(String hyperVer);
|
||||||
|
// TODO 미사용 끝
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,62 @@
|
|||||||
package com.kamco.cd.training.postgres.repository.hyperparam;
|
package com.kamco.cd.training.postgres.repository.hyperparam;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
public interface HyperParamRepositoryCustom {
|
public interface HyperParamRepositoryCustom {
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
/**
|
/**
|
||||||
* 마지막 버전 조회
|
* 마지막 버전 조회
|
||||||
*
|
*
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
|
@Deprecated
|
||||||
Optional<ModelHyperParamEntity> findHyperParamVer();
|
Optional<ModelHyperParamEntity> findHyperParamVer();
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 모델 타입별 마지막 버전 조회
|
||||||
|
*
|
||||||
|
* @param modelType 모델 타입
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 상세조회
|
||||||
|
*
|
||||||
|
* @param uuid
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid);
|
Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid);
|
||||||
|
|
||||||
Page<HyperParamDto.List> findByHyperVerList(HyperParamDto.SearchReq req);
|
/**
|
||||||
|
* 하이퍼 파라미터 목록 조회
|
||||||
|
*
|
||||||
|
* @param model
|
||||||
|
* @param req
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 하이퍼 파라미터 모델타입으로 조회
|
||||||
|
*
|
||||||
|
* @param modelType
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
List<ModelHyperParamEntity> getHyperParamByType(ModelType modelType);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,13 @@ package com.kamco.cd.training.postgres.repository.hyperparam;
|
|||||||
|
|
||||||
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
||||||
|
|
||||||
|
import com.kamco.cd.training.common.enums.ModelType;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
|
||||||
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.HyperType;
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.HyperType;
|
||||||
|
import com.kamco.cd.training.hyperparam.dto.HyperParamDto.SearchReq;
|
||||||
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
import com.kamco.cd.training.postgres.entity.ModelHyperParamEntity;
|
||||||
import com.querydsl.core.BooleanBuilder;
|
import com.querydsl.core.BooleanBuilder;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.core.types.dsl.NumberExpression;
|
|
||||||
import com.querydsl.jpa.impl.JPAQuery;
|
import com.querydsl.jpa.impl.JPAQuery;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
@@ -28,6 +29,7 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
|
|
||||||
private final JPAQueryFactory queryFactory;
|
private final JPAQueryFactory queryFactory;
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
public Optional<ModelHyperParamEntity> findHyperParamVer() {
|
||||||
|
|
||||||
@@ -41,6 +43,26 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<ModelHyperParamEntity> findHyperParamVerByModelType(ModelType modelType) {
|
||||||
|
|
||||||
|
return Optional.ofNullable(
|
||||||
|
queryFactory
|
||||||
|
.select(modelHyperParamEntity)
|
||||||
|
.from(modelHyperParamEntity)
|
||||||
|
.where(
|
||||||
|
modelHyperParamEntity
|
||||||
|
.delYn
|
||||||
|
.isFalse()
|
||||||
|
.and(modelHyperParamEntity.modelType.eq(modelType)))
|
||||||
|
.orderBy(modelHyperParamEntity.hyperVer.desc())
|
||||||
|
.limit(1)
|
||||||
|
.fetchOne());
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
public Optional<ModelHyperParamEntity> findHyperParamByHyperVer(String hyperVer) {
|
||||||
|
|
||||||
@@ -57,23 +79,30 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid) {
|
public Optional<ModelHyperParamEntity> findHyperParamByUuid(UUID uuid) {
|
||||||
return Optional.ofNullable(
|
return Optional.ofNullable(
|
||||||
queryFactory
|
queryFactory
|
||||||
.select(modelHyperParamEntity)
|
.select(modelHyperParamEntity)
|
||||||
.from(modelHyperParamEntity)
|
.from(modelHyperParamEntity)
|
||||||
.where(modelHyperParamEntity.delYn.isFalse().and(modelHyperParamEntity.uuid.eq(uuid)))
|
.where(modelHyperParamEntity.uuid.eq(uuid))
|
||||||
.fetchOne());
|
.fetchOne());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<HyperParamDto.List> findByHyperVerList(HyperParamDto.SearchReq req) {
|
public Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req) {
|
||||||
Pageable pageable = req.toPageable();
|
Pageable pageable = req.toPageable();
|
||||||
|
|
||||||
BooleanBuilder builder = new BooleanBuilder();
|
BooleanBuilder builder = new BooleanBuilder();
|
||||||
|
|
||||||
builder.and(modelHyperParamEntity.delYn.isFalse());
|
builder.and(modelHyperParamEntity.delYn.isFalse());
|
||||||
|
|
||||||
|
if (model != null) {
|
||||||
|
builder.and(modelHyperParamEntity.modelType.eq(model));
|
||||||
|
}
|
||||||
|
|
||||||
if (req.getHyperVer() != null && !req.getHyperVer().isEmpty()) {
|
if (req.getHyperVer() != null && !req.getHyperVer().isEmpty()) {
|
||||||
// 버전
|
// 버전
|
||||||
builder.and(modelHyperParamEntity.hyperVer.contains(req.getHyperVer()));
|
builder.and(modelHyperParamEntity.hyperVer.contains(req.getHyperVer()));
|
||||||
@@ -96,26 +125,18 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
NumberExpression<Long> totalUseCnt =
|
|
||||||
modelHyperParamEntity
|
|
||||||
.m1UseCnt
|
|
||||||
.coalesce(0L)
|
|
||||||
.add(modelHyperParamEntity.m2UseCnt.coalesce(0L))
|
|
||||||
.add(modelHyperParamEntity.m3UseCnt.coalesce(0L));
|
|
||||||
|
|
||||||
JPAQuery<HyperParamDto.List> query =
|
JPAQuery<HyperParamDto.List> query =
|
||||||
queryFactory
|
queryFactory
|
||||||
.select(
|
.select(
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
HyperParamDto.List.class,
|
HyperParamDto.List.class,
|
||||||
modelHyperParamEntity.uuid,
|
modelHyperParamEntity.uuid,
|
||||||
|
modelHyperParamEntity.modelType.as("model"),
|
||||||
modelHyperParamEntity.hyperVer,
|
modelHyperParamEntity.hyperVer,
|
||||||
modelHyperParamEntity.createdDttm,
|
modelHyperParamEntity.createdDttm,
|
||||||
modelHyperParamEntity.lastUsedDttm,
|
modelHyperParamEntity.lastUsedDttm,
|
||||||
modelHyperParamEntity.m1UseCnt,
|
modelHyperParamEntity.memo,
|
||||||
modelHyperParamEntity.m2UseCnt,
|
modelHyperParamEntity.totalUseCnt))
|
||||||
modelHyperParamEntity.m3UseCnt,
|
|
||||||
totalUseCnt.as("totalUseCnt")))
|
|
||||||
.from(modelHyperParamEntity)
|
.from(modelHyperParamEntity)
|
||||||
.where(builder);
|
.where(builder);
|
||||||
|
|
||||||
@@ -140,8 +161,11 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
asc
|
asc
|
||||||
? modelHyperParamEntity.lastUsedDttm.asc()
|
? modelHyperParamEntity.lastUsedDttm.asc()
|
||||||
: modelHyperParamEntity.lastUsedDttm.desc());
|
: modelHyperParamEntity.lastUsedDttm.desc());
|
||||||
|
case "totalUseCnt" ->
|
||||||
case "totalUseCnt" -> query.orderBy(asc ? totalUseCnt.asc() : totalUseCnt.desc());
|
query.orderBy(
|
||||||
|
asc
|
||||||
|
? modelHyperParamEntity.totalUseCnt.asc()
|
||||||
|
: modelHyperParamEntity.totalUseCnt.desc());
|
||||||
|
|
||||||
default -> query.orderBy(modelHyperParamEntity.createdDttm.desc());
|
default -> query.orderBy(modelHyperParamEntity.createdDttm.desc());
|
||||||
}
|
}
|
||||||
@@ -161,4 +185,17 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
|||||||
|
|
||||||
return new PageImpl<>(content, pageable, totalCount);
|
return new PageImpl<>(content, pageable, totalCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ModelHyperParamEntity> getHyperParamByType(ModelType modelType) {
|
||||||
|
return queryFactory
|
||||||
|
.select(modelHyperParamEntity)
|
||||||
|
.from(modelHyperParamEntity)
|
||||||
|
.where(
|
||||||
|
modelHyperParamEntity
|
||||||
|
.delYn
|
||||||
|
.isFalse()
|
||||||
|
.and(modelHyperParamEntity.modelType.eq(modelType)))
|
||||||
|
.fetch();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.kamco.cd.training.postgres.repository.log;
|
package com.kamco.cd.training.postgres.repository.log;
|
||||||
|
|
||||||
import com.kamco.cd.training.log.dto.AuditLogDto;
|
import com.kamco.cd.training.log.dto.AuditLogDto;
|
||||||
|
import com.kamco.cd.training.log.dto.AuditLogDto.DownloadReq;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
@@ -15,6 +16,9 @@ public interface AuditLogRepositoryCustom {
|
|||||||
Page<AuditLogDto.UserAuditList> findLogByAccount(
|
Page<AuditLogDto.UserAuditList> findLogByAccount(
|
||||||
AuditLogDto.searchReq searchReq, String searchValue);
|
AuditLogDto.searchReq searchReq, String searchValue);
|
||||||
|
|
||||||
|
Page<AuditLogDto.DownloadRes> findDownloadLog(
|
||||||
|
AuditLogDto.searchReq searchReq, DownloadReq downloadReq);
|
||||||
|
|
||||||
Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
||||||
AuditLogDto.searchReq searchReq, LocalDate logDate);
|
AuditLogDto.searchReq searchReq, LocalDate logDate);
|
||||||
|
|
||||||
|
|||||||
@@ -6,32 +6,42 @@ import static com.kamco.cd.training.postgres.entity.QMemberEntity.memberEntity;
|
|||||||
import static com.kamco.cd.training.postgres.entity.QMenuEntity.menuEntity;
|
import static com.kamco.cd.training.postgres.entity.QMenuEntity.menuEntity;
|
||||||
|
|
||||||
import com.kamco.cd.training.log.dto.AuditLogDto;
|
import com.kamco.cd.training.log.dto.AuditLogDto;
|
||||||
|
import com.kamco.cd.training.log.dto.AuditLogDto.DownloadReq;
|
||||||
|
import com.kamco.cd.training.log.dto.AuditLogDto.searchReq;
|
||||||
import com.kamco.cd.training.log.dto.ErrorLogDto;
|
import com.kamco.cd.training.log.dto.ErrorLogDto;
|
||||||
import com.kamco.cd.training.log.dto.EventStatus;
|
import com.kamco.cd.training.log.dto.EventStatus;
|
||||||
import com.kamco.cd.training.log.dto.EventType;
|
import com.kamco.cd.training.log.dto.EventType;
|
||||||
|
import com.kamco.cd.training.postgres.entity.AuditLogEntity;
|
||||||
import com.kamco.cd.training.postgres.entity.QMenuEntity;
|
import com.kamco.cd.training.postgres.entity.QMenuEntity;
|
||||||
|
import com.querydsl.core.BooleanBuilder;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.core.types.dsl.*;
|
import com.querydsl.core.types.dsl.*;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import io.micrometer.common.util.StringUtils;
|
import io.micrometer.common.util.StringUtils;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.PageImpl;
|
import org.springframework.data.domain.PageImpl;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
@RequiredArgsConstructor
|
public class AuditLogRepositoryImpl extends QuerydslRepositorySupport
|
||||||
public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
implements AuditLogRepositoryCustom {
|
||||||
|
|
||||||
|
private static final ZoneId ZONE = ZoneId.of("Asia/Seoul");
|
||||||
private final JPAQueryFactory queryFactory;
|
private final JPAQueryFactory queryFactory;
|
||||||
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
||||||
|
|
||||||
|
public AuditLogRepositoryImpl(JPAQueryFactory queryFactory) {
|
||||||
|
super(AuditLogEntity.class);
|
||||||
|
this.queryFactory = queryFactory;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<AuditLogDto.DailyAuditList> findLogByDaily(
|
public Page<AuditLogDto.DailyAuditList> findLogByDaily(
|
||||||
AuditLogDto.searchReq searchReq, LocalDate startDate, LocalDate endDate) {
|
AuditLogDto.searchReq searchReq, LocalDate startDate, LocalDate endDate) {
|
||||||
@@ -87,7 +97,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
.from(auditLogEntity)
|
.from(auditLogEntity)
|
||||||
.leftJoin(menuEntity)
|
.leftJoin(menuEntity)
|
||||||
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
||||||
.where(menuNameEquals(searchValue))
|
.where(auditLogEntity.menuUid.ne("SYSTEM"), menuNameEquals(searchValue))
|
||||||
.groupBy(auditLogEntity.menuUid)
|
.groupBy(auditLogEntity.menuUid)
|
||||||
.offset(pageable.getOffset())
|
.offset(pageable.getOffset())
|
||||||
.limit(pageable.getPageSize())
|
.limit(pageable.getPageSize())
|
||||||
@@ -128,7 +138,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
.from(auditLogEntity)
|
.from(auditLogEntity)
|
||||||
.leftJoin(memberEntity)
|
.leftJoin(memberEntity)
|
||||||
.on(auditLogEntity.userUid.eq(memberEntity.id))
|
.on(auditLogEntity.userUid.eq(memberEntity.id))
|
||||||
.where(loginIdOrUsernameContains(searchValue))
|
.where(auditLogEntity.userUid.isNotNull(), loginIdOrUsernameContains(searchValue))
|
||||||
.groupBy(auditLogEntity.userUid, memberEntity.employeeNo, memberEntity.name)
|
.groupBy(auditLogEntity.userUid, memberEntity.employeeNo, memberEntity.name)
|
||||||
.offset(pageable.getOffset())
|
.offset(pageable.getOffset())
|
||||||
.limit(pageable.getPageSize())
|
.limit(pageable.getPageSize())
|
||||||
@@ -147,6 +157,62 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
return new PageImpl<>(foundContent, pageable, countQuery);
|
return new PageImpl<>(foundContent, pageable, countQuery);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<AuditLogDto.DownloadRes> findDownloadLog(
|
||||||
|
AuditLogDto.searchReq searchReq, DownloadReq req) {
|
||||||
|
Pageable pageable = searchReq.toPageable();
|
||||||
|
|
||||||
|
BooleanBuilder whereBuilder = new BooleanBuilder();
|
||||||
|
|
||||||
|
whereBuilder.and(auditLogEntity.eventStatus.ne(EventStatus.valueOf("FAILED")));
|
||||||
|
whereBuilder.and(auditLogEntity.eventType.eq(EventType.valueOf("DOWNLOAD")));
|
||||||
|
|
||||||
|
// if (req.getMenuId() != null && !req.getMenuId().isEmpty()) {
|
||||||
|
// whereBuilder.and(auditLogEntity.menuUid.eq(req.getMenuId()));
|
||||||
|
// }
|
||||||
|
|
||||||
|
if (req.getUuid() != null) {
|
||||||
|
whereBuilder.and(auditLogEntity.requestUri.contains(req.getRequestUri()));
|
||||||
|
whereBuilder.and(auditLogEntity.downloadUuid.eq(req.getUuid()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.getSearchValue() != null && !req.getSearchValue().isEmpty()) {
|
||||||
|
whereBuilder.and(
|
||||||
|
memberEntity
|
||||||
|
.name
|
||||||
|
.contains(req.getSearchValue())
|
||||||
|
.or(memberEntity.employeeNo.contains(req.getSearchValue())));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AuditLogDto.DownloadRes> foundContent =
|
||||||
|
queryFactory
|
||||||
|
.select(
|
||||||
|
Projections.constructor(
|
||||||
|
AuditLogDto.DownloadRes.class,
|
||||||
|
memberEntity.name,
|
||||||
|
memberEntity.employeeNo,
|
||||||
|
auditLogEntity.createdDate.as("downloadDttm")))
|
||||||
|
.from(auditLogEntity)
|
||||||
|
.leftJoin(memberEntity)
|
||||||
|
.on(auditLogEntity.userUid.eq(memberEntity.id))
|
||||||
|
.where(whereBuilder, createdDateBetween(req.getStartDate(), req.getEndDate()))
|
||||||
|
.offset(pageable.getOffset())
|
||||||
|
.limit(pageable.getPageSize())
|
||||||
|
.orderBy(auditLogEntity.createdDate.desc())
|
||||||
|
.fetch();
|
||||||
|
|
||||||
|
Long countQuery =
|
||||||
|
queryFactory
|
||||||
|
.select(auditLogEntity.userUid.countDistinct())
|
||||||
|
.from(auditLogEntity)
|
||||||
|
.leftJoin(memberEntity)
|
||||||
|
.on(auditLogEntity.userUid.eq(memberEntity.id))
|
||||||
|
.where(whereBuilder, createdDateBetween(req.getStartDate(), req.getEndDate()))
|
||||||
|
.fetchOne();
|
||||||
|
|
||||||
|
return new PageImpl<>(foundContent, pageable, countQuery);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
public Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
||||||
AuditLogDto.searchReq searchReq, LocalDate logDate) {
|
AuditLogDto.searchReq searchReq, LocalDate logDate) {
|
||||||
@@ -176,6 +242,9 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
memberEntity.employeeNo.as("loginId"),
|
memberEntity.employeeNo.as("loginId"),
|
||||||
menuEntity.menuNm.as("menuName"),
|
menuEntity.menuNm.as("menuName"),
|
||||||
auditLogEntity.eventType.as("eventType"),
|
auditLogEntity.eventType.as("eventType"),
|
||||||
|
Expressions.stringTemplate(
|
||||||
|
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||||
|
.as("logDateTime"),
|
||||||
Projections.constructor(
|
Projections.constructor(
|
||||||
AuditLogDto.LogDetail.class,
|
AuditLogDto.LogDetail.class,
|
||||||
Expressions.constant("한국자산관리공사"), // serviceName
|
Expressions.constant("한국자산관리공사"), // serviceName
|
||||||
@@ -184,7 +253,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
menuEntity.menuUrl.as("menuUrl"),
|
menuEntity.menuUrl.as("menuUrl"),
|
||||||
menuEntity.description.as("menuDescription"),
|
menuEntity.description.as("menuDescription"),
|
||||||
menuEntity.menuOrder.as("sortOrder"),
|
menuEntity.menuOrder.as("sortOrder"),
|
||||||
menuEntity.isUse.as("used"))))
|
menuEntity.isUse.as("used")))) // TODO
|
||||||
.from(auditLogEntity)
|
.from(auditLogEntity)
|
||||||
.leftJoin(menuEntity)
|
.leftJoin(menuEntity)
|
||||||
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
||||||
@@ -238,8 +307,8 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
AuditLogDto.MenuDetail.class,
|
AuditLogDto.MenuDetail.class,
|
||||||
auditLogEntity.id.as("logId"),
|
auditLogEntity.id.as("logId"),
|
||||||
Expressions.stringTemplate(
|
Expressions.stringTemplate(
|
||||||
"to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate)
|
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||||
.as("logDateTime"), // ??
|
.as("logDateTime"),
|
||||||
memberEntity.name.as("userName"),
|
memberEntity.name.as("userName"),
|
||||||
memberEntity.employeeNo.as("loginId"),
|
memberEntity.employeeNo.as("loginId"),
|
||||||
auditLogEntity.eventType.as("eventType"),
|
auditLogEntity.eventType.as("eventType"),
|
||||||
@@ -305,7 +374,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
AuditLogDto.UserDetail.class,
|
AuditLogDto.UserDetail.class,
|
||||||
auditLogEntity.id.as("logId"),
|
auditLogEntity.id.as("logId"),
|
||||||
Expressions.stringTemplate(
|
Expressions.stringTemplate(
|
||||||
"to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate)
|
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||||
.as("logDateTime"),
|
.as("logDateTime"),
|
||||||
menuEntity.menuNm.as("menuName"),
|
menuEntity.menuNm.as("menuName"),
|
||||||
auditLogEntity.eventType.as("eventType"),
|
auditLogEntity.eventType.as("eventType"),
|
||||||
@@ -349,12 +418,23 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
LocalDateTime startDateTime = startDate.atStartOfDay();
|
ZoneId zoneId = ZoneId.of("Asia/Seoul");
|
||||||
LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay();
|
ZonedDateTime startDateTime = startDate.atStartOfDay(zoneId);
|
||||||
|
ZonedDateTime endDateTime = endDate.plusDays(1).atStartOfDay(zoneId);
|
||||||
return auditLogEntity
|
return auditLogEntity
|
||||||
.createdDate
|
.createdDate
|
||||||
.goe(ZonedDateTime.from(startDateTime))
|
.goe(startDateTime)
|
||||||
.and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime)));
|
.and(auditLogEntity.createdDate.lt(endDateTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BooleanExpression createdDateBetween(LocalDate startDate, LocalDate endDate) {
|
||||||
|
if (startDate == null || endDate == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
ZonedDateTime start = startDate.atStartOfDay(ZONE);
|
||||||
|
ZonedDateTime endExclusive = endDate.plusDays(1).atStartOfDay(ZONE);
|
||||||
|
|
||||||
|
return auditLogEntity.createdDate.goe(start).and(auditLogEntity.createdDate.lt(endExclusive));
|
||||||
}
|
}
|
||||||
|
|
||||||
private BooleanExpression menuNameEquals(String searchValue) {
|
private BooleanExpression menuNameEquals(String searchValue) {
|
||||||
@@ -393,11 +473,11 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private BooleanExpression eventEndedAtEqDate(LocalDate logDate) {
|
private BooleanExpression eventEndedAtEqDate(LocalDate logDate) {
|
||||||
StringExpression eventEndedDate =
|
ZoneId zoneId = ZoneId.of("Asia/Seoul");
|
||||||
Expressions.stringTemplate("to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate);
|
ZonedDateTime start = logDate.atStartOfDay(zoneId);
|
||||||
LocalDateTime comparisonDate = logDate.atStartOfDay();
|
ZonedDateTime end = logDate.plusDays(1).atStartOfDay(zoneId);
|
||||||
|
|
||||||
return eventEndedDate.eq(comparisonDate.toString());
|
return auditLogEntity.createdDate.goe(start).and(auditLogEntity.createdDate.lt(end));
|
||||||
}
|
}
|
||||||
|
|
||||||
private BooleanExpression menuUidEq(String menuUid) {
|
private BooleanExpression menuUidEq(String menuUid) {
|
||||||
@@ -410,7 +490,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
|
|
||||||
private NumberExpression<Integer> readCount() {
|
private NumberExpression<Integer> readCount() {
|
||||||
return new CaseBuilder()
|
return new CaseBuilder()
|
||||||
.when(auditLogEntity.eventType.eq(EventType.READ))
|
.when(auditLogEntity.eventType.in(EventType.LIST, EventType.DETAIL))
|
||||||
.then(1)
|
.then(1)
|
||||||
.otherwise(0)
|
.otherwise(0)
|
||||||
.sum();
|
.sum();
|
||||||
@@ -418,7 +498,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
|
|
||||||
private NumberExpression<Integer> cudCount() {
|
private NumberExpression<Integer> cudCount() {
|
||||||
return new CaseBuilder()
|
return new CaseBuilder()
|
||||||
.when(auditLogEntity.eventType.in(EventType.CREATE, EventType.UPDATE, EventType.DELETE))
|
.when(auditLogEntity.eventType.in(EventType.ADDED, EventType.MODIFIED, EventType.REMOVE))
|
||||||
.then(1)
|
.then(1)
|
||||||
.otherwise(0)
|
.otherwise(0)
|
||||||
.sum();
|
.sum();
|
||||||
@@ -426,7 +506,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
|||||||
|
|
||||||
private NumberExpression<Integer> printCount() {
|
private NumberExpression<Integer> printCount() {
|
||||||
return new CaseBuilder()
|
return new CaseBuilder()
|
||||||
.when(auditLogEntity.eventType.eq(EventType.PRINT))
|
.when(auditLogEntity.eventType.eq(EventType.OTHER))
|
||||||
.then(1)
|
.then(1)
|
||||||
.otherwise(0)
|
.otherwise(0)
|
||||||
.sum();
|
.sum();
|
||||||
|
|||||||
@@ -8,29 +8,35 @@ import static com.kamco.cd.training.postgres.entity.QMenuEntity.menuEntity;
|
|||||||
import com.kamco.cd.training.log.dto.ErrorLogDto;
|
import com.kamco.cd.training.log.dto.ErrorLogDto;
|
||||||
import com.kamco.cd.training.log.dto.EventStatus;
|
import com.kamco.cd.training.log.dto.EventStatus;
|
||||||
import com.kamco.cd.training.log.dto.EventType;
|
import com.kamco.cd.training.log.dto.EventType;
|
||||||
|
import com.kamco.cd.training.postgres.entity.AuditLogEntity;
|
||||||
import com.querydsl.core.types.Projections;
|
import com.querydsl.core.types.Projections;
|
||||||
import com.querydsl.core.types.dsl.BooleanExpression;
|
import com.querydsl.core.types.dsl.BooleanExpression;
|
||||||
import com.querydsl.core.types.dsl.Expressions;
|
import com.querydsl.core.types.dsl.Expressions;
|
||||||
import com.querydsl.core.types.dsl.StringExpression;
|
import com.querydsl.core.types.dsl.StringExpression;
|
||||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.ZoneId;
|
||||||
import java.time.ZonedDateTime;
|
import java.time.ZonedDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.PageImpl;
|
import org.springframework.data.domain.PageImpl;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
@RequiredArgsConstructor
|
public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport
|
||||||
public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
implements ErrorLogRepositoryCustom {
|
||||||
|
|
||||||
private final JPAQueryFactory queryFactory;
|
private final JPAQueryFactory queryFactory;
|
||||||
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
||||||
|
|
||||||
|
public ErrorLogRepositoryImpl(JPAQueryFactory queryFactory) {
|
||||||
|
super(AuditLogEntity.class);
|
||||||
|
this.queryFactory = queryFactory;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Page<ErrorLogDto.Basic> findLogByError(ErrorLogDto.ErrorSearchReq searchReq) {
|
public Page<ErrorLogDto.Basic> findLogByError(ErrorLogDto.ErrorSearchReq searchReq) {
|
||||||
Pageable pageable = searchReq.toPageable();
|
Pageable pageable = searchReq.toPageable();
|
||||||
@@ -52,7 +58,7 @@ public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
|||||||
errorLogEntity.errorMessage.as("errorMessage"),
|
errorLogEntity.errorMessage.as("errorMessage"),
|
||||||
errorLogEntity.stackTrace.as("errorDetail"),
|
errorLogEntity.stackTrace.as("errorDetail"),
|
||||||
Expressions.stringTemplate(
|
Expressions.stringTemplate(
|
||||||
"to_char({0}, 'YYYY-MM-DD')", errorLogEntity.createdDate)))
|
"to_char({0}, 'YYYY-MM-DD HH24:MI:SS.FF3')", errorLogEntity.createdDate)))
|
||||||
.from(errorLogEntity)
|
.from(errorLogEntity)
|
||||||
.leftJoin(auditLogEntity)
|
.leftJoin(auditLogEntity)
|
||||||
.on(errorLogEntity.id.eq(auditLogEntity.errorLogUid))
|
.on(errorLogEntity.id.eq(auditLogEntity.errorLogUid))
|
||||||
@@ -94,12 +100,14 @@ public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
|||||||
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
LocalDateTime startDateTime = startDate.atStartOfDay();
|
|
||||||
LocalDateTime endDateTime = endDate.plusDays(1).atStartOfDay();
|
ZoneId zoneId = ZoneId.of("Asia/Seoul");
|
||||||
|
ZonedDateTime startDateTime = startDate.atStartOfDay(zoneId);
|
||||||
|
ZonedDateTime endDateTime = endDate.plusDays(1).atStartOfDay(zoneId);
|
||||||
return auditLogEntity
|
return auditLogEntity
|
||||||
.createdDate
|
.createdDate
|
||||||
.goe(ZonedDateTime.from(startDateTime))
|
.goe(startDateTime)
|
||||||
.and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime)));
|
.and(auditLogEntity.createdDate.lt(endDateTime));
|
||||||
}
|
}
|
||||||
|
|
||||||
private BooleanExpression eventStatusEqFailed() {
|
private BooleanExpression eventStatusEqFailed() {
|
||||||
|
|||||||
@@ -7,14 +7,18 @@ import java.util.UUID;
|
|||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
|
|
||||||
public interface MembersRepositoryCustom {
|
public interface MembersRepositoryCustom {
|
||||||
|
// TODO 미사용시작
|
||||||
boolean existsByUserId(String userId);
|
boolean existsByUserId(String userId);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
boolean existsByEmployeeNo(String employeeNo);
|
boolean existsByEmployeeNo(String employeeNo);
|
||||||
|
|
||||||
Optional<MemberEntity> findByEmployeeNo(String employeeNo);
|
Optional<MemberEntity> findByEmployeeNo(String employeeNo);
|
||||||
|
|
||||||
|
// TODO 미사용시작
|
||||||
Optional<MemberEntity> findByUserId(String userId);
|
Optional<MemberEntity> findByUserId(String userId);
|
||||||
|
|
||||||
|
// TODO 미사용 끝
|
||||||
Optional<MemberEntity> findByUUID(UUID uuid);
|
Optional<MemberEntity> findByUUID(UUID uuid);
|
||||||
|
|
||||||
Page<MemberEntity> findByMembers(MembersDto.SearchReq searchReq);
|
Page<MemberEntity> findByMembers(MembersDto.SearchReq searchReq);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user