Skip to content

Commit

Permalink
Merge branch 'develop' into feature/#57
Browse files Browse the repository at this point in the history
  • Loading branch information
Suanna01 authored Aug 4, 2023
2 parents e6b765c + 7cebe44 commit 59d33a4
Show file tree
Hide file tree
Showing 25 changed files with 344 additions and 74 deletions.
82 changes: 41 additions & 41 deletions .github/workflows/master.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
name: Deploy to Amazon EC2
name: Spring Boot & Gradle CI/CD

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

# 본인이 설정한 값을 여기서 채워넣습니다.
# 리전, 버킷 이름, CodeDeploy 앱 이름, CodeDeploy 배포 그룹 이름
env:
AWS_REGION: ap-northeast-2
S3_BUCKET_NAME: dongnae-deploy
CODE_DEPLOY_APPLICATION_NAME: DongnaeFriend
S3_BUCKET_NAME: dongnae-bucket
CODE_DEPLOY_APPLICATION_NAME: dongnae-deploy
CODE_DEPLOY_DEPLOYMENT_GROUP_NAME: dongnae-group

permissions:
Expand All @@ -24,45 +24,45 @@ jobs:
environment: production

steps:
# (1) 기본 체크아웃
- name: Checkout
uses: actions/checkout@v3
# (1) 기본 체크아웃
- name: Checkout
uses: actions/checkout@v3

# (2) JDK 11 세팅
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'
# (2) JDK 11 세팅
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '11'

# (3) Gradle build (Test 제외)
- name: Build with Gradle
uses: gradle/gradle-build-action@0d13054264b0bb894ded474f08ebb30921341cee
with:
arguments: clean build -x test
# (3) Gradle build (Test 제외)
- name: Build with Gradle
uses: gradle/gradle-build-action@0d13054264b0bb894ded474f08ebb30921341cee
with:
arguments: clean build -x test

# (4) AWS 인증 (IAM 사용자 Access Key, Secret Key 활용)
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
# (4) AWS 인증 (IAM 사용자 Access Key, Secret Key 활용)
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}

# (5) 빌드 결과물을 S3 버킷에 업로드
- name: Upload to AWS S3
run: |
aws deploy push \
--application-name ${{ env.CODE_DEPLOY_APPLICATION_NAME }} \
--ignore-hidden-files \
--s3-location s3://$S3_BUCKET_NAME/$GITHUB_SHA.zip \
--source .
# (5) 빌드 결과물을 S3 버킷에 업로드
- name: Upload to AWS S3
run: |
aws deploy push \
--application-name ${{ env.CODE_DEPLOY_APPLICATION_NAME }} \
--ignore-hidden-files \
--s3-location s3://$S3_BUCKET_NAME/$GITHUB_SHA.zip \
--source .
# (6) S3 버킷에 있는 파일을 대상으로 CodeDeploy 실행
- name: Deploy to AWS EC2 from S3
run: |
aws deploy create-deployment \
--application-name ${{ env.CODE_DEPLOY_APPLICATION_NAME }} \
--deployment-config-name CodeDeployDefault.AllAtOnce \
--deployment-group-name ${{ env.CODE_DEPLOY_DEPLOYMENT_GROUP_NAME }} \
--s3-location bucket=$S3_BUCKET_NAME,key=$GITHUB_SHA.zip,bundleType=zip
# (6) S3 버킷에 있는 파일을 대상으로 CodeDeploy 실행
- name: Deploy to AWS EC2 from S3
run: |
aws deploy create-deployment \
--application-name ${{ env.CODE_DEPLOY_APPLICATION_NAME }} \
--deployment-config-name CodeDeployDefault.AllAtOnce \
--deployment-group-name ${{ env.CODE_DEPLOY_DEPLOYMENT_GROUP_NAME }} \
--s3-location bucket=$S3_BUCKET_NAME,key=$GITHUB_SHA.zip,bundleType=zip
15 changes: 7 additions & 8 deletions appspec.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
version: 0.0
os: linux

