2

在 Jenkinsfile 管道脚本中,如何查询正在运行的作业状态以判断它是否已中止?

通常会引发 FlowInterruptedException 或 AbortException(如果脚本正在运行),但这些可以被捕获和忽略。如果有多个语句,脚本也不会立即退出。

我尝试查看“currentBuild.Result”,但在构建完成之前似乎没有设置。'currentBuild.rawBuild' 中的某些东西可能吗?

4

2 回答 2

3

如果捕获到异常,则不会自动设置构建状态。如果您希望此类异常设置构建状态,但让脚本继续,您可以编写例如

try {
    somethingSlow()
} catch (InterruptedException x) {
    currentBuild.result = 'ABORTED'
    echo 'Ignoring abort attempt at this spot'
}
// proceed
于 2016-04-26T18:50:37.357 回答
0

您可以在并行步骤中实现看门狗分支。它使用全局来跟踪可能很危险的看门狗状态,我不知道在“并行”中访问全局变量是否是线程安全的。如果 '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)
}
于 2016-04-28T10:36:06.417 回答