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

젠킨스 개선 완료 #366

Merged
merged 2 commits into from
Jun 5, 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
4 changes: 4 additions & 0 deletions jenkins/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FROM openjdk:21
EXPOSE 8080
COPY build/libs/clab.jar /clab.jar
ENTRYPOINT ["java", "-jar", "-Dspring.profiles.active=stage", "/clab.jar"]
253 changes: 253 additions & 0 deletions jenkins/Jenkinsfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
pipeline {
agent any

environment {
SLACK_WEBHOOK_URL = credentials('slack-webhook-url')

PG_USER = credentials('pg_user')
PG_PASSWORD = credentials('pg_password')
BACKUP_DIR = credentials('backup_dir')

DOCKER_HUB_REPO = credentials('dockerhub_repo')
DOCKER_HUB_USER = credentials('dockerhub_user')
DOCKER_HUB_PASSWORD = credentials('dockerhub_password')

SERVER_CONFIG = credentials('server_config')
SERVER_CLOUD = credentials('server_cloud')

BLUE_CONTAINER = credentials('blue_container')
GREEN_CONTAINER = credentials('green_container')
BLUE_URL = credentials('blue_url')
GREEN_URL = credentials('green_url')
IMAGE_NAME = credentials('image_name')
NETWORK_NAME = credentials('network_name')

PORT_A = credentials('port_a')
PORT_B = credentials('port_b')

DOCKERFILE_PATH = "${env.WORKSPACE}/jenkins/Dockerfile"
NGINX_CONTAINER_NAME = 'nginx'
POSTGRESQL_CONTAINER_NAME = 'postgresql'
}

stages {
stage('Java 버전 확인') {
steps {
sh 'java -version'
}
}

stage('슬랙 알림: 스테이징 서버 테스트') {
steps {
script {
sendSlackNotification(":test_tube: Testing the Staging server...")
}
}
}

stage('PostgreSQL 백업') {
steps {
script {
backupPostgres()
}
}
}

stage('Docker Hub 로그인') {
steps {
script {
dockerLogin()
}
}
}

stage('컨테이너 결정') {
steps {
script {
determineContainers()
}
}
}

stage('애플리케이션 빌드') {
steps {
sh './gradlew clean build -Penv=stage --stacktrace --info'
}
}

stage('Docker 이미지 빌드 및 푸시') {
steps {
script {
buildAndPushDockerImage()
}
}
}

stage('새 인스턴스 배포') {
steps {
script {
deployNewInstance()
}
}
}

stage('헬스 체크') {
steps {
script {
performHealthCheck()
}
}
}

stage('트래픽 전환 및 정리') {
steps {
script {
switchTrafficAndCleanup()
}
}
}
}

post {
failure {
script {
sendSlackNotification(":scream_cat: Deployment failed.")
}
}

success {
script {
sendSlackNotification(":rocket: Deployment completed successfully.")
}
}
}
}

def sendSlackNotification(message) {
withEnv(["SLACK_WEBHOOK_URL=${env.SLACK_WEBHOOK_URL}"]) {
sh "curl -X POST --data-urlencode 'payload={\"text\": \"${message}\"}' ${SLACK_WEBHOOK_URL}"
}
}

def backupPostgres() {
def BACKUP_FILE = "postgres_backup_${new Date().format('yyyy-MM-dd_HH-mm-ss')}.sql"
withEnv(["BACKUP_DIR=${env.BACKUP_DIR}", "POSTGRESQL_CONTAINER_NAME=${env.POSTGRESQL_CONTAINER_NAME}", "PG_PASSWORD=${env.PG_PASSWORD}", "PG_USER=${env.PG_USER}"]) {
sh """
echo "Backing up PostgreSQL database to ${BACKUP_DIR}/${BACKUP_FILE}..."
docker exec -e PGPASSWORD=${PG_PASSWORD} ${POSTGRESQL_CONTAINER_NAME} sh -c 'pg_dumpall -c -U ${PG_USER} > ${BACKUP_DIR}/${BACKUP_FILE}'
"""
}
sendSlackNotification(":floppy_disk: PostgreSQL backup completed successfully: ${BACKUP_FILE}")
}

def dockerLogin() {
withEnv(["DOCKER_HUB_PASSWORD=${env.DOCKER_HUB_PASSWORD}", "DOCKER_HUB_USER=${env.DOCKER_HUB_USER}"]) {
sh """
echo "Logging in to Docker Hub..."
echo "${DOCKER_HUB_PASSWORD}" | docker login -u ${DOCKER_HUB_USER} --password-stdin
"""
}
}

def determineContainers() {
script {
withEnv(["BLUE_CONTAINER=${env.BLUE_CONTAINER}", "GREEN_CONTAINER=${env.GREEN_CONTAINER}", "BLUE_URL=${env.BLUE_URL}", "GREEN_URL=${env.GREEN_URL}", "PORT_A=${env.PORT_A}", "PORT_B=${env.PORT_B}"]) {
def blueRunning = sh(script: "docker ps --filter 'name=${BLUE_CONTAINER}' --format '{{.Names}}' | grep -q '${BLUE_CONTAINER}'", returnStatus: true) == 0
if (blueRunning) {
env.CURRENT_CONTAINER = BLUE_CONTAINER
env.DEPLOY_CONTAINER = GREEN_CONTAINER
env.NEW_TARGET = GREEN_URL
env.NEW_PORT = PORT_B
env.OLD_PORT = PORT_A
} else {
env.CURRENT_CONTAINER = GREEN_CONTAINER
env.DEPLOY_CONTAINER = BLUE_CONTAINER
env.NEW_TARGET = BLUE_URL
env.NEW_PORT = PORT_A
env.OLD_PORT = PORT_B
}
echo "Current container is ${env.CURRENT_CONTAINER}, deploying to ${env.DEPLOY_CONTAINER} on port ${env.NEW_PORT}."
}
}
}

