KACE框架流水线

import java.io.File

// 数据库对象
class KaceDb {
    // 用户名
    public String jdbcUsername;
    // 密码
    public String jdbcPassword;
    // 数据库类型
    public String type;
    // 数据库IP
    public String ip;
    // 数据库端口
    public String port;
    // 数据库名
    public String dbName;
    // jdbc驱动
    public String jdbcDriver;
    // 数据库链接
    public String jdbcUrl;

    public String dbPath;

    def KaceDb(jdbcUsername,jdbcPassword,type,ip,port,dbName,dbPath) {
        this.jdbcUsername = jdbcUsername
        this.jdbcPassword = jdbcPassword
        this.type = type
        this.ip = ip
        this.port = port

        if(type == "mysql") {
            this.jdbcDriver = "com.mysql.cj.jdbc.Driver"
            this.jdbcUrl = "jdbc:mysql://$ip:$port/$dbName?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&allowMultiQueries=true"
        }

        this.dbName = dbName
        this.dbPath = dbPath
    }
}

// 前端对象
class KaceWeb {
    // 项目名称
    public String projectName;
    // web 编译的路径
    public String webPath;

    def KaceWeb(String projectName, String webPath){
        this.projectName = projectName
        this.webPath = webPath
    }
} 

class KaceBase {
    public String  kdopPath;

    def KaceBase(kdopPath){
        this.kdopPath = kdopPath
    }

    def compareServer(Boolean skip,String op) {
        def testSkip = "-Dmaven.test.skip=true"
        if (!skip) {
            testSkip = ""
        }

        sh "cd $kdopPath && mvn clean $op $testSkip"
    }
}

// 后台服务对象
class KaceServer {
    // 部署路径
    public String deployPath;
    // 编译打包路径-gitclone路径
    public String kdopPath;
    // 服务名
    public String serverName;
    // 服务端口
    public String port;
    // 服务启动参数
    public def args;
    public String managementPort;

    def KaceServer(deployPath, kdopPath, serverName, port, args,managementPort){
        this.deployPath = deployPath
        this.kdopPath = kdopPath
        this.serverName = serverName
        this.port = port
        this.args = args
        this.managementPort = managementPort
    }
}


// git下载方法
def gitClone(String remoteAddr, String branch, String credentialsId,String dirName) {
    dir(dirName){
        checkout([$class: 'GitSCM',
            branches: [[name: (branch)]], doGenerateSubmoduleConfigurations: false, 
            extensions: [], submoduleCfg: [], 
            userRemoteConfigs: [[credentialsId: (credentialsId), url: (remoteAddr)]]])
    }
}

// 编译后台
def compareServer(String kdopPath,Boolean skip,String op) {
    def testSkip = "-Dmaven.test.skip=true"
    if (!skip) {
        testSkip = ""
    }

    sh "cd $kdopPath && mvn clean $op $testSkip"
}

// 重启bootapp
def startApp(KaceServer kaceServer,KaceDb db){
    def managementPortArgs = '';
    if (kaceServer.managementPort != ''){
        managementPortArgs = "--management.server.port=${kaceServer.managementPort}"
    }

    // 创建部署服务的目录
    sh """
        mkdir -p ${kaceServer.deployPath}
        ps -ef|grep java | grep koca|grep ${kaceServer.serverName}| awk '{print \$2}'|xargs -r kill -9
        rm -rf ${kaceServer.deployPath}/${kaceServer.serverName}
    """

    // 拷贝服务到指定目录,并启动服务
    sh """
        filename=`ls ${kaceServer.kdopPath}/${kaceServer.serverName}/target/|grep bin`
        tar -zxvf ${kaceServer.kdopPath}/${kaceServer.serverName}/target/\$filename -C ${kaceServer.deployPath}
        foldername=\${filename%-bin.tar.gz}
        JENKINS_NODE_COOKIE=dontKillMe  && ${kaceServer.deployPath}/\$foldername/bin/startup.sh \
            --server.port=${kaceServer.port} \
            --jdbc.data-sources[0].id=default \
            --jdbc.data-sources[0].pool.url='${db.jdbcUrl}' \
            --jdbc.data-sources[0].pool.username=${db.jdbcUsername} \
            --jdbc.data-sources[0].pool.password=${db.jdbcPassword} \
            --eureka.client.service-url.defaultZone=http://127.0.0.1:38085/eureka \
            ${managementPortArgs} \
            ${kaceServer.args}
        sleep 10
    """
}

  // 编译web并拷贝到/opt/nginx目录下
def compareWeb(KaceWeb kaceWeb){
    dir(kaceWeb.webPath) {
        sh """
            yarn install
            yarn run build
            mkdir -p /opt/nginx/$kaceWeb.projectName
            rm -rf /opt/nginx/$kaceWeb.projectName/*
            echo Y | cp -rf dist/* /opt/nginx/$kaceWeb.projectName/
        """
    }
}

def getAllSql(KaceDb db) {

    sh '''
        mkdir -p $workspace/all-sql
        rm -rf $workspace/all-sql/*
    ''' 
    
    sh """
        pwd 
        cd $db.dbPath
        for file in `find ./ -type f -name '*.sql' | grep 'V'`
        do 
            echo Y |cp -f \$file $workspace/all-sql/
        done
    """  

    return "filesystem:$workspace/all-sql"
}

// 清空数据库
def cleanDb(KaceDb db){
    sh "/opt/tools/flyway-6.2.2/flyway -driver=$db.jdbcDriver -url='$db.jdbcUrl' -user=$db.jdbcUsername -password=$db.jdbcPassword clean"
}

