Compare commits
168 Commits
feat/dean/
...
63794ec4ec
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 3106d36431 | |||
| ed48f697a4 | |||
| da92b28d97 | |||
| 6c865d26fd | |||
| e3f00876f1 | |||
| 16e156b5b4 | |||
| 60962bbc75 | |||
| 6a939118ff | |||
| 64d37dcc08 | |||
| 0c0ae16c2b | |||
| a2490f30e6 | |||
| 953f95aed6 | |||
| bd04e1f4e8 | |||
| 85633c8bab | |||
| 5fc15937c0 | |||
| 8b3940b446 | |||
| 201cfefb6b | |||
| 9958b0999a |
@@ -1,6 +1,11 @@
|
||||
# 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
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ services:
|
||||
- /mnt/nfs_share/model_output:/app/model-outputs
|
||||
- /mnt/nfs_share/train_dataset:/app/train-dataset
|
||||
- /home/kcomu/data:/home/kcomu/data
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
networks:
|
||||
- kamco-cds
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -23,7 +23,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final UserDetailsService userDetailsService;
|
||||
private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
|
||||
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
|
||||
|
||||
@@ -20,7 +20,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
@Tag(name = "공통코드 관리", description = "공통코드 관리 API")
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/code")
|
||||
@RequestMapping("/api/common-code")
|
||||
public class CommonCodeApiController {
|
||||
|
||||
private final CommonCodeService commonCodeService;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
) {}
|
||||
@@ -17,7 +17,10 @@ public enum ModelType implements EnumType {
|
||||
private String desc;
|
||||
|
||||
public static ModelType getValueData(String modelNo) {
|
||||
return Arrays.stream(ModelType.values()).filter(m -> m.getId().equals(modelNo)).findFirst().orElse(G1);
|
||||
return Arrays.stream(ModelType.values())
|
||||
.filter(m -> m.getId().equals(modelNo))
|
||||
.findFirst()
|
||||
.orElse(G1);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -6,6 +6,8 @@ import com.jcraft.jsch.ChannelExec;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
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 java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
@@ -15,6 +17,7 @@ import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
@@ -39,6 +42,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.geotools.coverage.grid.GridCoverage2D;
|
||||
import org.geotools.gce.geotiff.GeoTiffReader;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.util.FileSystemUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -722,6 +726,11 @@ public class FIleChecker {
|
||||
|
||||
File destDir = new File(destDirectory, folderName);
|
||||
|
||||
// 동일 폴더가 이미 있으면 삭제
|
||||
if (destDir.exists()) {
|
||||
deleteDirectoryRecursively(destDir.toPath());
|
||||
}
|
||||
|
||||
if (!destDir.exists()) {
|
||||
destDir.mkdirs();
|
||||
}
|
||||
@@ -757,6 +766,11 @@ public class FIleChecker {
|
||||
zipEntry = zis.getNextEntry();
|
||||
}
|
||||
zis.closeEntry();
|
||||
} catch (IOException e) {
|
||||
throw new CustomApiException(
|
||||
ApiResponseCode.INTERNAL_SERVER_ERROR.getId(),
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
"압축 해제 중 오류가 발생했습니다: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,4 +920,22 @@ public class FIleChecker {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -76,11 +76,13 @@ public class SecurityConfig {
|
||||
"/api/auth/logout",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**",
|
||||
"/api/members/*/password",
|
||||
"/api/upload/chunk-upload-dataset",
|
||||
"/api/upload/chunk-upload-complete")
|
||||
"/api/upload/chunk-upload-complete",
|
||||
"/download_progress_test.html",
|
||||
"/api/models/download/**")
|
||||
.permitAll()
|
||||
|
||||
.requestMatchers("/api/members/*/password")
|
||||
.authenticated()
|
||||
// default
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
|
||||
@@ -5,11 +5,14 @@ import com.kamco.cd.training.log.dto.EventType;
|
||||
import com.kamco.cd.training.menu.dto.MenuDto;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||
|
||||
@Slf4j
|
||||
public class ApiLogFunction {
|
||||
|
||||
// 클라이언트 IP 추출
|
||||
@@ -34,6 +37,14 @@ public class ApiLogFunction {
|
||||
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 기준)
|
||||
public static String getUserId(HttpServletRequest request) {
|
||||
try {
|
||||
@@ -47,20 +58,20 @@ public class ApiLogFunction {
|
||||
String method = request.getMethod().toUpperCase();
|
||||
String uri = request.getRequestURI().toLowerCase();
|
||||
|
||||
// URL 기반 DOWNLOAD/PRINT 분류
|
||||
// URL 기반 DOWNLOAD/PRINT 분류 -> /download는 FileDownloadInterceptor로 옮김
|
||||
if (uri.contains("/download") || uri.contains("/export")) {
|
||||
return EventType.DOWNLOAD;
|
||||
}
|
||||
if (uri.contains("/print")) {
|
||||
return EventType.PRINT;
|
||||
return EventType.OTHER;
|
||||
}
|
||||
|
||||
// 일반 CRUD
|
||||
return switch (method) {
|
||||
case "POST" -> EventType.CREATE;
|
||||
case "GET" -> EventType.READ;
|
||||
case "DELETE" -> EventType.DELETE;
|
||||
case "PUT", "PATCH" -> EventType.UPDATE;
|
||||
case "POST" -> EventType.ADDED;
|
||||
case "GET" -> EventType.LIST;
|
||||
case "DELETE" -> EventType.REMOVE;
|
||||
case "PUT", "PATCH" -> EventType.MODIFIED;
|
||||
default -> EventType.OTHER;
|
||||
};
|
||||
}
|
||||
@@ -121,12 +132,22 @@ public class ApiLogFunction {
|
||||
|
||||
public static String getUriMenuInfo(List<MenuDto.Basic> menuList, String uri) {
|
||||
|
||||
MenuDto.Basic m =
|
||||
String normalizedUri = uri.replace("/api", "");
|
||||
MenuDto.Basic basic =
|
||||
menuList.stream()
|
||||
.filter(menu -> menu.getMenuApiUrl() != null && uri.contains(menu.getMenuApiUrl()))
|
||||
.findFirst()
|
||||
.filter(
|
||||
menu -> menu.getMenuUrl() != null && normalizedUri.startsWith(menu.getMenuUrl()))
|
||||
.max(Comparator.comparingInt(m -> m.getMenuUrl().length()))
|
||||
.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.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.postgres.entity.AuditLogEntity;
|
||||
import com.kamco.cd.training.postgres.repository.log.AuditLogRepository;
|
||||
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.core.MethodParameter;
|
||||
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
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
|
||||
@@ -61,12 +69,27 @@ public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
if (body instanceof ApiResponseDto<?> apiResponse) {
|
||||
response.setStatusCode(apiResponse.getHttpStatus());
|
||||
|
||||
String ip = ApiLogFunction.getClientIp(servletRequest);
|
||||
Long userid = null;
|
||||
String actionType = HeaderUtil.get(servletRequest, "kamco-action-type");
|
||||
// actionType 이 없으면 로그 저장하지 않기 || download 는 FileDownloadInterceptor 에서 하기
|
||||
// (file down URL prefix 추가는 WebConfig.java 에 하기)
|
||||
if (actionType == null || actionType.equalsIgnoreCase("download")) {
|
||||
return body;
|
||||
}
|
||||
|
||||
if (servletRequest.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken auth
|
||||
&& auth.getPrincipal() instanceof CustomUserDetails customUserDetails) {
|
||||
userid = customUserDetails.getMember().getId();
|
||||
String ip =
|
||||
Optional.ofNullable(HeaderUtil.get(servletRequest, "kamco-user-ip"))
|
||||
.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;
|
||||
@@ -84,17 +107,33 @@ public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
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 =
|
||||
new AuditLogEntity(
|
||||
userid,
|
||||
ApiLogFunction.getEventType(servletRequest),
|
||||
EventType.fromName(actionType),
|
||||
ApiLogFunction.isSuccessFail(apiResponse),
|
||||
ApiLogFunction.getUriMenuInfo(
|
||||
menuService.getFindAll(), servletRequest.getRequestURI()),
|
||||
ApiLogFunction.getUriMenuInfo(result, servletRequest.getRequestURI()),
|
||||
ip,
|
||||
servletRequest.getRequestURI(),
|
||||
requestBody,
|
||||
apiResponse.getErrorLogUid());
|
||||
ApiLogFunction.cutRequestBody(requestBody),
|
||||
apiResponse.getErrorLogUid(),
|
||||
null,
|
||||
loginAttemptId);
|
||||
auditLogRepository.save(log);
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -208,8 +212,15 @@ public class DatasetApiController {
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/usable-bytes")
|
||||
public ApiResponseDto<DatasetStorage> getUsableBytes() {
|
||||
return ApiResponseDto.ok(datasetService.getUsableBytes());
|
||||
public ApiResponseDto<DatasetStorage> getUsableBytes() throws IOException {
|
||||
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파일 등록 합니다.")
|
||||
@@ -217,7 +228,7 @@ public class DatasetApiController {
|
||||
public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
|
||||
@RequestBody @Valid DatasetDto.AddReq addReq) {
|
||||
|
||||
return ApiResponseDto.ok(datasetService.insertDataset(addReq));
|
||||
return ApiResponseDto.okObject(datasetService.insertDataset(addReq));
|
||||
}
|
||||
|
||||
@Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
|
||||
|
||||
@@ -77,9 +77,16 @@ public class DatasetDto {
|
||||
}
|
||||
|
||||
public String getTotalSize(Long totalSize) {
|
||||
if (totalSize == null) return "0G";
|
||||
if (totalSize == null || totalSize <= 0) return "0M";
|
||||
|
||||
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) {
|
||||
|
||||
@@ -26,10 +26,14 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -56,6 +60,8 @@ public class DatasetService {
|
||||
private String datasetDir;
|
||||
|
||||
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");
|
||||
|
||||
/**
|
||||
* 데이터셋 목록 조회
|
||||
@@ -164,53 +170,28 @@ public class DatasetService {
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Transactional
|
||||
public ResponseObj insertDatasetTo86(@Valid AddReq addReq) {
|
||||
|
||||
Long datasetUid = null; // master id 값, 등록하면서 가져올 예정
|
||||
|
||||
// 압축 해제
|
||||
FIleChecker.unzipOn86Server(
|
||||
addReq.getFilePath() + addReq.getFileName(),
|
||||
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||
|
||||
// 해제한 폴더 읽어서 데이터 저장
|
||||
List<Map<String, Object>> list =
|
||||
getUnzipDatasetFilesTo86(
|
||||
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), "train");
|
||||
|
||||
int idx = 0;
|
||||
for (Map<String, Object> map : list) {
|
||||
datasetUid =
|
||||
this.insertTrainTestData(map, addReq, idx, datasetUid, "train"); // train 데이터 insert
|
||||
idx++;
|
||||
}
|
||||
|
||||
List<Map<String, Object>> testList =
|
||||
getUnzipDatasetFilesTo86(
|
||||
addReq.getFilePath() + addReq.getFileName().replace(".zip", ""), "test");
|
||||
|
||||
int testIdx = 0;
|
||||
for (Map<String, Object> test : testList) {
|
||||
datasetUid =
|
||||
this.insertTrainTestData(test, addReq, testIdx, datasetUid, "test"); // test 데이터 insert
|
||||
testIdx++;
|
||||
}
|
||||
|
||||
datasetCoreService.updateDatasetUploadStatus(datasetUid);
|
||||
return new ResponseObj(ApiResponseCode.OK, "업로드 성공하였습니다.");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ResponseObj insertDataset(@Valid AddReq addReq) {
|
||||
|
||||
Long datasetUid = null; // master id 값, 등록하면서 가져올 예정
|
||||
|
||||
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());
|
||||
|
||||
// 압축 해제한 폴더 하위에 train,val,test 폴더 모두 존재하는지 확인
|
||||
validateTrainValTestDirs(addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||
|
||||
// 압축 해제한 폴더의 갯수 맞는지 log 찍기
|
||||
validateDirFileCount(addReq.getFilePath() + addReq.getFileName().replace(".zip", ""));
|
||||
|
||||
// 해제한 폴더 읽어서 데이터 저장
|
||||
List<Map<String, Object>> list =
|
||||
getUnzipDatasetFiles(
|
||||
@@ -360,7 +341,10 @@ public class DatasetService {
|
||||
Path dir = root.resolve(dirName);
|
||||
|
||||
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)) {
|
||||
@@ -414,62 +398,6 @@ public class DatasetService {
|
||||
return datasetCoreService.getFilePathByUUIDPathType(uuid, pathType);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
private List<Map<String, Object>> getUnzipDatasetFilesTo86(String unzipRootPath, String subDir) {
|
||||
|
||||
// String root = Paths.get(unzipRootPath)
|
||||
// .resolve(subDir)
|
||||
// .toString();
|
||||
//
|
||||
String root = normalizeLinuxPath(unzipRootPath + "/" + subDir);
|
||||
|
||||
Map<String, Map<String, Object>> grouped = new HashMap<>();
|
||||
|
||||
for (String dirName : LABEL_DIRS) {
|
||||
|
||||
String remoteDir = root + "/" + dirName;
|
||||
|
||||
// 1. 86 서버에서 해당 디렉토리의 파일 목록 조회
|
||||
List<String> files = listFilesOn86Server(remoteDir);
|
||||
|
||||
if (files.isEmpty()) {
|
||||
throw new IllegalStateException("폴더가 존재하지 않거나 파일이 없습니다 : " + remoteDir);
|
||||
}
|
||||
|
||||
for (String fullPath : files) {
|
||||
|
||||
String fileName = Paths.get(fullPath).getFileName().toString();
|
||||
String baseName = getBaseName(fileName);
|
||||
|
||||
Map<String, Object> data = grouped.computeIfAbsent(baseName, k -> new HashMap<>());
|
||||
|
||||
data.put("baseName", baseName);
|
||||
|
||||
if ("label-json".equals(dirName)) {
|
||||
|
||||
// 2. json 내용도 86 서버에서 읽어서 가져와야 함
|
||||
String json = readRemoteFileAsString(fullPath);
|
||||
|
||||
data.put("label-json", parseJson(json));
|
||||
data.put("geojson_path", fullPath);
|
||||
|
||||
} else {
|
||||
|
||||
data.put(dirName, fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ArrayList<>(grouped.values());
|
||||
}
|
||||
|
||||
private List<String> listFilesOn86Server(String remoteDir) {
|
||||
|
||||
String command = "find " + escape(remoteDir) + " -maxdepth 1 -type f";
|
||||
|
||||
return FIleChecker.execCommandAndReadLines(command);
|
||||
}
|
||||
|
||||
private String readRemoteFileAsString(String remoteFilePath) {
|
||||
|
||||
String command = "cat " + escape(remoteFilePath);
|
||||
@@ -521,4 +449,78 @@ public class DatasetService {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,9 +88,8 @@ public class HyperParamApiController {
|
||||
@ApiResponse(responseCode = "404", description = "하이퍼파라미터를 찾을 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("{model}/list")
|
||||
@GetMapping("/list")
|
||||
public ApiResponseDto<Page<List>> getHyperParam(
|
||||
@PathVariable ModelType model,
|
||||
@Parameter(
|
||||
description = "구분 CREATE_DATE(생성일), LAST_USED_DATE(최근사용일)",
|
||||
example = "CREATE_DATE")
|
||||
@@ -102,6 +101,9 @@ public class HyperParamApiController {
|
||||
LocalDate endDate,
|
||||
@Parameter(description = "버전명", example = "G_000001") @RequestParam(required = false)
|
||||
String hyperVer,
|
||||
@Parameter(description = "모델 타입 (G1, G2, G3 중 하나)", example = "G1")
|
||||
@RequestParam(required = false)
|
||||
ModelType model,
|
||||
@Parameter(
|
||||
description = "정렬",
|
||||
example = "createdDttm desc",
|
||||
@@ -182,10 +184,8 @@ public class HyperParamApiController {
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/init/{model}")
|
||||
public ApiResponseDto<HyperParamDto.Basic> getInitHyperParam(
|
||||
@PathVariable ModelType model
|
||||
public ApiResponseDto<HyperParamDto.Basic> getInitHyperParam(@PathVariable ModelType model) {
|
||||
|
||||
) {
|
||||
return ApiResponseDto.ok(hyperParamService.getInitHyperParam(model));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,9 +110,11 @@ public class HyperParamDto {
|
||||
@AllArgsConstructor
|
||||
public static class List {
|
||||
private UUID uuid;
|
||||
private ModelType model;
|
||||
private String hyperVer;
|
||||
@JsonFormatDttm private ZonedDateTime createDttm;
|
||||
@JsonFormatDttm private ZonedDateTime lastUsedDttm;
|
||||
private String memo;
|
||||
private Long m1UseCnt;
|
||||
private Long m2UseCnt;
|
||||
private Long m3UseCnt;
|
||||
|
||||
@@ -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.kamco.cd.training.common.utils.interfaces.JsonFormatDttm;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.UUID;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
@@ -58,6 +60,7 @@ public class AuditLogDto {
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class AuditCommon {
|
||||
|
||||
private int readCount;
|
||||
private int cudCount;
|
||||
private int printCount;
|
||||
@@ -68,6 +71,7 @@ public class AuditLogDto {
|
||||
@Schema(name = "DailyAuditList", description = "일자별 목록")
|
||||
@Getter
|
||||
public static class DailyAuditList extends AuditCommon {
|
||||
|
||||
private final String baseDate;
|
||||
|
||||
public DailyAuditList(
|
||||
@@ -85,6 +89,7 @@ public class AuditLogDto {
|
||||
@Schema(name = "MenuAuditList", description = "메뉴별 목록")
|
||||
@Getter
|
||||
public static class MenuAuditList extends AuditCommon {
|
||||
|
||||
private final String menuId;
|
||||
private final String menuName;
|
||||
|
||||
@@ -105,6 +110,7 @@ public class AuditLogDto {
|
||||
@Schema(name = "UserAuditList", description = "사용자별 목록")
|
||||
@Getter
|
||||
public static class UserAuditList extends AuditCommon {
|
||||
|
||||
private final Long accountId;
|
||||
private final String loginId;
|
||||
private final String username;
|
||||
@@ -129,6 +135,7 @@ public class AuditLogDto {
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class AuditDetail {
|
||||
|
||||
private Long logId;
|
||||
private EventType eventType;
|
||||
private LogDetail detail;
|
||||
@@ -137,9 +144,11 @@ public class AuditLogDto {
|
||||
@Schema(name = "DailyDetail", description = "일자별 로그 상세")
|
||||
@Getter
|
||||
public static class DailyDetail extends AuditDetail {
|
||||
|
||||
private final String userName;
|
||||
private final String loginId;
|
||||
private final String menuName;
|
||||
private final String logDateTime;
|
||||
|
||||
public DailyDetail(
|
||||
Long logId,
|
||||
@@ -147,17 +156,20 @@ public class AuditLogDto {
|
||||
String loginId,
|
||||
String menuName,
|
||||
EventType eventType,
|
||||
String logDateTime,
|
||||
LogDetail detail) {
|
||||
super(logId, eventType, detail);
|
||||
this.userName = userName;
|
||||
this.loginId = loginId;
|
||||
this.menuName = menuName;
|
||||
this.logDateTime = logDateTime;
|
||||
}
|
||||
}
|
||||
|
||||
@Schema(name = "MenuDetail", description = "메뉴별 로그 상세")
|
||||
@Getter
|
||||
public static class MenuDetail extends AuditDetail {
|
||||
|
||||
private final String logDateTime;
|
||||
private final String userName;
|
||||
private final String loginId;
|
||||
@@ -179,6 +191,7 @@ public class AuditLogDto {
|
||||
@Schema(name = "UserDetail", description = "사용자별 로그 상세")
|
||||
@Getter
|
||||
public static class UserDetail extends AuditDetail {
|
||||
|
||||
private final String logDateTime;
|
||||
private final String menuNm;
|
||||
|
||||
@@ -194,6 +207,7 @@ public class AuditLogDto {
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
public static class LogDetail {
|
||||
|
||||
String serviceName;
|
||||
String parentMenuName;
|
||||
String menuName;
|
||||
@@ -226,4 +240,26 @@ public class AuditLogDto {
|
||||
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;
|
||||
|
||||
import com.kamco.cd.training.common.utils.enums.CodeExpose;
|
||||
import com.kamco.cd.training.common.utils.enums.EnumType;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.time.LocalDate;
|
||||
@@ -77,6 +78,7 @@ public class ErrorLogDto {
|
||||
}
|
||||
}
|
||||
|
||||
@CodeExpose
|
||||
public enum LogErrorLevel implements EnumType {
|
||||
WARNING("Warning"),
|
||||
ERROR("Error"),
|
||||
|
||||
@@ -1,22 +1,35 @@
|
||||
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 lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@CodeExpose
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum EventType implements EnumType {
|
||||
CREATE("생성"),
|
||||
READ("조회"),
|
||||
UPDATE("수정"),
|
||||
DELETE("삭제"),
|
||||
LIST("목록"),
|
||||
DETAIL("상세"),
|
||||
POPUP("팝업"),
|
||||
STATUS("상태"),
|
||||
ADDED("추가"),
|
||||
MODIFIED("수정"),
|
||||
REMOVE("삭제"),
|
||||
DOWNLOAD("다운로드"),
|
||||
PRINT("출력"),
|
||||
LOGIN("로그인"),
|
||||
OTHER("기타");
|
||||
|
||||
private final String desc;
|
||||
|
||||
public static EventType fromName(String name) {
|
||||
try {
|
||||
return EventType.valueOf(name.toUpperCase());
|
||||
} catch (Exception e) {
|
||||
return OTHER;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return name();
|
||||
|
||||
@@ -1,26 +1,39 @@
|
||||
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.model.dto.ModelTrainDetailDto;
|
||||
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.ModelTrainMngDto.Basic;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||
import com.kamco.cd.training.model.service.ModelTrainDetailService;
|
||||
import com.kamco.cd.training.model.service.ModelTrainMngService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.ArraySchema;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import 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.UUID;
|
||||
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.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -32,6 +45,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RequestMapping("/api/models")
|
||||
public class ModelTrainDetailApiController {
|
||||
private final ModelTrainDetailService modelTrainDetailService;
|
||||
private final ModelTrainMngService modelTrainMngService;
|
||||
private final RangeDownloadResponder rangeDownloadResponder;
|
||||
|
||||
@Value("${train.docker.responseDir}")
|
||||
private String responseDir;
|
||||
|
||||
@Operation(summary = "모델학습관리> 모델관리 > 상세정보탭 > 학습 진행정보", description = "학습 진행정보, 모델학습 정보 API")
|
||||
@ApiResponses(
|
||||
@@ -222,4 +240,90 @@ public class ModelTrainDetailApiController {
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||
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.train.service.ModelTestMetricsJobService;
|
||||
import com.kamco.cd.training.train.service.ModelTrainMetricsJobService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -16,6 +18,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -35,6 +38,8 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RequestMapping("/api/models")
|
||||
public class ModelTrainMngApiController {
|
||||
private final ModelTrainMngService modelTrainMngService;
|
||||
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||
private final ModelTestMetricsJobService modelTestMetricsJobService;
|
||||
|
||||
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
|
||||
@ApiResponses(
|
||||
@@ -50,7 +55,7 @@ public class ModelTrainMngApiController {
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/list")
|
||||
public ApiResponseDto<Page<Basic>> findByModelList(
|
||||
public ApiResponseDto<Page<ListDto>> findByModelList(
|
||||
@Parameter(
|
||||
description = "상태코드",
|
||||
example = "IN_PROGRESS",
|
||||
@@ -79,7 +84,8 @@ public class ModelTrainMngApiController {
|
||||
@DeleteMapping("/{uuid}")
|
||||
public ApiResponseDto<Void> deleteModelTrain(
|
||||
@Parameter(description = "학습 모델 uuid", example = "f2b02229-90f2-45f5-92ea-c56cf1c29f79")
|
||||
@PathVariable UUID uuid) {
|
||||
@PathVariable
|
||||
UUID uuid) {
|
||||
modelTrainMngService.deleteModelTrain(uuid);
|
||||
return ApiResponseDto.ok(null);
|
||||
}
|
||||
@@ -149,7 +155,9 @@ public class ModelTrainMngApiController {
|
||||
return ApiResponseDto.ok(modelTrainMngService.getDatasetSelectList(req));
|
||||
}
|
||||
|
||||
@Operation(summary = "모델학습 1단계 실행중인 것이 있는지 count", description = "모델학습 1단계 실행중인 것이 있는지 count")
|
||||
@Operation(
|
||||
summary = "모델학습 1단계/2단계 실행중인 것이 있는지 count",
|
||||
description = "모델학습 1단계/2단계 실행중인 것이 있는지 count")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
@@ -166,4 +174,44 @@ public class ModelTrainMngApiController {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,4 +245,13 @@ public class ModelTrainDetailDto {
|
||||
private Float iou;
|
||||
private Float accuracy;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ModelFileInfo {
|
||||
private Boolean fileExistsYn;
|
||||
private String fileName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,11 @@ public class ModelTrainMngDto {
|
||||
private String trainType;
|
||||
private String modelNo;
|
||||
private Long currentAttemptId;
|
||||
private String requestPath;
|
||||
|
||||
private String packingState;
|
||||
private ZonedDateTime packingStrtDttm;
|
||||
private ZonedDateTime packingEndDttm;
|
||||
|
||||
public String getStatusName() {
|
||||
if (this.statusCd == null || this.statusCd.isBlank()) return null;
|
||||
@@ -60,7 +65,7 @@ public class ModelTrainMngDto {
|
||||
}
|
||||
}
|
||||
|
||||
public String getStep2StatusNAme() {
|
||||
public String getStep2StatusName() {
|
||||
if (this.step2Status == null || this.step2Status.isBlank()) return null;
|
||||
try {
|
||||
return TrainStatusType.valueOf(this.step2Status).getText(); // 또는 getName()
|
||||
@@ -99,6 +104,10 @@ public class ModelTrainMngDto {
|
||||
public String getStep2Duration() {
|
||||
return formatDuration(this.step2StrtDttm, this.step2EndDttm);
|
||||
}
|
||||
|
||||
public String getPackingDuration() {
|
||||
return formatDuration(this.packingStrtDttm, this.packingEndDttm);
|
||||
}
|
||||
}
|
||||
|
||||
@Schema(name = "searchReq", description = "모델학습 관리 목록조회 파라미터")
|
||||
@@ -209,4 +218,110 @@ public class ModelTrainMngDto {
|
||||
@Schema(description = "메모", example = "메모 입니다.")
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kamco.cd.training.model.service;
|
||||
|
||||
import com.kamco.cd.training.common.enums.ModelType;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||
@@ -7,12 +8,14 @@ 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.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.TransferHyperSummary;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.Basic;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ModelProgressStepDto;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainDetailCoreService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import java.util.ArrayList;
|
||||
@@ -87,7 +90,7 @@ public class ModelTrainDetailService {
|
||||
datasetReq.setIds(datasetIds);
|
||||
datasetReq.setModelNo(modelInfo.getModelNo());
|
||||
|
||||
if (modelInfo.getModelNo().equals("G1")) {
|
||||
if (modelInfo.getModelNo().equals(ModelType.G1.getId())) {
|
||||
dataSets = mngCoreService.getDatasetSelectG1List(datasetReq);
|
||||
} else {
|
||||
dataSets = mngCoreService.getDatasetSelectG2G3List(datasetReq);
|
||||
@@ -116,4 +119,12 @@ public class ModelTrainDetailService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,7 @@ import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
|
||||
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import com.kamco.cd.training.train.service.TrainJobService;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -31,7 +30,7 @@ public class ModelTrainMngService {
|
||||
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
private final HyperParamCoreService hyperParamCoreService;
|
||||
private final TmpDatasetService tmpDatasetService;
|
||||
private final TrainJobService trainJobService;
|
||||
|
||||
/**
|
||||
* 모델학습 조회
|
||||
@@ -39,7 +38,7 @@ public class ModelTrainMngService {
|
||||
* @param searchReq 검색 조건
|
||||
* @return 페이징 처리된 모델 목록
|
||||
*/
|
||||
public Page<ModelTrainMngDto.Basic> getModelList(SearchReq searchReq) {
|
||||
public Page<ModelTrainMngDto.ListDto> getModelList(SearchReq searchReq) {
|
||||
return modelTrainMngCoreService.findByModelList(searchReq);
|
||||
}
|
||||
|
||||
@@ -94,22 +93,8 @@ public class ModelTrainMngService {
|
||||
// 모델 config 저장
|
||||
modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());
|
||||
|
||||
UUID tmpUuid = UUID.randomUUID();
|
||||
String raw = tmpUuid.toString().toUpperCase().replace("-", "");
|
||||
|
||||
List<String> uids =
|
||||
modelTrainMngCoreService.findDatasetUid(req.getTrainingDataset().getDatasetList());
|
||||
|
||||
try {
|
||||
// 데이터셋 심볼링크 생성
|
||||
Path path = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
|
||||
ModelTrainMngDto.UpdateReq updateReq = new ModelTrainMngDto.UpdateReq();
|
||||
updateReq.setRequestPath(path.toString());
|
||||
modelTrainMngCoreService.updateModelMaster(modelId, updateReq);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// 임시파일 생성
|
||||
trainJobService.createTmpFile(modelUuid);
|
||||
return modelUuid;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.kamco.cd.training.model.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TmpDatasetService {
|
||||
|
||||
@Value("${train.docker.requestDir}")
|
||||
private String requestDir;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Path buildTmpDatasetSymlink(String uid, List<String> datasetUids) throws IOException {
|
||||
|
||||
// 환경에 맞게 yml로 빼는 걸 추천
|
||||
Path BASE = Paths.get(requestDir);
|
||||
Path tmp = BASE.resolve("tmp").resolve(uid);
|
||||
|
||||
// mkdir -p "$TMP"/train/{input1,input2,label} ...
|
||||
for (String type : List.of("train", "val")) {
|
||||
for (String part : List.of("input1", "input2", "label")) {
|
||||
Files.createDirectories(tmp.resolve(type).resolve(part));
|
||||
}
|
||||
}
|
||||
|
||||
for (String id : datasetUids) {
|
||||
Path srcRoot = BASE.resolve(id);
|
||||
|
||||
for (String type : List.of("train", "val")) {
|
||||
for (String part : List.of("input1", "input2", "label")) {
|
||||
|
||||
Path srcDir = srcRoot.resolve(type).resolve(part);
|
||||
|
||||
// zsh NULL_GLOB: 폴더가 없으면 그냥 continue
|
||||
if (!Files.isDirectory(srcDir)) continue;
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(srcDir)) {
|
||||
for (Path f : stream) {
|
||||
if (!Files.isRegularFile(f)) continue;
|
||||
|
||||
String dstName = id + "__" + f.getFileName();
|
||||
Path dst = tmp.resolve(type).resolve(part).resolve(dstName);
|
||||
|
||||
// 이미 있으면 스킵(원하면 덮어쓰기 로직으로 바꿀 수 있음)
|
||||
if (Files.exists(dst)) continue;
|
||||
|
||||
// ln -s "$f" "$dst" 와 동일
|
||||
Files.createSymbolicLink(dst, f.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("tmp dataset created: {}", tmp);
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.kamco.cd.training.postgres.core;
|
||||
|
||||
import com.kamco.cd.training.common.service.BaseCoreService;
|
||||
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 java.time.LocalDate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -45,6 +46,11 @@ public class AuditLogCoreService
|
||||
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(
|
||||
AuditLogDto.searchReq searchRange, LocalDate logDate) {
|
||||
return auditLogRepository.findLogByDailyResult(searchRange, logDate);
|
||||
|
||||
@@ -246,4 +246,8 @@ public class DatasetCoreService
|
||||
public void insertDatasetValObj(DatasetObjRegDto objRegDto) {
|
||||
datasetObjRepository.insertDatasetValObj(objRegDto);
|
||||
}
|
||||
|
||||
public Long findDatasetByUidExistsCnt(String uid) {
|
||||
return datasetRepository.findDatasetByUidExistsCnt(uid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,15 +50,15 @@ public class HyperParamCoreService {
|
||||
/**
|
||||
* 하이퍼파라미터 수정
|
||||
*
|
||||
* @param uuid uuid
|
||||
* @param uuid uuid
|
||||
* @param createReq 등록 요청
|
||||
* @return ver
|
||||
*/
|
||||
public String updateHyperParam(UUID uuid, HyperParam createReq) {
|
||||
ModelHyperParamEntity entity =
|
||||
hyperParamRepository
|
||||
.findHyperParamByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
hyperParamRepository
|
||||
.findHyperParamByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
|
||||
if (entity.getIsDefault()) {
|
||||
throw new CustomApiException("UNPROCESSABLE_ENTITY_UPDATE", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
@@ -72,7 +72,6 @@ public class HyperParamCoreService {
|
||||
return entity.getHyperVer();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 하이퍼파라미터 삭제
|
||||
*
|
||||
@@ -80,15 +79,15 @@ public class HyperParamCoreService {
|
||||
*/
|
||||
public void deleteHyperParam(UUID uuid) {
|
||||
ModelHyperParamEntity entity =
|
||||
hyperParamRepository
|
||||
.findHyperParamByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
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.getHyperVer().equals("HPs_0001")) {
|
||||
// throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
// }
|
||||
|
||||
//디폴트면 삭제불가
|
||||
// 디폴트면 삭제불가
|
||||
if (entity.getIsDefault()) {
|
||||
throw new CustomApiException("UNPROCESSABLE_ENTITY", HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
@@ -105,9 +104,10 @@ public class HyperParamCoreService {
|
||||
*/
|
||||
public HyperParamDto.Basic getInitHyperParam(ModelType model) {
|
||||
ModelHyperParamEntity entity =
|
||||
hyperParamRepository
|
||||
.getHyperparamByType(model)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
hyperParamRepository.getHyperparamByType(model).stream()
|
||||
.filter(e -> e.getIsDefault() == Boolean.TRUE)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
@@ -118,9 +118,9 @@ public class HyperParamCoreService {
|
||||
*/
|
||||
public HyperParamDto.Basic getHyperParam(UUID uuid) {
|
||||
ModelHyperParamEntity entity =
|
||||
hyperParamRepository
|
||||
.findHyperParamByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
hyperParamRepository
|
||||
.findHyperParamByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
@@ -143,16 +143,16 @@ public class HyperParamCoreService {
|
||||
*/
|
||||
public String getFirstHyperParamVersion(ModelType model) {
|
||||
return hyperParamRepository
|
||||
.findHyperParamVerByModelType(model)
|
||||
.map(ModelHyperParamEntity::getHyperVer)
|
||||
.map(ver -> increase(ver, model))
|
||||
.orElse(model.name() + "_000001");
|
||||
.findHyperParamVerByModelType(model)
|
||||
.map(ModelHyperParamEntity::getHyperVer)
|
||||
.map(ver -> increase(ver, model))
|
||||
.orElse(model.name() + "_000001");
|
||||
}
|
||||
|
||||
/**
|
||||
* 하이퍼 파라미터의 버전을 증가시킨다.
|
||||
*
|
||||
* @param hyperVer 현재 버전
|
||||
* @param hyperVer 현재 버전
|
||||
* @param modelType 모델 타입
|
||||
* @return 증가된 버전
|
||||
*/
|
||||
@@ -214,5 +214,4 @@ public class HyperParamCoreService {
|
||||
// memo
|
||||
entity.setMemo(src.getMemo());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
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;
|
||||
@@ -26,4 +29,22 @@ public class ModelTestMetricsJobCoreService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,13 @@ 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.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.ModelProgressStepDto;
|
||||
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.ModelDetailRepository;
|
||||
@@ -97,4 +99,12 @@ public class ModelTrainDetailCoreService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,14 @@ import com.kamco.cd.training.postgres.repository.train.ModelTrainJobRepository;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Log4j2
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
@@ -42,6 +45,7 @@ public class ModelTrainJobCoreService {
|
||||
job.setQueuedDttm(queuedDttm != null ? queuedDttm : ZonedDateTime.now());
|
||||
|
||||
modelTrainJobRepository.save(job);
|
||||
modelTrainJobRepository.flush();
|
||||
return job.getId();
|
||||
}
|
||||
|
||||
@@ -91,6 +95,8 @@ public class ModelTrainJobCoreService {
|
||||
job.setExitCode(exitCode);
|
||||
job.setErrorMessage(errorMessage);
|
||||
job.setFinishedDttm(ZonedDateTime.now());
|
||||
|
||||
log.info("[TRAIN JOB FAIL] jobId={}, modelId={}", jobId, errorMessage);
|
||||
}
|
||||
|
||||
/** 취소 처리 */
|
||||
@@ -104,4 +110,20 @@ public class ModelTrainJobCoreService {
|
||||
job.setStatusCd("STOPPED");
|
||||
job.setFinishedDttm(ZonedDateTime.now());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateEpoch(String containerName, Integer epoch) {
|
||||
ModelTrainJobEntity job =
|
||||
modelTrainJobRepository
|
||||
.findByContainerName(containerName)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Job not found: " + containerName));
|
||||
|
||||
job.setCurrentEpoch(epoch);
|
||||
|
||||
if (Objects.equals(job.getTotalEpoch(), epoch)) {}
|
||||
}
|
||||
|
||||
public void insertModelTestTrainingRun(Long modelId, Long jobId, int epoch) {
|
||||
modelTrainJobRepository.insertModelTestTrainingRun(modelId, jobId, epoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,4 +29,9 @@ public class ModelTrainMetricsJobCoreService {
|
||||
public void insertModelMetricsValidation(List<Object[]> batchArgs) {
|
||||
modelTrainMetricsJobRepository.insertModelMetricsValidation(batchArgs);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateModelSelectedBestEpoch(Long modelId, Integer epoch) {
|
||||
modelTrainMetricsJobRepository.updateModelSelectedBestEpoch(modelId, epoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
|
||||
import com.kamco.cd.training.model.dto.ModelConfigDto;
|
||||
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.postgres.entity.ModelConfigEntity;
|
||||
import com.kamco.cd.training.postgres.entity.ModelDatasetEntity;
|
||||
@@ -23,6 +23,7 @@ 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.ModelDatasetRepository;
|
||||
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.util.ArrayList;
|
||||
@@ -53,9 +54,10 @@ public class ModelTrainMngCoreService {
|
||||
* @param searchReq 검색 조건
|
||||
* @return 페이징 처리된 모델 목록
|
||||
*/
|
||||
public Page<Basic> findByModelList(ModelTrainMngDto.SearchReq searchReq) {
|
||||
Page<ModelMasterEntity> entityPage = modelMngRepository.findByModels(searchReq);
|
||||
return entityPage.map(ModelMasterEntity::toDto);
|
||||
public Page<ListDto> findByModelList(ModelTrainMngDto.SearchReq searchReq) {
|
||||
// Page<ModelMasterEntity> entityPage = modelMngRepository.findByModels(searchReq);
|
||||
// return entityPage.map(ModelMasterEntity::toDto);
|
||||
return modelMngRepository.findByModels(searchReq);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,9 +67,9 @@ public class ModelTrainMngCoreService {
|
||||
*/
|
||||
public void deleteModel(UUID uuid) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
entity.setDelYn(true);
|
||||
entity.setUpdatedDttm(ZonedDateTime.now());
|
||||
entity.setUpdatedUid(userUtil.getId());
|
||||
@@ -83,15 +85,19 @@ public class ModelTrainMngCoreService {
|
||||
ModelMasterEntity entity = new ModelMasterEntity();
|
||||
ModelHyperParamEntity hyperParamEntity = new ModelHyperParamEntity();
|
||||
|
||||
// 최적화 파라미터는 모델 type의 디폴트사용
|
||||
// 최적화 파라미터는 모델 type의 디폴트사용
|
||||
if (HyperParamSelectType.OPTIMIZED.getId().equals(addReq.getHyperParamType())) {
|
||||
ModelType modelType = ModelType.getValueData(addReq.getModelNo());
|
||||
hyperParamEntity = hyperParamRepository.getHyperparamByType(modelType).orElse(null);
|
||||
// hyperParamEntity = hyperParamRepository.findByHyperVer("HPs_0001").orElse(null);
|
||||
hyperParamEntity =
|
||||
hyperParamRepository.getHyperparamByType(modelType).stream()
|
||||
.filter(e -> e.getIsDefault() == Boolean.TRUE)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
// hyperParamEntity = hyperParamRepository.findByHyperVer("HPs_0001").orElse(null);
|
||||
|
||||
} else {
|
||||
hyperParamEntity =
|
||||
hyperParamRepository.findHyperParamByUuid(addReq.getHyperUuid()).orElse(null);
|
||||
hyperParamRepository.findHyperParamByUuid(addReq.getHyperUuid()).orElse(null);
|
||||
}
|
||||
|
||||
if (hyperParamEntity == null || hyperParamEntity.getHyperVer() == null) {
|
||||
@@ -99,24 +105,16 @@ public class ModelTrainMngCoreService {
|
||||
}
|
||||
|
||||
String modelVer =
|
||||
String.join(
|
||||
".", addReq.getModelNo(), hyperParamEntity.getHyperVer(), entity.getUuid().toString());
|
||||
String.join(
|
||||
".", addReq.getModelNo(), hyperParamEntity.getHyperVer(), entity.getUuid().toString());
|
||||
entity.setModelVer(modelVer);
|
||||
entity.setHyperParamId(hyperParamEntity.getId());
|
||||
entity.setModelNo(addReq.getModelNo());
|
||||
entity.setTrainType(addReq.getTrainType()); // 일반, 전이
|
||||
entity.setBeforeModelId(addReq.getBeforeModelId());
|
||||
|
||||
if (addReq.getIsStart()) {
|
||||
entity.setModelStep((short) 1);
|
||||
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.setStep1State(TrainStatusType.READY.getId());
|
||||
}
|
||||
entity.setStatusCd(TrainStatusType.READY.getId());
|
||||
entity.setStep1State(TrainStatusType.READY.getId());
|
||||
|
||||
entity.setCreatedUid(userUtil.getId());
|
||||
ModelMasterEntity resultEntity = modelMngRepository.save(entity);
|
||||
@@ -132,7 +130,7 @@ public class ModelTrainMngCoreService {
|
||||
* data set 저장
|
||||
*
|
||||
* @param modelId 저장한 모델 학습 id
|
||||
* @param addReq 요청 파라미터
|
||||
* @param addReq 요청 파라미터
|
||||
*/
|
||||
public void saveModelDataset(Long modelId, ModelTrainMngDto.AddReq addReq) {
|
||||
TrainingDataset dataset = addReq.getTrainingDataset();
|
||||
@@ -165,22 +163,19 @@ public class ModelTrainMngCoreService {
|
||||
*/
|
||||
public void updateModelMaster(Long modelId, ModelTrainMngDto.UpdateReq req) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
// 임시폴더 UID업데이트
|
||||
if (req.getRequestPath() != null && !req.getRequestPath().isEmpty()) {
|
||||
entity.setRequestPath(req.getRequestPath());
|
||||
}
|
||||
|
||||
if (req.getResponsePath() != null && !req.getResponsePath().isEmpty()) {
|
||||
entity.setRequestPath(req.getResponsePath());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델 데이터셋 mapping 테이블 저장
|
||||
*
|
||||
* @param modelId 모델학습 id
|
||||
* @param modelId 모델학습 id
|
||||
* @param datasetList 선택한 data set
|
||||
*/
|
||||
public void saveModelDatasetMap(Long modelId, List<Long> datasetList) {
|
||||
@@ -197,7 +192,7 @@ public class ModelTrainMngCoreService {
|
||||
* 모델학습 config 저장
|
||||
*
|
||||
* @param modelId 모델학습 id
|
||||
* @param req 요청 파라미터
|
||||
* @param req 요청 파라미터
|
||||
* @return
|
||||
*/
|
||||
public void saveModelConfig(Long modelId, ModelTrainMngDto.ModelConfig req) {
|
||||
@@ -205,7 +200,10 @@ public class ModelTrainMngCoreService {
|
||||
ModelConfigEntity entity = new ModelConfigEntity();
|
||||
modelMasterEntity.setId(modelId);
|
||||
entity.setModel(modelMasterEntity);
|
||||
entity.setEpochCount(req.getEpochCnt());
|
||||
entity.setEpochCount(
|
||||
req.getEpochCnt() < 10
|
||||
? 10
|
||||
: req.getEpochCnt()); // 에폭이 10 이하이면 10으로 고정하기. 10 이상 에폭으로 해야 best 에폭 파일이 생성되어 내려옴
|
||||
entity.setTrainPercent(req.getTrainingCnt());
|
||||
entity.setValidationPercent(req.getValidationCnt());
|
||||
entity.setTestPercent(req.getTestCnt());
|
||||
@@ -217,7 +215,7 @@ public class ModelTrainMngCoreService {
|
||||
/**
|
||||
* 데이터셋 매핑 생성
|
||||
*
|
||||
* @param modelUid 모델 UID
|
||||
* @param modelUid 모델 UID
|
||||
* @param datasetIds 데이터셋 ID 목록
|
||||
*/
|
||||
public void createDatasetMappings(Long modelUid, List<Long> datasetIds) {
|
||||
@@ -239,8 +237,8 @@ public class ModelTrainMngCoreService {
|
||||
public ModelMasterEntity findByUuid(UUID uuid) {
|
||||
try {
|
||||
return modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new BadRequestException("잘못된 UUID 형식입니다: " + uuid);
|
||||
}
|
||||
@@ -254,9 +252,9 @@ public class ModelTrainMngCoreService {
|
||||
*/
|
||||
public Long findModelIdByUuid(UUID uuid) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
modelMngRepository
|
||||
.findByUuid(uuid)
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
return entity.getId();
|
||||
}
|
||||
|
||||
@@ -269,8 +267,8 @@ public class ModelTrainMngCoreService {
|
||||
public ModelConfigDto.Basic findModelConfigByModelId(UUID uuid) {
|
||||
ModelMasterEntity modelEntity = findByUuid(uuid);
|
||||
return modelConfigRepository
|
||||
.findModelConfigByModelId(modelEntity.getId())
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
.findModelConfigByModelId(modelEntity.getId())
|
||||
.orElseThrow(() -> new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -301,76 +299,68 @@ public class ModelTrainMngCoreService {
|
||||
*/
|
||||
public ModelTrainMngDto.Basic findModelById(Long id) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + id));
|
||||
modelMngRepository
|
||||
.findById(id)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + id));
|
||||
return entity.toDto();
|
||||
}
|
||||
|
||||
/**
|
||||
* 마스터를 IN_PROGRESS로 전환하고, 현재 실행 jobId를 연결 - UI/중단/상태조회 모두 currentAttemptId를 기준으로 동작
|
||||
*/
|
||||
/** 마스터를 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));
|
||||
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));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setLastError(null);
|
||||
modelMngRepository.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* 중단 처리(옵션) - cancel에서 쓰려고 하면 같이 구현
|
||||
*/
|
||||
/** 중단 처리(옵션) - cancel에서 쓰려고 하면 같이 구현 */
|
||||
@Transactional
|
||||
public void markStopped(Long modelId) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.STOPPED.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 완료 처리(옵션) - Worker가 성공 시 호출
|
||||
*/
|
||||
/** 완료 처리(옵션) - Worker가 성공 시 호출 */
|
||||
@Transactional
|
||||
public void markCompleted(Long modelId) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* step 1오류 처리(옵션) - Worker가 실패 시 호출
|
||||
*/
|
||||
/** step 1오류 처리(옵션) - Worker가 실패 시 호출 */
|
||||
@Transactional
|
||||
public void markError(Long modelId, String errorMessage) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.ERROR.getId());
|
||||
master.setStep1State(TrainStatusType.ERROR.getId());
|
||||
@@ -379,15 +369,13 @@ public class ModelTrainMngCoreService {
|
||||
master.setUpdatedDttm(ZonedDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* step 2오류 처리(옵션) - Worker가 실패 시 호출
|
||||
*/
|
||||
/** step 2오류 처리(옵션) - Worker가 실패 시 호출 */
|
||||
@Transactional
|
||||
public void markStep2Error(Long modelId, String errorMessage) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
master.setStatusCd(TrainStatusType.ERROR.getId());
|
||||
master.setStep2State(TrainStatusType.ERROR.getId());
|
||||
@@ -399,9 +387,9 @@ public class ModelTrainMngCoreService {
|
||||
@Transactional
|
||||
public void markSuccess(Long modelId) {
|
||||
ModelMasterEntity master =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
// 모델 상태 완료 처리
|
||||
master.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||
@@ -429,11 +417,12 @@ public class ModelTrainMngCoreService {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void markStep1InProgress(Long modelId, Long jobId) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
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);
|
||||
@@ -449,9 +438,9 @@ public class ModelTrainMngCoreService {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void markStep2InProgress(Long modelId, Long jobId) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
entity.setStatusCd(TrainStatusType.IN_PROGRESS.getId());
|
||||
entity.setStep2StrtDttm(ZonedDateTime.now());
|
||||
@@ -469,9 +458,9 @@ public class ModelTrainMngCoreService {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void markStep1Success(Long modelId) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
entity.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||
entity.setStep1State(TrainStatusType.COMPLETED.getId());
|
||||
@@ -488,9 +477,9 @@ public class ModelTrainMngCoreService {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void markStep2Success(Long modelId) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
entity.setStatusCd(TrainStatusType.COMPLETED.getId());
|
||||
entity.setStep2State(TrainStatusType.COMPLETED.getId());
|
||||
@@ -501,9 +490,9 @@ public class ModelTrainMngCoreService {
|
||||
|
||||
public void updateModelMasterBestEpoch(Long modelId, int epoch) {
|
||||
ModelMasterEntity entity =
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
modelMngRepository
|
||||
.findById(modelId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Model not found: " + modelId));
|
||||
|
||||
entity.setBestEpoch(epoch);
|
||||
}
|
||||
@@ -531,4 +520,34 @@ public class ModelTrainMngCoreService {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.postgres.CommonCreateEntity;
|
||||
import jakarta.persistence.*;
|
||||
import java.util.UUID;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
@@ -14,6 +15,7 @@ import lombok.NoArgsConstructor;
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Table(name = "tb_audit_log")
|
||||
public class AuditLogEntity extends CommonCreateEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "audit_log_uid", nullable = false)
|
||||
@@ -43,6 +45,12 @@ public class AuditLogEntity extends CommonCreateEntity {
|
||||
@Column(name = "error_log_uid")
|
||||
private Long errorLogUid;
|
||||
|
||||
@Column(name = "download_uuid")
|
||||
private UUID downloadUuid;
|
||||
|
||||
@Column(name = "login_attempt_id")
|
||||
private String loginAttemptId;
|
||||
|
||||
public AuditLogEntity(
|
||||
Long userUid,
|
||||
EventType eventType,
|
||||
@@ -51,7 +59,9 @@ public class AuditLogEntity extends CommonCreateEntity {
|
||||
String ipAddress,
|
||||
String requestUri,
|
||||
String requestBody,
|
||||
Long errorLogUid) {
|
||||
Long errorLogUid,
|
||||
UUID downloadUuid,
|
||||
String loginAttemptId) {
|
||||
this.userUid = userUid;
|
||||
this.eventType = eventType;
|
||||
this.eventStatus = eventStatus;
|
||||
@@ -60,6 +70,31 @@ public class AuditLogEntity extends CommonCreateEntity {
|
||||
this.requestUri = requestUri;
|
||||
this.requestBody = requestBody;
|
||||
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() {
|
||||
|
||||
@@ -316,7 +316,6 @@ public class ModelHyperParamEntity {
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ModelType modelType;
|
||||
|
||||
|
||||
@Column(name = "default_param")
|
||||
private Boolean isDefault = false;
|
||||
|
||||
@@ -395,8 +394,7 @@ public class ModelHyperParamEntity {
|
||||
// -------------------------
|
||||
this.gpuCnt,
|
||||
this.gpuIds,
|
||||
this.masterPort
|
||||
, this.isDefault
|
||||
);
|
||||
this.masterPort,
|
||||
this.isDefault);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,15 @@ public class ModelMasterEntity {
|
||||
@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() {
|
||||
return new ModelTrainMngDto.Basic(
|
||||
this.id,
|
||||
@@ -127,6 +136,10 @@ public class ModelMasterEntity {
|
||||
this.statusCd,
|
||||
this.trainType,
|
||||
this.modelNo,
|
||||
this.currentAttemptId);
|
||||
this.currentAttemptId,
|
||||
this.requestPath,
|
||||
this.packingState,
|
||||
this.packingStrtDttm,
|
||||
this.packingEndDttm);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -57,8 +57,7 @@ public class ModelTrainJobEntity {
|
||||
@Column(name = "exit_code")
|
||||
private Integer exitCode;
|
||||
|
||||
@Size(max = 2000)
|
||||
@Column(name = "error_message", length = 2000)
|
||||
@Column(name = "error_message", columnDefinition = "TEXT")
|
||||
private String errorMessage;
|
||||
|
||||
@ColumnDefault("now()")
|
||||
|
||||
@@ -24,4 +24,6 @@ public interface DatasetRepositoryCustom {
|
||||
Long insertDatasetMngData(DatasetMngRegDto mngRegDto);
|
||||
|
||||
List<String> findDatasetUid(List<Long> datasetIds);
|
||||
|
||||
Long findDatasetByUidExistsCnt(String uid);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,11 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
// Count 쿼리 별도 실행 (null safe handling)
|
||||
long total =
|
||||
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);
|
||||
|
||||
return new PageImpl<>(content, pageable, total);
|
||||
@@ -239,7 +243,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
return queryFactory
|
||||
.select(dataset.id)
|
||||
.from(dataset)
|
||||
.where(dataset.uid.eq(mngRegDto.getUid()))
|
||||
.where(dataset.uid.eq(mngRegDto.getUid()), dataset.deleted.isFalse())
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
@@ -247,4 +251,13 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.kamco.cd.training.common.enums.ModelType;
|
||||
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 java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -32,5 +33,5 @@ public interface HyperParamRepositoryCustom {
|
||||
|
||||
Page<HyperParamDto.List> findByHyperVerList(ModelType model, SearchReq req);
|
||||
|
||||
Optional<ModelHyperParamEntity> getHyperparamByType(ModelType modelType);
|
||||
List<ModelHyperParamEntity> getHyperparamByType(ModelType modelType);
|
||||
}
|
||||
|
||||
@@ -91,7 +91,9 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
Pageable pageable = req.toPageable();
|
||||
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
builder.and(modelHyperParamEntity.modelType.eq(model));
|
||||
if (model != null) {
|
||||
builder.and(modelHyperParamEntity.modelType.eq(model));
|
||||
}
|
||||
builder.and(modelHyperParamEntity.delYn.isFalse());
|
||||
|
||||
if (req.getHyperVer() != null && !req.getHyperVer().isEmpty()) {
|
||||
@@ -129,9 +131,11 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
Projections.constructor(
|
||||
HyperParamDto.List.class,
|
||||
modelHyperParamEntity.uuid,
|
||||
modelHyperParamEntity.modelType.as("model"),
|
||||
modelHyperParamEntity.hyperVer,
|
||||
modelHyperParamEntity.createdDttm,
|
||||
modelHyperParamEntity.lastUsedDttm,
|
||||
modelHyperParamEntity.memo,
|
||||
modelHyperParamEntity.m1UseCnt,
|
||||
modelHyperParamEntity.m2UseCnt,
|
||||
modelHyperParamEntity.m3UseCnt,
|
||||
@@ -183,12 +187,15 @@ public class HyperParamRepositoryImpl implements HyperParamRepositoryCustom {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ModelHyperParamEntity> getHyperparamByType(ModelType modelType) {
|
||||
return Optional.ofNullable(
|
||||
queryFactory
|
||||
public List<ModelHyperParamEntity> getHyperparamByType(ModelType modelType) {
|
||||
return queryFactory
|
||||
.select(modelHyperParamEntity)
|
||||
.from(modelHyperParamEntity)
|
||||
.where(modelHyperParamEntity.delYn.isFalse().and(modelHyperParamEntity.modelType.eq(modelType)))
|
||||
.fetchOne());
|
||||
.where(
|
||||
modelHyperParamEntity
|
||||
.delYn
|
||||
.isFalse()
|
||||
.and(modelHyperParamEntity.modelType.eq(modelType)))
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kamco.cd.training.postgres.repository.log;
|
||||
|
||||
import com.kamco.cd.training.log.dto.AuditLogDto;
|
||||
import com.kamco.cd.training.log.dto.AuditLogDto.DownloadReq;
|
||||
import java.time.LocalDate;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
@@ -15,6 +16,9 @@ public interface AuditLogRepositoryCustom {
|
||||
Page<AuditLogDto.UserAuditList> findLogByAccount(
|
||||
AuditLogDto.searchReq searchReq, String searchValue);
|
||||
|
||||
Page<AuditLogDto.DownloadRes> findDownloadLog(
|
||||
AuditLogDto.searchReq searchReq, DownloadReq downloadReq);
|
||||
|
||||
Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
||||
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 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.EventStatus;
|
||||
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.querydsl.core.BooleanBuilder;
|
||||
import com.querydsl.core.types.Projections;
|
||||
import com.querydsl.core.types.dsl.*;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import io.micrometer.common.util.StringUtils;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
public class AuditLogRepositoryImpl extends QuerydslRepositorySupport
|
||||
implements AuditLogRepositoryCustom {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Seoul");
|
||||
private final JPAQueryFactory queryFactory;
|
||||
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
||||
|
||||
public AuditLogRepositoryImpl(JPAQueryFactory queryFactory) {
|
||||
super(AuditLogEntity.class);
|
||||
this.queryFactory = queryFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<AuditLogDto.DailyAuditList> findLogByDaily(
|
||||
AuditLogDto.searchReq searchReq, LocalDate startDate, LocalDate endDate) {
|
||||
@@ -87,7 +97,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
.from(auditLogEntity)
|
||||
.leftJoin(menuEntity)
|
||||
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
||||
.where(menuNameEquals(searchValue))
|
||||
.where(auditLogEntity.menuUid.ne("SYSTEM"), menuNameEquals(searchValue))
|
||||
.groupBy(auditLogEntity.menuUid)
|
||||
.offset(pageable.getOffset())
|
||||
.limit(pageable.getPageSize())
|
||||
@@ -128,7 +138,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
.from(auditLogEntity)
|
||||
.leftJoin(memberEntity)
|
||||
.on(auditLogEntity.userUid.eq(memberEntity.id))
|
||||
.where(loginIdOrUsernameContains(searchValue))
|
||||
.where(auditLogEntity.userUid.isNotNull(), loginIdOrUsernameContains(searchValue))
|
||||
.groupBy(auditLogEntity.userUid, memberEntity.employeeNo, memberEntity.name)
|
||||
.offset(pageable.getOffset())
|
||||
.limit(pageable.getPageSize())
|
||||
@@ -147,6 +157,62 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
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
|
||||
public Page<AuditLogDto.DailyDetail> findLogByDailyResult(
|
||||
AuditLogDto.searchReq searchReq, LocalDate logDate) {
|
||||
@@ -176,6 +242,9 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
memberEntity.employeeNo.as("loginId"),
|
||||
menuEntity.menuNm.as("menuName"),
|
||||
auditLogEntity.eventType.as("eventType"),
|
||||
Expressions.stringTemplate(
|
||||
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||
.as("logDateTime"),
|
||||
Projections.constructor(
|
||||
AuditLogDto.LogDetail.class,
|
||||
Expressions.constant("한국자산관리공사"), // serviceName
|
||||
@@ -184,7 +253,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
menuEntity.menuUrl.as("menuUrl"),
|
||||
menuEntity.description.as("menuDescription"),
|
||||
menuEntity.menuOrder.as("sortOrder"),
|
||||
menuEntity.isUse.as("used"))))
|
||||
menuEntity.isUse.as("used")))) // TODO
|
||||
.from(auditLogEntity)
|
||||
.leftJoin(menuEntity)
|
||||
.on(auditLogEntity.menuUid.eq(menuEntity.menuUid))
|
||||
@@ -238,8 +307,8 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
AuditLogDto.MenuDetail.class,
|
||||
auditLogEntity.id.as("logId"),
|
||||
Expressions.stringTemplate(
|
||||
"to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate)
|
||||
.as("logDateTime"), // ??
|
||||
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||
.as("logDateTime"),
|
||||
memberEntity.name.as("userName"),
|
||||
memberEntity.employeeNo.as("loginId"),
|
||||
auditLogEntity.eventType.as("eventType"),
|
||||
@@ -305,7 +374,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
AuditLogDto.UserDetail.class,
|
||||
auditLogEntity.id.as("logId"),
|
||||
Expressions.stringTemplate(
|
||||
"to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate)
|
||||
"to_char({0}, 'YYYY-MM-DD HH24:MI')", auditLogEntity.createdDate)
|
||||
.as("logDateTime"),
|
||||
menuEntity.menuNm.as("menuName"),
|
||||
auditLogEntity.eventType.as("eventType"),
|
||||
@@ -349,12 +418,23 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
||||
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
|
||||
.createdDate
|
||||
.goe(ZonedDateTime.from(startDateTime))
|
||||
.and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime)));
|
||||
.goe(startDateTime)
|
||||
.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) {
|
||||
@@ -393,11 +473,11 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
}
|
||||
|
||||
private BooleanExpression eventEndedAtEqDate(LocalDate logDate) {
|
||||
StringExpression eventEndedDate =
|
||||
Expressions.stringTemplate("to_char({0}, 'YYYY-MM-DD')", auditLogEntity.createdDate);
|
||||
LocalDateTime comparisonDate = logDate.atStartOfDay();
|
||||
ZoneId zoneId = ZoneId.of("Asia/Seoul");
|
||||
ZonedDateTime start = logDate.atStartOfDay(zoneId);
|
||||
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) {
|
||||
@@ -410,7 +490,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
|
||||
private NumberExpression<Integer> readCount() {
|
||||
return new CaseBuilder()
|
||||
.when(auditLogEntity.eventType.eq(EventType.READ))
|
||||
.when(auditLogEntity.eventType.in(EventType.LIST, EventType.DETAIL))
|
||||
.then(1)
|
||||
.otherwise(0)
|
||||
.sum();
|
||||
@@ -418,7 +498,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
|
||||
private NumberExpression<Integer> cudCount() {
|
||||
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)
|
||||
.otherwise(0)
|
||||
.sum();
|
||||
@@ -426,7 +506,7 @@ public class AuditLogRepositoryImpl implements AuditLogRepositoryCustom {
|
||||
|
||||
private NumberExpression<Integer> printCount() {
|
||||
return new CaseBuilder()
|
||||
.when(auditLogEntity.eventType.eq(EventType.PRINT))
|
||||
.when(auditLogEntity.eventType.eq(EventType.OTHER))
|
||||
.then(1)
|
||||
.otherwise(0)
|
||||
.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.EventStatus;
|
||||
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.dsl.BooleanExpression;
|
||||
import com.querydsl.core.types.dsl.Expressions;
|
||||
import com.querydsl.core.types.dsl.StringExpression;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
||||
public class ErrorLogRepositoryImpl extends QuerydslRepositorySupport
|
||||
implements ErrorLogRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
private final StringExpression NULL_STRING = Expressions.stringTemplate("cast(null as text)");
|
||||
|
||||
public ErrorLogRepositoryImpl(JPAQueryFactory queryFactory) {
|
||||
super(AuditLogEntity.class);
|
||||
this.queryFactory = queryFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<ErrorLogDto.Basic> findLogByError(ErrorLogDto.ErrorSearchReq searchReq) {
|
||||
Pageable pageable = searchReq.toPageable();
|
||||
@@ -52,7 +58,7 @@ public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
||||
errorLogEntity.errorMessage.as("errorMessage"),
|
||||
errorLogEntity.stackTrace.as("errorDetail"),
|
||||
Expressions.stringTemplate(
|
||||
"to_char({0}, 'YYYY-MM-DD')", errorLogEntity.createdDate)))
|
||||
"to_char({0}, 'YYYY-MM-DD HH24:MI:SS.FF3')", errorLogEntity.createdDate)))
|
||||
.from(errorLogEntity)
|
||||
.leftJoin(auditLogEntity)
|
||||
.on(errorLogEntity.id.eq(auditLogEntity.errorLogUid))
|
||||
@@ -94,12 +100,14 @@ public class ErrorLogRepositoryImpl implements ErrorLogRepositoryCustom {
|
||||
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
|
||||
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
|
||||
.createdDate
|
||||
.goe(ZonedDateTime.from(startDateTime))
|
||||
.and(auditLogEntity.createdDate.lt(ZonedDateTime.from(endDateTime)));
|
||||
.goe(startDateTime)
|
||||
.and(auditLogEntity.createdDate.lt(endDateTime));
|
||||
}
|
||||
|
||||
private BooleanExpression eventStatusEqFailed() {
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
package com.kamco.cd.training.postgres.repository.model;
|
||||
|
||||
import com.kamco.cd.training.postgres.entity.ModelDatasetMappEntity;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface ModelDatasetMappRepositoryCustom {
|
||||
List<ModelDatasetMappEntity> findByModelUid(Long modelId);
|
||||
|
||||
List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId);
|
||||
|
||||
List<ModelTrainLinkDto> findDatasetValPath(Long modelId);
|
||||
|
||||
List<ModelTrainLinkDto> findDatasetTestPath(Long modelId);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
package com.kamco.cd.training.postgres.repository.model;
|
||||
|
||||
import static com.kamco.cd.training.postgres.entity.QDatasetEntity.datasetEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.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.postgres.entity.ModelDatasetMappEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QDatasetObjEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QDatasetTestObjEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QDatasetValObjEntity;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||
import com.querydsl.core.types.Projections;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -16,10 +24,142 @@ public class ModelDatasetMappRepositoryImpl implements ModelDatasetMappRepositor
|
||||
|
||||
@Override
|
||||
public List<ModelDatasetMappEntity> findByModelUid(Long modelId) {
|
||||
queryFactory
|
||||
return queryFactory
|
||||
.select(modelDatasetMappEntity)
|
||||
.from(modelDatasetMappEntity)
|
||||
.where(modelDatasetMappEntity.modelUid.eq(modelId));
|
||||
return List.of();
|
||||
.where(modelDatasetMappEntity.modelUid.eq(modelId))
|
||||
.fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ModelTrainLinkDto> findDatasetTrainPath(Long modelId) {
|
||||
|
||||
QDatasetObjEntity datasetObjEntity = QDatasetObjEntity.datasetObjEntity;
|
||||
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelTrainLinkDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.trainType,
|
||||
modelMasterEntity.modelNo,
|
||||
modelDatasetMappEntity.datasetUid,
|
||||
datasetObjEntity.targetClassCd,
|
||||
datasetObjEntity.comparePath,
|
||||
datasetObjEntity.targetPath,
|
||||
datasetObjEntity.labelPath,
|
||||
datasetObjEntity.geojsonPath,
|
||||
datasetEntity.uid))
|
||||
.from(modelMasterEntity)
|
||||
.leftJoin(modelDatasetMappEntity)
|
||||
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||
.leftJoin(datasetEntity)
|
||||
.on(datasetEntity.id.eq(modelDatasetMappEntity.datasetUid))
|
||||
.leftJoin(datasetObjEntity)
|
||||
.on(
|
||||
datasetObjEntity
|
||||
.datasetUid
|
||||
.eq(modelDatasetMappEntity.datasetUid)
|
||||
.and(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G1.getId())
|
||||
.and(datasetObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
||||
.or(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G2.getId())
|
||||
.and(datasetObjEntity.targetClassCd.upper().eq("WASTE")))
|
||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ModelTrainLinkDto> findDatasetValPath(Long modelId) {
|
||||
|
||||
QDatasetValObjEntity datasetValObjEntity = QDatasetValObjEntity.datasetValObjEntity;
|
||||
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelTrainLinkDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.trainType,
|
||||
modelMasterEntity.modelNo,
|
||||
modelDatasetMappEntity.datasetUid,
|
||||
datasetValObjEntity.targetClassCd,
|
||||
datasetValObjEntity.comparePath,
|
||||
datasetValObjEntity.targetPath,
|
||||
datasetValObjEntity.labelPath,
|
||||
datasetValObjEntity.geojsonPath,
|
||||
datasetEntity.uid))
|
||||
.from(modelMasterEntity)
|
||||
.leftJoin(modelDatasetMappEntity)
|
||||
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||
.leftJoin(datasetEntity)
|
||||
.on(datasetEntity.id.eq(modelDatasetMappEntity.datasetUid))
|
||||
.leftJoin(datasetValObjEntity)
|
||||
.on(
|
||||
datasetValObjEntity
|
||||
.datasetUid
|
||||
.eq(modelDatasetMappEntity.datasetUid)
|
||||
.and(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G1.getId())
|
||||
.and(datasetValObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
||||
.or(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G2.getId())
|
||||
.and(datasetValObjEntity.targetClassCd.upper().eq("WASTE")))
|
||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ModelTrainLinkDto> findDatasetTestPath(Long modelId) {
|
||||
|
||||
QDatasetTestObjEntity datasetTestObjEntity = QDatasetTestObjEntity.datasetTestObjEntity;
|
||||
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelTrainLinkDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.trainType,
|
||||
modelMasterEntity.modelNo,
|
||||
modelDatasetMappEntity.datasetUid,
|
||||
datasetTestObjEntity.targetClassCd,
|
||||
datasetTestObjEntity.comparePath,
|
||||
datasetTestObjEntity.targetPath,
|
||||
datasetTestObjEntity.labelPath,
|
||||
datasetTestObjEntity.geojsonPath,
|
||||
datasetEntity.uid))
|
||||
.from(modelMasterEntity)
|
||||
.leftJoin(modelDatasetMappEntity)
|
||||
.on(modelDatasetMappEntity.modelUid.eq(modelMasterEntity.id))
|
||||
.leftJoin(datasetEntity)
|
||||
.on(datasetEntity.id.eq(modelDatasetMappEntity.datasetUid))
|
||||
.leftJoin(datasetTestObjEntity)
|
||||
.on(
|
||||
datasetTestObjEntity
|
||||
.datasetUid
|
||||
.eq(modelDatasetMappEntity.datasetUid)
|
||||
.and(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G1.getId())
|
||||
.and(datasetTestObjEntity.targetClassCd.upper().in("CONTAINER", "BUILDING"))
|
||||
.or(
|
||||
modelMasterEntity
|
||||
.modelNo
|
||||
.eq(ModelType.G2.getId())
|
||||
.and(datasetTestObjEntity.targetClassCd.upper().eq("WASTE")))
|
||||
.or(modelMasterEntity.modelNo.eq(ModelType.G3.getId()))))
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,12 @@ 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.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.ModelProgressStepDto;
|
||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -34,4 +36,8 @@ public interface ModelDetailRepositoryCustom {
|
||||
List<ModelTestMetrics> getModelTestMetricResult(UUID uuid);
|
||||
|
||||
ModelBestEpoch getModelTrainBestEpoch(UUID uuid);
|
||||
|
||||
ModelFileInfo getModelTrainFileInfo(UUID uuid);
|
||||
|
||||
List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid);
|
||||
}
|
||||
|
||||
@@ -9,20 +9,24 @@ import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.mode
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsValidationEntity.modelMetricsValidationEntity;
|
||||
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
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.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.ModelProgressStepDto;
|
||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QModelHyperParamEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QModelMasterEntity;
|
||||
import com.querydsl.core.types.Projections;
|
||||
import com.querydsl.jpa.JPAExpressions;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -269,4 +273,86 @@ public class ModelDetailRepositoryImpl implements ModelDetailRepositoryCustom {
|
||||
modelMetricsTrainEntity.epoch.eq(modelMasterEntity.getBestEpoch()))
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelFileInfo getModelTrainFileInfo(UUID uuid) {
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelFileInfo.class,
|
||||
modelMasterEntity
|
||||
.packingState
|
||||
.eq(TrainStatusType.COMPLETED.getId())
|
||||
.coalesce(false),
|
||||
modelMasterEntity.modelVer))
|
||||
.from(modelMasterEntity)
|
||||
.where(modelMasterEntity.uuid.eq(uuid))
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ModelProgressStepDto> findModelTrainProgressInfo(UUID uuid) {
|
||||
ModelMasterEntity entity = findByModelByUUID(uuid);
|
||||
if (entity == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<ModelProgressStepDto> steps = new ArrayList<>();
|
||||
|
||||
// 0단계 : 대기 상태
|
||||
steps.add(
|
||||
ModelProgressStepDto.builder()
|
||||
.step(0)
|
||||
.status(TrainStatusType.READY.getId())
|
||||
.startTime(entity.getCreatedDttm())
|
||||
.endTime(null)
|
||||
.isError(false)
|
||||
.build());
|
||||
|
||||
// 1단계 : Train/Validation 실행
|
||||
boolean step1Active =
|
||||
entity.getStep1StrtDttm() != null
|
||||
&& !TrainStatusType.READY.getId().equals(entity.getStep1State());
|
||||
|
||||
if (step1Active) {
|
||||
steps.add(
|
||||
ModelProgressStepDto.builder()
|
||||
.step(1)
|
||||
.status(entity.getStep1State())
|
||||
.startTime(entity.getStep1StrtDttm())
|
||||
.endTime(entity.getStep1EndDttm())
|
||||
.isError(TrainStatusType.ERROR.getId().equals(entity.getStep1State()))
|
||||
.build());
|
||||
}
|
||||
|
||||
// 2단계 : Test 실행
|
||||
boolean step2Done = entity.getStep2State() != null;
|
||||
|
||||
if (step2Done) {
|
||||
steps.add(
|
||||
ModelProgressStepDto.builder()
|
||||
.step(2)
|
||||
.status(entity.getStep2State())
|
||||
.startTime(entity.getStep2StrtDttm())
|
||||
.endTime(entity.getStep2EndDttm())
|
||||
.isError(TrainStatusType.ERROR.getId().equals(entity.getStep2State()))
|
||||
.build());
|
||||
}
|
||||
|
||||
// 3단계 : 패키징
|
||||
boolean step3Done = entity.getPackingState() != null;
|
||||
|
||||
if (step3Done) {
|
||||
steps.add(
|
||||
ModelProgressStepDto.builder()
|
||||
.step(3)
|
||||
.status(entity.getPackingState())
|
||||
.startTime(entity.getPackingStrtDttm())
|
||||
.endTime(entity.getPackingEndDttm())
|
||||
.isError(TrainStatusType.ERROR.getId().equals(entity.getPackingState()))
|
||||
.build());
|
||||
}
|
||||
|
||||
return steps;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kamco.cd.training.postgres.repository.model;
|
||||
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import java.util.Optional;
|
||||
@@ -15,7 +16,7 @@ public interface ModelMngRepositoryCustom {
|
||||
* @param searchReq
|
||||
* @return
|
||||
*/
|
||||
Page<ModelMasterEntity> findByModels(ModelTrainMngDto.SearchReq searchReq);
|
||||
Page<ListDto> findByModels(ModelTrainMngDto.SearchReq searchReq);
|
||||
|
||||
Optional<ModelMasterEntity> findByUuid(UUID uuid);
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.kamco.cd.training.postgres.repository.model;
|
||||
|
||||
import static com.kamco.cd.training.postgres.entity.QMemberEntity.memberEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelConfigEntity.modelConfigEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelHyperParamEntity.modelHyperParamEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto.ListDto;
|
||||
import com.kamco.cd.training.postgres.entity.ModelMasterEntity;
|
||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import com.querydsl.core.BooleanBuilder;
|
||||
@@ -34,12 +36,16 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Page<ModelMasterEntity> findByModels(ModelTrainMngDto.SearchReq req) {
|
||||
public Page<ListDto> findByModels(ModelTrainMngDto.SearchReq req) {
|
||||
Pageable pageable = req.toPageable();
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (req.getStatus() != null && !req.getStatus().isEmpty()) {
|
||||
builder.and(modelMasterEntity.statusCd.eq(req.getStatus()));
|
||||
builder.and(
|
||||
modelMasterEntity
|
||||
.step1State
|
||||
.eq(req.getStatus())
|
||||
.or(modelMasterEntity.step2State.eq(req.getStatus())));
|
||||
}
|
||||
|
||||
if (req.getModelNo() != null && !req.getModelNo().isEmpty()) {
|
||||
@@ -48,9 +54,36 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
||||
|
||||
builder.and(modelMasterEntity.delYn.isFalse());
|
||||
|
||||
List<ModelMasterEntity> content =
|
||||
List<ListDto> content =
|
||||
queryFactory
|
||||
.selectFrom(modelMasterEntity)
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ListDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.uuid,
|
||||
modelMasterEntity.modelVer,
|
||||
modelMasterEntity.strtDttm,
|
||||
modelMasterEntity.step1StrtDttm,
|
||||
modelMasterEntity.step1EndDttm,
|
||||
modelMasterEntity.step2StrtDttm,
|
||||
modelMasterEntity.step2EndDttm,
|
||||
modelMasterEntity.step1State,
|
||||
modelMasterEntity.step2State,
|
||||
modelMasterEntity.statusCd,
|
||||
modelMasterEntity.trainType,
|
||||
modelMasterEntity.modelNo,
|
||||
modelMasterEntity.currentAttemptId,
|
||||
modelMasterEntity.requestPath,
|
||||
modelMasterEntity.packingState,
|
||||
modelMasterEntity.packingStrtDttm,
|
||||
modelMasterEntity.packingEndDttm,
|
||||
modelConfigEntity.memo,
|
||||
memberEntity.name))
|
||||
.from(modelMasterEntity)
|
||||
.innerJoin(modelConfigEntity)
|
||||
.on(modelMasterEntity.id.eq(modelConfigEntity.model.id))
|
||||
.leftJoin(memberEntity)
|
||||
.on(modelMasterEntity.createdUid.eq(memberEntity.id))
|
||||
.where(builder)
|
||||
.offset(pageable.getOffset())
|
||||
.limit(pageable.getPageSize())
|
||||
@@ -62,6 +95,10 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
||||
queryFactory
|
||||
.select(modelMasterEntity.count())
|
||||
.from(modelMasterEntity)
|
||||
.innerJoin(modelConfigEntity)
|
||||
.on(modelMasterEntity.id.eq(modelConfigEntity.model.id))
|
||||
.leftJoin(memberEntity)
|
||||
.on(modelMasterEntity.createdUid.eq(memberEntity.id))
|
||||
.where(builder)
|
||||
.fetchOne();
|
||||
|
||||
@@ -154,7 +191,11 @@ public class ModelMngRepositoryImpl implements ModelMngRepositoryCustom {
|
||||
return queryFactory
|
||||
.select(modelMasterEntity.id.count())
|
||||
.from(modelMasterEntity)
|
||||
.where(modelMasterEntity.step1State.eq(TrainStatusType.IN_PROGRESS.getId()))
|
||||
.where(
|
||||
modelMasterEntity
|
||||
.step1State
|
||||
.eq(TrainStatusType.IN_PROGRESS.getId())
|
||||
.or(modelMasterEntity.step2State.eq(TrainStatusType.IN_PROGRESS.getId())))
|
||||
.fetchOne();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.kamco.cd.training.postgres.repository.train;
|
||||
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public interface ModelTestMetricsJobRepositoryCustom {
|
||||
@@ -10,4 +13,12 @@ public interface ModelTestMetricsJobRepositoryCustom {
|
||||
List<ResponsePathDto> getTestMetricSaveNotYetModelIds();
|
||||
|
||||
void insertModelMetricsTest(List<Object[]> batchArgs);
|
||||
|
||||
ModelMetricJsonDto getTestMetricPackingInfo(Long modelId);
|
||||
|
||||
ModelTestFileName findModelTestFileNames(Long modelId);
|
||||
|
||||
void updatePackingStart(Long modelId, ZonedDateTime now);
|
||||
|
||||
void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
package com.kamco.cd.training.postgres.repository.train;
|
||||
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMasterEntity.modelMasterEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTestEntity.modelMetricsTestEntity;
|
||||
import static com.kamco.cd.training.postgres.entity.QModelMetricsTrainEntity.modelMetricsTrainEntity;
|
||||
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.postgres.entity.ModelMetricsTestEntity;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.Properties;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||
import com.querydsl.core.types.Projections;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
@@ -42,7 +48,10 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ResponsePathDto.class, modelMasterEntity.id, modelMasterEntity.responsePath))
|
||||
ResponsePathDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.responsePath,
|
||||
modelMasterEntity.uuid))
|
||||
.from(modelMasterEntity)
|
||||
.where(
|
||||
modelMasterEntity.step2EndDttm.isNotNull(),
|
||||
@@ -56,15 +65,107 @@ public class ModelTestMetricsJobRepositoryImpl extends QuerydslRepositorySupport
|
||||
|
||||
@Override
|
||||
public void insertModelMetricsTest(List<Object[]> batchArgs) {
|
||||
String sql =
|
||||
"""
|
||||
insert into tb_model_metrics_test
|
||||
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||
detection_count, gt_count
|
||||
)
|
||||
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""";
|
||||
// AS-IS
|
||||
// String sql =
|
||||
// """
|
||||
// insert into tb_model_metrics_test
|
||||
// (model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||
// detection_count, gt_count
|
||||
// )
|
||||
// values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
// """;
|
||||
//
|
||||
// jdbcTemplate.batchUpdate(sql, batchArgs);
|
||||
|
||||
jdbcTemplate.batchUpdate(sql, batchArgs);
|
||||
// TO-BE: modelId, model(best_fscore_10) 같은 데이터가 있으면 update, 없으면 insert
|
||||
String updateSql =
|
||||
"""
|
||||
UPDATE tb_model_metrics_test
|
||||
SET tp=?, fp=?, fn=?, precisions=?, recall=?, f1_score=?, accuracy=?, iou=?,
|
||||
detection_count=?, gt_count=?
|
||||
WHERE model_id=? AND model=?
|
||||
""";
|
||||
|
||||
String insertSql =
|
||||
"""
|
||||
INSERT INTO tb_model_metrics_test
|
||||
(model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||
detection_count, gt_count)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""";
|
||||
|
||||
// row 단위 처리 (batch 안에서 upsert)
|
||||
for (Object[] row : batchArgs) {
|
||||
// row 순서: (model_id, model, tp, fp, fn, precisions, recall, f1_score, accuracy, iou,
|
||||
// detection_count, gt_count)
|
||||
int updated =
|
||||
jdbcTemplate.update(
|
||||
updateSql, row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10],
|
||||
row[11], row[0], row[1]);
|
||||
|
||||
if (updated == 0) {
|
||||
jdbcTemplate.update(insertSql, row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelMetricJsonDto getTestMetricPackingInfo(Long modelId) {
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelMetricJsonDto.class,
|
||||
modelMasterEntity.modelNo,
|
||||
modelMasterEntity.modelVer,
|
||||
Projections.constructor(
|
||||
Properties.class,
|
||||
modelMetricsTestEntity.f1Score,
|
||||
modelMetricsTestEntity.precisions,
|
||||
modelMetricsTestEntity.recall,
|
||||
modelMetricsTestEntity.iou,
|
||||
modelMetricsTrainEntity.loss)))
|
||||
.from(modelMetricsTestEntity)
|
||||
.innerJoin(modelMasterEntity)
|
||||
.on(modelMetricsTestEntity.model.id.eq(modelMasterEntity.id))
|
||||
.innerJoin(modelMetricsTrainEntity)
|
||||
.on(
|
||||
modelMetricsTestEntity.model.eq(modelMetricsTrainEntity.model),
|
||||
modelMasterEntity.bestEpoch.eq(modelMetricsTrainEntity.epoch))
|
||||
.where(modelMetricsTestEntity.model.id.eq(modelId))
|
||||
.orderBy(modelMetricsTestEntity.createdDttm.desc())
|
||||
.fetchFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelTestFileName findModelTestFileNames(Long modelId) {
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ModelTestFileName.class, modelMetricsTestEntity.model1, modelMasterEntity.modelVer))
|
||||
.from(modelMetricsTestEntity)
|
||||
.innerJoin(modelMasterEntity)
|
||||
.on(modelMetricsTestEntity.model.id.eq(modelMasterEntity.id))
|
||||
.where(modelMetricsTestEntity.model.id.eq(modelId))
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updatePackingStart(Long modelId, ZonedDateTime now) {
|
||||
queryFactory
|
||||
.update(modelMasterEntity)
|
||||
.set(modelMasterEntity.packingStrtDttm, ZonedDateTime.now())
|
||||
.set(modelMasterEntity.packingState, TrainStatusType.READY.getId())
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.execute();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updatePackingEnd(Long modelId, ZonedDateTime now, String failSuccState) {
|
||||
queryFactory
|
||||
.update(modelMasterEntity)
|
||||
.set(modelMasterEntity.packingEndDttm, ZonedDateTime.now())
|
||||
.set(modelMasterEntity.packingState, failSuccState)
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,8 @@ public interface ModelTrainJobRepositoryCustom {
|
||||
int findMaxAttemptNo(Long modelId);
|
||||
|
||||
Optional<ModelTrainJobEntity> findLatestByModelId(Long modelId);
|
||||
|
||||
Optional<ModelTrainJobEntity> findByContainerName(String containerName);
|
||||
|
||||
void insertModelTestTrainingRun(Long modelId, Long jobId, int epoch);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.kamco.cd.training.postgres.repository.train;
|
||||
|
||||
import static com.kamco.cd.training.postgres.entity.QModelTestTrainingRunEntity.modelTestTrainingRunEntity;
|
||||
|
||||
import com.kamco.cd.training.postgres.entity.ModelTrainJobEntity;
|
||||
import com.kamco.cd.training.postgres.entity.QModelTrainJobEntity;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
@@ -40,4 +42,40 @@ public class ModelTrainJobRepositoryImpl implements ModelTrainJobRepositoryCusto
|
||||
|
||||
return Optional.ofNullable(job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ModelTrainJobEntity> findByContainerName(String containerName) {
|
||||
QModelTrainJobEntity j = QModelTrainJobEntity.modelTrainJobEntity;
|
||||
|
||||
ModelTrainJobEntity job =
|
||||
queryFactory
|
||||
.selectFrom(j)
|
||||
.where(j.containerName.eq(containerName))
|
||||
.orderBy(j.id.desc())
|
||||
.fetchFirst();
|
||||
|
||||
return Optional.ofNullable(job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insertModelTestTrainingRun(Long modelId, Long jobId, int epoch) {
|
||||
Integer maxAttemptNo =
|
||||
queryFactory
|
||||
.select(modelTestTrainingRunEntity.attemptNo.max().coalesce(0))
|
||||
.from(modelTestTrainingRunEntity)
|
||||
.where(modelTestTrainingRunEntity.modelId.eq(modelId))
|
||||
.fetchOne();
|
||||
|
||||
int nextAttemptNo = (maxAttemptNo == null ? 1 : maxAttemptNo + 1);
|
||||
|
||||
queryFactory
|
||||
.insert(modelTestTrainingRunEntity)
|
||||
.columns(
|
||||
modelTestTrainingRunEntity.modelId,
|
||||
modelTestTrainingRunEntity.attemptNo,
|
||||
modelTestTrainingRunEntity.jobId,
|
||||
modelTestTrainingRunEntity.epoch)
|
||||
.values(modelId, nextAttemptNo, jobId, epoch)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,6 @@ public interface ModelTrainMetricsJobRepositoryCustom {
|
||||
void updateModelMetricsTrainSaveYn(Long modelId, String stepNo);
|
||||
|
||||
void insertModelMetricsValidation(List<Object[]> batchArgs);
|
||||
|
||||
void updateModelSelectedBestEpoch(Long modelId, Integer epoch);
|
||||
}
|
||||
|
||||
@@ -29,7 +29,10 @@ public class ModelTrainMetricsJobRepositoryImpl extends QuerydslRepositorySuppor
|
||||
return queryFactory
|
||||
.select(
|
||||
Projections.constructor(
|
||||
ResponsePathDto.class, modelMasterEntity.id, modelMasterEntity.responsePath))
|
||||
ResponsePathDto.class,
|
||||
modelMasterEntity.id,
|
||||
modelMasterEntity.responsePath,
|
||||
modelMasterEntity.uuid))
|
||||
.from(modelMasterEntity)
|
||||
.where(
|
||||
modelMasterEntity.step1EndDttm.isNotNull(),
|
||||
@@ -79,4 +82,13 @@ public class ModelTrainMetricsJobRepositoryImpl extends QuerydslRepositorySuppor
|
||||
|
||||
jdbcTemplate.batchUpdate(sql, batchArgs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateModelSelectedBestEpoch(Long modelId, Integer epoch) {
|
||||
queryFactory
|
||||
.update(modelMasterEntity)
|
||||
.set(modelMasterEntity.bestEpoch, epoch)
|
||||
.where(modelMasterEntity.id.eq(modelId))
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kamco.cd.training.train;
|
||||
|
||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||
import com.kamco.cd.training.train.service.DataSetCountersService;
|
||||
import com.kamco.cd.training.train.service.TestJobService;
|
||||
import com.kamco.cd.training.train.service.TrainJobService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -12,6 +13,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -25,6 +28,7 @@ public class TrainApiController {
|
||||
|
||||
private final TrainJobService trainJobService;
|
||||
private final TestJobService testJobService;
|
||||
private final DataSetCountersService dataSetCountersService;
|
||||
|
||||
@Operation(summary = "학습 실행", description = "학습 실행 API")
|
||||
@ApiResponses(
|
||||
@@ -46,6 +50,7 @@ public class TrainApiController {
|
||||
UUID uuid) {
|
||||
Long modelId = trainJobService.getModelIdByUuid(uuid);
|
||||
trainJobService.enqueue(modelId);
|
||||
|
||||
return ApiResponseDto.ok("ok");
|
||||
}
|
||||
|
||||
@@ -186,4 +191,26 @@ public class TrainApiController {
|
||||
|
||||
return ApiResponseDto.ok(trainJobService.createTmpFile(uuid));
|
||||
}
|
||||
|
||||
@Operation(summary = "getCount", description = "getCount 서버 로그확인")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "데이터셋 tmp 파일생성 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = String.class))),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping(path = "/counts/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ApiResponseDto<String> getCount(
|
||||
@Parameter(description = "uuid", example = "e22181eb-2ac4-4100-9941-d06efce25c49")
|
||||
@PathVariable
|
||||
UUID uuid) {
|
||||
Long modelId = trainJobService.getModelIdByUuid(uuid);
|
||||
return ApiResponseDto.ok(dataSetCountersService.getCount(modelId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,4 +13,10 @@ public class EvalRunRequest {
|
||||
private String uuid;
|
||||
private int epoch; // best_changed_fscore_epoch_1.pth
|
||||
private Integer timeoutSeconds;
|
||||
private String datasetFolder;
|
||||
private String outputFolder;
|
||||
|
||||
public String getOutputFolder() {
|
||||
return this.outputFolder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.kamco.cd.training.train.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ModelTrainLinkDto {
|
||||
|
||||
private Long modelId;
|
||||
private String trainType;
|
||||
private String modelNo;
|
||||
private Long datasetId;
|
||||
private String targetClassCd;
|
||||
private String comparePath;
|
||||
private String targetPath;
|
||||
private String labelPath;
|
||||
private String geoJsonPath;
|
||||
private String datasetUid;
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.kamco.cd.training.train.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
@@ -17,5 +20,40 @@ public class ModelTrainMetricsDto {
|
||||
|
||||
private Long modelId;
|
||||
private String responsePath;
|
||||
private UUID uuid;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class ModelMetricJsonDto {
|
||||
|
||||
@JsonProperty("cd_model_type")
|
||||
private String cdModelType;
|
||||
|
||||
@JsonProperty("model_version")
|
||||
private String modelVersion;
|
||||
|
||||
private Properties properties;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class Properties {
|
||||
|
||||
@JsonProperty("f1_score")
|
||||
private Float f1Score;
|
||||
|
||||
private Float precision;
|
||||
private Float recall;
|
||||
private Float loss;
|
||||
private Double iou;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public static class ModelTestFileName {
|
||||
|
||||
private String bestEpochFileName;
|
||||
private String modelVersion;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
@RequiredArgsConstructor
|
||||
public class DataSetCountersService {
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
|
||||
@Value("${train.docker.requestDir}")
|
||||
private String requestDir;
|
||||
|
||||
@Value("${train.docker.basePath}")
|
||||
private String trainBaseDir;
|
||||
|
||||
public String getCount(Long modelId) {
|
||||
ModelTrainMngDto.Basic basic = modelTrainMngCoreService.findModelById(modelId);
|
||||
List<Long> datasetIds = modelTrainMngCoreService.findModelDatasetMapp(modelId);
|
||||
List<String> uids = modelTrainMngCoreService.findDatasetUid(datasetIds);
|
||||
|
||||
StringBuilder allLogs = new StringBuilder();
|
||||
|
||||
try {
|
||||
// request 폴더
|
||||
for (String uid : uids) {
|
||||
Path path = Path.of(requestDir, uid);
|
||||
DatasetCounters counters = countTmpAfterBuild(path);
|
||||
allLogs.append(counters.prints(uid, "REQUEST")).append(System.lineSeparator());
|
||||
}
|
||||
|
||||
// tmp
|
||||
Path tmpPath = Path.of(trainBaseDir, "tmp", basic.getRequestPath());
|
||||
DatasetCounters counters2 = countTmpAfterBuild(tmpPath);
|
||||
allLogs
|
||||
.append(counters2.prints(basic.getRequestPath(), "TMP"))
|
||||
.append(System.lineSeparator());
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
return allLogs.toString();
|
||||
}
|
||||
|
||||
private int countTif(Path dir) throws IOException {
|
||||
if (!Files.isDirectory(dir)) return 0;
|
||||
|
||||
try (var stream = Files.walk(dir)) {
|
||||
return (int)
|
||||
stream.filter(Files::isRegularFile).filter(p -> p.toString().endsWith(".tif")).count();
|
||||
}
|
||||
|
||||
/*
|
||||
대소문자 및 geojson 필요시
|
||||
* try (var stream = Files.walk(dir)) {
|
||||
return (int)
|
||||
stream
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(p -> {
|
||||
String name = p.getFileName().toString().toLowerCase();
|
||||
return name.endsWith(".tif") || name.endsWith(".geojson");
|
||||
})
|
||||
.count();
|
||||
}
|
||||
* */
|
||||
}
|
||||
|
||||
public DatasetCounters countTmpAfterBuild(Path path) throws IOException {
|
||||
|
||||
// input1
|
||||
int in1Train = countTif(path.resolve("train/input1"));
|
||||
int in1Val = countTif(path.resolve("val/input1"));
|
||||
int in1Test = countTif(path.resolve("test/input1"));
|
||||
|
||||
// input2
|
||||
int in2Train = countTif(path.resolve("train/input2"));
|
||||
int in2Val = countTif(path.resolve("val/input2"));
|
||||
int in2Test = countTif(path.resolve("test/input2"));
|
||||
|
||||
List<DatasetCounter> input1List = new ArrayList<>();
|
||||
List<DatasetCounter> input2List = new ArrayList<>();
|
||||
|
||||
input1List.add(new DatasetCounter(in1Train, in1Test, in1Val));
|
||||
input2List.add(new DatasetCounter(in2Train, in2Test, in2Val));
|
||||
|
||||
return new DatasetCounters(input1List, input2List);
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static class DatasetCounter {
|
||||
private int inputTrain = 0;
|
||||
private int inputTest = 0;
|
||||
private int inputVal = 0;
|
||||
|
||||
public DatasetCounter(int inputTrain, int inputTest, int inputVal) {
|
||||
this.inputTrain = inputTrain;
|
||||
this.inputTest = inputTest;
|
||||
this.inputVal = inputVal;
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
public static class DatasetCounters {
|
||||
private List<DatasetCounter> input1 = new ArrayList<>();
|
||||
private List<DatasetCounter> input2 = new ArrayList<>();
|
||||
|
||||
public DatasetCounters(List<DatasetCounter> input1, List<DatasetCounter> input2) {
|
||||
this.input1 = input1;
|
||||
this.input2 = input2;
|
||||
}
|
||||
|
||||
public String prints(String uuid, String type) {
|
||||
int train = 0, test = 0, val = 0;
|
||||
int train2 = 0, test2 = 0, val2 = 0;
|
||||
|
||||
for (DatasetCounter datasetCounter : input1) {
|
||||
train += datasetCounter.inputTrain;
|
||||
test += datasetCounter.inputTest;
|
||||
val += datasetCounter.inputVal;
|
||||
}
|
||||
|
||||
for (DatasetCounter datasetCounter : input2) {
|
||||
train2 += datasetCounter.inputTrain;
|
||||
test2 += datasetCounter.inputTest;
|
||||
val2 += datasetCounter.inputVal;
|
||||
}
|
||||
|
||||
log.info("======== UUID FOLDER COUNT {} : {}", type, uuid);
|
||||
log.info("input 1 = train : {} | val : {} | test : {} ", train, val, test);
|
||||
log.info("input 2 = train : {} | val : {} | test : {} ", train2, val2, test2);
|
||||
log.info(
|
||||
"*total* = train : {} | val : {} | test : {} ",
|
||||
train + train2,
|
||||
val + val2,
|
||||
test + test2);
|
||||
|
||||
return String.format(
|
||||
"======== UUID FOLDER COUNT %s : %s%n"
|
||||
+ "input 1 = train : %s | val : %s | test : %s%n"
|
||||
+ "input 2 = train : %s | val : %s | test : %s%n"
|
||||
+ "*total* = train : %s | val : %s | test : %s",
|
||||
type,
|
||||
uuid,
|
||||
train,
|
||||
val,
|
||||
test,
|
||||
train2,
|
||||
val2,
|
||||
test2,
|
||||
train + train2,
|
||||
val + val2,
|
||||
test + test2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainJobCoreService;
|
||||
import com.kamco.cd.training.train.dto.EvalRunRequest;
|
||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import com.kamco.cd.training.train.dto.TrainRunResult;
|
||||
@@ -9,14 +10,17 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Log4j2
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DockerTrainService {
|
||||
|
||||
// 실행할 Docker 이미지명
|
||||
@@ -43,6 +47,8 @@ public class DockerTrainService {
|
||||
@Value("${train.docker.ipcHost:true}")
|
||||
private boolean ipcHost;
|
||||
|
||||
private final ModelTrainJobCoreService modelTrainJobCoreService;
|
||||
|
||||
/** Docker 학습 컨테이너를 동기 실행 - 요청 스레드에서 docker run 실행 - 컨테이너 종료까지 대기 - stdout/stderr 로그 수집 후 결과 반환 */
|
||||
public TrainRunResult runTrainSync(TrainRunRequest req, String containerName) throws Exception {
|
||||
|
||||
@@ -56,12 +62,42 @@ public class DockerTrainService {
|
||||
ProcessBuilder pb = new ProcessBuilder(cmd);
|
||||
pb.redirectErrorStream(true);
|
||||
|
||||
Process p = pb.start();
|
||||
|
||||
// 로그는 별도 스레드에서 읽기 (메인 스레드가 readLine에 안 걸리게)
|
||||
StringBuilder logBuilder = new StringBuilder();
|
||||
Process p = pb.start();
|
||||
|
||||
Pattern epochPattern = Pattern.compile("(?i)\\bepoch\\s*\\[?(\\d+)\\s*/\\s*(\\d+)\\]?\\b");
|
||||
log.info("[TRAIN-BOOT] docker run started. container={}", containerName);
|
||||
|
||||
try {
|
||||
log.info("[TRAIN-BOOT] pid={}", p.pid()); // Java 9+
|
||||
} catch (Throwable ignore) {
|
||||
}
|
||||
|
||||
try {
|
||||
// 바로 죽었는지 100ms만 체크
|
||||
if (p.waitFor(100, TimeUnit.MILLISECONDS)) {
|
||||
int exit = p.exitValue();
|
||||
String earlyLogs;
|
||||
synchronized (logBuilder) {
|
||||
earlyLogs = logBuilder.toString();
|
||||
}
|
||||
log.error(
|
||||
"[TRAIN-BOOT] docker run exited immediately. container={} exit={}",
|
||||
containerName,
|
||||
exit);
|
||||
log.error("[TRAIN-BOOT] early logs:\n{}", earlyLogs);
|
||||
} else {
|
||||
log.info("[TRAIN-BOOT] docker run is still running. container={}", containerName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("[TRAIN-BOOT] early-exit check failed: {}", e.toString(), e);
|
||||
}
|
||||
|
||||
Pattern epochPattern = Pattern.compile("Epoch\\(train\\)\\s+\\[(\\d+)\\]\\[(\\d+)/(\\d+)\\]");
|
||||
|
||||
// 너무 잦은 업데이트 방지용
|
||||
AtomicInteger lastEpoch = new AtomicInteger(0);
|
||||
AtomicInteger lastIter = new AtomicInteger(0);
|
||||
|
||||
Thread logThread =
|
||||
new Thread(
|
||||
@@ -73,23 +109,40 @@ public class DockerTrainService {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
|
||||
// 1) 로그 누적
|
||||
synchronized (logBuilder) {
|
||||
logBuilder.append(line).append('\n');
|
||||
}
|
||||
|
||||
// 2) epoch 감지 + DB 업데이트
|
||||
Matcher m = epochPattern.matcher(line);
|
||||
if (m.find()) {
|
||||
int currentEpoch = Integer.parseInt(m.group(1));
|
||||
int totalEpoch = Integer.parseInt(m.group(2));
|
||||
int epoch = Integer.parseInt(m.group(1));
|
||||
int iter = Integer.parseInt(m.group(2));
|
||||
int totalIter = Integer.parseInt(m.group(3));
|
||||
|
||||
log.info("[EPOCH] container={} {}/{}", containerName, currentEpoch, totalEpoch);
|
||||
// (선택) maxEpochs는 req에서 알고 있으니 req.getEpochs() 같은 걸로 사용
|
||||
int maxEpochs = req.getEpochs() != null ? req.getEpochs() : 0;
|
||||
|
||||
// TODO 실행중인 에폭 저장 필요하면 만들어야함
|
||||
// TODO 하지만 여기서 트랜젝션 걸리는 db 작업하면 안좋다고하는데..?
|
||||
// modelTrainMngCoreService.updateCurrentEpoch(modelId,
|
||||
// currentEpoch, totalEpoch);
|
||||
// 쓰로틀링: 에폭 끝 or 10 iter마다
|
||||
boolean shouldUpdate = (iter == totalIter) || (iter % 10 == 0);
|
||||
|
||||
// 중복 방지
|
||||
if (shouldUpdate) {
|
||||
int prevEpoch = lastEpoch.get();
|
||||
int prevIter = lastIter.get();
|
||||
if (epoch != prevEpoch || iter != prevIter) {
|
||||
lastEpoch.set(epoch);
|
||||
lastIter.set(iter);
|
||||
|
||||
log.info(
|
||||
"[TRAIN] container={} epoch={} iter={}/{}",
|
||||
containerName,
|
||||
epoch,
|
||||
iter,
|
||||
totalIter);
|
||||
|
||||
modelTrainJobCoreService.updateEpoch(containerName, epoch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -97,21 +150,6 @@ public class DockerTrainService {
|
||||
}
|
||||
},
|
||||
"train-log-" + containerName);
|
||||
// new Thread(
|
||||
// () -> {
|
||||
// try (BufferedReader br =
|
||||
// new BufferedReader(
|
||||
// new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
// String line;
|
||||
// while ((line = br.readLine()) != null) {
|
||||
// synchronized (log) {
|
||||
// log.append(line).append('\n');
|
||||
// }
|
||||
// }
|
||||
// } catch (Exception ignored) {
|
||||
// }
|
||||
// },
|
||||
// "train-log-" + containerName);
|
||||
|
||||
logThread.setDaemon(true);
|
||||
logThread.start();
|
||||
@@ -169,7 +207,7 @@ public class DockerTrainService {
|
||||
|
||||
// 컨테이너 이름 지정
|
||||
c.add("--name");
|
||||
c.add(containerName + "-" + req.getUuid().substring(0, 8));
|
||||
c.add(containerName);
|
||||
|
||||
// 실행 종료 시 자동 삭제
|
||||
c.add("--rm");
|
||||
@@ -206,7 +244,7 @@ public class DockerTrainService {
|
||||
|
||||
// 요청/결과 디렉토리 볼륨 마운트
|
||||
c.add("-v");
|
||||
c.add(requestDir + ":/data");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
|
||||
@@ -272,7 +310,12 @@ public class DockerTrainService {
|
||||
addArg(c, "--saturation-range", req.getSaturationRange());
|
||||
addArg(c, "--hue-delta", req.getHueDelta());
|
||||
|
||||
addArg(c, "--resume-from", req.getResumeFrom());
|
||||
if (req.getResumeFrom() != null && !req.getResumeFrom().isBlank()) {
|
||||
c.add("--resume");
|
||||
addArg(c, "--load-from", req.getResumeFrom());
|
||||
}
|
||||
|
||||
addArg(c, "--save-interval", 1);
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -341,7 +384,6 @@ public class DockerTrainService {
|
||||
synchronized (log) {
|
||||
logs = log.toString();
|
||||
}
|
||||
|
||||
return new TrainRunResult(null, containerName, -1, "TIMEOUT", logs);
|
||||
}
|
||||
|
||||
@@ -376,30 +418,28 @@ public class DockerTrainService {
|
||||
|
||||
c.add("docker");
|
||||
c.add("run");
|
||||
c.add("--name");
|
||||
c.add(containerName + "=" + req.getUuid().substring(0, 8));
|
||||
c.add("--rm");
|
||||
|
||||
c.add("--gpus");
|
||||
c.add("all");
|
||||
if (ipcHost) c.add("--ipc=host");
|
||||
c.add("--ipc=host");
|
||||
c.add("--shm-size=" + shmSize);
|
||||
|
||||
c.add("-v");
|
||||
c.add(requestDir + ":/data");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
|
||||
c.add(image);
|
||||
c.add("kamco-cd-train:latest");
|
||||
|
||||
c.add("python");
|
||||
c.add("/workspace/change-detection-code/run_evaluation_pipeline.py");
|
||||
|
||||
c.add("--dataset_dir");
|
||||
c.add("/data/" + uuid);
|
||||
addArg(c, "--dataset-folder", req.getDatasetFolder());
|
||||
addArg(c, "--output-folder", req.getOutputFolder());
|
||||
|
||||
c.add("--model");
|
||||
c.add("/checkpoints/" + uuid + "/" + modelFile);
|
||||
c.add("--epoch");
|
||||
c.add(modelFile);
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.postgres.core.ModelTestMetricsJobCoreService;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelMetricJsonDto;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ModelTestFileName;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainMetricsDto.ResponsePathDto;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
@@ -27,6 +41,13 @@ public class ModelTestMetricsJobService {
|
||||
@Value("${spring.profiles.active}")
|
||||
private String profile;
|
||||
|
||||
// 학습 결과가 저장될 호스트 디렉토리
|
||||
@Value("${train.docker.responseDir}")
|
||||
private String responseDir;
|
||||
|
||||
@Value("${file.pt-path}")
|
||||
private String ptPathDir;
|
||||
|
||||
/**
|
||||
* 실행중인 profile
|
||||
*
|
||||
@@ -36,8 +57,8 @@ public class ModelTestMetricsJobService {
|
||||
return "local".equalsIgnoreCase(profile);
|
||||
}
|
||||
|
||||
// @Scheduled(cron = "0 * * * * *")
|
||||
public void findTestValidMetricCsvFiles() {
|
||||
// @Scheduled(cron = "0 * * * * *")
|
||||
public void findTestValidMetricCsvFiles() throws IOException {
|
||||
// if (isLocalProfile()) {
|
||||
// return;
|
||||
// }
|
||||
@@ -51,7 +72,7 @@ public class ModelTestMetricsJobService {
|
||||
|
||||
for (ResponsePathDto modelInfo : modelIds) {
|
||||
|
||||
String testPath = modelInfo.getResponsePath() + "/metrics/test.csv";
|
||||
String testPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/test.csv";
|
||||
try (BufferedReader reader =
|
||||
Files.newBufferedReader(Paths.get(testPath), StandardCharsets.UTF_8); ) {
|
||||
|
||||
@@ -92,11 +113,116 @@ public class ModelTestMetricsJobService {
|
||||
|
||||
modelTestMetricsJobCoreService.insertModelMetricsTest(batchArgs);
|
||||
|
||||
// test.csv 파일 읽어서 저장한 여부로만 사용하기
|
||||
modelTestMetricsJobCoreService.updateModelMetricsTrainSaveYn(
|
||||
modelInfo.getModelId(), "step2");
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
modelTestMetricsJobCoreService.updateModelMetricsTrainSaveYn(modelInfo.getModelId(), "step2");
|
||||
// 패키징할 파일 만들기
|
||||
modelTestMetricsJobCoreService.updatePackingStart(
|
||||
modelInfo.getModelId(), ZonedDateTime.now());
|
||||
|
||||
ModelMetricJsonDto jsonDto =
|
||||
modelTestMetricsJobCoreService.getTestMetricPackingInfo(modelInfo.getModelId());
|
||||
try {
|
||||
writeJsonFile(
|
||||
jsonDto,
|
||||
Paths.get(
|
||||
responseDir
|
||||
+ "/"
|
||||
+ modelInfo.getUuid()
|
||||
+ "/"
|
||||
+ jsonDto.getModelVersion()
|
||||
+ ".json"));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
|
||||
|
||||
ModelTestFileName fileInfo =
|
||||
modelTestMetricsJobCoreService.findModelTestFileNames(modelInfo.getModelId());
|
||||
|
||||
Path zipPath =
|
||||
Paths.get(
|
||||
responseDir + "/" + modelInfo.getUuid() + "/" + fileInfo.getModelVersion() + ".zip");
|
||||
Set<String> targetNames =
|
||||
Set.of(
|
||||
"model_config.py",
|
||||
fileInfo.getBestEpochFileName() + ".pth",
|
||||
fileInfo.getModelVersion() + ".json");
|
||||
|
||||
List<Path> files = new ArrayList<>();
|
||||
try (Stream<Path> s = Files.list(responsePath)) {
|
||||
files.addAll(
|
||||
s.filter(Files::isRegularFile)
|
||||
.filter(p -> targetNames.contains(p.getFileName().toString()))
|
||||
.collect(Collectors.toList()));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try (Stream<Path> s = Files.list(Path.of(ptPathDir))) {
|
||||
files.addAll(
|
||||
s.filter(Files::isRegularFile)
|
||||
.limit(1) // yolov8_6th-6m.pt 파일 1개만
|
||||
.collect(Collectors.toList()));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
zipFiles(files, zipPath);
|
||||
|
||||
modelTestMetricsJobCoreService.updatePackingEnd(
|
||||
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.COMPLETED.getId());
|
||||
} catch (IOException e) {
|
||||
modelTestMetricsJobCoreService.updatePackingEnd(
|
||||
modelInfo.getModelId(), ZonedDateTime.now(), TrainStatusType.ERROR.getId());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeJsonFile(Object data, Path outputPath) throws IOException {
|
||||
|
||||
Path parent = outputPath.getParent();
|
||||
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
try (OutputStream os =
|
||||
Files.newOutputStream(
|
||||
outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
objectMapper.writeValue(os, data);
|
||||
}
|
||||
}
|
||||
|
||||
private void zipFiles(List<Path> files, Path zipPath) throws IOException {
|
||||
|
||||
Path parent = zipPath.getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipPath))) {
|
||||
|
||||
for (Path file : files) {
|
||||
|
||||
ZipEntry entry = new ZipEntry(file.getFileName().toString());
|
||||
zos.putNextEntry(entry);
|
||||
|
||||
Files.copy(file, zos);
|
||||
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,14 @@ import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
@@ -55,7 +60,7 @@ public class ModelTrainMetricsJobService {
|
||||
|
||||
for (ResponsePathDto modelInfo : modelIds) {
|
||||
|
||||
String trainPath = responseDir + "{uuid}/metrics/train.csv"; // TODO
|
||||
String trainPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/train.csv";
|
||||
try (BufferedReader reader =
|
||||
Files.newBufferedReader(Paths.get(trainPath), StandardCharsets.UTF_8); ) {
|
||||
|
||||
@@ -65,7 +70,7 @@ public class ModelTrainMetricsJobService {
|
||||
|
||||
for (CSVRecord record : parser) {
|
||||
|
||||
int epoch = Integer.parseInt(record.get("Epoch")) + 1; // TODO : 나중에 AI 개발 완료되면 -1 하기
|
||||
int epoch = Integer.parseInt(record.get("Epoch"));
|
||||
long iteration = Long.parseLong(record.get("Iteration"));
|
||||
double Loss = Double.parseDouble(record.get("Loss"));
|
||||
double LR = Double.parseDouble(record.get("LR"));
|
||||
@@ -80,7 +85,7 @@ public class ModelTrainMetricsJobService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
String validationPath = modelInfo.getResponsePath() + "/metrics/val.csv";
|
||||
String validationPath = responseDir + "/" + modelInfo.getUuid() + "/metrics/val.csv";
|
||||
try (BufferedReader reader =
|
||||
Files.newBufferedReader(Paths.get(validationPath), StandardCharsets.UTF_8); ) {
|
||||
|
||||
@@ -129,6 +134,33 @@ public class ModelTrainMetricsJobService {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Path responsePath = Paths.get(responseDir + "/" + modelInfo.getUuid());
|
||||
Integer epoch = null;
|
||||
boolean exists;
|
||||
Pattern pattern = Pattern.compile("best_changed_fscore_epoch_(\\d+)\\.pth");
|
||||
|
||||
try (Stream<Path> s = Files.list(responsePath)) {
|
||||
epoch =
|
||||
s.filter(Files::isRegularFile)
|
||||
.map(
|
||||
p -> {
|
||||
Matcher matcher = pattern.matcher(p.getFileName().toString());
|
||||
if (matcher.matches()) {
|
||||
return Integer.parseInt(matcher.group(1)); // ← 숫자 부분 추출
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// best_changed_fscore_epoch_숫자.pth -> 숫자 값 가지고 와서 베스트 에폭에 업데이트 하기
|
||||
modelTrainMetricsJobCoreService.updateModelSelectedBestEpoch(modelInfo.getModelId(), epoch);
|
||||
|
||||
modelTrainMetricsJobCoreService.updateModelMetricsTrainSaveYn(
|
||||
modelInfo.getModelId(), "step1");
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainJobCoreService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainJobQueuedEvent;
|
||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
@@ -20,8 +20,8 @@ public class TestJobService {
|
||||
private final ModelTrainJobCoreService modelTrainJobCoreService;
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
private final DockerTrainService dockerTrainService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final DataSetCountersService dataSetCounters;
|
||||
|
||||
@Transactional
|
||||
public Long enqueue(Long modelId, UUID uuid, int epoch) {
|
||||
@@ -29,13 +29,21 @@ public class TestJobService {
|
||||
// 마스터 확인
|
||||
modelTrainMngCoreService.findModelById(modelId);
|
||||
|
||||
// 폴더 카운트
|
||||
dataSetCounters.getCount(modelId);
|
||||
|
||||
// best epoch 업데이트
|
||||
modelTrainMngCoreService.updateModelMasterBestEpoch(modelId, epoch);
|
||||
|
||||
// 파라미터 조회
|
||||
TrainRunRequest trainRunRequest = modelTrainMngCoreService.findTrainRunRequest(modelId);
|
||||
|
||||
Map<String, Object> params = new java.util.LinkedHashMap<>();
|
||||
params.put("jobType", "EVAL");
|
||||
params.put("uuid", String.valueOf(uuid));
|
||||
params.put("epoch", epoch);
|
||||
params.put("datasetFolder", trainRunRequest.getDatasetFolder());
|
||||
params.put("outputFolder", trainRunRequest.getOutputFolder());
|
||||
|
||||
int nextAttemptNo = modelTrainJobCoreService.findMaxAttemptNo(modelId) + 1;
|
||||
|
||||
@@ -46,6 +54,9 @@ public class TestJobService {
|
||||
// step2 시작으로 마킹
|
||||
modelTrainMngCoreService.markStep2InProgress(modelId, jobId);
|
||||
|
||||
// test training run 테이블에 적재하기
|
||||
modelTrainJobCoreService.insertModelTestTrainingRun(modelId, jobId, epoch);
|
||||
|
||||
eventPublisher.publishEvent(new ModelTrainJobQueuedEvent(jobId));
|
||||
return jobId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TmpDatasetService {
|
||||
|
||||
@Value("${train.docker.requestDir}")
|
||||
private String requestDir;
|
||||
|
||||
@Value("${train.docker.basePath}")
|
||||
private String trainBaseDir;
|
||||
|
||||
/**
|
||||
* train, val, test 폴더별로 link
|
||||
*
|
||||
* @param uid 임시폴더 uuid
|
||||
* @param type train, val, test
|
||||
* @param links tif pull path
|
||||
* @throws IOException
|
||||
*/
|
||||
public void buildTmpDatasetHardlink(String uid, String type, List<ModelTrainLinkDto> links)
|
||||
throws IOException {
|
||||
|
||||
if (links == null || links.isEmpty()) {
|
||||
throw new IOException("links is empty");
|
||||
}
|
||||
|
||||
Path tmp = Path.of(trainBaseDir, "tmp", uid);
|
||||
|
||||
long hardlinksMade = 0;
|
||||
|
||||
for (ModelTrainLinkDto dto : links) {
|
||||
|
||||
if (type == null) {
|
||||
log.warn("SKIP - trainType null: {}", dto);
|
||||
continue;
|
||||
}
|
||||
|
||||
// type별 디렉토리 생성
|
||||
Files.createDirectories(tmp.resolve(type).resolve("input1"));
|
||||
Files.createDirectories(tmp.resolve(type).resolve("input2"));
|
||||
Files.createDirectories(tmp.resolve(type).resolve("label"));
|
||||
Files.createDirectories(tmp.resolve(type).resolve("label-json"));
|
||||
|
||||
// comparePath → input1
|
||||
hardlinksMade += link(tmp, type, "input1", dto.getComparePath());
|
||||
|
||||
// targetPath → input2
|
||||
hardlinksMade += link(tmp, type, "input2", dto.getTargetPath());
|
||||
|
||||
// labelPath → label
|
||||
hardlinksMade += link(tmp, type, "label", dto.getLabelPath());
|
||||
|
||||
// geoJsonPath -> label-json
|
||||
hardlinksMade += link(tmp, type, "label-json", dto.getGeoJsonPath());
|
||||
}
|
||||
|
||||
if (hardlinksMade == 0) {
|
||||
throw new IOException("No hardlinks created.");
|
||||
}
|
||||
|
||||
log.info("tmp dataset created: {}, hardlinksMade={}", tmp, hardlinksMade);
|
||||
}
|
||||
|
||||
private long link(Path tmp, String type, String part, String fullPath) throws IOException {
|
||||
|
||||
if (fullPath == null || fullPath.isBlank()) return 0;
|
||||
|
||||
Path src = Path.of(fullPath);
|
||||
|
||||
if (!Files.isRegularFile(src)) {
|
||||
log.warn("SKIP (not file): {}", src);
|
||||
return 0;
|
||||
}
|
||||
|
||||
String fileName = src.getFileName().toString();
|
||||
Path dst = tmp.resolve(type).resolve(part).resolve(fileName);
|
||||
|
||||
// 충돌 시 덮어쓰기
|
||||
if (Files.exists(dst)) {
|
||||
Files.delete(dst);
|
||||
}
|
||||
|
||||
Files.createLink(dst, src);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private String safe(String s) {
|
||||
return (s == null || s.isBlank()) ? null : s.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* request 전체 폴더 link
|
||||
*
|
||||
* @param uid
|
||||
* @param datasetUids
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public String buildTmpDatasetSymlink(String uid, List<String> datasetUids) throws IOException {
|
||||
|
||||
log.info("========== buildTmpDatasetHardlink START ==========");
|
||||
log.info("uid={}", uid);
|
||||
log.info("datasetUids={}", datasetUids);
|
||||
log.info("requestDir(raw)={}", requestDir);
|
||||
|
||||
Path BASE = toPath(requestDir);
|
||||
Path tmp = Path.of(trainBaseDir, "tmp", uid);
|
||||
|
||||
log.info("BASE={}", BASE);
|
||||
log.info("BASE exists? {}", Files.isDirectory(BASE));
|
||||
log.info("tmp={}", tmp);
|
||||
|
||||
long noDir = 0, scannedDirs = 0, regularFiles = 0, hardlinksMade = 0;
|
||||
|
||||
// tmp 디렉토리 준비
|
||||
for (String type : List.of("train", "val", "test")) {
|
||||
for (String part : List.of("input1", "input2", "label", "label-json")) {
|
||||
Path dir = tmp.resolve(type).resolve(part);
|
||||
Files.createDirectories(dir);
|
||||
log.info("createDirectories: {}", dir);
|
||||
}
|
||||
}
|
||||
|
||||
// 하드링크는 "같은 파일시스템"에서만 가능하므로 BASE/tmp가 같은 FS인지 미리 확인(권장)
|
||||
try {
|
||||
var baseStore = Files.getFileStore(BASE);
|
||||
var tmpStore = Files.getFileStore(tmp.getParent()); // BASE/tmp
|
||||
if (!baseStore.name().equals(tmpStore.name()) || !baseStore.type().equals(tmpStore.type())) {
|
||||
throw new IOException(
|
||||
"Hardlink requires same filesystem. baseStore="
|
||||
+ baseStore.name()
|
||||
+ "("
|
||||
+ baseStore.type()
|
||||
+ "), tmpStore="
|
||||
+ tmpStore.name()
|
||||
+ "("
|
||||
+ tmpStore.type()
|
||||
+ ")");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// FileStore 비교가 환경마다 애매할 수 있어서, 여기서는 경고만 주고 실제 createLink에서 최종 판단하게 둘 수도 있음.
|
||||
log.warn("FileStore check skipped/failed (will rely on createLink): {}", e.toString());
|
||||
}
|
||||
|
||||
for (String id : datasetUids) {
|
||||
Path srcRoot = BASE.resolve(id);
|
||||
log.info("---- dataset id={} srcRoot={} exists? {}", id, srcRoot, Files.isDirectory(srcRoot));
|
||||
|
||||
for (String type : List.of("train", "val", "test")) {
|
||||
for (String part : List.of("input1", "input2", "label", "label-json")) {
|
||||
|
||||
Path srcDir = srcRoot.resolve(type).resolve(part);
|
||||
if (!Files.isDirectory(srcDir)) {
|
||||
log.warn("SKIP (not directory): {}", srcDir);
|
||||
noDir++;
|
||||
continue;
|
||||
}
|
||||
|
||||
scannedDirs++;
|
||||
log.info("SCAN dir={}", srcDir);
|
||||
|
||||
try (DirectoryStream<Path> stream = Files.newDirectoryStream(srcDir)) {
|
||||
for (Path f : stream) {
|
||||
if (!Files.isRegularFile(f)) {
|
||||
log.debug("skip non-regular file: {}", f);
|
||||
continue;
|
||||
}
|
||||
|
||||
regularFiles++;
|
||||
|
||||
String dstName = id + "__" + f.getFileName();
|
||||
Path dst = tmp.resolve(type).resolve(part).resolve(dstName);
|
||||
|
||||
// dst가 남아있으면 삭제(심볼릭링크든 파일이든)
|
||||
if (Files.exists(dst) || Files.isSymbolicLink(dst)) {
|
||||
Files.delete(dst);
|
||||
log.debug("deleted existing: {}", dst);
|
||||
}
|
||||
|
||||
try {
|
||||
// 하드링크 생성 (dst가 새 파일로 생기지만 inode는 f와 동일)
|
||||
Files.createLink(dst, f);
|
||||
hardlinksMade++;
|
||||
log.debug("created hardlink: {} => {}", dst, f);
|
||||
} catch (IOException e) {
|
||||
// 여기서 바로 실패시키면 “tmp는 만들었는데 내용은 0개” 같은 상태를 방지할 수 있음
|
||||
log.error("FAILED create hardlink: {} => {}", dst, f, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hardlinksMade == 0) {
|
||||
throw new IOException(
|
||||
"No hardlinks created. regularFiles="
|
||||
+ regularFiles
|
||||
+ ", scannedDirs="
|
||||
+ scannedDirs
|
||||
+ ", noDir="
|
||||
+ noDir);
|
||||
}
|
||||
|
||||
log.info("tmp dataset created: {}", tmp);
|
||||
log.info(
|
||||
"summary: scannedDirs={}, noDir={}, regularFiles={}, hardlinksMade={}",
|
||||
scannedDirs,
|
||||
noDir,
|
||||
regularFiles,
|
||||
hardlinksMade);
|
||||
|
||||
return uid;
|
||||
}
|
||||
|
||||
private static Path toPath(String p) {
|
||||
if (p.startsWith("~/")) {
|
||||
return Paths.get(System.getProperty("user.home")).resolve(p.substring(2)).normalize();
|
||||
}
|
||||
return Paths.get(p).toAbsolutePath().normalize();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
package com.kamco.cd.training.train.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.kamco.cd.training.common.enums.TrainStatusType;
|
||||
import com.kamco.cd.training.common.exception.CustomApiException;
|
||||
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
|
||||
import com.kamco.cd.training.model.service.TmpDatasetService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainJobCoreService;
|
||||
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainJobDto;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainJobQueuedEvent;
|
||||
import com.kamco.cd.training.train.dto.ModelTrainLinkDto;
|
||||
import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -17,12 +18,15 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@Log4j2
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class TrainJobService {
|
||||
@@ -33,6 +37,7 @@ public class TrainJobService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final TmpDatasetService tmpDatasetService;
|
||||
private final DataSetCountersService dataSetCounters;
|
||||
|
||||
// 학습 결과가 저장될 호스트 디렉토리
|
||||
@Value("${train.docker.responseDir}")
|
||||
@@ -46,6 +51,9 @@ public class TrainJobService {
|
||||
@Transactional
|
||||
public Long enqueue(Long modelId) {
|
||||
|
||||
// 폴더 카운트
|
||||
dataSetCounters.getCount(modelId);
|
||||
|
||||
// 마스터 존재 확인(없으면 예외)
|
||||
modelTrainMngCoreService.findModelById(modelId);
|
||||
|
||||
@@ -135,11 +143,7 @@ public class TrainJobService {
|
||||
|
||||
ModelTrainMngDto.Basic master = modelTrainMngCoreService.findModelById(modelId);
|
||||
|
||||
if (TrainStatusType.IN_PROGRESS.getId().equals(master.getStatusCd())) {
|
||||
throw new IllegalStateException("이미 진행중입니다.");
|
||||
}
|
||||
|
||||
var lastJob =
|
||||
ModelTrainJobDto lastJob =
|
||||
modelTrainJobCoreService
|
||||
.findLatestByModelId(modelId)
|
||||
.orElseThrow(() -> new IllegalStateException("이전 실행 이력이 없습니다."));
|
||||
@@ -163,7 +167,7 @@ public class TrainJobService {
|
||||
// 체크포인트 탐지해서 resumeFrom 세팅
|
||||
String resumeFrom = findResumeFromOrNull(nextParams);
|
||||
if (resumeFrom == null) {
|
||||
throw new IllegalStateException("이어하기 체크포인트가 없습니다.");
|
||||
throw new CustomApiException("NOT_FOUND_DATA", HttpStatus.NOT_FOUND, "이어하기 체크포인트가 없습니다.");
|
||||
}
|
||||
nextParams.put("resumeFrom", resumeFrom);
|
||||
nextParams.put("resume", true);
|
||||
@@ -191,49 +195,92 @@ public class TrainJobService {
|
||||
Object out = paramsJson.get("outputFolder");
|
||||
if (out == null) return null;
|
||||
|
||||
String outputFolder = String.valueOf(out).trim(); // uuid
|
||||
String outputFolder = String.valueOf(out).trim();
|
||||
if (outputFolder.isEmpty()) return null;
|
||||
|
||||
// 호스트 기준 경로
|
||||
Path outDir = Paths.get(responseDir, outputFolder);
|
||||
log.info("resume outDir response path: {}", outDir);
|
||||
|
||||
Path last = outDir.resolve("last_checkpoint");
|
||||
log.info("resume last response path: {}", last);
|
||||
|
||||
if (!Files.isRegularFile(last)) return null;
|
||||
|
||||
try {
|
||||
String ckptFile = Files.readString(last).trim(); // epoch_10.pth
|
||||
if (ckptFile.isEmpty()) return null;
|
||||
// last_checkpoint 내용 그대로 읽기
|
||||
String containerPath = Files.readString(last).trim();
|
||||
log.info("resume containerPath: {}", containerPath);
|
||||
|
||||
Path ckptHost = outDir.resolve(ckptFile);
|
||||
if (!Files.isRegularFile(ckptHost)) return null;
|
||||
if (containerPath.isEmpty()) return null;
|
||||
|
||||
// 컨테이너 경로 반환
|
||||
return "/checkpoints/" + outputFolder + "/" + ckptFile;
|
||||
// 호스트 경로로 변환해서 실제 파일 존재 확인
|
||||
String hostPathStr = containerPath.replace("/checkpoints", responseDir);
|
||||
Path hostPath = Paths.get(hostPathStr);
|
||||
|
||||
log.info("resume hostPath: {}", hostPath);
|
||||
|
||||
if (!Files.isRegularFile(hostPath)) return null;
|
||||
|
||||
// 3컨테이너 경로 그대로 반환
|
||||
return containerPath;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("resume error", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UUID createTmpFile(UUID modelUuid) {
|
||||
UUID tmpUuid = UUID.randomUUID();
|
||||
String raw = tmpUuid.toString().toUpperCase().replace("-", "");
|
||||
|
||||
// model id 가져오기
|
||||
Long modelId = modelTrainMngCoreService.findModelIdByUuid(modelUuid);
|
||||
// model 에 연결된 dataset id 가져오기
|
||||
List<Long> datasetIds = modelTrainMngCoreService.findModelDatasetMapp(modelId);
|
||||
|
||||
List<String> uids = modelTrainMngCoreService.findDatasetUid(datasetIds);
|
||||
|
||||
try {
|
||||
// 데이터셋 심볼링크 생성
|
||||
Path path = tmpDatasetService.buildTmpDatasetSymlink(raw, uids);
|
||||
// train path
|
||||
List<ModelTrainLinkDto> trainList = modelTrainMngCoreService.findDatasetTrainPath(modelId);
|
||||
// validation path
|
||||
List<ModelTrainLinkDto> valList = modelTrainMngCoreService.findDatasetValPath(modelId);
|
||||
// test path
|
||||
List<ModelTrainLinkDto> testList = modelTrainMngCoreService.findDatasetTestPath(modelId);
|
||||
|
||||
// train 데이터셋 심볼링크 생성
|
||||
tmpDatasetService.buildTmpDatasetHardlink(raw, "train", trainList);
|
||||
// val 데이터셋 심볼링크 생성
|
||||
tmpDatasetService.buildTmpDatasetHardlink(raw, "val", valList);
|
||||
// test 데이터셋 심볼링크 생성
|
||||
tmpDatasetService.buildTmpDatasetHardlink(raw, "test", testList);
|
||||
|
||||
ModelTrainMngDto.UpdateReq updateReq = new ModelTrainMngDto.UpdateReq();
|
||||
updateReq.setRequestPath(path.toString());
|
||||
updateReq.setRequestPath(raw);
|
||||
|
||||
// 학습모델을 수정한다.
|
||||
modelTrainMngCoreService.updateModelMaster(modelId, updateReq);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
log.error(
|
||||
"createTmpFile failed. modelUuid={}, modelId={}, tmpRaw={}, datasetIdsSize={}, uidsSize={}",
|
||||
modelUuid,
|
||||
modelId,
|
||||
raw,
|
||||
(datasetIds == null ? null : datasetIds.size()),
|
||||
(uids == null ? null : uids.size()),
|
||||
e);
|
||||
|
||||
// 런타임 예외로 래핑하되, 메시지에 핵심 정보 포함
|
||||
throw new IllegalStateException(
|
||||
"tmp dataset build failed: modelUuid="
|
||||
+ modelUuid
|
||||
+ ", modelId="
|
||||
+ modelId
|
||||
+ ", tmpRaw="
|
||||
+ raw,
|
||||
e);
|
||||
}
|
||||
return modelUuid;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,17 +11,21 @@ import com.kamco.cd.training.train.dto.TrainRunRequest;
|
||||
import com.kamco.cd.training.train.dto.TrainRunResult;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
@Log4j2
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class TrainJobWorker {
|
||||
|
||||
private final ModelTrainJobCoreService modelTrainJobCoreService;
|
||||
private final ModelTrainMngCoreService modelTrainMngCoreService;
|
||||
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||
private final ModelTestMetricsJobService modelTestMetricsJobService;
|
||||
private final DockerTrainService dockerTrainService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -56,9 +60,9 @@ public class TrainJobWorker {
|
||||
totalEpoch = Integer.parseInt(params.get("totalEpoch").toString());
|
||||
}
|
||||
}
|
||||
|
||||
log.info("[JOB] markRunning start jobId={}, containerName={}", jobId, containerName);
|
||||
modelTrainJobCoreService.markRunning(jobId, containerName, null, "TRAIN_WORKER", totalEpoch);
|
||||
|
||||
log.info("[JOB] markRunning done jobId={}", jobId);
|
||||
try {
|
||||
TrainRunResult result;
|
||||
|
||||
@@ -66,8 +70,16 @@ public class TrainJobWorker {
|
||||
modelTrainMngCoreService.markStep2InProgress(modelId, jobId);
|
||||
String uuid = String.valueOf(params.get("uuid"));
|
||||
int epoch = (int) params.get("epoch");
|
||||
String datasetFolder = String.valueOf(params.get("datasetFolder"));
|
||||
String outputFolder = String.valueOf(params.get("outputFolder"));
|
||||
|
||||
EvalRunRequest evalReq = new EvalRunRequest(uuid, epoch, null);
|
||||
EvalRunRequest evalReq = new EvalRunRequest();
|
||||
evalReq.setUuid(uuid);
|
||||
evalReq.setEpoch(epoch);
|
||||
evalReq.setTimeoutSeconds(null);
|
||||
evalReq.setDatasetFolder(datasetFolder);
|
||||
evalReq.setOutputFolder(outputFolder);
|
||||
log.info("[JOB] selected test epoch={}", epoch);
|
||||
result = dockerTrainService.runEvalSync(evalReq, containerName);
|
||||
|
||||
} else {
|
||||
@@ -90,11 +102,14 @@ public class TrainJobWorker {
|
||||
|
||||
if (isEval) {
|
||||
modelTrainMngCoreService.markStep2Success(modelId);
|
||||
modelTestMetricsJobService.findTestValidMetricCsvFiles();
|
||||
} else {
|
||||
modelTrainMngCoreService.markStep1Success(modelId);
|
||||
modelTrainMetricsJobService.findTrainValidMetricCsvFiles();
|
||||
}
|
||||
|
||||
} else {
|
||||
String failMsg = result.getStatus() + "\n" + result.getLogs();
|
||||
modelTrainJobCoreService.markFailed(
|
||||
jobId, result.getExitCode(), result.getStatus() + "\n" + result.getLogs());
|
||||
|
||||
@@ -106,7 +121,7 @@ public class TrainJobWorker {
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
modelTrainJobCoreService.markFailed(jobId, null, e.toString());
|
||||
modelTrainJobCoreService.markFailed(jobId, null, e.getMessage());
|
||||
|
||||
if ("EVAL".equals(params.get("jobType"))) {
|
||||
modelTrainMngCoreService.markStep2Error(modelId, e.getMessage());
|
||||
|
||||
@@ -58,11 +58,15 @@ file:
|
||||
dataset-dir: /home/kcomu/data/request/
|
||||
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||
|
||||
pt-path: /home/kcomu/data/response/v6-cls-checkpoints/
|
||||
pt-FileName: yolov8_6th-6m.pt
|
||||
|
||||
train:
|
||||
docker:
|
||||
image: "kamco-cd-train:love_latest"
|
||||
requestDir: "/home/kcomu/data/request"
|
||||
responseDir: "/home/kcomu/data/response"
|
||||
containerPrefix: "kamco-cd-train"
|
||||
shmSize: "16g"
|
||||
image: kamco-cd-train:latest
|
||||
requestDir: /home/kcomu/data/request
|
||||
responseDir: /home/kcomu/data/response
|
||||
basePath: /home/kcomu/data
|
||||
containerPrefix: kamco-cd-train
|
||||
shmSize: 16g
|
||||
ipcHost: true
|
||||
|
||||
@@ -46,11 +46,27 @@ springdoc:
|
||||
member:
|
||||
init_password: kamco1234!
|
||||
|
||||
swagger:
|
||||
local-port: 9080
|
||||
|
||||
file:
|
||||
sync-root-dir: /app/original-images/
|
||||
sync-tmp-dir: ${file.sync-root-dir}tmp/
|
||||
sync-file-extention: tfw,tif
|
||||
|
||||
dataset-dir: /home/kcomu/data/request/
|
||||
dataset-tmp-dir: ${file.dataset-dir}tmp/
|
||||
|
||||
pt-path: /home/kcomu/data/response/v6-cls-checkpoints/
|
||||
pt-FileName: yolov8_6th-6m.pt
|
||||
|
||||
train:
|
||||
docker:
|
||||
image: "kamco-cd-train:latest"
|
||||
requestDir: "/home/kcomu/data/request"
|
||||
responseDir: "/home/kcomu/data/response"
|
||||
containerPrefix: "kamco-cd-train"
|
||||
shmSize: "16g"
|
||||
image: kamco-cd-train:latest
|
||||
requestDir: /home/kcomu/data/request
|
||||
responseDir: /home/kcomu/data/response
|
||||
basePath: /home/kcomu/data
|
||||
containerPrefix: kamco-cd-train
|
||||
shmSize: 16g
|
||||
ipcHost: true
|
||||
|
||||
|
||||
@@ -51,8 +51,8 @@ logging:
|
||||
level:
|
||||
org:
|
||||
springframework:
|
||||
web: DEBUG
|
||||
security: DEBUG
|
||||
web: INFO
|
||||
security: INFO
|
||||
root: INFO
|
||||
# actuator
|
||||
management:
|
||||
|
||||
87
src/main/resources/static/download_progress_test.html
Normal file
87
src/main/resources/static/download_progress_test.html
Normal file
@@ -0,0 +1,87 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>학습데이터 ZIP 다운로드</title>
|
||||
</head>
|
||||
<body>
|
||||
<h3>학습데이터 ZIP 다운로드</h3>
|
||||
|
||||
UUID:
|
||||
<input id="uuid" value="95cb116c-380a-41c0-98d8-4d1142f15bbf" />
|
||||
<br><br>
|
||||
modelVer:
|
||||
<input id="moderVer" value="G2.HPs_0001.95cb116c-380a-41c0-98d8-4d1142f15bbf" />
|
||||
<br><br>
|
||||
|
||||
JWT Token:
|
||||
<input id="token" style="width:600px;" placeholder="Bearer 토큰 붙여넣기" />
|
||||
<br><br>
|
||||
|
||||
<button onclick="download()">다운로드</button>
|
||||
|
||||
<br><br>
|
||||
<progress id="bar" value="0" max="100" style="width:400px;"></progress>
|
||||
<div id="status"></div>
|
||||
|
||||
<script>
|
||||
async function download() {
|
||||
const uuid = document.getElementById("uuid").value.trim();
|
||||
const moderVer = document.getElementById("moderVer").value.trim();
|
||||
const token = document.getElementById("token").value.trim();
|
||||
|
||||
if (!uuid) {
|
||||
alert("UUID 입력하세요");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
alert("토큰 입력하세요");
|
||||
return;
|
||||
}
|
||||
|
||||
const url = `/api/models/download/${uuid}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"Authorization": token.startsWith("Bearer ")
|
||||
? token
|
||||
: `Bearer ${token}`,
|
||||
"kamco-download-uuid": uuid
|
||||
}
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
document.getElementById("status").innerText =
|
||||
"실패: " + res.status;
|
||||
return;
|
||||
}
|
||||
|
||||
const total = parseInt(res.headers.get("Content-Length") || "0", 10);
|
||||
const reader = res.body.getReader();
|
||||
const chunks = [];
|
||||
let received = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
received += value.length;
|
||||
|
||||
if (total) {
|
||||
document.getElementById("bar").value =
|
||||
(received / total) * 100;
|
||||
}
|
||||
}
|
||||
|
||||
const blob = new Blob(chunks);
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = moderVer + ".zip";
|
||||
a.click();
|
||||
|
||||
document.getElementById("status").innerText = "완료 ✅";
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user