Java Code Examples for hudson.model.Queue#Item

The following examples show how to use hudson.model.Queue#Item . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PipelineRunImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public BlueRun replay() {
    ReplayAction replayAction = run.getAction(ReplayAction.class);
    if(!isReplayable(replayAction)) {
        throw new ServiceException.BadRequestException("This run does not support replay");
    }

    Queue.Item item = replayAction.run2(replayAction.getOriginalScript(), replayAction.getOriginalLoadedScripts());

    if(item == null){
        throw new ServiceException.UnexpectedErrorException("Run was not added to queue.");
    }

    BlueQueueItem queueItem = QueueUtil.getQueuedItem(this.organization, item, run.getParent());
    WorkflowRun replayedRun = QueueUtil.getRun(run.getParent(), item.getId());
    if (queueItem != null) { // If the item is still queued
        return queueItem.toRun();
    } else if (replayedRun != null) { // If the item has left the queue and is running
        return new PipelineRunImpl(replayedRun, parent, organization);
    } else { // For some reason could not be added to the queue
        throw new ServiceException.UnexpectedErrorException("Run was not added to queue.");
    }
}
 
Example 2
Source File: Reaper.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(@NonNull Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) throws IOException, InterruptedException {
    List<ContainerStatus> backOffContainers = PodUtils.getContainers(pod, cs -> {
        ContainerStateWaiting waiting = cs.getState().getWaiting();
        return waiting != null && waiting.getMessage() != null && waiting.getMessage().contains("Back-off pulling image");
    });
    if (backOffContainers.isEmpty()) {
        return;
    }
    backOffContainers.forEach(cs -> {
        TaskListener runListener = node.getTemplate().getListener();
        runListener.error("Unable to pull Docker image \""+cs.getImage()+"\". Check if image tag name is spelled correctly.");
    });
    Queue q = Jenkins.get().getQueue();
    String runUrl = pod.getMetadata().getAnnotations().get("runUrl");
    for (Queue.Item item: q.getItems()) {
        if (item.task.getUrl().equals(runUrl)) {
            q.cancel(item);
            break;
        }
    }
    node.terminate();
}
 
Example 3
Source File: JobRunnerForBranchCause.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Cancel previous builds for specified PR id.
 */
private static boolean cancelQueuedBuildByBranchName(final String branch) {
    Queue queue = getJenkinsInstance().getQueue();

    for (Queue.Item item : queue.getItems()) {
        Optional<Cause> cause = from(item.getAllActions())
                .filter(instanceOf(CauseAction.class))
                .transformAndConcat(new CausesFromAction())
                .filter(instanceOf(GitHubBranchCause.class))
                .firstMatch(new CauseHasBranch(branch));

        if (cause.isPresent()) {
            queue.cancel(item);
            return true;
        }
    }

    return false;
}
 
Example 4
Source File: BuildFlowAction.java    From yet-another-build-visualizer-plugin with MIT License 5 votes vote down vote up
private static boolean isChildrenStillBuilding(Object current, ChildrenFunction children) {
  Iterator childIter = children.children(current).iterator();
  while (childIter.hasNext()) {
    Object child = childIter.next();
    if (child instanceof Queue.Item) {
      return true;
    }
    if (child instanceof Run && ((Run) child).isBuilding()) {
      return true;
    }
    return isChildrenStillBuilding(child, children);
  }
  return false;
}
 
Example 5
Source File: QueueItemImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public QueueItemImpl(BlueOrganization organization, Queue.Item item, BluePipeline pipeline, int expectedBuildNumber) {
    this(organization,
        item,
        pipeline,
        expectedBuildNumber,
        pipeline.getQueue().getLink().rel(Long.toString(item.getId())),
        pipeline.getLink());
}
 
Example 6
Source File: QueueItemImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
QueueItemImpl(BlueOrganization organization, Queue.Item item, BluePipeline pipeline, int expectedBuildNumber, Link self, Link parent) {
    this.organization = organization;
    this.item = item;
    this.pipeline = pipeline;
    this.expectedBuildNumber = expectedBuildNumber;
    this.self = self;
    this.parent = parent;
}
 
