stages.ssh.groovy 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. try {
  61. sshCommand remote: remote,
  62. command: """
  63. cd ${CONFIG.ssh.remotePath}/${gitTargetPath}
  64. nohup ${CONFIG.ssh.command} > runtime.log 2>&1 &
  65. echo \$! > PID
  66. sleep 3
  67. pgrep -f 'python.*restful.py' >/dev/null
  68. """
  69. echo "✅ Python(${gitTargetPath}) 服务已启动 (目录: ${CONFIG.ssh.remotePath}/${gitTargetPath})"
  70. } catch (Exception e) {
  71. echo "❌ 命令执行失败: ${e.getMessage()}"
  72. }
  73. }
  74. }
  75. }
  76. return this