26 Commits

Author SHA1 Message Date
3d2a4049d3 시스템 사용율 모니터링 기능 로그 수정 2026-03-19 17:38:30 +09:00
0cbaf53e86 시스템 사용율 모니터링 기능 추가 2026-03-19 17:08:37 +09:00
80fd2bda3e 시스템 사용율 모니터링 기능 테스트 2026-03-19 16:52:26 +09:00
fb647e5991 시스템 사용율 모니터링 기능 테스트 2026-03-19 16:36:39 +09:00
87575a62f7 시스템 사용율 모니터링 기능 테스트 2026-03-19 16:27:05 +09:00
246c11f8b0 시스템 사용율 모니터링 기능 테스트 2026-03-19 16:12:27 +09:00
2c1f9bdf5c 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:46:23 +09:00
5799f7dfb2 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:41:18 +09:00
9f428e9572 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:37:26 +09:00
904968a1be 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:25:20 +09:00
4b44be6a29 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:25:11 +09:00
f9f0662f8e 시스템 사용율 모니터링 기능 테스트 2026-03-19 15:24:03 +09:00
7416327cc3 ai 학습실행 run command 수정 2026-03-11 10:18:33 +09:00
da31bd9d99 ai 학습실행 run command 수정 2026-03-10 23:09:39 +09:00
f3e5347335 ai 학습실행 run command 수정 2026-03-10 22:48:10 +09:00
7d5581f60c 데이터셋 삭제 플래그 추가 2026-03-10 19:09:00 +09:00
b4428217ea hello 2026-03-10 18:01:03 +09:00
8a63fdacdd confict 2026-03-10 17:27:14 +09:00
cb2e42143a confict 2026-03-10 17:23:27 +09:00
997e85c0cc 운영환경처리 2026-03-10 17:22:27 +09:00
731ca59475 심볼릭 링크로 수정 2026-03-10 17:16:54 +09:00
fe6d37456d 하드링크 실패 시 심볼릭 링크로 만들어보기 2026-03-10 16:56:35 +09:00
6c98a48a5d 에러 수정 2026-03-10 16:34:02 +09:00
81b69caa99 운영환경처리 2026-03-10 16:00:23 +09:00
7fce070686 spotless 2026-03-10 15:25:32 +09:00
8d83505ee7 운영환경처리 2026-03-10 15:00:31 +09:00
15 changed files with 473 additions and 133 deletions

View File

@@ -5,6 +5,13 @@ services:
dockerfile: Dockerfile-dev dockerfile: Dockerfile-dev
image: kamco-cd-training-api:${IMAGE_TAG:-latest} image: kamco-cd-training-api:${IMAGE_TAG:-latest}
container_name: kamco-cd-training-api container_name: kamco-cd-training-api
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
ports: ports:
- "7200:8080" - "7200:8080"
environment: environment:

View File

@@ -5,6 +5,13 @@ services:
dockerfile: Dockerfile dockerfile: Dockerfile
image: kamco-train-api:${IMAGE_TAG:-latest} image: kamco-train-api:${IMAGE_TAG:-latest}
container_name: kamco-train-api container_name: kamco-train-api
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
expose: expose:
- "8080" - "8080"
environment: environment:

View File

@@ -0,0 +1,8 @@
package com.kamco.cd.training.common.dto;
public class MonitorDto {
public int cpu; // CPU 사용률 (%)
public long[] memory; // "사용/전체"
public int gpu; // 🔥 전체 GPU 평균 (%)
}

View File

