jenkins中管理java项目部署启动的shell脚本

#!/bin/bash
BUILD_ID=dontkillme

export JAVA_HOME=/home/jdk1.8.0_321


#base info
bash_source_name=${BASH_SOURCE[0]}
script_path=$(readlink -f "${bash_source_name}")
SERVICE_ROOT=$(dirname $script_path)

FILENAME=mobile-api.jar
SERVER_PORT=8987
new_release=$SERVICE_ROOT/new_release
LOG_DIR=$SERVICE_ROOT/logs
release_backup_dir=$SERVICE_ROOT/backup
timestamp=`date +%F-%H-%M-%S`
JAVA_PATH=/usr/local/java11/bin/java

mkdir -p $LOG_DIR
mkdir -p $release_backup_dir


stop () {
    # Stop service forloop, 4 times failed will exit.
    count=0
    while [ 1 ]
    do
        sleep 3s
        count=$(($count+1))
        echo "Stop the service...[$count/4]"
        if [ $count -gt 4 ];
        then
            echo "Stop service failed..."
            exit 1
        fi
        ps aux | grep java | grep $SERVICE_ROOT/$FILENAME | awk  '{print $2}' | xargs kill -9 &> /dev/null
        if ps aux | grep java | grep $SERVICE_ROOT/$FILENAME;
        then 
            continue 
        else 
            echo "Stop service successfully." 
            break
        fi
    done
}


start () {
    boot_parameter_front=""
    boot_parameter_behind="--server.port=${SERVER_PORT} --spring.profiles.active=stage,storage-stage,sms"
    cd $SERVICE_ROOT
    echo 'Start service....'
    nohup $JAVA_PATH $boot_parameter_front -jar $SERVICE_ROOT/$FILENAME $boot_parameter_behind >> $LOG_DIR/nohup_${timestamp}.out 2>&1 &
}


restart () {
    stop
    sleep 2
    start
}


deploy () {
    stop
    sleep 2
    mv $SERVICE_ROOT/$FILENAME $release_backup_dir/${FILENAME}.$timestamp
    if [[ $? -eq 0 ]];
    then
        echo ${FILENAME}.$timestamp >> $release_backup_dir/filename
    fi
    mv $new_release/$FILENAME $SERVICE_ROOT
    start
}

rollback () {

    stop
    sleep 2
    
    echo "delete the current datafiles..."
    rm -f $SERVICE_ROOT/$FILENAME
    
    # copy from backup
    # read version filenames
    if [[ ! -s $release_backup_dir/filename ]]
    then
        echo "Version file not exist..."
        exit 1
    fi
    
    filename=`tail -1 $release_backup_dir/filename`
    
    # recover from backup 
    cp -r $release_backup_dir/$filename $SERVICE_ROOT/$FILENAME
    
    if [ $? -ne 0 ]
    then 
        echo "Recover data files failed."
        exit 1
    fi
    
    echo "Recover from version ${filename}..."
    
    # start service
    start
}


case $1 in
    start)
    start;;

    stop)
    stop;;

    deploy)
    deploy;;
    
    rollback)
    rollback;;

    *)
    echo "Usage: $0 [start|stop|deploy|rollback]";;
esac

posted @ 2023-11-24 14:18  哈喽哈喽111111  阅读(150)  评论(0编辑  收藏  举报