Example 7
Source File: OrganizationFolderPipelineImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public BlueQueueContainer getQueue() {
    return new BlueQueueContainer() {
        @Override
        public BlueQueueItem get(String name) {
            for(Queue.Item item: Jenkins.getInstance().getQueue().getItems(folder)){
                if(item.getId() == Long.parseLong(name)){
                    return new QueueItemImpl(organization, item, OrganizationFolderPipelineImpl.this, 1);
                }
            }
            return null;
        }

        @Override
        public Link getLink() {
            return OrganizationFolderPipelineImpl.this.getLink().rel("queue");
        }

        @Override
        public Iterator<BlueQueueItem> iterator() {
            return new Iterator<BlueQueueItem>(){
                Iterator<Queue.Item> it = Jenkins.getInstance().getQueue().getItems(folder).iterator();
                @Override
                public boolean hasNext() {
                    return it.hasNext();
                }

                @Override
                public BlueQueueItem next() {
                    return new QueueItemImpl(organization, it.next(), OrganizationFolderPipelineImpl.this, 1);
                }

                @Override
                public void remove() {
                    //noop
                }
            };
        }
    };
}
 
Example 8
Source File: PendingBuildsHandlerTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@After
public void clearQueue() {
    Queue queue = jenkins.getInstance().getQueue();
    for (Queue.Item item : queue.getItems()) {
        queue.cancel(item);
    }
}
 
Example 9
Source File: MultibranchPipelineRunContainer.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public BlueRun create(StaplerRequest request) {
    blueMbPipeline.mbp.checkPermission(Item.BUILD);
    Queue.Item queueItem = blueMbPipeline.mbp.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause()));
    if(queueItem == null){ // possible mbp.isBuildable() was false due to no sources fetched yet
        return null;
    }
    return new QueueItemImpl(
            blueMbPipeline.getOrganization(),
            queueItem,
            blueMbPipeline,
            1
    ).toRun();
}
 
Example 10
Source File: DynamicRunPtr.java    From DotCi with MIT License 5 votes vote down vote up
public String getTooltip() {
    final Build r = getRun();
    if (r != null) {
        return r.getIconColor().getDescription();
    }
    final Queue.Item item = Jenkins.getInstance().getQueue().getItem(this.dynamicBuild.getParent().getItem(this.combination));
    if (item != null) {
        return item.getWhy();
    }
    return null; // fall back
}
 
Example 11
Source File: ResetStuckBuildsInQueueActor.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
private void resetStuckBuildsInQueue() throws IOException {
    try {
        final Queue.Item[] items = Jenkins.getInstance().getQueue().getItems();
        for (int i = items.length - 1; i >= 0; i--) { // reverse order
            final Queue.Item item = items[i];
            final DockerSwarmLabelAssignmentAction lblAssignmentAction = item
                    .getAction(DockerSwarmLabelAssignmentAction.class); // This can be null here if computer was
                                                                        // never provisioned. Build will sit in
                                                                        // queue forever
            if (lblAssignmentAction != null) {
                long inQueueForMinutes = TimeUnit.MILLISECONDS
                        .toMinutes(new Date().getTime() - lblAssignmentAction.getProvisionedTime());
                if (inQueueForMinutes > RESET_MINUTES) {
                    final String computerName = lblAssignmentAction.getLabel().getName();
                    final Node provisionedNode = Jenkins.getInstance().getNode(computerName);
                    if (provisionedNode != null) {
                        LOGGER.info(String.format("Rescheduling %s and Deleting %s computer ", item, computerName));
                        BuildScheduler.scheduleBuild((Queue.BuildableItem) item);
                        ((DockerSwarmAgent) provisionedNode).terminate();
                    }
                }
            }
        }
    } finally {
        resechedule();
    }

}
 
Example 12
Source File: SubBuildScheduler.java    From DotCi with MIT License 5 votes vote down vote up
public CurrentBuildState waitForCompletion(final DynamicSubProject c, final TaskListener listener) throws InterruptedException {

        // wait for the completion
        int appearsCancelledCount = 0;
        while (true) {
            Thread.sleep(1000);
            final CurrentBuildState b = c.getCurrentStateByNumber(this.dynamicBuild.getNumber());
            if (b != null) { // its building or is done
                if (b.isBuilding()) {
                    continue;
                } else {
                    final Result buildResult = b.getResult();
                    if (buildResult != null) {
                        return b;
                    }
                }
            } else { // not building or done, check queue
                final Queue.Item qi = c.getQueueItem();
                if (qi == null) {
                    appearsCancelledCount++;
                    listener.getLogger().println(c.getName() + " appears cancelled: " + appearsCancelledCount);
                } else {
                    appearsCancelledCount = 0;
                }

                if (appearsCancelledCount >= 5) {
                    listener.getLogger().println(Messages.MatrixBuild_AppearsCancelled(ModelHyperlinkNote.encodeTo(c)));
                    return new CurrentBuildState("COMPLETED", Result.ABORTED);
                }
            }

        }
    }
 
