hudson.model.Queue Java Examples

The following examples show how to use hudson.model.Queue. 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: 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 #2
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Populates a {@link ListBoxModel} with the checkout credentials appropriate for the supplied context against the
 * supplied API endpoint.
 *
 * @param context the context.
 * @param apiUri  the api endpoint.
 * @return a {@link ListBoxModel}.
 */
@NonNull
public static ListBoxModel listCheckoutCredentials(@CheckForNull Item context, String apiUri) {
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.add("- same as scan credentials -", GitHubSCMSource.DescriptorImpl.SAME);
    result.add("- anonymous -", GitHubSCMSource.DescriptorImpl.ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            githubDomainRequirements(apiUri),
            GitClient.CREDENTIALS_MATCHER
    );
}
 
Example #3
Source File: GitPushStep.java    From simple-pull-request-job-plugin with Apache License 2.0 6 votes vote down vote up
protected Void run() throws Exception {
    FilePath ws = getContext().get(FilePath.class);
    TaskListener listener = this.getContext().get(TaskListener.class);
    EnvVars envVars = getContext().get(EnvVars.class);
    WorkflowJob job = getContext().get(WorkflowJob.class);
    GitOperations gitOperations = new GitOperations(ws, listener, envVars, url);
    StandardCredentials c = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    job,
                    Tasks.getAuthenticationOf((Queue.Task) job)),
            CredentialsMatchers.withId(credentialId));

    gitOperations.setUsernameAndPasswordCredential((StandardUsernameCredentials) c);
    gitOperations.setCurrentBranch(branch);
    gitOperations.push(true);
    return null;
}
 
Example #4
Source File: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public ListBoxModel doFillCredentialsIdItems(
    @AncestorInPath Item context,
    @QueryParameter String remote,
    @QueryParameter String credentialsId) {
  if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
      || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
    return new StandardListBoxModel().includeCurrentValue(credentialsId);
  }
  return new StandardListBoxModel()
      .includeEmptyValue()
      .includeMatchingAs(
          context instanceof Queue.Task
              ? Tasks.getAuthenticationOf((Queue.Task) context)
              : ACL.SYSTEM,
          context,
          StandardUsernameCredentials.class,
          URIRequirementBuilder.fromUri(remote).build(),
          GitClient.CREDENTIALS_MATCHER)
      .includeCurrentValue(credentialsId);
}
 
Example #5
Source File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example #6
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public ListBoxModel doFillCredentialsItems(@AncestorInPath Item context) {

			if (context == null || !context.hasPermission(Item.CONFIGURE)) {
				return new ListBoxModel();
			}

			return new StandardListBoxModel()
					.includeEmptyValue()
					.includeMatchingAs(
							context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							StandardUsernamePasswordCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class))
					.includeMatchingAs(context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							AmazonWebServicesCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(AmazonWebServicesCredentials.class));
		}
 
Example #7
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 #8
Source File: DockerSwarmAgentRetentionStrategy.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
private synchronized void done(final DockerSwarmComputer c) {
    c.setAcceptingTasks(false); // just in case
    if (terminating) {
        return;
    }
    terminating = true;
    Computer.threadPoolForRemoting.submit(() -> {
        Queue.withLock(() -> {
            DockerSwarmAgent node = c.getNode();
            if (node != null) {
                try {
                    node.terminate();
                } catch (IOException e) {
                }
            }
        });
    });
}
 
Example #9
Source File: PipelineNodeUtil.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 *  Gives cause of block for declarative style plugin where agent (node block) is declared inside a stage.
 *  <pre>
 *    pipeline {
 *      agent none
 *      stages {
 *          stage ('first') {
 *              agent {
 *                  label 'first'
 *              }
 *              steps{
 *                  sh 'echo "from first"'
 *              }
 *          }
 *      }
 *    }
 *  </pre>
 *
 * @param stage stage's {@link FlowNode}
 * @param nodeBlock agent or node block's {@link FlowNode}
 * @return cause of block if present, nul otherwise
 */
public static @CheckForNull String getCauseOfBlockage(@Nonnull FlowNode stage, @Nullable FlowNode nodeBlock) {
    if(nodeBlock != null){
        //Check and see if this node block is inside this stage
        for(FlowNode p:nodeBlock.getParents()){
            if(p.equals(stage)){
                Queue.Item item = QueueItemAction.getQueueItem(nodeBlock);
                if (item != null) {
                    CauseOfBlockage causeOfBlockage = item.getCauseOfBlockage();
                    String cause = null;
                    if (causeOfBlockage != null) {
                        cause = causeOfBlockage.getShortDescription();
                        if (cause == null) {
                            causeOfBlockage = item.task.getCauseOfBlockage();
                            if(causeOfBlockage != null) {
                                return causeOfBlockage.getShortDescription();
                            }
                        }
                    }
                    return cause;
                }
            }
        }
    }
    return null;
}
 
