Search in sources :

Example 1 with BlueQueueItem

use of io.jenkins.blueocean.rest.model.BlueQueueItem in project blueocean-plugin by jenkinsci.

the class QueueContainerImpl method getQueuedItems.

/**
     * This function gets gets a list of all queued items if the job is a buildable item.
     *
     * Note the estimated build number calculation is a guess - job types need not return
     * sequential build numbers.
     *
     * @return List of items newest first
     */
public static List<BlueQueueItem> getQueuedItems(Job job) {
    Link pipelineLink = LinkResolver.resolveLink(job);
    if (job instanceof BuildableItem) {
        BuildableItem task = (BuildableItem) job;
        List<Queue.Item> items = Jenkins.getInstance().getQueue().getItems(task);
        List<BlueQueueItem> items2 = Lists.newArrayList();
        for (int i = 0; i < items.size(); i++) {
            Link self = pipelineLink.rel("queue").rel(Long.toString(items.get(i).getId()));
            items2.add(0, new QueueItemImpl(items.get(i), job.getName(), (items.size() == 1 ? job.getNextBuildNumber() : job.getNextBuildNumber() + i), self, pipelineLink));
        }
        return items2;
    } else {
        throw new ServiceException.UnexpectedErrorException("This pipeline is not buildable and therefore does not have a queue.");
    }
}
Also used : BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) BuildableItem(hudson.model.BuildableItem) BuildableItem(hudson.model.BuildableItem) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) Link(io.jenkins.blueocean.rest.hal.Link)

Example 2 with BlueQueueItem

use of io.jenkins.blueocean.rest.model.BlueQueueItem in project blueocean-plugin by jenkinsci.

the class BlueMessageEnricher method maybeEnrichMessage.

private void maybeEnrichMessage(@Nonnull Message message) {
    String channelName = message.getChannelName();
    if (channelName.equals(Events.JobChannel.NAME) && message instanceof JobChannelMessage) {
        JobChannelMessage jobChannelMessage = (JobChannelMessage) message;
        Item jobChannelItem = jobChannelMessage.getJobChannelItem();
        if (jobChannelItem == null) {
            return;
        }
        Link jobUrl = LinkResolver.resolveLink(jobChannelItem);
        if (jobUrl == null) {
            return;
        }
        BlueOrganization org = OrganizationFactory.getInstance().getContainingOrg(jobChannelItem);
        if (org != null) {
            message.set(EventProps.Jenkins.jenkins_org, org.getName());
        }
        jobChannelMessage.set(BlueEventProps.blueocean_job_rest_url, jobUrl.getHref());
        jobChannelMessage.set(BlueEventProps.blueocean_job_pipeline_name, AbstractPipelineImpl.getFullName(org, jobChannelItem));
        if (jobChannelItem instanceof WorkflowJob) {
            ItemGroup<? extends Item> parent = jobChannelItem.getParent();
            if (parent instanceof WorkflowMultiBranchProject) {
                String multiBranchProjectName = AbstractPipelineImpl.getFullName(org, (WorkflowMultiBranchProject) parent);
                jobChannelMessage.set(BlueEventProps.blueocean_job_pipeline_name, multiBranchProjectName);
                jobChannelMessage.set(BlueEventProps.blueocean_job_branch_name, jobChannelItem.getName());
            }
        }
        if (message.containsKey("job_run_queueId") && jobChannelItem instanceof hudson.model.Job) {
            String queueIdStr = message.get("job_run_queueId");
            if (queueIdStr == null) {
                return;
            }
            final long queueId = Long.parseLong(queueIdStr);
            Queue.Item queueItem = Jenkins.get().getQueue().getItem(queueId);
            if (queueItem == null) {
                return;
            }
            hudson.model.Job job = (hudson.model.Job) jobChannelItem;
            BlueQueueItem blueQueueItem = QueueUtil.getQueuedItem(null, queueItem, job);
            if (blueQueueItem != null) {
                jobChannelMessage.set(BlueEventProps.blueocean_queue_item_expected_build_number, Integer.toString(blueQueueItem.getExpectedBuildNumber()));
            } else {
                // If build is already running, we simply take the run id and pass it on
                if (message.get("job_run_status") != null) {
                    String buildNumberStr = message.get("jenkins_object_id");
                    if (StringUtils.isNotBlank(buildNumberStr)) {
                        jobChannelMessage.set(BlueEventProps.blueocean_queue_item_expected_build_number, message.get("jenkins_object_id"));
                    }
                }
            }
        }
    }
}
Also used : JobChannelMessage(org.jenkinsci.plugins.pubsub.JobChannelMessage) BlueOrganization(io.jenkins.blueocean.rest.model.BlueOrganization) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Item(hudson.model.Item) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) Link(io.jenkins.blueocean.rest.hal.Link)

