sharedLibsPath = "${env.WORKSPACE}/sharedLibs" gitTargetPath = 'reverseSearch' def upgrade(Object CONFIG, String base_branch, closures=[:]) { stage('source code check out') { println "loading ${sharedLibsPath}/gitUtil.groovy..." def gitUtils = load "${sharedLibsPath}/gitUtil.groovy" COMMIT_SHA = closures.GITCLONE == null ? gitUtils.clone(CONFIG.git, base_branch, gitTargetPath) : closures.GITCLONE() } stage('transfer files to remote') { withCredentials([ sshUserPrivateKey( credentialsId: CONFIG.ssh.credentialId, keyFileVariable: 'SSH_KEY') ]) { def remote = [ name: 'transfer-files', host: CONFIG.ssh.server, user: CONFIG.ssh.username ?: "root", allowAnyHosts: true, identityFile: env.SSH_KEY, timeoutSec: 60 ] sshCommand remote: remote, command: """ if [ -d "${CONFIG.ssh.remotePath}/${gitTargetPath}" ]; then cd ${CONFIG.ssh.remotePath}/${gitTargetPath} my_pid=\$\$ pgrep -f 'python.*restful.py' | while read pid; do [ "\$pid" = "\$my_pid" ] && continue [ "\$(readlink -f /proc/\$pid/cwd)" = "\$(pwd)" ] || continue kill "\$pid" done || true sleep 2 echo '🛑 停止 Python 服务...' fi """ sshCommand remote: remote, command: """ if [ -d "${CONFIG.ssh.remotePath}/${gitTargetPath}" ]; then rm -rf "${CONFIG.ssh.remotePath}/${gitTargetPath}" echo '✅ 远程目录已清空' fi """ sshPut remote: remote, from: gitTargetPath, into: "${CONFIG.ssh.remotePath}" echo "✅ 文件传输完成" } } stage('run project') { withCredentials([ sshUserPrivateKey( credentialsId: CONFIG.ssh.credentialId, keyFileVariable: 'SSH_KEY') ]) { def remote = [ name: 'transfer-files', host: CONFIG.ssh.server, user: CONFIG.ssh.username ?: "root", allowAnyHosts: true, identityFile: env.SSH_KEY, timeoutSec: 60 ] // 6.2 启动服务 echo '🚀 启动 Python 服务...' try { sshCommand remote: remote, command: """ cd ${CONFIG.ssh.remotePath}/${gitTargetPath} nohup ${CONFIG.ssh.command} > runtime.log 2>&1 & echo \$! > PID sleep 3 pgrep -f 'python.*restful.py' >/dev/null """ echo "✅ Python(${gitTargetPath}) 服务已启动 (目录: ${CONFIG.ssh.remotePath}/${gitTargetPath})" } catch (Exception e) { echo "❌ 命令执行失败: ${e.getMessage()}" // 处理失败情况 } // if (startStatus != 0) error "❌ 服务启动失败" } } } return this