Example #10
Source File: DockerOnceRetentionStrategy.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
protected void done(Executor executor) {
    final AbstractCloudComputer<?> c = (AbstractCloudComputer) executor.getOwner();
    Queue.Executable exec = executor.getCurrentExecutable();
    if (executor instanceof OneOffExecutor) {
        LOG.debug("Not terminating {} because {} was a flyweight task", c.getName(), exec);
        return;
    }

    if (exec instanceof ContinuableExecutable && ((ContinuableExecutable) exec).willContinue()) {
        LOG.debug("not terminating {} because {} says it will be continued", c.getName(), exec);
        return;
    }

    LOG.debug("terminating {} since {} seems to be finished", c.getName(), exec);
    done(c);
}
 
Example #11
Source File: PipelineTriggerService.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
/**
 * Check NO infinite loop of job triggers caused by {@link hudson.model.Cause.UpstreamCause}.
 *
 * @param initialBuild
 * @throws IllegalStateException if an infinite loop is detected
 */
public void checkNoInfiniteLoopOfUpstreamCause(@Nonnull Run initialBuild) throws IllegalStateException {
    java.util.Queue<Run> builds = new LinkedList<>(Collections.singleton(initialBuild));
    Run currentBuild;
    while ((currentBuild = builds.poll()) != null) {
        for (Cause cause : ((List<Cause>) currentBuild.getCauses())) {
            if (cause instanceof Cause.UpstreamCause) {
                Cause.UpstreamCause upstreamCause = (Cause.UpstreamCause) cause;
                Run<?, ?> upstreamBuild = upstreamCause.getUpstreamRun();
                if (upstreamBuild == null) {
                    // Can be Authorization, build deleted on the file system...
                } else if (Objects.equals(upstreamBuild.getParent().getFullName(), initialBuild.getParent().getFullName())) {
                    throw new IllegalStateException("Infinite loop of job triggers ");
                } else {
                    builds.add(upstreamBuild);
                }
            }
        }
    }
}
 
Example #12
Source File: SubBuildScheduler.java    From DotCi with MIT License 6 votes vote down vote up
public void cancelSubBuilds(final PrintStream logger) {
    final Queue q = getJenkins().getQueue();
    synchronized (q) {
        final int n = this.dynamicBuild.getNumber();
        for (final Item i : q.getItems()) {
            final ParentBuildAction parentBuildAction = i.getAction(ParentBuildAction.class);
            if (parentBuildAction != null && this.dynamicBuild.equals(parentBuildAction.getParent())) {
                q.cancel(i);
            }
        }
        for (final DynamicSubProject c : this.dynamicBuild.getAllSubProjects()) {
            final DynamicSubBuild b = c.getBuildByNumber(n);
            if (b != null && b.isBuilding()) {
                final Executor exe = b.getExecutor();
                if (exe != null) {
                    logger.println(Messages.MatrixBuild_Interrupting(ModelHyperlinkNote.encodeTo(b)));
                    exe.interrupt();
                }
            }
        }
    }
}
 
Example #13
Source File: SSHCheckoutTrait.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Form completion.
 *
 * @param context       the context.
 * @param apiUri        the server url.
 * @param credentialsId the current selection.
 * @return the form items.
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String apiUri,
                                             @QueryParameter String credentialsId) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    StandardListBoxModel result = new StandardListBoxModel();
    result.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            Connector.githubDomainRequirements(apiUri),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
}
 
Example #14
Source File: OneShotProvisionQueueListener.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
@Override
public void onLeft(final Queue.LeftItem li) {
    if (li.isCancelled()) {
        final DockerSwarmLabelAssignmentAction labelAssignmentAction = li
                .getAction(DockerSwarmLabelAssignmentAction.class);
        if (labelAssignmentAction != null) {
            final String computerName = labelAssignmentAction.getLabel().getName();

            final Node node = Jenkins.getInstance().getNode(computerName);
            Computer.threadPoolForRemoting.submit(() -> {
                try {
                    ((DockerSwarmAgent) node).terminate();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Failed to terminate agent.", e);
                }
            });
        }
    }
}
 
Example #15
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example #16
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
        @QueryParameter String serverName, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        // must have admin if you want the list without a context
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you
            // want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            context, StandardUsernameCredentials.class, fromUri(getServerUrlFromName(serverName)).build(),
            GitClient.CREDENTIALS_MATCHER);
    return result;
}
 
Example #17
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example #18
Source File: ECSComputer.java    From amazon-ecs-plugin with MIT License 5 votes vote down vote up
@Override
public void taskAccepted(Executor executor, Queue.Task task) {
    super.taskAccepted(executor, task);
    LOGGER.log(Level.INFO, "[{0}]: JobName: {1}", new Object[] {this.getName(), task.getDisplayName()});
    LOGGER.log(Level.INFO, "[{0}]: JobUrl: {1}", new Object[] {this.getName(), task.getUrl()});
    LOGGER.log(Level.FINE, "[{0}]: taskAccepted", this);
}
 