@@ -0,0 +1,142 @@
package com.kamco.cd.training.common.service;
import jakarta.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
@Component
@Log4j2
public class GpuDmonReader {
// =========================
// GPU 사용률 저장소
// key: GPU index (0,1,2...)
// value: 현재 GPU 사용률 (%)
// ConcurrentHashMap → 멀티스레드 안전
// =========================
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
// =========================
// 외부 조회용
// SystemMonitorService에서 호출
// =========================
public Map<Integer, Integer> getGpuUtilMap() {
return gpuUtilMap;
}
// =========================
// Bean 초기화 시 실행
// - 별도 스레드에서 GPU 모니터링 시작
// - 메인 스레드 block 방지
// =========================
@PostConstruct
public void start() {
// nvidia-smi 없는 환경이면 GPU 모니터링 비활성화
if (!isNvidiaAvailable()) {
log.warn("nvidia-smi not found. GPU monitoring disabled.");
return;
}
// 데몬 스레드로 실행 (서버 종료 시 자동 종료)
Thread t = new Thread(this::runLoop, "gpu-dmon-thread");
t.setDaemon(true);
t.start();
}
// =========================
// 무한 루프
// - dmon 실행
// - 죽으면 자동 재시작
// =========================
private void runLoop() {
while (true) {
try {
runDmon(); // GPU 사용률 수집 시작
} catch (Exception e) {
// dmon 프로세스 종료되면 여기로 들어옴
log.warn("dmon restart: {}", e.getMessage());
}
// 5초 대기 후 재시작
sleep(5000);
}
}
// =========================
// nvidia-smi dmon 실행
// - GPU 사용률 스트리밍으로 계속 수신
// =========================
private void runDmon() throws Exception {
// -s u → GPU utilization만 출력
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
// 프로세스 실행 후 stdout 읽기
try (BufferedReader br =
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
String line;
// dmon은 계속 출력됨 (스트리밍)
while ((line = br.readLine()) != null) {
// 헤더 제거 (#로 시작)
if (line.startsWith("#")) continue;
line = line.trim();
if (line.isEmpty()) continue;
// 공백 기준 분리
String[] parts = line.split("\\s+");
// 첫 번째 값이 GPU index인지 확인
if (!parts[0].matches("\\d+")) continue;
int index = Integer.parseInt(parts[0]);
try {
// 두 번째 값이 GPU 사용률 (sm)
int util = Integer.parseInt(parts[1]);
// 최신 값 갱신
gpuUtilMap.put(index, util);
} catch (Exception ignored) {
// 파싱 실패 시 무시
}
}
}
// 여기까지 왔다는 건 dmon 프로세스 종료됨
// → runLoop에서 재시작하도록 예외 발생
throw new IllegalStateException("dmon stopped");
}
// =========================
// nvidia-smi 존재 여부 확인
// =========================
private boolean isNvidiaAvailable() {
try {
Process p = new ProcessBuilder("which", "nvidia-smi").start();
return p.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
// =========================
// sleep 유틸
// =========================
private void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
}
}
}

View File