// 全量升级数据库
def execFlywayAll(KaceDb db) {
    def sqlPath =  getAllSql(db) 
    cleanDb(db)
    sh "flyway -locations=$sqlPath -driver=$db.jdbcDriver -url='$db.jdbcUrl' -encoding=GBK -user=$db.jdbcUsername -password=$db.jdbcPassword migrate"
}


// 初始化服务
def initServer(String dbType,String gateType){
    def cloudDeployPath = "/opt/application/koca-center/cloud-center"
    def cloudKdopPath = "/opt/kdop/workspace/KACE_frame/KACE_frame/ace/bootapps/koca-center/cloud-center"

    def appDeployPath = "/opt/application/koca-center/app-center"
    def appKdopPath = "/opt/kdop/workspace/KACE_frame/KACE_frame/ace/bootapps/koca-center/app-center"

    def serviceDeployPath = "/opt/application/koca-center/service-center"
    def serviceKdopPath = "/opt/kdop/workspace/KACE_frame/KACE_frame/ace/bootapps/koca-center/service-center"

    // 初始化服务对象
    def registry = new KaceServer(cloudDeployPath,cloudKdopPath,"registry-eureka","38085","","");

    def gatewayName="";
    if(gateType == 'gateway') {
        gatewayName = "cloud-gateway" 
    }else {
        gatewayName = "cloud-zuul" 
    }
    def gateway = new KaceServer(cloudDeployPath,cloudKdopPath,gatewayName,"38080","","37011");

    def dac = new KaceServer(appDeployPath,appKdopPath,"dac-app","39090","","");
  
    def manager = new KaceServer(serviceDeployPath,serviceKdopPath,"manager-service","39091","","37012");

    def serviceList = new ArrayList();
    serviceList.add(registry)
    serviceList.add(gateway)
    serviceList.add(dac)
    serviceList.add(manager)
    serviceList.add(manager)

    return serviceList
}

// 初始化db
def initDb(String dbType){
    // 初始化数据库对象
    def kacedb = new KaceDb("xx","xx","$dbType","10.202.63.26","3306","koca_ace_develop","$MYSQL_DB_PATH")
   return kacedb 
}

// 初始化web
def initWeb(String projectName,String webPath){
    def kaceWeb = new KaceWeb(projectName, webPath)
    return kaceWeb
}

pipeline{

    agent{

        node{
            label 'Node10.202.63.17'
        }
    }

    parameters{
        booleanParam (defaultValue: false, description: '拉取KACE框架代码', name: 'git_clone_code')
        choice(description: '指定想要升级的数据库类型',name: 'selected_database',choices: ['mysql'])
        booleanParam (defaultValue: false, description: '全量升级数据库', name: 'all_db')
        booleanParam (defaultValue: false, description: '编译后台', name: 'compile_app')
        choice(description: '选择网关类型',name: 'gateway_type',choices: ['gateway','zuul'])
        booleanParam (defaultValue: false, description: '启动后台', name: 'start_app')
        booleanParam (defaultValue: false, description: '编译前端', name: 'compile_web')
        booleanParam (defaultValue: false, description: '发布KACE到MAVEN制品库[SNAPSHOT]', name: 'publish_kace')
    }

    environment{
        DEFAULT_ENV = 'develop'
        MYSQL_DB_PATH = 'KACE_frame/ace/database/koca-ace/mysql'
        PARENT_PATH = 'KACE_frame/ace/parent'
        MODULES_PATH = 'KACE_frame/ace/modules'
        BOOT_APP_PATH = 'KACE_frame/ace/bootapps/koca-center'
        WEB_PATH = "KACE_frame/web/framework"
    }

    stages{

        stage('并行阶段'){

            parallel{

                stage("初始化"){

                    steps{

                        script{
                            // 初始化数据库对象
                            db = initDb("$params.selected_database")
                            println(db)
                            // 初始化服务对象
                            serviceList = initServer("$params.selected_database","$gateway_type")
                            parent = new KaceBase("$PARENT_PATH")
                            modules = new KaceBase("$MODULES_PATH")
                            // 初始化web对象
                            kaceWeb = initWeb("kace_frame","$WEB_PATH")
                        }
                    }
                }
            }
        }

        stage("拉取代码"){

            when{

                expression{
                    return params.git_clone_code
                }
            }

            steps{
                print("拉取kace框架代码")
                gitClone('http://xxx/jr/kace/koca-cf.git',"refs/heads/${DEFAULT_ENV}",'gitlab-kace','KACE_frame')
            }
        }

        stage("全量升级数据库"){

            when{

                expression{
                    return params.all_db
                }
            }

            steps{

                script{
                    print("升级数据库")
                    execFlywayAll(db)
                }
            }
        }

        stage("编译后台"){

            when{

                expression{
                    return params.compile_app
                }
            }

            steps{

                script{

                    print("编译后台")
                    compareServer(parent.kdopPath,true,"install")
                    compareServer(modules.kdopPath,true,"install")
                    // 编译bootapp
                    serviceList.each{
                        compareServer(it.kdopPath,true,"package")
                    }
                }
            }
        }

        stage("启动后台服务"){

            when{

                expression{
                    return params.start_app
                }
            }

            steps{

                script{

                    print("启动后台服务")
                    serviceList.each{
                        startApp(it,db)
                    }
                }
            }
        }

        stage("构建前端"){

            when{

                expression{
                    return params.compile_web
                }
            }

            steps{

                script{
                    print("构建前端")
                    compareWeb(kaceWeb)
                }
            }
        }

        stage("发布到maven制品库"){

            when{

                expression{
                    return params.publish_kace
                }
            }

            steps{
                print("发布到maven制品库")
            }
        }
    }
}