Example 3 with BlueQueueItem

use of io.jenkins.blueocean.rest.model.BlueQueueItem in project blueocean-plugin by jenkinsci.

the class MultiBranchTest method testMultiBranchPipelineQueueContainer.

@Test
public void testMultiBranchPipelineQueueContainer() throws Exception {
    j.jenkins.setQuietPeriod(0);
    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);
    Resource r = BluePipelineFactory.resolve(mp);
    assertTrue(r instanceof MultiBranchPipelineImpl);
    for (WorkflowJob job : mp.getItems()) {
        Queue.Item item = job.getQueueItem();
        job.setConcurrentBuild(false);
        job.scheduleBuild2(0);
        job.scheduleBuild2(0);
    }
    Queue.Item[] queueItems = Jenkins.get().getQueue().getItems();
    MultiBranchPipelineQueueContainer mbpQueueContainer = new MultiBranchPipelineQueueContainer((MultiBranchPipelineImpl) r);
    Iterator<BlueQueueItem> blueQueueItems = mbpQueueContainer.iterator(0, 100);
    if (queueItems.length > 0) {
        assertTrue(mbpQueueContainer.iterator().hasNext());
        assertEquals("/blue/rest/organizations/jenkins/pipelines/p/queue/", mbpQueueContainer.getLink().getHref());
        BlueQueueItem blueQueueItem = mbpQueueContainer.get(String.valueOf(queueItems[0].getId()));
        assertNotNull(blueQueueItem);
        assertTrue(blueQueueItems.hasNext());
    }
}
Also used : Resource(io.jenkins.blueocean.rest.model.Resource) GitSCMSource(jenkins.plugins.git.GitSCMSource) SCMSource(jenkins.scm.api.SCMSource) GitSCMSource(jenkins.plugins.git.GitSCMSource) BranchSource(jenkins.branch.BranchSource) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) DefaultBranchPropertyStrategy(jenkins.branch.DefaultBranchPropertyStrategy) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) Test(org.junit.Test)

Example 4 with BlueQueueItem

use of io.jenkins.blueocean.rest.model.BlueQueueItem in project blueocean-plugin by jenkinsci.

the class MultiBranchPipelineQueueContainer method iterator.

@Override
public Iterator<BlueQueueItem> iterator(int start, int limit) {
    List<BluePipeline> branches = StreamSupport.stream(multiBranchPipeline.getBranches().spliterator(), false).sorted((o1, o2) -> PipelineRunImpl.LATEST_RUN_START_TIME_COMPARATOR.compare(o1.getLatestRun(), o2.getLatestRun())).collect(Collectors.toList());
    int l = branches.size() > 0 && limit / branches.size() > 0 ? limit / branches.size() : 1;
    int s = 0;
    if (start > 0) {
        s = Math.max(start - l, 0);
    }
    List<BlueQueueItem> c = new ArrayList<>();
    int count = 0;
    int retry = 0;
    while (retry < 5 && count < limit) {
        for (BluePipeline b : branches) {
            Iterator<BlueQueueItem> it = b.getQueue().iterator(s, l);
            while (it.hasNext()) {
                count++;
                c.add(it.next());
            }
        }
        retry++;
    }
    c.sort((o1, o2) -> o2.getQueuedTime().compareTo(o1.getQueuedTime()));
    return c.iterator();
}
Also used : Iterator(java.util.Iterator) Jenkins(jenkins.model.Jenkins) ServiceException(io.jenkins.blueocean.commons.ServiceException) QueueUtil(io.jenkins.blueocean.service.embedded.rest.QueueUtil) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Queue(hudson.model.Queue) Job(hudson.model.Job) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) StreamSupport(java.util.stream.StreamSupport) BlueQueueContainer(io.jenkins.blueocean.rest.model.BlueQueueContainer) Link(io.jenkins.blueocean.rest.hal.Link) ArrayList(java.util.ArrayList) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem)

Example 5 with BlueQueueItem

use of io.jenkins.blueocean.rest.model.BlueQueueItem in project blueocean-plugin by jenkinsci.

the class PipelineNodeImpl method restart.

