linux 后台运行
Jenkins 构建完后推送到业务机器,在执行脚本时,脚本中的 nohup 命令无法正常退出,构建前台任务就卡住了,或者是nohup总是无效,setsid也是一样启动后自动退出
在coding.net 中 设置Jenkinsfile的pipeline脚本 nohup也是不能正常运行
多次尝试后得出以下一些小经验,希望其他人避免踩抗
方案1:nohup (失败)
sh 'nohup pyhon3 xxx.py &'
方案2:setsid(失败)
sh 'setsid python3 xxx.py >> xxx.out &'
方案3: BUILD_ID="dontKillMe" (失败)
pipeline {
agent any
environment {
BUILD_ID="dontKillMe"
}
stages{
stage("发布"){
sh "nohup python3 xxx.py &"
}
}
}
方案4:JENKINS_NODE_COOKIE=dontKillMe (成功)
sh " JENKINS_NODE_COOKIE=dontKillMe nohup python3 xxx.py &"
方案5:JENKINS_NODE_COOKIE=background_job (成功)
pipeline {
agent any
environment {}
stages {
stage('关掉') {
steps {
script{
def PID2 = sh(script: "ps -ef|grep python3| grep xxx.py | awk '{print \$2}'", returnStdout: true).trim()
if(PID2 != null && PID2 != ""){
sh "echo ${PID2}; kill -9 ${PID2}"
}
}
}
}
stage('启动新的') {
steps {
script{
withEnv(['JENKINS_NODE_COOKIE=background_job']) {
sh '''
setsid python3 xxxx.py >> log/xxx.out &
'''
}
}
}
}
}
}
完整代码:
pipeline {
agent any
environment {
// BUILD_ID="dontKillMe"
}
stages {
stage("检出") {
steps {
checkout(
[$class: 'GitSCM',
branches: [[name: GIT_BUILD_REF]],
userRemoteConfigs: [[
url: GIT_REPO_URL,
credentialsId: CREDENTIALS_ID
]]]
)
}
}
stage('安装依赖') {
steps {
sh ""
}
}
stage('复制文件') {
steps {
sh 'printenv'
sh 'pwd'
sh 'echo ${WORK_DIR}'
sh 'ls -ll'
sh '''
cp -f x1.py ${WORK_DIR} && cp -f x2.py ${WORK_DIR}
'''
}
}
stage('关掉脚本') {
steps {
sh '''PID=`ps -ef | grep python3 | grep x1.py | awk \'{print $2}\'`
if [ "$PID" = "" ] ; then
echo " x1 not running"
else
echo "the x1 service is RUNNING and it will be killed by agent"
kill -9 $PID
fi'''
//另外一种写法
script{
def PID2 = sh(script: "ps -ef|grep python3| grep x2.py | awk '{print \$2}'", returnStdout: true).trim()
if(PID2 != null && PID2 != ""){
sh "echo ${PID2}; kill -9 ${PID2}"
}
}
}
}
stage('启动新的脚本') {
steps {
script{
withEnv(['JENKINS_NODE_COOKIE=background_job']) {
sh '''cd ${WORK_DIR}
pwd
setsid python3 x1.py -i config-test.ini >> log/x1.out &
nohup python3 x2.py -i config-test.ini >> log/x2.out &
'''
}
}
}
}
}
post{
always {
sh 'echo always'
}
success {
sh "echo success"
}
failure {
sh "echo fail"
}
cleanup {
deleteDir()
dir("${workspace}@tmp"){deleteDir()}
dir("${workspace}@script"){deleteDir()}
}
}
}