Jenkins-CICD-python/Java包升级与回退

Jenkins- CICD流水线 python/Java代码升级与回退

1、执行思路

1.1、代码升级

jenkins上点击 upgrade和 代码版本号 --${tag}

jenkins 推送 代码 和 执行脚本 到目标服务器/opt目录下

执行命令 sh run.sh 代码名称 版本号 upgrade

版本号 来自jenkins的 构建参数中的 标签参数,标签值从gitee处获取
run.sh 升级代码执行逻辑

1、在目标服务器上 新代码名称+标签 cp 到 bak目录下

2、停服,新代码 mv 到执行目录下,启动

1.2、代码回退

jenkins上点 rollbak 和 代码版本号
run.sh 回退代码执行逻辑

停服,cp bak/代码-版本号 到执行目录,启动

2、gitee代码如下

run.sh 执行脚本

test_flask.py python代码

2.1、执行脚本run.sh代码如下

shell 复制代码
#!/bin/bash

# cd `dirname $0`
APP_NAME=$1
APP_file=/opt/test/${APP_NAME}
tag=$2

#使用说明,用来提示输入参数
usage() {
    echo "Usage: ./run.sh [start|stop|status|restart|upgrade]"
    exit 1
}

#检查程序是否在运行
is_exist(){
	# pid=`jps -l|grep $APP_NAME|grep -v grep|awk '{print $1}'` >> 此次获取java进程pid <<
  pid=`curl localhost:10080/pid 2>/dev/null`
  #如果不存在返回1,存在返回0     
	if [ -z "${pid}" ]; then
    echo "pid不存在"
		return 1
	else
		return 0
	fi
}

#启动方法
start(){
  echo "${APP_file} is starting ..."
	is_exist
	if [ $? -eq 0 ]; then
		echo "${APP_file} is already running. pid=${pid}"
	else
		# nohup java -Xmx100m -Xms100m -jar ${APP_file} --server.port=8181 >/dev/null 2>&1 & >> 此处启动java jar包 <<
    nohup python3 test/test_flask.py &
		echo "START..."
		sleep 5
		is_exist
		if [ $? -eq 0 ]; then
			echo "${APP_file} is running success. pid=${pid}"
		fi
	fi
}

#停止方法
stop(){
  echo "${APP_file} is stopping ..."
  is_exist
  if [ $? -eq "0" ]; then
    kill -15 $pid
    echo "..."
    sleep 2
    is_exist
    if [ $? -eq 0 ]; then
      echo "${APP_file} still in the running. pid=${pid}"
    else
      echo "${APP_file} has stopped running."
    fi
  else
    echo "${APP_file} is not running"
  fi  
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_file} is running. Pid is ${pid}"
  else
    echo "${APP_file} is NOT running."
  fi
}

#重启
restart(){
  echo "${APP_file} is restarting ..."
  stop
  #sleep 5
  start
}

#程序升级
#upgrade(){
#  ./run.sh stop
#  cd ..
#  mv $APP_NAME $backup
#  cp $rjxf ./
#  ./bin/run.sh start
#}

upgrade(){
  cd /opt/
  cp ./${APP_NAME} ./bak/${APP_NAME}-${tag}
  ./run.sh ${APP_NAME} ${tag} stop
  mv ${APP_NAME}  test/${APP_NAME}
  ./run.sh ${APP_NAME} ${tag} start;exit
}

rollback(){
  cd /opt/
  ./run.sh ${APP_NAME} ${tag} stop
  cp ./bak/${APP_NAME}-${tag} test/${APP_NAME}
  ./run.sh ${APP_NAME} ${tag} start
  echo "slepp 5s ..."
  sleep 5
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$3" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "upgrade")
    upgrade
    ;;
  "rollback")
    rollback
    ;;
  *)
    usage
    ;;
esac

2.1、python代码如下

python 复制代码
from flask import Flask
import time,os

app = Flask(__name__)

@app.route("/")
def status():
    msg = time.strftime("%Y-%m-%d %H:%M:%S")+"\tMyPid: "+str(os.getpid())+"\tv2.1.0"+"\n"
    return msg

@app.route("/pid")
def pid():
    msg = str(os.getpid()) + "\n"
    return msg

if __name__ == '__main__':
    app.run(port=10080,host="0.0.0.0")

2.3、pipeline流水线,Jenkinsfile配置如下

json 复制代码
pipeline {
    agent any

    stages {
        stage('代码部署') {
            when {
                expression { params.ACTION == 'upgrade'}
            }
            steps {
                script {
                    echo "从git上拉取代码"
                    checkout scmGit(branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[credentialsId: 'c2b40745-be98-4627-93af-5cc975b0e355', url: 'https://gitee.com/****/test.git']])
                    
                    echo '新代码+tag标签 推送到目标服务器备份目录下'
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'aly-arm', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'test_flask.py,run.sh')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])

                    sshPublisher(publishers: [sshPublisherDesc(configName: 'aly-arm', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: """cd /opt;chmod +x run.sh;sh run.sh test_flask.py ${tag} ${ACTION};exit""", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '',usePty: true)], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
                }
            }
        }

        stage('代码回退') {
            when {
                expression { params.ACTION == 'rollback'}
            }
            steps {
                script {
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'aly-arm', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: "cd /opt;sh run.sh test_flask.py ${tag} ${ACTION};exit", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '',usePty: true)], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
                }
            }
        }
    }
}

3、Jenkins配置

3.1、添加2个构建化参数

1、选项参数,用于选择upgrade升级或者rollback回退

2、git参数,用于从gitee上拉取对于标签的值


3.2、添加流水线配置

3.3、执行

相关推荐
sun00770032 分钟前
ubuntu dpkg 删除安装包
运维·服务器·ubuntu
让生命变得有价值1 小时前
使用 helm 部署 gitlab
gitlab·helm
Kkooe1 小时前
GitLab|GitLab报错:PG::ConnectionBad: could not connect to server...
gitlab
吃肉不能购2 小时前
Label-studio-ml-backend 和YOLOV8 YOLO11自动化标注,目标检测,实例分割,图像分类,关键点估计,视频跟踪
运维·yolo·自动化
学Linux的语莫2 小时前
Ansible使用简介和基础使用
linux·运维·服务器·nginx·云计算·ansible
qq_312920113 小时前
docker 部署 kvm 图形化管理工具 WebVirtMgr
运维·docker·容器
学Linux的语莫3 小时前
搭建服务器VPN,Linux客户端连接WireGuard,Windows客户端连接WireGuard
linux·运维·服务器
黑牛先生3 小时前
【Linux】进程-PCB
linux·运维·服务器
Karoku0663 小时前
【企业级分布式系统】ELK优化
运维·服务器·数据库·elk·elasticsearch