Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RAC-67 deploy : 운영 서버 작업 #117

Merged
merged 3 commits into from
Feb 19, 2024
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
77 changes: 77 additions & 0 deletions .github/workflows/CD-prod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
name: Java CD with Gradle

on:
push:
branches: [ "main" ]

permissions:
contents: read

jobs:
build:

runs-on: ubuntu-latest
env :
working-directory: ./
APPLICATION: ${{ secrets.APPLICATION_PROD }}

steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: '17'
distribution: 'adopt'

- name: Cache Gradle packages
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-

- name: Create application.yml
run: |
echo "${{env.APPLICATION}}" > ./src/main/resources/application.yml

- name: Grant execute permission for gradlew
run: chmod +x gradlew
working-directory: ${{ env.working-directory }}

- name: Build with Gradle
run: ./gradlew build
working-directory: ${{ env.working-directory }}

- name: Cleanup Gradle Cache
if: ${{ always() }}
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties

- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Build and Push Docker image
run: |
docker build -t ywj9811/kimseonbae:latest .
docker push ywj9811/kimseonbae:latest

- name: Deploy
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_SERVER_HOST_PROD }}
username: ${{ secrets.EC2_SERVER_USERNAME }}
key: ${{ secrets.PRIVATE_KEY_PROD }}
envs: GITHUB_SHA
script: |
chmod +x /home/ec2-user/config/deploy.sh
/home/ec2-user/config/deploy.sh
debug: true


52 changes: 52 additions & 0 deletions .github/workflows/CI-prod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: Java CI with Gradle

on:
pull_request:
branches: [ "main" ]

permissions:
contents: read

jobs:
build:

runs-on: ubuntu-latest
env :
working-directory: ./
APPLICATION: ${{ secrets.APPLICATION_PROD }}

steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: '17'
distribution: 'adopt'

- name: Cache Gradle packages
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-

- name: Create application.yml
run: |
echo "${{env.APPLICATION}}" > ./src/main/resources/application.yml

- name: Grant execute permission for gradlew
run: chmod +x gradlew
working-directory: ${{ env.working-directory }}

- name: Build with Gradle
run: ./gradlew build
working-directory: ${{ env.working-directory }}

- name: Cleanup Gradle Cache
if: ${{ always() }}
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ out/
.vscode/

### yml ###
application.yml
application.yml
application-*.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
Expand All @@ -21,6 +22,9 @@
@Component
@RequiredArgsConstructor
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Value("${log.Type}")
private String env;

private final ObjectMapper objectMapper;
private final LogService logService;

