Search code examples
jenkinsjenkins-pipeline

Skip Jenkins Pipeline Steps If Node Is Offline


I have a Jenkins Pipeline job that, for part of the build, uses a node with a lot of downtime. I'd like this step performed if the node is online and skipped without failing the build if the node is offline.

This is related, but different from the problem of skipping parts of a Matrix Project.

I tried to programmatically check if a node is online like so.

jenkins.model.Nodes.getNode('my-node').toComputer().isOnline()

This runs up against the Jenkins security sandbox:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified method java.lang.Class getNode java.lang.String

I tried setting a timeout that will be tripped if the node is offline.

try {
    timeout(time: 10, unit: 'MINUTES') {
        node('my-node') {
            // Do optional step
        }
    }
} catch (e) {
    echo 'Time out on optional step. Node down?'
}

This has a major downside. I have to know what the longest time the step would take, then wait even longer when the node is down. I tried working around that with a "canary" step:

try {
    timeout(time: 1, unit: 'SECONDS') {
        node('my-node') {
            echo 'Node is up. Performing optional step.'
        }
    }
    node('my-node') {
        echo 'This is an optional step.'
    }
} catch (e) {
    echo 'Time out on optional step. Node down?'
}

This skips the step if the node is up, but busy with another job. This is the best solution I have come up with so far. Is there just a way to check if the node is online without using a timeout?


Solution

  • This should work:

    Jenkins.instance.getNode('my-node').toComputer().isOnline()

    see http://javadoc.jenkins-ci.org/jenkins/model/Jenkins.html