Compare commits
7 Commits
feat/train
...
a4b5e20db2
| Author | SHA1 | Date | |
|---|---|---|---|
| a4b5e20db2 | |||
| da260f35ea | |||
| 6cf81bf60f | |||
| ed95829a34 | |||
| 52ffe53815 | |||
| 5887a954ea | |||
|
|
72bc2fd47b |
@@ -5,13 +5,7 @@ services:
|
||||
dockerfile: Dockerfile-dev
|
||||
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
||||
container_name: kamco-cd-training-api
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
runtime: nvidia
|
||||
ports:
|
||||
- "7200:8080"
|
||||
environment:
|
||||
|
||||
@@ -5,13 +5,6 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
image: kamco-train-api:${IMAGE_TAG:-latest}
|
||||
container_name: kamco-train-api
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
expose:
|
||||
- "8080"
|
||||
environment:
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
package com.kamco.cd.training.common.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class MonitorDto {
|
||||
|
||||
public int cpu; // CPU 사용률 (%)
|
||||
public long[] memory; // "사용/전체"
|
||||
public int gpu; // 🔥 전체 GPU 평균 (%)
|
||||
public int cpu; // 30초 평균 (%)
|
||||
public String memory; // "3.2/16GB"
|
||||
public List<Gpu> gpus = new ArrayList<>();
|
||||
|
||||
public static class Gpu {
|
||||
public int index;
|
||||
public int util;
|
||||
|
||||
public Gpu(int index, int util) {
|
||||
this.index = index;
|
||||
this.util = util;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,15 +14,20 @@ public class GpuDmonReader {
|
||||
|
||||
// =========================
|
||||
// GPU 사용률 저장소
|
||||
// key: GPU index (0,1,2...)
|
||||
// value: 현재 GPU 사용률 (%)
|
||||
// ConcurrentHashMap → 멀티스레드 안전
|
||||
// - key: GPU index (0,1,2...)
|
||||
// - value: 현재 GPU 사용률 (%)
|
||||
// - ConcurrentHashMap → 멀티스레드 안전
|
||||
// =========================
|
||||
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
||||
|
||||
// =========================
|
||||
// 외부 조회용
|
||||
// SystemMonitorService에서 호출
|
||||
// nvidia-smi dmon 프로세스
|
||||
// - 스트리밍으로 GPU 상태를 계속 받아옴
|
||||
// =========================
|
||||
private volatile Process process;
|
||||
|
||||
// =========================
|
||||
// 외부에서 GPU 사용률 조회
|
||||
// =========================
|
||||
public Map<Integer, Integer> getGpuUtilMap() {
|
||||
return gpuUtilMap;
|
||||
@@ -30,97 +35,123 @@ public class GpuDmonReader {
|
||||
|
||||
// =========================
|
||||
// Bean 초기화 시 실행
|
||||
// - 별도 스레드에서 GPU 모니터링 시작
|
||||
// - 별도 스레드에서 dmon 실행
|
||||
// - 메인 스레드 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);
|
||||
Thread t = new Thread(this::runWithRestart, "gpu-dmon-thread");
|
||||
t.setDaemon(true); // 서버 종료 시 같이 종료
|
||||
t.start();
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 무한 루프
|
||||
// - dmon 실행
|
||||
// - 죽으면 자동 재시작
|
||||
// dmon 실행 + 자동 재시작 루프
|
||||
// - dmon이 죽어도 계속 재시작
|
||||
// =========================
|
||||
private void runLoop() {
|
||||
private void runWithRestart() {
|
||||
boolean firstError = true;
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
runDmon(); // GPU 사용률 수집 시작
|
||||
log.info("Starting nvidia-smi dmon...");
|
||||
runDmon();
|
||||
firstError = true; // 정상 실행되면 초기화
|
||||
|
||||
} catch (Exception e) {
|
||||
// dmon 프로세스 종료되면 여기로 들어옴
|
||||
log.warn("dmon restart: {}", e.getMessage());
|
||||
|
||||
if (firstError) {
|
||||
log.error("nvidia-smi not available. GPU monitoring disabled.", e);
|
||||
firstError = false;
|
||||
} else {
|
||||
log.warn("dmon retry...");
|
||||
}
|
||||
}
|
||||
|
||||
// 5초 대기 후 재시작
|
||||
sleep(5000);
|
||||
try {
|
||||
Thread.sleep(5000); // 5초 후에 시작
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi dmon 실행
|
||||
// - GPU 사용률 스트리밍으로 계속 수신
|
||||
// nvidia-smi dmon 실행 및 출력 파싱
|
||||
// =========================
|
||||
private void runDmon() throws Exception {
|
||||
|
||||
// -s u → GPU utilization만 출력
|
||||
// GPU utilization만 출력 (-s u)
|
||||
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
||||
|
||||
// 프로세스 실행 후 stdout 읽기
|
||||
try (BufferedReader br =
|
||||
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
||||
process = pb.start();
|
||||
|
||||
// dmon은 stdout으로 계속 데이터를 뿌림 (스트리밍)
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
String line;
|
||||
|
||||
// dmon은 계속 출력됨 (스트리밍)
|
||||
while ((line = br.readLine()) != null) {
|
||||
|
||||
// 헤더 제거 (#로 시작)
|
||||
// 디버깅 로그
|
||||
// log.info("RAW: [{}]", line);
|
||||
|
||||
// 헤더 제거
|
||||
if (line.startsWith("#")) continue;
|
||||
|
||||
line = line.trim();
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
// 공백 기준 분리
|
||||
String[] parts = line.split("\\s+");
|
||||
|
||||
// 첫 번째 값이 GPU index인지 확인
|
||||
// GPU index 확인
|
||||
if (!parts[0].matches("\\d+")) continue;
|
||||
|
||||
int index = Integer.parseInt(parts[0]);
|
||||
|
||||
int util = 0;
|
||||
try {
|
||||
// 두 번째 값이 GPU 사용률 (sm)
|
||||
int util = Integer.parseInt(parts[1]);
|
||||
|
||||
// 최신 값 갱신
|
||||
gpuUtilMap.put(index, util);
|
||||
|
||||
} catch (Exception ignored) {
|
||||
// 파싱 실패 시 무시
|
||||
util = Integer.parseInt(parts[1]); // sm 값
|
||||
} catch (Exception e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
gpuUtilMap.put(index, util);
|
||||
}
|
||||
}
|
||||
|
||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||
// → runLoop에서 재시작하도록 예외 발생
|
||||
// 여기 도달했다는 건 dmon 프로세스가 종료된 상태
|
||||
int exitCode = process.waitFor();
|
||||
log.warn("dmon exited. code={}", exitCode);
|
||||
|
||||
// 상위 루프에서 재시작하도록 예외 발생
|
||||
throw new IllegalStateException("dmon stopped");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi 존재 여부 확인
|
||||
// dmon 프로세스 살아있는지 확인
|
||||
// =========================
|
||||
public boolean isAlive() {
|
||||
return process != null && process.isAlive();
|
||||
}
|
||||
|
||||
// =========================
|
||||
// dmon 강제 재시작
|
||||
// - 기존 프로세스 종료 → runWithRestart에서 자동 재시작
|
||||
// =========================
|
||||
public void restart() {
|
||||
try {
|
||||
if (process != null && process.isAlive()) {
|
||||
process.destroy();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNvidiaAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder("which", "nvidia-smi").start();
|
||||
@@ -129,14 +160,4 @@ public class GpuDmonReader {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// sleep 유틸
|
||||
// =========================
|
||||
private void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -18,9 +17,7 @@ import org.springframework.stereotype.Service;
|
||||
public class SystemMonitorService {
|
||||
|
||||
// =========================
|
||||
// CPU 이전값 (delta 계산용)
|
||||
// - /proc/stat은 누적값이기 때문에
|
||||
// - 이전 값과 비교해서 사용률 계산
|
||||
// CPU 이전값 (누적값 → delta 계산용)
|
||||
// =========================
|
||||
private long prevIdle = 0;
|
||||
private long prevTotal = 0;
|
||||
@@ -31,28 +28,27 @@ public class SystemMonitorService {
|
||||
// - GPU: GPU별 30개
|
||||
// =========================
|
||||
private final Deque<Double> cpuHistory = new ArrayDeque<>();
|
||||
|
||||
// key: GPU index
|
||||
// value: 최근 30개 사용률
|
||||
private final Map<Integer, Deque<Integer>> gpuHistory = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, Deque<Integer>> gpuHistory = new java.util.HashMap<>();
|
||||
|
||||
// =========================
|
||||
// GPU 데이터 제공 (dmon reader)
|
||||
// GPU dmon reader (스트리밍)
|
||||
// =========================
|
||||
private final GpuDmonReader gpuReader;
|
||||
|
||||
// =========================
|
||||
// 캐시 (API 응답용)
|
||||
// - 매 요청마다 계산하지 않기 위해 사용
|
||||
// - volatile → 멀티스레드 안전하게 최신값 유지
|
||||
// - volatile로 동시성 안전 보장
|
||||
// =========================
|
||||
private volatile MonitorDto cached = new MonitorDto();
|
||||
|
||||
// =========================
|
||||
// 1초마다 수집
|
||||
// 1초마다 실행되는 수집 스케줄러
|
||||
// =========================
|
||||
@Scheduled(fixedRate = 1000)
|
||||
public void collect() {
|
||||
// 디버깅용
|
||||
// log.info("collect instance = {}", this);
|
||||
try {
|
||||
|
||||
// =====================
|
||||
@@ -66,19 +62,16 @@ public class SystemMonitorService {
|
||||
if (cpuHistory.size() > 30) cpuHistory.poll();
|
||||
|
||||
// =====================
|
||||
// 2. GPU 수집
|
||||
// 2. GPU (dmon 데이터 사용)
|
||||
// =====================
|
||||
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();
|
||||
}
|
||||
@@ -86,7 +79,7 @@ public class SystemMonitorService {
|
||||
// =====================
|
||||
// 3. 캐시 업데이트
|
||||
// =====================
|
||||
updateCache();
|
||||
updateCache(gpuMap);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("collect error", e);
|
||||
@@ -94,9 +87,7 @@ public class SystemMonitorService {
|
||||
}
|
||||
|
||||
// =========================
|
||||
// CPU 사용률 계산
|
||||
// - /proc/stat 사용
|
||||
// - 이전값과의 차이로 계산 (delta 방식)
|
||||
// CPU 사용률 계산 (/proc/stat)
|
||||
// =========================
|
||||
private double readCpu() throws Exception {
|
||||
|
||||
@@ -104,7 +95,8 @@ public class SystemMonitorService {
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("/proc/stat"))) {
|
||||
|
||||
String[] p = br.readLine().split("\\s+");
|
||||
String line = br.readLine();
|
||||
String[] p = line.split("\\s+");
|
||||
|
||||
long user = Long.parseLong(p[1]);
|
||||
long nice = Long.parseLong(p[2]);
|
||||
@@ -117,7 +109,6 @@ public class SystemMonitorService {
|
||||
long total = user + nice + system + idle + iowait + irq + softirq;
|
||||
long idleAll = idle + iowait;
|
||||
|
||||
// 최초 실행 시 기준값만 저장
|
||||
if (prevTotal == 0) {
|
||||
prevTotal = total;
|
||||
prevIdle = idleAll;
|
||||
@@ -132,54 +123,58 @@ public class SystemMonitorService {
|
||||
|
||||
if (totalDiff == 0) return 0;
|
||||
|
||||
// CPU 사용률 (%)
|
||||
return (1.0 - (double) idleDiff / totalDiff) * 100;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("CPU read fail", e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Linux 환경 체크
|
||||
// =========================
|
||||
private boolean isLinux() {
|
||||
return System.getProperty("os.name").toLowerCase().contains("linux");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Memory 조회 (/proc/meminfo)
|
||||
// - OS 값 그대로 사용 (kB)
|
||||
// - [사용량, 전체]
|
||||
// Memory (/proc/meminfo)
|
||||
// - 현재값 (평균 아님)
|
||||
// =========================
|
||||
private long[] readMemory() throws Exception {
|
||||
private String 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};
|
||||
// linux 환경일때만 실행
|
||||
if (!isLinux()) {
|
||||
return "N/A";
|
||||
}
|
||||
|
||||
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+", ""));
|
||||
}
|
||||
}
|
||||
|
||||
br.close();
|
||||
|
||||
long used = total - available;
|
||||
|
||||
// kB → GB
|
||||
double usedGB = used / (1024.0 * 1024);
|
||||
double totalGB = total / (1024.0 * 1024);
|
||||
|
||||
return String.format("%.1f/%.0fGB", usedGB, totalGB);
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 캐시 업데이트
|
||||
// - CPU: 30초 평균
|
||||
// - GPU: 전체 샘플 평균
|
||||
// - Memory: 현재값
|
||||
// =========================
|
||||
private void updateCache() throws Exception {
|
||||
private void updateCache(Map<Integer, Integer> gpuMap) throws Exception {
|
||||
|
||||
MonitorDto dto = new MonitorDto();
|
||||
|
||||
@@ -189,25 +184,23 @@ public class SystemMonitorService {
|
||||
dto.cpu = (int) cpuHistory.stream().mapToDouble(Double::doubleValue).average().orElse(0);
|
||||
|
||||
// =====================
|
||||
// Memory (kB 그대로)
|
||||
// Memory (현재값)
|
||||
// =====================
|
||||
dto.memory = readMemory();
|
||||
|
||||
// =====================
|
||||
// GPU 평균 (🔥 전체 샘플 기준)
|
||||
// GPU 평균 (30초)
|
||||
// =====================
|
||||
int sum = 0;
|
||||
int count = 0;
|
||||
for (Map.Entry<Integer, Deque<Integer>> entry : gpuHistory.entrySet()) {
|
||||
|
||||
for (Deque<Integer> q : gpuHistory.values()) {
|
||||
for (int v : q) {
|
||||
sum += v;
|
||||
count++;
|
||||
}
|
||||
int index = entry.getKey();
|
||||
Deque<Integer> q = entry.getValue();
|
||||
|
||||
int avg = (int) q.stream().mapToInt(i -> i).average().orElse(0);
|
||||
|
||||
dto.gpus.add(new MonitorDto.Gpu(index, avg));
|
||||
}
|
||||
|
||||
dto.gpu = (count == 0) ? 0 : sum / count;
|
||||
|
||||
// =====================
|
||||
// 캐시 교체 (atomic)
|
||||
// =====================
|
||||
@@ -215,8 +208,7 @@ public class SystemMonitorService {
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 외부 조회
|
||||
// - Controller에서 호출
|
||||
// 외부 조회 (Controller에서 호출)
|
||||
// =========================
|
||||
public MonitorDto get() {
|
||||
return cached;
|
||||
|
||||
@@ -16,6 +16,12 @@ public class ApiLogFilter extends OncePerRequestFilter {
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri.contains("/download/")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
|
||||
|
||||
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
|
||||
|
||||
Reference in New Issue
Block a user