files:
- source: /
destination: /home/ubuntu/app
Expand All @@ -12,13 +13,11 @@ permissions:
group: ubuntu

hooks:
ApplicationStart:
- location: scripts/run_new_was.sh
timeout: 180
AfterInstall:
- location: scripts/stop.sh
timeout: 60
runas: ubuntu
- location: scripts/health_check.sh
timeout: 180
runas: ubuntu
- location: scripts/switch.sh
timeout: 180
ApplicationStart:
- location: scripts/start.sh
timeout: 60
runas: ubuntu
1 change: 0 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ tasks.named('test') {
useJUnitPlatform()
}


jar {
enabled = false
}
Expand Down
34 changes: 34 additions & 0 deletions scripts/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env bash

REPOSITORY=/home/ubuntu/app

echo "> 현재 구동 중인 애플리케이션 pid 확인"

CURRENT_PID=$(pgrep -fla java | grep approval | awk '{print $1}')

echo "현재 구동 중인 애플리케이션 pid: $CURRENT_PID"

if [ -z "$CURRENT_PID" ]; then
echo "현재 구동 중인 애플리케이션이 없으므로 종료하지 않습니다."
else
echo "> kill -15 $CURRENT_PID"
kill -15 $CURRENT_PID
sleep 5
fi

echo "> 새 애플리케이션 배포"