Example 13
Source File: BuildFlowAction.java    From yet-another-build-visualizer-plugin with MIT License 5 votes vote down vote up
private static final ChildrenFunction getChildrenFunc() {
  final Queue.Item[] items = Queue.getInstance().getItems();
  return build -> {
    List<Object> result = new ArrayList<>();
    if (build instanceof Run) {
      result.addAll(BuildCache.getCache().getDownstreamBuilds((Run) build));
      result.addAll(BuildCache.getDownstreamQueueItems(items, (Run) build));
    }
    return result;
  };
}
 
Example 14
Source File: BuildHistory.java    From DotCi with MIT License 5 votes vote down vote up
public List<Queue.Item> getQueuedItems() {
    final LinkedList<Queue.Item> list = new LinkedList<>();
    for (final Queue.Item item : Jenkins.getInstance().getQueue().getApproximateItemsQuickly()) {
        if (item.task == this.dynamicProject) {
            list.addFirst(item);
        }
    }
    return list;
}
 
Example 15
Source File: QueuedBuild.java    From DotCi with MIT License 4 votes vote down vote up
public QueuedBuild(final Queue.Item item, final int number) {
    this.item = item;
    this.number = number;
}
 
Example 16
Source File: Utils.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
public static Job<?, ?> getProject(Queue.Item item) {
	if (item.task instanceof Job)
		return (Job<?, ?>) item.task;
	return null;
}
 
Example 17
Source File: JobRunnerForCause.java    From github-integration-plugin with MIT License 4 votes vote down vote up
/**
 * Cancel previous builds for specified PR id.
 */
public int cancelQueuedBuildByPrNumber(final int id) {
    int canceled = 0;
    SecurityContext old = impersonate(ACL.SYSTEM);
    try {
        final Queue queue = getJenkinsInstance().getQueue();
        final Queue.Item[] items = queue.getItems();

        //todo replace with stream?
        for (Queue.Item item : items) {
            if (!(item.task instanceof Job)) {
                LOGGER.debug("Item {} not instanceof job", item);
                continue;
            }

            final Job<?, ?> jobTask = (Job<?, ?>) item.task;
            if (!jobTask.getFullName().equals(job.getFullName())) {
                LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName());
                continue;
            }

            final CauseAction action = item.getAction(CauseAction.class);
            if (isNull(action)) {
                LOGGER.debug("Cause action is null for {}", jobTask.getFullName());
                continue;
            }

            Optional<Cause> cause = from(action.getCauses())
                    .filter(instanceOf(GitHubPRCause.class))
                    .firstMatch(new CauseHasPRNum(id));

            if (cause.isPresent()) {
                LOGGER.debug("Cancelling {}", item);
                queue.cancel(item);
                canceled++;
            }
        }
    } finally {
        SecurityContextHolder.setContext(old);
    }

    return canceled;
}
 