public HttpResponse restart(StaplerRequest request) {
    try {
        JSONObject body = JSONObject.fromObject(IOUtils.toString(request.getReader()));
        boolean restart = body.getBoolean("restart");
        if (restart && isRestartable()) {
            LOGGER.debug("submitInputStep, restart: {}, step: {}", restart, this.getDisplayName());
            RestartDeclarativePipelineAction restartDeclarativePipelineAction = this.run.getAction(RestartDeclarativePipelineAction.class);
            Queue.Item item = restartDeclarativePipelineAction.run(this.getDisplayName());
            BluePipeline bluePipeline = BluePipelineFactory.getPipelineInstance(this.run.getParent(), this.parent);
            BlueQueueItem queueItem = QueueUtil.getQueuedItem(bluePipeline.getOrganization(), item, run.getParent());
            if (queueItem != null) {
                // If the item is still queued
                return (req, rsp, node1) -> {
                    rsp.setStatus(HttpServletResponse.SC_OK);
                    rsp.getOutputStream().print(Export.toJson(queueItem.toRun()));
                };
            }
            final WorkflowRun restartRun = getRun(run.getParent(), item.getId());
            if (restartRun != null) {
                return (req, rsp, node1) -> {
                    rsp.setStatus(HttpServletResponse.SC_OK);
                    rsp.getOutputStream().print(Export.toJson(new PipelineRunImpl(restartRun, parent, bluePipeline.getOrganization())));
                };
            } else {
                // For some reason could not be added to the queue
                throw new ServiceException.UnexpectedErrorException("Run was not added to queue.");
            }
        }
    // ISE cant happen if stage not restartable or anything else :)
    } catch (Exception e) {
        LOGGER.warn("error restarting stage: " + e.getMessage(), e);
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
    return null;
}
Also used : ActionProxiesImpl(io.jenkins.blueocean.service.embedded.rest.ActionProxiesImpl) Date(java.util.Date) RestartDeclarativePipelineAction(org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction) StaplerRequest(org.kohsuke.stapler.StaplerRequest) LoggerFactory(org.slf4j.LoggerFactory) Exported(org.kohsuke.stapler.export.Exported) Export(io.jenkins.blueocean.commons.stapler.Export) HashSet(java.util.HashSet) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) AbstractRunImpl(io.jenkins.blueocean.service.embedded.rest.AbstractRunImpl) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) LogAction(org.jenkinsci.plugins.workflow.actions.LogAction) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Action(hudson.model.Action) Logger(org.slf4j.Logger) HttpResponse(org.kohsuke.stapler.HttpResponse) Collection(java.util.Collection) Reachable(io.jenkins.blueocean.rest.Reachable) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) HttpServletResponse(javax.servlet.http.HttpServletResponse) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) ServiceException(io.jenkins.blueocean.commons.ServiceException) QueueUtil(io.jenkins.blueocean.service.embedded.rest.QueueUtil) Collectors(java.util.stream.Collectors) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) JSONObject(net.sf.json.JSONObject) BlueActionProxy(io.jenkins.blueocean.rest.model.BlueActionProxy) BlueInputStep(io.jenkins.blueocean.rest.model.BlueInputStep) BluePipelineStepContainer(io.jenkins.blueocean.rest.model.BluePipelineStepContainer) BluePipelineFactory(io.jenkins.blueocean.rest.factory.BluePipelineFactory) CheckForNull(javax.annotation.CheckForNull) Collections(java.util.Collections) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) ServiceException(io.jenkins.blueocean.commons.ServiceException) RestartDeclarativePipelineAction(org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction) JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) BluePipeline(io.jenkins.blueocean.rest.model.BluePipeline) Queue(hudson.model.Queue) BlueQueueItem(io.jenkins.blueocean.rest.model.BlueQueueItem)

Aggregations

BlueQueueItem (io.jenkins.blueocean.rest.model.BlueQueueItem)8 Queue (hudson.model.Queue)5 Link (io.jenkins.blueocean.rest.hal.Link)5 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 BluePipeline (io.jenkins.blueocean.rest.model.BluePipeline)3 WorkflowJob (org.jenkinsci.plugins.workflow.job.WorkflowJob)3 BuildableItem (hudson.model.BuildableItem)2 QueueUtil (io.jenkins.blueocean.service.embedded.rest.QueueUtil)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)2 WorkflowMultiBranchProject (org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 Action (hudson.model.Action)1 Item (hudson.model.Item)1 Job (hudson.model.Job)1 NotFoundException (io.jenkins.blueocean.commons.ServiceException.NotFoundException)1 Export (io.jenkins.blueocean.commons.stapler.Export)1 NodeDownstreamBuildAction (io.jenkins.blueocean.listeners.NodeDownstreamBuildAction)1