Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for Issue-1140 - cancel running jobs on merge request update when source branch is same #1268

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
import com.dabsquared.gitlabjenkins.gitlab.api.model.BuildState;
import com.dabsquared.gitlabjenkins.publisher.GitLabCommitStatusPublisher;
import com.dabsquared.gitlabjenkins.util.LoggerUtil;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.*;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider;
Expand All @@ -24,7 +21,7 @@ public class PendingBuildsHandler {

private static final Logger LOGGER = Logger.getLogger(PendingBuildsHandler.class.getName());

public void cancelPendingBuilds(Job<?, ?> job, Integer projectId, String branch) {
public void cancelPendingBuilds(Job<?, ?> job, Integer projectId, String sourceBranch) {
Queue queue = Jenkins.getInstance().getQueue();
for (Queue.Item item : queue.getItems()) {
if (!job.getName().equals(item.task.getName())) {
Expand All @@ -38,11 +35,29 @@ public void cancelPendingBuilds(Job<?, ?> job, Integer projectId, String branch)
if (!projectId.equals(queueItemCauseData.getSourceProjectId())) {
continue;
}
if (branch.equals(queueItemCauseData.getBranch())) {
cancel(item, queue, branch);
if (sourceBranch.equals(queueItemCauseData.getBranch())) {
cancel(item, queue, sourceBranch);
setCommitStatusCancelledIfNecessary(queueItemCauseData, job);
}
}
stopRunningBuilds(job, sourceBranch);
}

private void stopRunningBuilds(Job<?, ?> job, String sourceBranch) {
for (Run<?, ?> build : job.getBuilds()) {
if (build.isBuilding() && runsCausedByMergeToSourceBranch(build, sourceBranch)) {
LOGGER.log(Level.INFO, "Stopping build {0} of job {1} caused by commit to branch {2}", LoggerUtil.toArray(build.getDisplayName(), job.getName(), sourceBranch));
Executor executor = build.getExecutor();
if (executor != null) executor.doStop();
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
if (cause != null) setCommitStatusCancelledIfNecessary(cause.getData(), job);
}
}
}

private boolean runsCausedByMergeToSourceBranch(Run<?, ?> build, String sourceBranch) {
GitLabWebHookCause cause = build.getCause(GitLabWebHookCause.class);
return cause != null && cause.getData().getSourceBranch().equals(sourceBranch);
}

private GitLabWebHookCause getGitLabWebHookCauseData(Queue.Item item) {
Expand Down