sybkar
sybkar

Reputation: 386

How to prevent a build from plugin code in Jenkins

I'm trying to write a plugin that will prevent a build from occurring based on certain conditions. I've tried putting the conditional checks in the prebuild method (overridden), but from what I can see, the best I can hope to accomplish from there is setting the build status to Result.ABORTED or Result.FAILURE.

Does anyone know how to either

Upvotes: 1

Views: 374

Answers (1)

hyde
hyde

Reputation: 62777

At least one way is to extend QueueTaskDispatcher. With it you get job and node and can block it from being built on that node at that time. You can of course not care about the node, and just block the job always. The method will be called periodically for scheduled jobs, when Jenkins is trying to find a node to build it with.

import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Node;
import hudson.model.Queue.BuildableItem;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.QueueTaskDispatcher;

@Extension
public class MyTaskDispatcher extends QueueTaskDispatcher {

    @Override
    public CauseOfBlockage canTake(Node node, BuildableItem item) {

        // only care about AbstractProject tasks
        if (!(item.task instanceof AbstractProject<?, ?>)) return null;

        AbstractProject<?, ?> proj = (AbstractProject<?, ?>) item.task;

        if(!proj.getName().contains(node.getNodeName()) {
            return new CauseOfBlockage.BecauseNodeIsBusy("Job name does not contain node name");
        }
        return null;
    }
}

Upvotes: 1

Related Questions