Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import DGU_AI_LAB.admin_be.domain.dashboard.controller.docs.DashBoardApi;
import DGU_AI_LAB.admin_be.domain.dashboard.service.DashboardService;
import DGU_AI_LAB.admin_be.domain.monitoring.service.MyGpuUsageService;
import DGU_AI_LAB.admin_be.domain.requests.dto.response.UserServerResponseDTO;
import DGU_AI_LAB.admin_be.domain.requests.entity.StatusFilter;
import DGU_AI_LAB.admin_be.global.auth.CustomUserDetails;
Expand All @@ -11,6 +12,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -24,6 +26,7 @@
public class DashboardController implements DashBoardApi {

private final DashboardService dashboardService;
private final MyGpuUsageService myGpuUsageService;

/**
* 사용자 신청 현황 서버 목록 조회 API
Expand All @@ -40,4 +43,13 @@ public ResponseEntity<SuccessResponse<?>> getUserServers(
return SuccessResponse.ok(userServers);
}

}
/** 내 서버의 GPU별 사용률·메모리·내 프로세스. 다른 사용자는 사람 수와 메모리 합계만 돌려준다. */
@Override
public ResponseEntity<SuccessResponse<?>> getMyGpuUsage(
@AuthenticationPrincipal CustomUserDetails principal,
@PathVariable Long requestId
) {
return SuccessResponse.ok(myGpuUsageService.getMyGpuUsage(requestId, principal.getUserId()));
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package DGU_AI_LAB.admin_be.domain.dashboard.controller.docs;

import DGU_AI_LAB.admin_be.domain.monitoring.dto.response.MyGpuUsageResponseDTO;
import DGU_AI_LAB.admin_be.domain.requests.dto.response.UserServerResponseDTO;
import DGU_AI_LAB.admin_be.domain.requests.entity.StatusFilter;
import DGU_AI_LAB.admin_be.error.dto.ErrorResponse;
Expand All @@ -14,6 +15,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

Expand All @@ -34,4 +36,25 @@ ResponseEntity<SuccessResponse<?>> getUserServers(
@Parameter(description = "조회할 서버 신청 상태 필터 (PENDING, FULFILLED, DENIED, DELETED, ALL)", required = true, example = "FULFILLED")
@RequestParam(name = "status") StatusFilter statusFilter
);

@Operation(summary = "내 서버 GPU 사용 현황 조회",
description = "내 서버(FULFILLED 신청)의 GPU별 사용률·메모리와 내 프로세스를 조회합니다. 다른 사용자는 사람 수와 메모리 합계로만 담기며 식별 정보는 없습니다. "
+ "프로세스 정보를 읽지 못하면 processesAvailable=false, GPU 지표를 읽지 못하면 502입니다.")
@ApiResponse(responseCode = "200", description = "성공",
content = @Content(schema = @Schema(implementation = MyGpuUsageResponseDTO.class)))
@ApiResponse(responseCode = "401", description = "인증되지 않은 사용자",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "403", description = "다른 사용자의 신청",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "404", description = "없는 신청이거나 실행 중(FULFILLED)이 아닌 신청",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "502", description = "GPU 지표 조회 실패",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@GetMapping("/me/servers/{requestId}/gpus")
ResponseEntity<SuccessResponse<?>> getMyGpuUsage(
@Parameter(hidden = true)
@AuthenticationPrincipal CustomUserDetails principal,
@Parameter(description = "신청 ID", required = true, example = "1")
@PathVariable Long requestId
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,39 +32,54 @@ public PrometheusClient(@Value("${prometheus.base-url}") String baseUrl) {
this.webClient = webClient;
}

/** 시계열 하나의 라벨 전체와 수치. */
public record Sample(Map<String, String> labels, double value) {
}

/**
* 결과 벡터를 labelKey 값 → 수치로 돌려준다. 해당 라벨이 없는 시계열은 "unknown"으로 묶는다.
* 값이 없거나 수로 읽히지 않는 시계열은 건너뛴다 — 하나 때문에 나머지 결과까지 버리지 않는다.
*/
@SuppressWarnings("unchecked")
public Map<String, Double> queryVector(String promql, String labelKey) {
Map<String, Double> out = new LinkedHashMap<>();
for (Sample s : querySeries(promql)) {
out.put(s.labels().getOrDefault(labelKey, "unknown"), s.value());
}
return out;
}

/**
* 결과 벡터를 라벨 전체와 함께 돌려준다. 값이 없거나 수로 읽히지 않는 시계열은 건너뛴다 —
* 하나 때문에 나머지 결과까지 버리지 않는다.
*/
@SuppressWarnings("unchecked")
public List<Sample> querySeries(String promql) {
Map<String, Object> response = webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/api/v1/query")
.queryParam("query", promql)
.build())
// PromQL의 {Hostname=~"…"} 같은 중괄호가 URI 템플릿 변수로 읽히지 않게 값은 변수로 넘긴다.
.queryParam("query", "{promql}")
.build(promql))
.retrieve()
.bodyToMono(Map.class)
.timeout(TIMEOUT)
.block();

if (response == null) return Map.of();
if (response == null) return List.of();
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return Map.of();
if (data == null) return List.of();
List<Map<String, Object>> results = (List<Map<String, Object>>) data.get("result");
if (results == null) return Map.of();
if (results == null) return List.of();

Map<String, Double> out = new LinkedHashMap<>();
List<Sample> out = new java.util.ArrayList<>();
for (Map<String, Object> item : results) {
Map<String, String> metric = (Map<String, String>) item.get("metric");
List<Object> value = (List<Object>) item.get("value");
String key = metric == null ? "unknown" : metric.getOrDefault(labelKey, "unknown");
Double parsed = parseSample(value);
if (parsed == null) {
log.warn("[PrometheusClient] 읽을 수 없는 시계열을 건너뜀: label={}, value={}", key, value);
log.warn("[PrometheusClient] 읽을 수 없는 시계열을 건너뜀: labels={}, value={}", metric, value);
continue;
}
out.put(key, parsed);
out.add(new Sample(metric == null ? Map.of() : metric, parsed));
}
return out;
}
Expand All @@ -73,7 +88,9 @@ public Map<String, Double> queryVector(String promql, String labelKey) {
private static Double parseSample(List<Object> value) {
if (value == null || value.size() < 2 || value.get(1) == null) return null;
try {
return Double.valueOf(value.get(1).toString());
double v = Double.parseDouble(value.get(1).toString());
// Prometheus는 "NaN"·"+Inf"도 문자열로 돌려준다. 비유한 값은 수치로 쓸 수 없다.
return Double.isFinite(v) ? v : null;
} catch (NumberFormatException e) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package DGU_AI_LAB.admin_be.domain.monitoring.controller;

import DGU_AI_LAB.admin_be.domain.monitoring.controller.docs.AdminGpuUsageApi;
import DGU_AI_LAB.admin_be.domain.monitoring.service.AdminGpuUsageService;
import DGU_AI_LAB.admin_be.global.common.SuccessResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/** 관리자 전용(/api/admin/** 은 SecurityConfig에서 ADMIN만 허용). */
@RestController
@RequiredArgsConstructor
public class AdminGpuUsageController implements AdminGpuUsageApi {

private final AdminGpuUsageService adminGpuUsageService;

@Override
public ResponseEntity<SuccessResponse<?>> getGpuUsage(@RequestParam(name = "node", required = false) String node) {
return SuccessResponse.ok(adminGpuUsageService.getGpuUsage(node));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package DGU_AI_LAB.admin_be.domain.monitoring.controller.docs;

import DGU_AI_LAB.admin_be.domain.monitoring.dto.response.AdminGpuUsageResponseDTO;
import DGU_AI_LAB.admin_be.error.dto.ErrorResponse;
import DGU_AI_LAB.admin_be.global.common.SuccessResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Tag(name = "9. 관리자 GPU 사용 현황", description = "관리자용 노드별 GPU 사용률·프로세스·소유자 조회 API")
@RequestMapping("/api/admin/gpu-usage")
public interface AdminGpuUsageApi {

@Operation(summary = "노드별 GPU 사용 현황 조회",
description = "GPU별 사용률·메모리와 그 위에서 도는 프로세스(소유자 이름·계정·신청 번호 포함)를 노드별로 조회합니다. "
+ "node를 생략하면 DB의 모든 노드입니다. exporter가 없으면 processesAvailable=false이고 프로세스는 비어 있습니다. "
+ "소유자를 못 찾은 프로세스는 ownerName 등이 null입니다.")
@ApiResponse(responseCode = "200", description = "성공",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = AdminGpuUsageResponseDTO.class))))
@ApiResponse(responseCode = "401", description = "인증되지 않은 사용자",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "403", description = "관리자가 아님",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "404", description = "DB에 없는 노드",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@ApiResponse(responseCode = "502", description = "노드 하나를 지정했는데 GPU 지표 조회에 실패",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
@GetMapping
ResponseEntity<SuccessResponse<?>> getGpuUsage(
@Parameter(description = "노드 이름(생략하면 전체)", example = "farm6")
@RequestParam(name = "node", required = false) String node
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package DGU_AI_LAB.admin_be.domain.monitoring.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;

import java.util.List;

/**
* 관리자용 노드별 GPU 사용 현황. 사용자 응답(MyGpuUsageResponseDTO)과 달리 프로세스마다 소유자를 담는다 — 관리자 전용 경로에서만 쓴다.
*/
@Builder
@Schema(description = "관리자용 노드 하나의 GPU 사용 현황")
public record AdminGpuUsageResponseDTO(
@Schema(description = "노드 이름", example = "farm6") String nodeName,
@Schema(description = "프로세스 정보를 읽을 수 있는지. false면 processes는 비어 있고 '없음'이 아니라 '모름'이다") boolean processesAvailable,
@Schema(description = "GPU별 현황") List<Gpu> gpus) {

@Builder
public record Gpu(
@Schema(description = "GPU 번호", example = "0") int index,
@Schema(description = "GPU UUID") String uuid,
@Schema(description = "GPU 모델명") String model,
@Schema(description = "GPU 전체 사용률(%)") double utilizationPercent,
@Schema(description = "GPU 전체 사용 메모리(MiB)") double memoryUsedMiB,
@Schema(description = "GPU 전체 메모리(MiB)") double memoryTotalMiB,
@Schema(description = "이 GPU에서 도는 프로세스(메모리 큰 순)") List<Process> processes) {
}

@Builder
public record Process(
@Schema(description = "소유자 이름. 소유자를 못 찾았으면 null(미확인)", nullable = true) String ownerName,
@Schema(description = "소유자 우분투 계정. 미확인이면 null", nullable = true) String ubuntuUsername,
@Schema(description = "소유자 사용자 번호. 미확인이거나 옛 Docker 컨테이너면 null", nullable = true) Long userId,
@Schema(description = "소유 신청 번호. 미확인이거나 옛 Docker 컨테이너면 null", nullable = true) Long requestId,
@Schema(description = "컨테이너 ID 앞 12자") String containerId,
@Schema(description = "프로세스 이름(파일 이름만)") String processName,
@Schema(description = "GPU 메모리(MiB)") double memoryUsedMiB,
@Schema(description = "실행된 지 지난 시간(초)") long elapsedSeconds) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package DGU_AI_LAB.admin_be.domain.monitoring.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;

import java.util.List;

/**
* 내 서버의 GPU별 사용 현황. 다른 사용자는 사람 수와 메모리 합계로만 담는다 —
* 이름·계정·Pod·프로세스 등 식별 정보는 이 응답에 넣지 않는다.
*/
@Builder
@Schema(description = "내 서버의 GPU별 사용 현황")
public record MyGpuUsageResponseDTO(
@Schema(description = "서버(노드) 이름", example = "farm1") String nodeName,
@Schema(description = "GPU별 현황") List<Gpu> gpus,
@Schema(description = "프로세스·다른 사용자 정보를 읽었는지. false면 내 프로세스 없음·다른 사용자 0명이 '없음'이 아니라 '모름'이다")
boolean processesAvailable) {

@Builder
public record Gpu(
@Schema(description = "GPU 번호", example = "0") int index,
@Schema(description = "GPU 모델명") String modelName,
@Schema(description = "GPU 전체 사용률(%)") double utilizationPercent,
@Schema(description = "GPU 전체 사용 메모리(MiB)") double memoryUsedMiB,
@Schema(description = "GPU 전체 메모리(MiB)") double memoryTotalMiB,
@Schema(description = "내 프로세스(이름·실행 시간·GPU 메모리)") List<Process> myProcesses,
@Schema(description = "같은 GPU를 쓰는 다른 사용자 수") int otherUserCount,
@Schema(description = "다른 사용자들의 GPU 메모리 합계(MiB)") double otherMemoryMiB) {
}

@Builder
public record Process(
@Schema(description = "프로세스 이름") String name,
@Schema(description = "실행된 지 지난 시간(초)") long elapsedSeconds,
@Schema(description = "GPU 메모리(MiB)") double memoryMiB) {
}
}
Loading
Loading