在Jenkinfile管道脚本中,如何查询正在运行的作业状态以判断它是否已被中止?
通常会引发FlowInterruptedException或AbortException(如果脚本正在运行),但可以捕获并忽略这些内容。如果脚本有多个语句,脚本也不会立即退出。
我试着查看“currentBuild.Result'但是在构建完成之前似乎没有设置。在' currentBuild.rawBuild'中的东西也许?
答案 0 :(得分:2)
如果捕获到异常,则没有任何内容会自动设置构建状态。如果您想要这样的例外来设置构建状态,但让脚本继续,您可以编写例如
try {
somethingSlow()
} catch (InterruptedException x) {
currentBuild.result = 'ABORTED'
echo 'Ignoring abort attempt at this spot'
}
// proceed
答案 1 :(得分:0)
您可以在并行步骤中实现监视程序分支。它使用全局来跟踪可能危险的看门狗状态,我不知道在'parallel'中访问全局变量是否是线程安全的。如果'bat'忽略了终止并且根本没有引发异常,它甚至可以工作。
代码:
runWithAbortCheck { abortState ->
// run all tests, print which failed
node ('windows') {
for (int i = 0; i < 5; i++) {
try {
bat "ping 127.0.0.1 -n ${10-i}"
} catch (e) {
echo "${i} FAIL"
currentBuild.result = "UNSTABLE"
// continue with remaining tests
}
abortCheck(abortState) // sometimes bat doesn't even raise an exception! so check here
}
}
}
def runWithAbortCheck(closure) {
def abortState = [complete:false, aborted:false]
parallel (
"_watchdog": {
try {
waitUntil { abortState.complete || abortState.aborted }
} catch (e) {
abortState.aborted = true
echo "caught: ${e}"
throw e
} finally {
abortState.complete = true
}
},
"work": {
try {
closure.call(abortState)
}
finally {
abortState.complete = true
}
},
"failFast": true
)
}
def _abortCheckInstant(abortState) {
if (abortState.aborted) {
echo "Job Aborted Detected"
throw new org.jenkinsci.plugins.workflow.steps.FlowInterruptedException(Result.ABORTED)
}
}
def abortCheck(abortState) {
_abortCheckInstant(abortState)
sleep time:500, unit:"MILLISECONDS"
_abortCheckInstant(abortState)
}