@@ -0,0 +1,224 @@
package com.kamco.cd.training.common.service;
import com.kamco.cd.training.common.dto.MonitorDto;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Log4j2
public class SystemMonitorService {
// =========================
// CPU 이전값 (delta 계산용)
// - /proc/stat은 누적값이기 때문에
// - 이전 값과 비교해서 사용률 계산
// =========================
private long prevIdle = 0;
private long prevTotal = 0;
// =========================
// 최근 30초 히스토리
// - CPU: 30개 (1초 * 30)
// - GPU: GPU별 30개
// =========================
private final Deque<Double> cpuHistory = new ArrayDeque<>();
// key: GPU index
// value: 최근 30개 사용률
private final Map<Integer, Deque<Integer>> gpuHistory = new ConcurrentHashMap<>();
// =========================
// GPU 데이터 제공 (dmon reader)
// =========================
private final GpuDmonReader gpuReader;
// =========================
// 캐시 (API 응답용)
// - 매 요청마다 계산하지 않기 위해 사용
// - volatile → 멀티스레드 안전하게 최신값 유지
// =========================
private volatile MonitorDto cached = new MonitorDto();
// =========================
// 1초마다 수집
// =========================
@Scheduled(fixedRate = 1000)
public void collect() {
try {
// =====================
// 1. CPU 수집
// =====================
double cpu = readCpu();
cpuHistory.add(cpu);
// 30개 유지 (rolling window)
if (cpuHistory.size() > 30) cpuHistory.poll();
// =====================
// 2. GPU 수집
// =====================
Map<Integer, Integer> gpuMap = gpuReader.getGpuUtilMap();
for (Map.Entry<Integer, Integer> entry : gpuMap.entrySet()) {
int index = entry.getKey();
int util = entry.getValue();
// GPU별 히스토리 생성 및 추가
gpuHistory.computeIfAbsent(index, k -> new ArrayDeque<>()).add(util);
// 30개 유지
Deque<Integer> q = gpuHistory.get(index);
if (q.size() > 30) q.poll();
}
// =====================
// 3. 캐시 업데이트
// =====================
updateCache();
} catch (Exception e) {
log.error("collect error", e);
}
}
// =========================
// CPU 사용률 계산
// - /proc/stat 사용
// - 이전값과의 차이로 계산 (delta 방식)
// =========================
private double readCpu() throws Exception {
if (!isLinux()) return 0;
try (BufferedReader br = new BufferedReader(new FileReader("/proc/stat"))) {
String[] p = br.readLine().split("\\s+");
long user = Long.parseLong(p[1]);
long nice = Long.parseLong(p[2]);
long system = Long.parseLong(p[3]);
long idle = Long.parseLong(p[4]);
long iowait = Long.parseLong(p[5]);
long irq = Long.parseLong(p[6]);
long softirq = Long.parseLong(p[7]);
long total = user + nice + system + idle + iowait + irq + softirq;
long idleAll = idle + iowait;
// 최초 실행 시 기준값만 저장
if (prevTotal == 0) {
prevTotal = total;
prevIdle = idleAll;
return 0;
}
long totalDiff = total - prevTotal;
long idleDiff = idleAll - prevIdle;
prevTotal = total;
prevIdle = idleAll;
if (totalDiff == 0) return 0;
// CPU 사용률 (%)
return (1.0 - (double) idleDiff / totalDiff) * 100;
}
}
// =========================
// Linux 환경 체크
// =========================
private boolean isLinux() {
return System.getProperty("os.name").toLowerCase().contains("linux");
}
// =========================
// Memory 조회 (/proc/meminfo)
// - OS 값 그대로 사용 (kB)
// - [사용량, 전체]
// =========================
private long[] readMemory() throws Exception {
if (!isLinux()) return new long[] {0, 0};
try (BufferedReader br = new BufferedReader(new FileReader("/proc/meminfo"))) {
long total = 0;
long available = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("MemTotal")) {
total = Long.parseLong(line.replaceAll("\\D+", ""));
} else if (line.startsWith("MemAvailable")) {
available = Long.parseLong(line.replaceAll("\\D+", ""));
}
}
long used = total - available;
return new long[] {used, total};
}
}
// =========================
// 캐시 업데이트
// - CPU: 30초 평균
// - GPU: 전체 샘플 평균
// - Memory: 현재값
// =========================
private void updateCache() throws Exception {
MonitorDto dto = new MonitorDto();
// =====================
// CPU 평균 (30초)
// =====================
dto.cpu = (int) cpuHistory.stream().mapToDouble(Double::doubleValue).average().orElse(0);
// =====================
// Memory (kB 그대로)
// =====================
dto.memory = readMemory();
// =====================
// GPU 평균 (🔥 전체 샘플 기준)
// =====================
int sum = 0;
int count = 0;
for (Deque<Integer> q : gpuHistory.values()) {
for (int v : q) {
sum += v;
count++;
}
}
dto.gpu = (count == 0) ? 0 : sum / count;
// =====================
// 캐시 교체 (atomic)
// =====================
this.cached = dto;
}
// =========================
// 외부 조회
// - Controller에서 호출
// =========================
public MonitorDto get() {
return cached;
}
}

View File