Expand All @@ -29,7 +33,7 @@ public void handle(HttpServletRequest request, HttpServletResponse response, Acc
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
logService.save(new LogRequest(CustomAccessDeniedHandler.class.getSimpleName(), PERMISSION_DENIED.getMessage()));
logService.save(new LogRequest(env, CustomAccessDeniedHandler.class.getSimpleName(), PERMISSION_DENIED.getMessage()));
objectMapper.writeValue(
response.getOutputStream(),
new ErrorResponse(AUTH_DENIED.getCode(), PERMISSION_DENIED.getMessage())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
Expand All @@ -22,6 +23,9 @@
@Component
@RequiredArgsConstructor
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Value("${log.Type}")
private String env;

private final ObjectMapper objectMapper;
private final LogService logService;

Expand All @@ -30,7 +34,7 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
logService.save(new LogRequest(CustomAuthenticationEntryPoint.class.getSimpleName(), FAILED_AUTH.getMessage()));
logService.save(new LogRequest(env, CustomAuthenticationEntryPoint.class.getSimpleName(), FAILED_AUTH.getMessage()));
objectMapper.writeValue(
response.getOutputStream(),
new ErrorResponse(AUTH_FAILED.getCode(), FAILED_AUTH.getMessage())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public class JwtUtils {
private int refreshExpiration;
@Value("${jwt.accessExpiration}")
private int accessExpiration;
@Value("${log.Type}")
private String env;

private static final String ROLE = "role";
private static final String TYPE = "type";
private static final String AUTHORIZATION = "Authorization";
Expand Down Expand Up @@ -153,7 +156,7 @@ private void jwtExceptionHandler(HttpStatus status, HttpServletResponse response
response.setContentType(CONTENT_TYPE);
response.setCharacterEncoding(CHARACTER_ENCODING);
try {
logService.save(new LogRequest(JwtFilter.class.getSimpleName(), ex.getMessage()));
logService.save(new LogRequest(env, JwtFilter.class.getSimpleName(), ex.getMessage()));
String json = new ObjectMapper().writeValueAsString(ResponseDto.create(ex.getErrorCode(), ex.getMessage()));
response.getWriter().write(json);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.postgraduate.global.logging.service.LogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand All @@ -18,6 +19,9 @@
@RequiredArgsConstructor
public class GlobalExceptionHandler {
private final LogService logService;

@Value("${log.Type}")
private String env;
private static final String LOG_FORMAT = "Code : {}, Message : {}";

@ExceptionHandler(ApplicationException.class)
Expand All @@ -27,7 +31,7 @@ public ResponseDto<ErrorResponse> handleApplicationException(ApplicationExceptio

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseDto<ErrorResponse> handleArgumentValidException(MethodArgumentNotValidException ex) throws IOException {
logService.save(new LogRequest("@Valid", ex.getBindingResult().getAllErrors().get(0).getDefaultMessage()));
logService.save(new LogRequest(env, "@Valid", ex.getBindingResult().getAllErrors().get(0).getDefaultMessage()));
log.error(LOG_FORMAT, "@Valid Error", "MethodArgumentNotValidException");
return ResponseDto.create(ErrorCode.VALID_BLANK.getCode(), ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
}
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/postgraduate/global/logging/aop/LogAspect.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,19 @@
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static com.postgraduate.global.logging.aop.LogUtils.*;
import static com.postgraduate.global.logging.aop.LogUtils.clearLogId;
import static com.postgraduate.global.logging.aop.LogUtils.setLogId;

@Aspect
@Slf4j
@Component
@RequiredArgsConstructor
public class LogAspect {
@Value("${log.Type}")
private String env;
private final LogTrace logTrace;
private final LogService logService;

Expand All @@ -42,18 +46,18 @@ private Object getObject(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = joinPoint.proceed();
Integer executionTime = logTrace.end(traceStatus);
log.info("ExecutionTime : {}", executionTime);
logService.save(new LogRequest(traceStatus.threadId(), executionTime, traceStatus.methodName()));
logService.save(new LogRequest(env, traceStatus.threadId(), executionTime, traceStatus.methodName()));
return result;
}catch (ApplicationException e) {
if (traceStatus != null) {
logTrace.exception(e, traceStatus);
logService.save(new LogRequest(traceStatus.threadId(), traceStatus.methodName(), e.getMessage()));
logService.save(new LogRequest(env, traceStatus.threadId(), traceStatus.methodName(), e.getMessage()));
}
throw e;
}catch (Exception e) {
if (traceStatus != null) {
logTrace.exception(e, traceStatus);
logService.save(new LogRequest(traceStatus.threadId(), traceStatus.methodName(), e.getMessage()));
logService.save(new LogRequest(env, traceStatus.threadId(), traceStatus.methodName(), e.getMessage()));
}
throw e;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package com.postgraduate.global.logging.dto;

public record LogRequest(String logId, Integer executeTime, String methodName, String exceptionMessage) {
public LogRequest(String logId, Integer executeTime, String methodName) {
this(logId, executeTime, methodName, null);
public record LogRequest(String env, String logId, Integer executeTime, String methodName, String exceptionMessage) {
public LogRequest(String env, String logId, Integer executeTime, String methodName) {
this(env, logId, executeTime, methodName, null);
}

public LogRequest(String logId, String methodName, String exceptionMessage) {
this(logId, null, methodName, exceptionMessage);
public LogRequest(String env, String logId, String methodName, String exceptionMessage) {
this(env, logId, null, methodName, exceptionMessage);
}

public LogRequest(String methodName, String exceptionMessage) {
this(null, null, methodName, exceptionMessage);
public LogRequest(String env, String methodName, String exceptionMessage) {
this(env, null, null, methodName, exceptionMessage);
}
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,49 @@
package com.postgraduate.global.logging.service;

import com.postgraduate.global.logging.dto.LogRequest;
import com.postgraduate.global.mq.producer.MessageProducer;
import com.postgraduate.global.slack.SlackLogErrorMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;

@Service
@Slf4j
@RequiredArgsConstructor
public class LogService {
private final MessageProducer messageProducer;
private final WebClient webClient;
private final SlackLogErrorMessage slackLogErrorMessage;

@Value("${log.uri}")
private String logUri;

public void save(LogRequest logRequest) throws IOException {
try {
log.info("log save");
messageProducer.sendMessage(logRequest);
} catch (Exception ex) {
log.error("로그 서버 연결 실패");
slackLogErrorMessage.sendSlackLog(ex);
}
log.info("log save");
webClient.post()
.uri(logUri)
.accept(MediaType.APPLICATION_JSON)
.bodyValue(logRequest)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, clientResponse -> {
log.error("클라이언트 에러 발생: " + clientResponse.statusCode());
return Mono.error(new RuntimeException("클라이언트 에러"));
})
.onStatus(HttpStatusCode::is5xxServerError, clientResponse -> {
log.error("서버 에러 발생: " + clientResponse.statusCode());
return Mono.error(new RuntimeException("서버 에러"));
})
.bodyToMono(Void.class)
.doOnError(ex -> {
log.error("예상치 못한 에러 발생: " + ex.getMessage());
slackLogErrorMessage.sendSlackLog(new IllegalArgumentException("로그 서버 예외 발생"));
})
.subscribe();

}
}
Loading
Loading