stages.ssh.groovy 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. sharedLibsPath = "${env.WORKSPACE}/sharedLibs"
  2. gitTargetPath = 'reverseSearch'
  3. def upgrade(Object CONFIG, String base_branch, closures=[:]) {
  4. stage('source code check out') {
  5. println "loading ${sharedLibsPath}/gitUtil.groovy..."
  6. def gitUtils = load "${sharedLibsPath}/gitUtil.groovy"
  7. COMMIT_SHA = closures.GITCLONE == null ? gitUtils.clone(CONFIG.git, base_branch, gitTargetPath) : closures.GITCLONE()
  8. }
  9. stage('transfer files to remote') {
  10. withCredentials([
  11. sshUserPrivateKey(
  12. credentialsId: CONFIG.ssh.credentialId,
  13. keyFileVariable: 'SSH_KEY')
  14. ]) {
  15. def remote = [
  16. name: 'transfer-files',
  17. host: CONFIG.ssh.server,
  18. user: CONFIG.ssh.username ?: "root",
  19. allowAnyHosts: true,
  20. identityFile: env.SSH_KEY,
  21. timeoutSec: 60
  22. ]
  23. sshCommand remote: remote, command: """
  24. if [ -d "${CONFIG.ssh.remotePath}/${gitTargetPath}" ]; then
  25. cd ${CONFIG.ssh.remotePath}/${gitTargetPath}
  26. my_pid=\$\$
  27. pgrep -f 'python.*restful.py' | while read pid; do
  28. [ "\$pid" = "\$my_pid" ] && continue
  29. [ "\$(readlink -f /proc/\$pid/cwd)" = "\$(pwd)" ] || continue
  30. kill "\$pid"
  31. done || true
  32. sleep 2
  33. echo '🛑 停止 Python 服务...'
  34. fi
  35. """
  36. sshCommand remote: remote, command: """
  37. if [ -d "${CONFIG.ssh.remotePath}/${gitTargetPath}" ]; then
  38. rm -rf "${CONFIG.ssh.remotePath}/${gitTargetPath}"
  39. echo '✅ 远程目录已清空'
  40. fi
  41. """
  42. sshPut remote: remote, from: gitTargetPath, into: "${CONFIG.ssh.remotePath}"
  43. echo "✅ 文件传输完成"
  44. }
  45. }
  46. stage('run project') {
  47. withCredentials([
  48. sshUserPrivateKey(
  49. credentialsId: CONFIG.ssh.credentialId,
  50. keyFileVariable: 'SSH_KEY')
  51. ]) {
  52. def remote = [
  53. name: 'transfer-files',
  54. host: CONFIG.ssh.server,
  55. user: CONFIG.ssh.username ?: "root",
  56. allowAnyHosts: true,
  57. identityFile: env.SSH_KEY,
  58. timeoutSec: 60
  59. ]
  60. // 6.2 启动服务
  61. echo '🚀 启动 Python 服务...'
  62. try {
  63. sshCommand remote: remote,
  64. command: """
  65. cd ${CONFIG.ssh.remotePath}/${gitTargetPath}
  66. nohup ${CONFIG.ssh.command} > runtime.log 2>&1 &
  67. echo \$! > PID
  68. sleep 3
  69. pgrep -f 'python.*restful.py' >/dev/null
  70. """
  71. echo "✅ Python(${gitTargetPath}) 服务已启动 (目录: ${CONFIG.ssh.remotePath}/${gitTargetPath})"
  72. } catch (Exception e) {
  73. echo "❌ 命令执行失败: ${e.getMessage()}"
  74. // 处理失败情况
  75. }
  76. // if (startStatus != 0) error "❌ 服务启动失败"
  77. }
  78. }
  79. }
  80. return this