JAR_NAME=$(ls -tr $REPOSITORY/*SNAPSHOT.jar | tail -n 1)

echo "> JAR NAME: $JAR_NAME"

echo "> $JAR_NAME 에 실행권한 추가"

chmod +x $JAR_NAME

echo "> $JAR_NAME 실행"

nohup java -jar \
-Duser.timezone=Asia/Seoul \
-Dspring.config.location=/home/ubuntu/app/application.yml \
$JAR_NAME >> $REPOSITORY/nohup.out 2>&1 &
24 changes: 24 additions & 0 deletions scripts/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env bash

PROJECT_ROOT="/home/ubuntu/app"
JAR_FILE="$PROJECT_ROOT/spring-webapp.jar"
#JAR_FILE=$(ls -tr $PROJECT_ROOT/*SNAPSHOT.jar | tail -n 1)

APP_LOG="$PROJECT_ROOT/application.log"
ERROR_LOG="$PROJECT_ROOT/error.log"
DEPLOY_LOG="$PROJECT_ROOT/deploy.log"

TIME_NOW=$(date +%c)

# build 파일 복사
echo "$TIME_NOW > $JAR_FILE 파일 복사" >> $DEPLOY_LOG
cp $PROJECT_ROOT/build/libs/*.jar $JAR_FILE

# jar 파일 실행
echo "$TIME_NOW > $JAR_FILE 파일 실행" >> $DEPLOY_LOG
nohup sudo java -jar \
-Dspring.config.location=/home/ubuntu/app/application.yml \
$JAR_FILE > $APP_LOG 2> $ERROR_LOG &

CURRENT_PID=$(pgrep -f $JAR_FILE)
echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG
19 changes: 19 additions & 0 deletions scripts/stop.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash

PROJECT_ROOT="/home/ubuntu/app"
JAR_FILE="$PROJECT_ROOT/spring-webapp.jar"

DEPLOY_LOG="$PROJECT_ROOT/deploy.log"

TIME_NOW=$(date +%c)

# 현재 구동 중인 애플리케이션 pid 확인
CURRENT_PID=$(pgrep -f $JAR_FILE)

# 프로세스가 켜져 있으면 종료
if [ -z $CURRENT_PID ]; then
echo "$TIME_NOW > 현재 실행중인 애플리케이션이 없습니다" >> $DEPLOY_LOG
else
echo "$TIME_NOW > 실행중인 $CURRENT_PID 애플리케이션 종료 " >> $DEPLOY_LOG
sudo kill -15 $CURRENT_PID
fi
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ public class HealthCheckController {

@GetMapping("/health")
public String healthCheck() {
return "health check ok!!!!";
return "health check ok";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.umc.DongnaeFriend.domain.account.book.entity.AccountBook;
import com.umc.DongnaeFriend.domain.type.TransactionCategory;
import com.umc.DongnaeFriend.domain.user.entity.User;
import lombok.*;

import java.util.List;
Expand Down Expand Up @@ -32,13 +33,14 @@ public static BudgetResponse of(Long accountBookId, Long budget){

@Getter
public static class BudgetRequest{
public static AccountBook toEntity(Integer year, Integer month, Long amount){
public static AccountBook toEntity(Integer year, Integer month, Long amount, User user){
return AccountBook.builder()
.expenditure(0L)
.income(0L)
.budget(amount)
.year(year)
.month(month)
.user(user)
.build();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ public class AccountBook extends BaseTimeEntity {
private Long id;

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

private Long budget;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
import com.umc.DongnaeFriend.domain.account.book.dto.AccountBookDto;
import com.umc.DongnaeFriend.domain.account.book.entity.AccountBook;
import com.umc.DongnaeFriend.domain.account.book.repository.accountBook.AccountBookRepository;
import com.umc.DongnaeFriend.domain.user.entity.User;
import com.umc.DongnaeFriend.domain.user.repository.UserRepository;
import com.umc.DongnaeFriend.global.exception.CustomException;
import com.umc.DongnaeFriend.global.exception.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Objects;


@Slf4j
Expand All @@ -18,16 +22,19 @@
public class AccountBookService {

private final AccountBookRepository accountBookRepository;
private final UserRepository userRepository;


// 가계부 예산 설정 (한달)
@Transactional
public void createBudget(Integer year, Integer month, Long budget){
accountBookRepository.save(AccountBookDto.BudgetRequest.toEntity(year, month, budget));
User user = findUser();
accountBookRepository.save(AccountBookDto.BudgetRequest.toEntity(year, month, budget, user));
}

// 가계부 예산 설정 조회
public AccountBookDto.BudgetResponse getBudget(Integer year, Integer month){
User user = findUser();
AccountBook accountBook = accountBookRepository.findByYearAndMonth(year, month)
.orElseThrow(() -> new CustomException(ErrorCode.NO_CONTENT_FOUND));
return AccountBookDto.BudgetResponse.of(accountBook.getId(),accountBook.getBudget());
Expand All @@ -36,21 +43,39 @@ public AccountBookDto.BudgetResponse getBudget(Integer year, Integer month){
// 가계부 예산 설정 수정
@Transactional
public void updateBudget(Integer year, Integer month, Long budget){
User user = findUser();

AccountBook accountBook = accountBookRepository.findByYearAndMonth(year, month)
.orElseThrow(() -> new CustomException(ErrorCode.NO_CONTENT_FOUND));

if (!Objects.equals(accountBook.getUser().getId(), user.getId())) {
throw new CustomException(ErrorCode.INVALID_AUTH_TOKEN);
}
accountBook.updateBudget(budget);
}


// 가계부 조회 -> 이번달 남은 예산 & 지출, 저축(수입), 카테고리별 지출
public AccountBookDto.AccountBookResponse getAccountBookResponse(Integer year, Integer month) {
User user = findUser();

AccountBook accountBook = accountBookRepository.findByYearAndMonth(year, month)
.orElseThrow(() -> new CustomException(ErrorCode.NO_CONTENT_FOUND));

if (!Objects.equals(accountBook.getUser().getId(), user.getId())) {
throw new CustomException(ErrorCode.INVALID_AUTH_TOKEN);
}
return AccountBookDto.AccountBookResponse.builder()
.income(accountBook.getIncome())
.expenditure(accountBook.getExpenditure())
.budget(accountBook.getBudget()+accountBook.getIncome()-accountBook.getExpenditure())
.expense(accountBookRepository.getAccountBook(year,month))
.build();
}

public User findUser() {
Object userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userRepository.findById((Long) userId)
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
}
}
Loading

0 comments on commit 59d33a4

Please sign in to comment.