Example 18
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test @Ignore
public void getPipelineJobrRuns() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    sampleRepo1.init();
    sampleRepo1.write("Jenkinsfile", "stage 'build'\n "+"node {echo 'Building'}\n"+
        "stage 'test'\nnode { echo 'Testing'}\n" +
        "sleep 10000 \n"+
        "stage 'deploy'\nnode { echo 'Deploying'}\n"
    );
    sampleRepo1.write("file", "initial content");
    sampleRepo1.git("add", "Jenkinsfile");
    sampleRepo1.git("commit", "--all", "--message=flow");

    //create feature branch
    sampleRepo1.git("checkout", "-b", "abc");
    sampleRepo1.write("Jenkinsfile", "echo \"branch=${env.BRANCH_NAME}\"; "+"node {" +
        "   stage ('Build'); " +
        "   echo ('Building'); " +
        "   stage ('Test'); sleep 10000; " +
        "   echo ('Testing'); " +
        "   stage ('Deploy'); " +
        "   echo ('Deploying'); " +
        "}");
    ScriptApproval.get().approveSignature("method java.lang.String toUpperCase");
    sampleRepo1.write("file", "subsequent content1");
    sampleRepo1.git("commit", "--all", "--message=tweaked1");


    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo1.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }
    scheduleAndFindBranchProject(mp);

    for(WorkflowJob job : mp.getItems()) {
        Queue.Item item =  job.getQueueItem();
        if(item != null ) {
            item.getFuture().waitForStart();
        }
        job.setConcurrentBuild(false);
        job.scheduleBuild2(0);
        job.scheduleBuild2(0);
    }
    List l = request().get("/organizations/jenkins/pipelines/p/activities").build(List.class);

    Assert.assertEquals(4, l.size());
    Assert.assertEquals("io.jenkins.blueocean.service.embedded.rest.QueueItemImpl", ((Map) l.get(0)).get("_class"));
    Assert.assertEquals("io.jenkins.blueocean.rest.impl.pipeline.PipelineRunImpl", ((Map) l.get(2)).get("_class"));
}
 
Example 19
Source File: GitHubBranchTriggerTest.java    From github-integration-plugin with MIT License 2 votes vote down vote up
@LocalData
@Test
public void buildButtonsPerms() throws Exception {
    jRule.getInstance().setNumExecutors(0);

    jRule.jenkins.setSecurityRealm(jRule.createDummySecurityRealm());
    ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
    auth.add(Jenkins.READ, "alice");
    auth.add(Computer.BUILD, "alice");

    auth.add(Jenkins.ADMINISTER, "admin");

    auth.add(Jenkins.READ, "bob");
    auth.add(Computer.BUILD, "bob");

    jRule.jenkins.setAuthorizationStrategy(auth);

    final FreeStyleProject project = (FreeStyleProject) jRule.getInstance().getItem("project");

    Map<Permission, Set<String>> perms = new HashMap<>();

    HashSet<String> users = new HashSet<>();
    users.add("alice");
    users.add("bob");

    perms.put(Item.READ, users);

    perms.put(Item.BUILD, Collections.singleton("bob"));

    project.addProperty(new AuthorizationMatrixProperty(perms));


    JenkinsRule.WebClient webClient = jRule.createWebClient();
    webClient = webClient.login("bob", "bob");

    HtmlPage repoPage = webClient.getPage(project, "github-branch");
    HtmlForm form = repoPage.getFormByName("rebuildAllFailed");
    HtmlFormUtil.getButtonByCaption(form, "Rebuild all failed builds").click();
    HtmlPage page = (HtmlPage) submit(form);

    Queue.Item[] items = jRule.getInstance().getQueue().getItems();
    assertThat(items, arrayWithSize(0));

}
 
Example 20
Source File: GitHubPRTriggerTest.java    From github-integration-plugin with MIT License 2 votes vote down vote up
@LocalData
@Test
public void buildButtonsPerms() throws Exception {
    j.getInstance().setNumExecutors(0);

    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
    auth.add(Jenkins.READ, "alice");
    auth.add(Computer.BUILD, "alice");

    auth.add(Jenkins.ADMINISTER, "admin");

    auth.add(Jenkins.READ, "bob");
    auth.add(Computer.BUILD, "bob");

    j.jenkins.setAuthorizationStrategy(auth);

    final FreeStyleProject project =  (FreeStyleProject) j.getInstance().getItem("project");

    Map<Permission,Set<String>> perms = new HashMap<>();

    HashSet<String> users = new HashSet<>();
    users.add("alice");
    users.add("bob");

    perms.put(Item.READ, users);

    perms.put(Item.BUILD, Collections.singleton("bob"));

    project.addProperty(new AuthorizationMatrixProperty(perms));


    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient = webClient.login("bob", "bob");

    HtmlPage repoPage = webClient.getPage(project, "github-pullrequest");
    HtmlForm form = repoPage.getFormByName("rebuildAllFailed");
    HtmlFormUtil.getButtonByCaption(form, "Rebuild all failed builds").click();
    HtmlPage page = (HtmlPage) submit(form);

    Queue.Item[] items = j.getInstance().getQueue().getItems();
    assertThat(items, arrayWithSize(0));
}