@@ -3,7 +3,6 @@ package com.kamco.cd.training.config;
import com.kamco.cd.training.auth.CustomAuthenticationProvider; import com.kamco.cd.training.auth.CustomAuthenticationProvider;
import com.kamco.cd.training.auth.JwtAuthenticationFilter; import com.kamco.cd.training.auth.JwtAuthenticationFilter;
import java.util.List; import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
@@ -26,9 +25,6 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@EnableWebSecurity @EnableWebSecurity
public class SecurityConfig { public class SecurityConfig {
@Value("${cors.allowed-origins}")
private List<String> allowedOrigins;
@Bean @Bean
public SecurityFilterChain securityFilterChain( public SecurityFilterChain securityFilterChain(
org.springframework.security.config.annotation.web.builders.HttpSecurity http, org.springframework.security.config.annotation.web.builders.HttpSecurity http,
@@ -114,7 +110,7 @@ public class SecurityConfig {
CorsConfiguration config = new CorsConfiguration(); // CORS 객체 생성 CorsConfiguration config = new CorsConfiguration(); // CORS 객체 생성
// application.yml에서 환경별로 설정된 도메인 사용 // application.yml에서 환경별로 설정된 도메인 사용
config.setAllowedOriginPatterns(allowedOrigins); config.setAllowedOriginPatterns(List.of("*")); // 도메인 허용
config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*")); // 헤더요청 Authorization, Content-Type, X-Custom-Header config.setAllowedHeaders(List.of("*")); // 헤더요청 Authorization, Content-Type, X-Custom-Header

View File

@@ -57,7 +57,7 @@ public class StartupLogger {
""" """
╔════════════════════════════════════════════════════════════════════════════════╗ ╔════════════════════════════════════════════════════════════════════════════════╗
║ 🚀 APPLICATION STARTUP INFORMATION ║ 🚀 APPLICATION STARTUP INFORMATION 2
╠════════════════════════════════════════════════════════════════════════════════╣ ╠════════════════════════════════════════════════════════════════════════════════╣
║ PROFILE CONFIGURATION ║ ║ PROFILE CONFIGURATION ║
╠────────────────────────────────────────────────────────────────────────────────╣ ╠────────────────────────────────────────────────────────────────────────────────╣

View File

@@ -1,5 +1,7 @@
package com.kamco.cd.training.model; package com.kamco.cd.training.model;
import com.kamco.cd.training.common.dto.MonitorDto;
import com.kamco.cd.training.common.service.SystemMonitorService;
import com.kamco.cd.training.config.api.ApiResponseDto; import com.kamco.cd.training.config.api.ApiResponseDto;
import com.kamco.cd.training.dataset.dto.DatasetDto; import com.kamco.cd.training.dataset.dto.DatasetDto;
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq; import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
@@ -40,6 +42,7 @@ public class ModelTrainMngApiController {
private final ModelTrainMngService modelTrainMngService; private final ModelTrainMngService modelTrainMngService;
private final ModelTrainMetricsJobService modelTrainMetricsJobService; private final ModelTrainMetricsJobService modelTrainMetricsJobService;
private final ModelTestMetricsJobService modelTestMetricsJobService; private final ModelTestMetricsJobService modelTestMetricsJobService;
private final SystemMonitorService systemMonitorService;
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API") @Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
@ApiResponses( @ApiResponses(
@@ -214,4 +217,22 @@ public class ModelTrainMngApiController {
modelTestMetricsJobService.findTestValidMetricCsvFiles(); modelTestMetricsJobService.findTestValidMetricCsvFiles();
return ApiResponseDto.ok(null); return ApiResponseDto.ok(null);
} }
@Operation(summary = "학습서버 시스템 사용율 조회", description = "cpu, gpu, memory 사용율 조회")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "검색 성공",
content =
@Content(
mediaType = "application/json",
schema = @Schema(implementation = Long.class))),
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
})
@GetMapping("/monitor")
public ApiResponseDto<MonitorDto> getSystem() throws IOException {
return ApiResponseDto.ok(systemMonitorService.get());
}
} }

View File

@@ -98,6 +98,8 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
BooleanBuilder builder = new BooleanBuilder(); BooleanBuilder builder = new BooleanBuilder();
builder.and(dataset.deleted.isFalse());
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) { if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
builder.and(dataset.dataType.eq(req.getDataType())); builder.and(dataset.dataType.eq(req.getDataType()));
} }
@@ -249,6 +251,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) { public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
BooleanBuilder builder = new BooleanBuilder(); BooleanBuilder builder = new BooleanBuilder();
builder.and(dataset.deleted.isFalse());
NumberExpression<Long> selectedCnt = null; NumberExpression<Long> selectedCnt = null;
NumberExpression<Long> wasteCnt = NumberExpression<Long> wasteCnt =

View File

@@ -46,10 +46,17 @@ public class DockerTrainService {
@Value("${train.docker.shmSize:16g}") @Value("${train.docker.shmSize:16g}")
private String shmSize; private String shmSize;
// data 경로 request,response 상위 폴더
@Value("${train.docker.basePath}")
private String basePath;
// IPC host 사용 여부 // IPC host 사용 여부
@Value("${train.docker.ipcHost:true}") @Value("${train.docker.ipcHost:true}")
private boolean ipcHost; private boolean ipcHost;
@Value("${spring.profiles.active}")
private String profile;
private final ModelTrainJobCoreService modelTrainJobCoreService; private final ModelTrainJobCoreService modelTrainJobCoreService;
/** /**
@@ -254,7 +261,9 @@ public class DockerTrainService {
// 요청/결과 디렉토리 볼륨 마운트 // 요청/결과 디렉토리 볼륨 마운트
c.add("-v"); c.add("-v");
c.add("/home/kcomu/data" + "/tmp:/data"); c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
c.add("-v");
c.add(basePath + "/tmp:/data");
c.add("-v"); c.add("-v");
c.add(responseDir + ":/checkpoints"); c.add(responseDir + ":/checkpoints");
@@ -273,8 +282,15 @@ public class DockerTrainService {
addArg(c, "--output-folder", req.getOutputFolder()); addArg(c, "--output-folder", req.getOutputFolder());
addArg(c, "--input-size", req.getInputSize()); addArg(c, "--input-size", req.getInputSize());
addArg(c, "--crop-size", req.getCropSize()); addArg(c, "--crop-size", req.getCropSize());
addArg(c, "--batch-size", req.getBatchSize()); // addArg(c, "--batch-size", req.getBatchSize());
addArg(c, "--gpu-ids", req.getGpuIds()); // null // addArg(c, "--gpu-ids", req.getGpuIds()); // null
if ("prod".equals(profile)) {
addArg(c, "--batch-size", 2); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
addArg(c, "--gpus", "1"); // 학습서버 GPU 1개인 곳은 1이어야 함
addArg(c, "--gpu-ids", "0"); // 학습서버 GPU 1개인 곳은 0이어야 함
} else {
addArg(c, "--batch-size", req.getBatchSize()); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
}
addArg(c, "--lr", req.getLearningRate()); addArg(c, "--lr", req.getLearningRate());
addArg(c, "--backbone", req.getBackbone()); addArg(c, "--backbone", req.getBackbone());
addArg(c, "--epochs", req.getEpochs()); addArg(c, "--epochs", req.getEpochs());
@@ -440,11 +456,14 @@ public class DockerTrainService {
c.add("--rm"); c.add("--rm");
c.add("--gpus"); c.add("--gpus");
c.add("all"); c.add("all");
c.add("--ipc=host"); c.add("--ipc=host");
c.add("--shm-size=" + shmSize); c.add("--shm-size=" + shmSize);
c.add("-v"); c.add("-v");
c.add("/home/kcomu/data" + "/tmp:/data"); c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
c.add("-v");
c.add(basePath + "/tmp:/data");
c.add("-v"); c.add("-v");
c.add(responseDir + ":/checkpoints"); c.add(responseDir + ":/checkpoints");

View File

@@ -38,7 +38,7 @@ public class TmpDatasetService {
Path tmp = Path.of(trainBaseDir, "tmp", uid); Path tmp = Path.of(trainBaseDir, "tmp", uid);
long hardlinksMade = 0; long linksMade = 0;
for (ModelTrainLinkDto dto : links) { for (ModelTrainLinkDto dto : links) {
@@ -54,27 +54,26 @@ public class TmpDatasetService {
Files.createDirectories(tmp.resolve(type).resolve("label-json")); Files.createDirectories(tmp.resolve(type).resolve("label-json"));
// comparePath → input1 // comparePath → input1
hardlinksMade += link(tmp, type, "input1", dto.getComparePath()); linksMade += link(tmp, type, "input1", dto.getComparePath());
// targetPath → input2 // targetPath → input2
hardlinksMade += link(tmp, type, "input2", dto.getTargetPath()); linksMade += link(tmp, type, "input2", dto.getTargetPath());
// labelPath → label // labelPath → label
hardlinksMade += link(tmp, type, "label", dto.getLabelPath()); linksMade += link(tmp, type, "label", dto.getLabelPath());
// geoJsonPath -> label-json // geoJsonPath -> label-json
hardlinksMade += link(tmp, type, "label-json", dto.getGeoJsonPath()); linksMade += link(tmp, type, "label-json", dto.getGeoJsonPath());
} }
if (hardlinksMade == 0) { if (linksMade == 0) {
throw new IOException("No hardlinks created."); throw new IOException("No symlinks created.");
} }
log.info("tmp dataset created: {}, hardlinksMade={}", tmp, hardlinksMade); log.info("tmp dataset created: {}, linksMade={}", tmp, linksMade);
} }
private long link(Path tmp, String type, String part, String fullPath) throws IOException { private long link(Path tmp, String type, String part, String fullPath) throws IOException {
if (fullPath == null || fullPath.isBlank()) return 0; if (fullPath == null || fullPath.isBlank()) return 0;
Path src = Path.of(fullPath); Path src = Path.of(fullPath);
@@ -87,20 +86,18 @@ public class TmpDatasetService {
String fileName = src.getFileName().toString(); String fileName = src.getFileName().toString();
Path dst = tmp.resolve(type).resolve(part).resolve(fileName); Path dst = tmp.resolve(type).resolve(part).resolve(fileName);
// 충돌 시 덮어쓰기 Files.createDirectories(dst.getParent());
if (Files.exists(dst)) {
if (Files.exists(dst) || Files.isSymbolicLink(dst)) {
Files.delete(dst); Files.delete(dst);
} }
Files.createLink(dst, src); Files.createSymbolicLink(dst, src);
log.info("symlink created: {} -> {}", dst, src);
return 1; return 1;
} }
private String safe(String s) {
return (s == null || s.isBlank()) ? null : s.trim();
}
/** /**
* request 전체 폴더 link * request 전체 폴더 link
* *
@@ -111,7 +108,7 @@ public class TmpDatasetService {
*/ */
public String buildTmpDatasetSymlink(String uid, List<String> datasetUids) throws IOException { public String buildTmpDatasetSymlink(String uid, List<String> datasetUids) throws IOException {
log.info("========== buildTmpDatasetHardlink START =========="); log.info("========== buildTmpDatasetSymlink START ==========");
log.info("uid={}", uid); log.info("uid={}", uid);
log.info("datasetUids={}", datasetUids); log.info("datasetUids={}", datasetUids);
log.info("requestDir(raw)={}", requestDir); log.info("requestDir(raw)={}", requestDir);
@@ -123,7 +120,7 @@ public class TmpDatasetService {
log.info("BASE exists? {}", Files.isDirectory(BASE)); log.info("BASE exists? {}", Files.isDirectory(BASE));
log.info("tmp={}", tmp); log.info("tmp={}", tmp);
long noDir = 0, scannedDirs = 0, regularFiles = 0, hardlinksMade = 0; long noDir = 0, scannedDirs = 0, regularFiles = 0, symlinksMade = 0;
// tmp 디렉토리 준비 // tmp 디렉토리 준비
for (String type : List.of("train", "val", "test")) { for (String type : List.of("train", "val", "test")) {
@@ -134,26 +131,7 @@ public class TmpDatasetService {
} }
} }
// 하드링크는 "같은 파일시스템"에서만 가능하므로 BASE/tmp가 같은 FS인지 미리 확인(권장) // 심볼릭 링크는 파일시스템이 달라도 작동하므로 FileStore 체크 불필요
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) { for (String id : datasetUids) {
Path srcRoot = BASE.resolve(id); Path srcRoot = BASE.resolve(id);
@@ -191,13 +169,12 @@ public class TmpDatasetService {
} }
try { try {
// 하드링크 생성 (dst가 새 파일로 생기지만 inode는 f와 동일) // 심볼릭 링크 생성 (파일시스템이 달라도 작동)
Files.createLink(dst, f); Files.createSymbolicLink(dst, f);
hardlinksMade++; symlinksMade++;
log.debug("created hardlink: {} => {}", dst, f); log.debug("created symlink: {} => {}", dst, f);
} catch (IOException e) { } catch (IOException e) {
// 여기서 바로 실패시키면 “tmp는 만들었는데 내용은 0개” 같은 상태를 방지할 수 있음 log.error("FAILED create symlink: {} => {}", dst, f, e);
log.error("FAILED create hardlink: {} => {}", dst, f, e);
throw e; throw e;
} }
} }
@@ -206,9 +183,9 @@ public class TmpDatasetService {
} }
} }
if (hardlinksMade == 0) { if (symlinksMade == 0) {
throw new IOException( throw new IOException(
"No hardlinks created. regularFiles=" "No symlinks created. regularFiles="
+ regularFiles + regularFiles
+ ", scannedDirs=" + ", scannedDirs="
+ scannedDirs + scannedDirs
@@ -218,11 +195,11 @@ public class TmpDatasetService {
log.info("tmp dataset created: {}", tmp); log.info("tmp dataset created: {}", tmp);
log.info( log.info(
"summary: scannedDirs={}, noDir={}, regularFiles={}, hardlinksMade={}", "summary: scannedDirs={}, noDir={}, regularFiles={}, symlinksMade={}",
scannedDirs, scannedDirs,
noDir, noDir,
regularFiles, regularFiles,
hardlinksMade); symlinksMade);
return uid; return uid;
} }

View File

@@ -16,7 +16,6 @@ spring:
datasource: datasource:
url: jdbc:postgresql://192.168.2.127:15432/kamco_training_db url: jdbc:postgresql://192.168.2.127:15432/kamco_training_db
# url: jdbc:postgresql://localhost:15432/kamco_training_db
username: kamco_training_user username: kamco_training_user
password: kamco_training_user_2025_!@# password: kamco_training_user_2025_!@#
hikari: hikari:
@@ -48,7 +47,7 @@ member:
init_password: kamco1234! init_password: kamco1234!
swagger: swagger:
local-port: 9080 local-port: 8080
file: file:
sync-root-dir: /app/original-images/ sync-root-dir: /app/original-images/
@@ -71,10 +70,3 @@ train:
shmSize: 16g shmSize: 16g
ipcHost: true ipcHost: true
# CORS 설정 (개발 환경)
cors:
allowed-origins:
- https://kamco.training-dev.gs.dabeeo.com
- http://localhost:3002
- http://192.168.2.109:3002
- http://192.168.2.109:7100

View File

@@ -4,19 +4,16 @@ spring:
on-profile: prod on-profile: prod
jpa: jpa:
show-sql: true show-sql: false # 운영 환경에서는 성능을 위해 비활성화
hibernate: hibernate:
ddl-auto: validate ddl-auto: validate
properties: properties:
hibernate: hibernate:
default_batch_fetch_size: 100 # ✅ 성능 - N+1 쿼리 방지 default_batch_fetch_size: 100 # N+1 쿼리 방지
order_updates: true # ✅ 성능 - 업데이트 순서 정렬로 데드락 방지 order_updates: true # 업데이트 순서 정렬로 데드락 방지
use_sql_comments: true # ⚠️ 선택 - SQL에 주석 추가 (디버깅용)
format_sql: true # ⚠️ 선택 - SQL 포맷팅 (가독성)
datasource: datasource:
url: jdbc:postgresql://kamco-cd-train-db:5432/kamco_training_db url: jdbc:postgresql://kamco-cd-train-db:5432/kamco_training_db
# url: jdbc:postgresql://localhost:15432/kamco_training_db
username: kamco_training_user username: kamco_training_user
password: kamco_training_user_2025_!@# password: kamco_training_user_2025_!@#
hikari: hikari:
@@ -31,13 +28,14 @@ spring:
default-timeout: 300 # 5분 트랜잭션 타임아웃 default-timeout: 300 # 5분 트랜잭션 타임아웃
jwt: jwt:
secret: "kamco_token_dev_dfc6446d-68fc-4eba-a2ff-c80a14a0bf3a" # ⚠️ 운영 환경에서는 반드시 별도의 강력한 시크릿 키를 사용하세요
secret: "kamco_token_prod_CHANGE_THIS_TO_SECURE_SECRET_KEY"
access-token-validity-in-ms: 86400000 # 1일 access-token-validity-in-ms: 86400000 # 1일
refresh-token-validity-in-ms: 604800000 # 7일 refresh-token-validity-in-ms: 604800000 # 7일
token: token:
refresh-cookie-name: kamco # 개발용 쿠키 이름 refresh-cookie-name: kamco
refresh-cookie-secure: false # 로컬 http 테스트면 false refresh-cookie-secure: true # HTTPS 환경에서 필수
springdoc: springdoc:
swagger-ui: swagger-ui:
@@ -70,8 +68,5 @@ train:
shmSize: 16g shmSize: 16g
ipcHost: true ipcHost: true
# CORS 설정 (운영 환경)
cors:
allowed-origins:
- https://train-kamco.com

View File

@@ -10,10 +10,6 @@ spring:
datasource: datasource:
driver-class-name: org.postgresql.Driver driver-class-name: org.postgresql.Driver
hikari: hikari:
jdbc:
time_zone: UTC
batch_size: 50
# 권장 설정
minimum-idle: 2 minimum-idle: 2
maximum-pool-size: 2 maximum-pool-size: 2
connection-timeout: 20000 connection-timeout: 20000
@@ -21,18 +17,11 @@ spring:
max-lifetime: 1800000 max-lifetime: 1800000
leak-detection-threshold: 60000 leak-detection-threshold: 60000
data:
redis:
host: localhost
port: 6379
password:
jpa: jpa:
hibernate: hibernate:
ddl-auto: update # 스키마 자동 관리 활성화 ddl-auto: update # 스키마 자동 관리 활성화
properties: properties:
hibernate: hibernate:
hbm2ddl:
auto: update
javax: javax:
persistence: persistence:
validation: validation:
@@ -55,11 +44,8 @@ logging:
security: INFO security: INFO
root: INFO root: INFO
# CORS 설정
cors:
allowed-origins:
- http://localhost:3000
- http://localhost:3002
# actuator # actuator
management: management:
health: health:
@@ -83,20 +69,3 @@ management:
exposure: exposure:
include: include:
- "health" - "health"
# GeoJSON 파일 모니터링 설정
geojson:
monitor:
watch-directory: ~/geojson/upload
processed-directory: ~/geojson/processed
error-directory: ~/geojson/error
temp-directory: /tmp/geojson_extract
cron-expression: "0/30 * * * * *" # 매 30초마다 실행
supported-extensions:
- zip
- tar
- tar.gz
- tgz
max-file-size: 104857600 # 100MB

View File

@@ -18,12 +18,6 @@ spring:
max-lifetime: 1800000 max-lifetime: 1800000
leak-detection-threshold: 60000 leak-detection-threshold: 60000
data:
redis:
host: localhost
port: 6379
password:
jpa: jpa:
hibernate: hibernate:
ddl-auto: none # 테스트 환경에서는 DDL 자동 생성/수정 비활성화 ddl-auto: none # 테스트 환경에서는 DDL 자동 생성/수정 비활성화
@@ -69,20 +63,6 @@ management:
include: include:
- "health" - "health"
geojson:
monitor:
watch-directory: ~/geojson/upload
processed-directory: ~/geojson/processed
error-directory: ~/geojson/error
temp-directory: /tmp/geojson_extract
cron-expression: "0/30 * * * * *"
supported-extensions:
- zip
- tar
- tar.gz
- tgz
max-file-size: 104857600
jwt: jwt:
secret: "test_secret_key_for_testing_purposes_only" secret: "test_secret_key_for_testing_purposes_only"
access-token-validity-in-ms: 86400000 access-token-validity-in-ms: 86400000