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 @@ -167,8 +167,8 @@ public void sendContainerCreatedNotification(Request request, String sshPort, St
image == null ? "-" : SlackText.line(image.getImageName() + ":" + image.getImageVersion()), // {6}
serverProfileRegistry.publicPort(serverName, sshPort), // {7}
serverProfileRegistry.publicPort(serverName, jupyterPort), // {8}
String.valueOf(user.getUbuntuUid()), // {9}
String.valueOf(user.getUbuntuGid())); // {10}
String.valueOf(request.getUbuntuUid()), // {9}
String.valueOf(request.getUbuntuGid())); // {10}
replyToRequest(message, requestChannel(request, serverName), request.getSlackMessageTs());
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class HomeCleanup extends BaseTimeEntity {

private HomeCleanup(User user, LocalDateTime lastContainerEndedAt) {
this.user = user;
this.ubuntuUsername = user.getUbuntuUsername();
this.ubuntuUsername = user.ubuntuUsernameOn(User.PRIMARY_SERVER);
this.ubuntuUid = user.getUbuntuUid();
this.lastContainerEndedAt = lastContainerEndedAt;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,11 @@ static Target of(HomeCleanup cleanup) {
@Transactional
public Optional<Target> begin(Long userId, LocalDateTime now) {
User user = userRepository.findByIdForUpdate(userId).orElseThrow();
if (user.getUbuntuUsername() == null || user.getUbuntuUid() == null || user.hasOpenRequest()) {
if (user.getUbuntuUsername() == null || user.getUbuntuUid() == null
|| user.hasOpenRequest(User.PRIMARY_SERVER)) {
return Optional.empty();
}
Optional<LocalDateTime> endedAt = user.lastContainerEndedAt()
Optional<LocalDateTime> endedAt = user.lastContainerEndedAt(User.PRIMARY_SERVER)
.filter(ended -> ended.isBefore(retentionPolicy.deletableEndedBefore(now)));
if (endedAt.isEmpty() || cleanupRepository.existsByUser_UserIdAndStatusInAndLastContainerEndedAtGreaterThanEqual(
userId, SETTLED_OR_RUNNING, endedAt.get())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ private static List<String> row(Request request, List<String> ports, LocalDate h
return List.of(
text(request.getRequestId()),
text(user.getName()),
text(user.getUbuntuUsername()),
text(request.getUbuntuUsername()),
user.getUserGroups().stream()
.map(userGroup -> userGroup.getGroup().getGroupName())
.sorted().collect(Collectors.joining(", ")),
text(request.getNodeName()),
text(user.getUbuntuUid()),
text(user.getUbuntuGid()),
text(request.getUbuntuUid()),
text(request.getUbuntuGid()),
String.join(", ", ports),
date(request.getExpiresAt()),
text(homeDeletionDate),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,18 +340,23 @@ public void deleteAfterCleanup() {
this.jobId = null;
}

/** 신청 유저네임은 웹 계정에 한 번 정해지면 바뀌지 않는 값이라 따로 저장하지 않고 소유자에게서 읽는다. */
/** 이 신청이 쓰는 서버(리소스 그룹의 serverName). */
public String getServerName() {
return resourceGroup.getServerName();
}

/** 신청의 서버에 있는 계정의 유저네임. 계정 행이 아직 없으면 가입 때 고른 이름이다. */
public String getUbuntuUsername() {
return user.getUbuntuUsername();
return user.ubuntuUsernameOn(getServerName());
}

/** UID/GID는 사람에게 영구히 귀속된다(User). 신청은 소유자의 값을 그대로 보여 준다. */
/** UID/GID는 사람에게, 서버별로 영구히 귀속된다(UbuntuAccount). 계정이 아직 없으면 null이다. */
public Long getUbuntuUid() {
return user.getUbuntuUid();
return user.ubuntuUidOn(getServerName());
}

public Long getUbuntuGid() {
return user.getUbuntuGid();
return user.ubuntuGidOn(getServerName());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public SaveRequestResponseDTO approveRequest(ApproveRequestDTO dto) {
// 이용 정지 중에는 새 컨테이너를 만들지 않는다. 신청은 대기로 남아 정지가 끝난 뒤 승인할 수 있다.
suspensionGuard.requireNotSuspendedLocked(owner.getUserId());
// 계정 회수가 도는 중이면 새 컨테이너가 곧 지워질 계정을 쓰게 된다. 회수가 끝난 뒤 승인하면 되살린다.
if (owner.isReleasingUbuntuAccount()) {
if (owner.isReleasingUbuntuAccount(req.getServerName())) {
throw new BusinessException(ErrorCode.UBUNTU_ACCOUNT_RELEASING);
}
// 비밀번호 교체 작업이 도는 중이면 이 컨테이너만 옛 비밀번호로 만들어진다. 교체가 끝난 뒤 승인한다.
Expand All @@ -176,7 +176,7 @@ public SaveRequestResponseDTO approveRequest(ApproveRequestDTO dto) {
req.getUbuntuUsername(),
false,
supplementaryGroups,
previousUbuntuUid(req.getUser())
previousUbuntuUid(req.getUser(), req.getServerName())
);
// 응답은 트랜잭션 안에서 만든다. 밖에서 만들면 DTO가 새로 읽는 lazy 연관(예: user.userGroups)마다
// 초기화 목록을 따로 맞춰야 하고, 빠뜨리면 승인은 진행됐는데 관리자는 500을 받는다.
Expand Down Expand Up @@ -214,7 +214,7 @@ public SaveRequestResponseDTO approveRequest(ApproveRequestDTO dto) {
boolean reuseAccount = Boolean.TRUE.equals(new TransactionTemplate(transactionManager).execute(status ->
userRepository.findByIdForUpdate(userId)
.orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND))
.hasUbuntuAccount()));
.hasUbuntuAccount(serverName)));

// 계정을 새로 만드는 경우의 그룹은 작업이 계정을 만들 때 함께 넣는다.
// 재사용 계정의 경우, config-server의 provision 제어기가 Pod 생성 후 그룹을 추가하므로
Expand Down Expand Up @@ -296,8 +296,8 @@ private static RuntimeException asRuntime(Exception e) {
* 원장 UID가 같을 때만 이어받고, 없으면 NAS 홈 소유자가 이 값일 때 같은 UID로 다시 만든다.
* 첫 승인이면 null이라 새 번호를 받는다.
*/
private Long previousUbuntuUid(User user) {
return user.hasUbuntuAccount() ? null : user.getUbuntuUid();
private Long previousUbuntuUid(User user, String serverName) {
return user.hasUbuntuAccount(serverName) ? null : user.ubuntuUidOn(serverName);
}

/**
Expand Down Expand Up @@ -335,10 +335,10 @@ public void completeApprovalJob(Long requestId, JobResultResponseDTO.Result made
status.setRollbackOnly();
return new ApprovalOutcome(null, groupProblem);
}
if (!owner.hasUbuntuAccount() && made.uid() != null && made.gid() != null) {
if (!owner.hasUbuntuAccount(req.getServerName()) && made.uid() != null && made.gid() != null) {
// 작업이 계정을 새로 만들었거나 원장에 남은 계정을 이어받은 경우다. 이미 기록이 있으면
// 재사용 경로라 결과의 UID는 같은 값이다.
owner.assignUbuntuAccount(made.uid(), made.gid());
owner.assignUbuntuAccount(req.getServerName(), made.uid(), made.gid());
}
req.assignPodInfo(made.podName(), made.node());
req.completeApproval();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package DGU_AI_LAB.admin_be.domain.scheduler;

import DGU_AI_LAB.admin_be.domain.users.entity.UbuntuAccountStatus;
import DGU_AI_LAB.admin_be.domain.users.entity.User;
import DGU_AI_LAB.admin_be.domain.users.repository.UserRepository;
import DGU_AI_LAB.admin_be.domain.users.service.UbuntuAccountReleaseService;
Expand All @@ -20,7 +19,7 @@ public class AccountRevokeJobPoller {

@Scheduled(fixedDelayString = "${operations.revoke.poll-ms:3000}")
public void pollAccountRevokes() {
for (User user : userRepository.findAllByUbuntuAccountStatus(UbuntuAccountStatus.RELEASING)) {
for (User user : userRepository.findAllWithReleasingAccount()) {
try {
ubuntuAccountReleaseService.advance(user.getUserId());
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class HomeCleanupScheduler {
public void runHomeCleanup() {
LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Seoul"));
for (User user : userRepository.findHomeCleanupCandidates(
retentionPolicy.deletableEndedBefore(now), Status.openStatuses())) {
retentionPolicy.deletableEndedBefore(now), Status.openStatuses(), User.PRIMARY_SERVER)) {
try {
// 사용자별 독립 트랜잭션 — 한 사용자의 실패가 나머지를 막지 않게 한다.
homeCleanupService.begin(user.getUserId(), now).ifPresent(this::register);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ void remind(LocalDate today) {
LocalDate firstEnded = retentionPolicy.containerEndDateFor(today.plusDays(1));
LocalDate lastEnded = retentionPolicy.containerEndDateFor(today.plusDays(window));
List<User> users = userRepository.findHomeReminderCandidates(
firstEnded.atStartOfDay(), lastEnded.plusDays(1).atStartOfDay(), Status.openStatuses());
firstEnded.atStartOfDay(), lastEnded.plusDays(1).atStartOfDay(), Status.openStatuses(), User.PRIMARY_SERVER);
for (User user : users) {
try {
remind(user, today);
Expand All @@ -72,7 +72,7 @@ void remind(LocalDate today) {
}

private void remind(User user, LocalDate today) {
Optional<LocalDateTime> endedAt = user.lastContainerEndedAt();
Optional<LocalDateTime> endedAt = user.lastContainerEndedAt(User.PRIMARY_SERVER);
if (endedAt.isEmpty()) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package DGU_AI_LAB.admin_be.domain.users.entity;

import DGU_AI_LAB.admin_be.error.ErrorCode;
import DGU_AI_LAB.admin_be.error.exception.BusinessException;
import DGU_AI_LAB.admin_be.global.common.BaseTimeEntity;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
* 서버(리소스 그룹의 serverName)마다 따로 가지는 리눅스 계정. 서버마다 AD·NAS가 다르므로 사용자 한 명이 서버 수만큼
* 계정(유저네임·UID·GID)을 가질 수 있다. UID/GID/유저네임은 사람에게 영구히 남아, 회수돼도 지우지 않는다 — 다시 승인되면
* 같은 번호·같은 홈으로 돌아온다.
*/
@Entity
@Table(name = "ubuntu_accounts", uniqueConstraints = {
@UniqueConstraint(name = "uk_ubuntu_accounts_user_server", columnNames = {"user_id", "server_name"}),
@UniqueConstraint(name = "uk_ubuntu_accounts_server_username", columnNames = {"server_name", "username"}),
@UniqueConstraint(name = "uk_ubuntu_accounts_server_uid", columnNames = {"server_name", "uid"})
})
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class UbuntuAccount extends BaseTimeEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ubuntu_account_id")
private Long ubuntuAccountId;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;

@Column(name = "server_name", nullable = false, length = 300)
private String serverName;

/** 이 서버에서 쓰는 유저네임. 가입 때 고른 이름이 기본값이고, 서버가 달라 이름이 다른 사람(이전 계정)은 다른 값을 가진다. */
@Column(name = "username", length = 100)
private String username;

@Column(name = "uid")
private Long uid;

@Column(name = "gid")
private Long gid;

@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false, length = 20)
private UbuntuAccountStatus status = UbuntuAccountStatus.NONE;

UbuntuAccount(User user, String serverName, String username) {
this.user = user;
this.serverName = serverName;
this.username = username;
}

public boolean isServer(String serverName) {
return this.serverName.equalsIgnoreCase(serverName);
}

public boolean isActive() {
return status == UbuntuAccountStatus.ACTIVE;
}

public boolean isReleasing() {
return status == UbuntuAccountStatus.RELEASING;
}

/**
* 계정이 만들어졌거나 되살아났음을 기록한다. 예전에 받은 UID/GID가 있으면 같은 값이어야 한다(멱등) — 다른 값이면
* 보존된 홈의 소유자와 어긋나고 옛 번호가 다른 사람에게 넘어간 것처럼 보인다.
*/
public void assign(Long uid, Long gid) {
if (uid == null || gid == null || uid <= 0 || gid <= 0) {
throw new BusinessException(ErrorCode.UID_ALLOCATION_FAILED);
}
if (this.uid != null && (!this.uid.equals(uid) || !gid.equals(this.gid))) {
throw new BusinessException(
"이미 다른 UID/GID가 배정된 계정입니다.", ErrorCode.UBUNTU_ACCOUNT_ALREADY_ASSIGNED);
}
if (isReleasing()) {
throw new BusinessException(ErrorCode.UBUNTU_ACCOUNT_RELEASING);
}
this.uid = uid;
this.gid = gid;
this.status = UbuntuAccountStatus.ACTIVE;
}

/** 회수를 시작한다. 이미 회수 중이면 그대로 둔다(재시도). 계정이 없으면 회수할 것도 없다. */
public boolean beginRelease() {
if (status == UbuntuAccountStatus.NONE) {
return false;
}
this.status = UbuntuAccountStatus.RELEASING;
return true;
}

/** 회수할 노드를 몰라 계정을 지우지 못했을 때 살아 있는 상태로 되돌린다. */
public void abortRelease() {
requireReleasing();
this.status = UbuntuAccountStatus.ACTIVE;
}

/** 리눅스 계정이 실제로 삭제됐음을 기록한다. 유저네임·UID·GID는 남긴다. */
public void release() {
requireReleasing();
this.status = UbuntuAccountStatus.NONE;
}

private void requireReleasing() {
if (!isReleasing()) {
throw new BusinessException("회수 중인 계정이 아닙니다.", ErrorCode.INVALID_REQUEST_STATUS);
}
}
}
Loading
Loading