def buildAndPushDockerImage() {
withEnv(["DOCKER_HUB_REPO=${env.DOCKER_HUB_REPO}", "DEPLOY_CONTAINER=${env.DEPLOY_CONTAINER}", "DOCKERFILE_PATH=${env.DOCKERFILE_PATH}", "IMAGE_NAME=${env.IMAGE_NAME}"]) {
sh """
docker build -f ${DOCKERFILE_PATH} -t ${IMAGE_NAME}:${DEPLOY_CONTAINER} .
docker tag ${IMAGE_NAME}:${DEPLOY_CONTAINER} ${DOCKER_HUB_REPO}:${DEPLOY_CONTAINER}
docker push ${DOCKER_HUB_REPO}:${DEPLOY_CONTAINER}
"""
}
}

def deployNewInstance() {
withEnv(["NEW_PORT=${env.NEW_PORT}", "NETWORK_NAME=${env.NETWORK_NAME}", "SERVER_CONFIG=${env.SERVER_CONFIG}", "SERVER_CLOUD=${env.SERVER_CLOUD}", "DEPLOY_CONTAINER=${env.DEPLOY_CONTAINER}", "IMAGE_NAME=${env.IMAGE_NAME}"]) {
sh """
echo "Stopping and removing existing container if it exists"
if docker ps | grep -q ${DEPLOY_CONTAINER}; then
docker stop ${DEPLOY_CONTAINER}
docker rm ${DEPLOY_CONTAINER}
fi

echo "Running new container ${DEPLOY_CONTAINER} with image ${IMAGE_NAME}:${DEPLOY_CONTAINER}"
docker run -d --name ${DEPLOY_CONTAINER} \\
-p ${NEW_PORT}:8080 \\
--network ${NETWORK_NAME} \\
-v ${SERVER_CONFIG}:/config \\
-v ${SERVER_CLOUD}:/cloud \\
${IMAGE_NAME}:${DEPLOY_CONTAINER}

echo "Listing all containers"
docker ps -a
"""
}
sendSlackNotification(":low_battery: Restarting the Staging server...")
}

def performHealthCheck() {
def PUBLIC_IP = sh(script: "curl -s ifconfig.me", returnStdout: true).trim()
echo "Public IP address: ${PUBLIC_IP}"

def start_time = System.currentTimeMillis()
def timeout = start_time + 240000 // 4 minutes

while (System.currentTimeMillis() < timeout) {
def elapsed = (System.currentTimeMillis() - start_time) / 1000
echo "Checking health... ${elapsed} seconds elapsed."
if (sh(script: "curl -s http://${PUBLIC_IP}:${env.NEW_PORT}/actuator/health | grep 'UP'", returnStatus: true) == 0) {
echo "New application started successfully after ${elapsed} seconds."
break
}
sleep 1
}

if (System.currentTimeMillis() >= timeout) {
sendSlackNotification(":scream_cat: New Staging application did not start successfully within 4 minutes.")
sh "docker stop ${env.DEPLOY_CONTAINER}"
sh "docker rm ${env.DEPLOY_CONTAINER}"
error "Health check failed"
}
}

def switchTrafficAndCleanup() {
withEnv(["NEW_PORT=${env.NEW_PORT}", "OLD_PORT=${env.OLD_PORT}", "NEW_TARGET=${env.NEW_TARGET}", "CURRENT_CONTAINER=${env.CURRENT_CONTAINER}", "DEPLOY_CONTAINER=${env.DEPLOY_CONTAINER}", "NGINX_CONTAINER_NAME=${env.NGINX_CONTAINER_NAME}"]) {
sh """
echo "Switching traffic to ${DEPLOY_CONTAINER} on port ${NEW_PORT}."
docker exec ${NGINX_CONTAINER_NAME} bash -c '
export BACKEND_URL=${NEW_TARGET}
envsubst "\\\$BACKEND_URL" < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf
'
docker exec ${NGINX_CONTAINER_NAME} sed -i 's/${OLD_PORT}/${NEW_PORT}/' /etc/nginx/conf.d/default.conf
docker exec ${NGINX_CONTAINER_NAME} nginx -t
docker exec ${NGINX_CONTAINER_NAME} nginx -s reload

echo "Checking if current container ${CURRENT_CONTAINER} is running..."
if docker ps | grep -q ${CURRENT_CONTAINER}; then
docker stop ${CURRENT_CONTAINER}
docker rm ${CURRENT_CONTAINER}
echo "Removed old container ${CURRENT_CONTAINER}."
fi
"""
}
}
13 changes: 0 additions & 13 deletions src/test/java/page/clab/api/ApiApplicationTests.java

This file was deleted.