Example #19
Source File: PipelineEventListener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static @CheckForNull Run<?, ?> runFor(FlowExecution exec) {
    Queue.Executable executable;
    try {
        executable = exec.getOwner().getExecutable();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, null, x);
        return null;
    }
    if (executable instanceof Run) {
        return (Run<?, ?>) executable;
    } else {
        return null;
    }
}
 
Example #20
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 #21
Source File: DbBackedProject.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public synchronized Item getQueueItem() {
    final Queue queue = Jenkins.getInstance().getQueue();
    final Item[] items = queue.getItems();
    for (int i = 0; i < items.length; i++) {
        if (items[i].task != null && items[i].task.equals(this)) {
            return items[i];
        }
    }
    return super.getQueueItem();
}
 
Example #22
Source File: DockerOnceRetentionStrategy.java    From docker-plugin with MIT License 5 votes vote down vote up
private void done(Executor executor) {
    final DockerComputer c = (DockerComputer) executor.getOwner();
    Queue.Executable exec = executor.getCurrentExecutable();
    if (exec instanceof ContinuableExecutable && ((ContinuableExecutable) exec).willContinue()) {
        LOGGER.log(Level.FINE, "not terminating {0} because {1} says it will be continued", new Object[]{c.getName(), exec});
        return;
    }
    LOGGER.log(Level.FINE, "terminating {0} since {1} seems to be finished", new Object[]{c.getName(), exec});
    done(c);
}
 
Example #23
Source File: IntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
protected static void assertQueueIsEmpty() {
    tryUntil(new Runnable() {
        @Override
        public void run() {
            System.out.println("check if queue is empty");
            Assert.assertTrue(Queue.getInstance().isEmpty());
        }
    });
}
 
Example #24
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 #25
Source File: OrganizationFolderRunContainerImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public BlueRun create(StaplerRequest request) {
    pipeline.folder.checkPermission(Item.BUILD);
    Queue.Item queueItem = pipeline.folder.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause()));
    if(queueItem == null){ // possible folder.isBuildable() was false due to no repo fetched yet
        return null;
    }
    return new QueueItemImpl(
            pipeline.getOrganization(),
            queueItem,
            pipeline,
            1
    ).toRun();
}
 
Example #26
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 #27
Source File: RunContainerImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Schedules a build. If build already exists in the queue and the pipeline does not
 * support running multiple builds at the same time, return a reference to the existing
 * build.
 *
 * @return Queue item.
 */
@Override
public BlueRun create(StaplerRequest request) {
    job.checkPermission(Item.BUILD);
    if (job instanceof Queue.Task) {
        ScheduleResult scheduleResult;

        List<ParameterValue> parameterValues = getParameterValue(request);
        int expectedBuildNumber = job.getNextBuildNumber();
        if(parameterValues.size() > 0) {
            scheduleResult = Jenkins.getInstance()
                    .getQueue()
                    .schedule2((Queue.Task) job, 0, new ParametersAction(parameterValues),
                            new CauseAction(new Cause.UserIdCause()));
        }else {
            scheduleResult = Jenkins.getInstance()
                    .getQueue()
                    .schedule2((Queue.Task) job, 0, new CauseAction(new Cause.UserIdCause()));
        }
        // Keep FB happy.
        // scheduleResult.getItem() will always return non-null if scheduleResult.isAccepted() is true
        final Queue.Item item = scheduleResult.getItem();
        if(scheduleResult.isAccepted() && item != null) {
            return new QueueItemImpl(
                pipeline.getOrganization(),
                item,
                pipeline,
                expectedBuildNumber, pipeline.getLink().rel("queue").rel(Long.toString(item.getId())),
                pipeline.getLink()
            ).toRun();
        } else {
            throw new ServiceException.UnexpectedErrorException("Queue item request was not accepted");
        }
    } else {
        throw new ServiceException.NotImplementedException("This pipeline type does not support being queued.");
    }
}
 
Example #28
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 #29
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Runs specified job and asserts that in finished with given build result.
 * @since TODO
 */
@Nonnull
public <J extends Job<J,R> & ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends Run<J,R> & Queue.Executable> R buildAndAssertStatus(@Nonnull Result status, @Nonnull J job) throws Exception {
    final QueueTaskFuture<R> f = new ParameterizedJobMixIn<J, R>() {
        @Override protected J asJob() {
            return job;
        }
    }.scheduleBuild2(0);
    return assertBuildStatus(status, f);
}
 
Example #30
Source File: GithubBuildStatusGraphListener.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the jenkins run object of the specified executing workflow.
 *
 * @param exec execution of a workflow
 * @return jenkins run object of a job
 */
private static @CheckForNull Run<?, ?> runFor(FlowExecution exec) {
    Queue.Executable executable;
    try {
        executable = exec.getOwner().getExecutable();
    } catch (IOException x) {
        getLogger().log(Level.WARNING, null, x);
        return null;
    }
    if (executable instanceof Run) {
        return (Run<?, ?>) executable;
    } else {
        return null;
    }
}