Java 类hudson.model.Queue 实例源码

项目:no-agent-job-purge-plugin    文件:PurgeNoAgentJobs.java   
public void doEndOfflineAgentJobs(final StaplerRequest request, final StaplerResponse response) {

        Jenkins j;
        if ((j = Jenkins.getInstance()) != null) {
            Queue queue = j.getQueue();
            if (queue != null) {
                for (Item job : queue.getItems()) {
                    if (job.getCauseOfBlockage() instanceof BecauseNodeIsOffline
                            || job.getCauseOfBlockage() instanceof BecauseLabelIsOffline) {
                        queue.cancel(job);
                    }
                }
            }
        }

        try {
            response.sendRedirect2(request.getRootPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
项目:gerrit-plugin    文件:GerritSCMSource.java   
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);
}
项目:gitlab-branch-source-plugin    文件:GitLabSCMSourceSettings.java   
@Restricted(NoExternalUse.class)
public ListBoxModel doFillCheckoutCredentialsIdItems(@AncestorInPath SCMSourceOwner context, @QueryParameter String connectionName, @QueryParameter String checkoutCredentialsId) {
    if (context == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ||
            context != null && !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(checkoutCredentialsId);
    }

    StandardListBoxModel result = new StandardListBoxModel();
    result.add("- anonymous -", CHECKOUT_CREDENTIALS_ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            SettingsUtils.gitLabConnectionRequirements(connectionName),
            GitClient.CREDENTIALS_MATCHER
    );
}
项目:openshift-sync-plugin    文件:JenkinsUtils.java   
@SuppressFBWarnings("SE_BAD_FIELD")
public static boolean cancelQueuedBuild(WorkflowJob job, Build build) {
    String buildUid = build.getMetadata().getUid();
    final Queue buildQueue = Jenkins.getActiveInstance().getQueue();
    for (final Queue.Item item : buildQueue.getItems()) {
        for (Cause cause : item.getCauses()) {
            if (cause instanceof BuildCause && ((BuildCause) cause).getUid().equals(buildUid)) {
                return ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Boolean, RuntimeException>() {
                    @Override
                    public Boolean call() throws RuntimeException {
                        buildQueue.cancel(item);
                        return true;
                    }
                });
            }
        }
    }
    return cancelNotYetStartedBuild(job, build);
}
项目:pipeline-maven-plugin    文件:DownstreamPipelineTriggerRunListener.java   
protected boolean isUpstreamBuildVisibleByDownstreamBuildAuth(@Nonnull WorkflowJob upstreamPipeline, @Nonnull Queue.Task downstreamPipeline) {
    Authentication auth = Tasks.getAuthenticationOf(downstreamPipeline);
    Authentication downstreamPipelineAuth;
    if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) {
        downstreamPipelineAuth = Jenkins.ANONYMOUS; // cf. BuildTrigger
    } else {
        downstreamPipelineAuth = auth;
    }

    try (ACLContext _ = ACL.as(downstreamPipelineAuth)) {
        WorkflowJob upstreamPipelineObtainedAsImpersonated = Jenkins.getInstance().getItemByFullName(upstreamPipeline.getFullName(), WorkflowJob.class);
        boolean result = upstreamPipelineObtainedAsImpersonated != null;
        LOGGER.log(Level.FINE, "isUpstreamBuildVisibleByDownstreamBuildAuth({0}, {1}): taskAuth: {2}, downstreamPipelineAuth: {3}, upstreamPipelineObtainedAsImpersonated:{4}, result: {5}",
                new Object[]{upstreamPipeline, downstreamPipeline, auth, downstreamPipelineAuth, upstreamPipelineObtainedAsImpersonated, result});
        return result;
    }
}
项目:yet-another-docker-plugin    文件:DockerOnceRetentionStrategy.java   
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);
}
项目:dockerhub-notification-plugin    文件:JSONWebHook.java   
boolean schedule(Cause cause) {
    if (!asJob().isBuildable()) {
        return false;
    }
    List<Action> queueActions = new LinkedList<Action>();

    queueActions.add(new ParametersAction(getParameterValues()));
    queueActions.add(new CauseAction(cause));

    int quiet = Math.max(MIN_QUIET, asJob().getQuietPeriod());

    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        logger.log(Level.WARNING, "Tried to schedule a build while Jenkins was gone.");
        return false;
    }
    final Queue queue = jenkins.getQueue();
    if (queue == null) {
        throw new IllegalStateException("The queue is not initialized?!");
    }
    Queue.Item i = queue.schedule2(asJob(), quiet, queueActions).getItem();
    return i != null && i.getFuture() != null;
}
项目:github-integration-plugin    文件:GitHubPRLabelUnblockQueueCondition.java   
@Override
public boolean isUnblocked(Queue.Item item) {
    final List<Cause> causes = item.getCauses();
    for (Cause cause : causes) {
        if (cause instanceof GitHubPRCause) {
            final GitHubPRCause gitHubPRCause = (GitHubPRCause) cause;
            final Set<String> causeLabels = gitHubPRCause.getLabels();
            if (getLabel() != null) {
                if (causeLabels.containsAll(label.getLabelsSet())) {
                    if (item.task instanceof Job<?, ?>) {
                        final Job<?, ?> job = (Job<?, ?>) item.task;
                        LOGGER.debug("Unblocking job item {} with matched labels {}",
                                job.getFullName(), label.getLabelsSet());
                    }

                    return true;
                }
            }
        }
    }

    return false;
}
项目:github-integration-plugin    文件:JobRunnerForBranchCause.java   
/**
 * Cancel previous builds for specified PR id.
 */
private static boolean cancelQueuedBuildByBranchName(final String branch) {
    Queue queue = getJenkinsInstance().getQueue();

    for (Queue.Item item : queue.getApproximateItemsQuickly()) {
        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;
}
项目:p4-jenkins    文件:P4CredentialsImpl.java   
@SuppressFBWarnings(value="NP_NULL_PARAM_DEREF", justification="pending https://github.com/jenkinsci/credentials-plugin/pull/68")
static public ListBoxModel doFillCredentialItems(Item project, String credentialsId) {

    if(project == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER) ||
            project != null && !project.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    project instanceof Queue.Task
                            ? Tasks.getAuthenticationOf((Queue.Task) project)
                            : ACL.SYSTEM,
                    project,
                    P4BaseCredentials.class,
                    Collections.<DomainRequirement>emptyList(),
                    CredentialsMatchers.instanceOf(P4BaseCredentials.class));
}
项目:DotCi    文件:SubBuildScheduler.java   
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();
                }
            }
        }
    }
}
项目:mesos-plugin    文件:JenkinsSchedulerTest.java   
@Test
public void testDeclineOffersWithBuildsInQueue() throws Exception {
    Protos.Offer offer = createOfferWithVariableRanges(31000, 32000);
    ArrayList<Protos.Offer> offers = new ArrayList<Protos.Offer>();
    offers.add(offer);

    Queue queue = Mockito.mock(Queue.class);
    Mockito.when(jenkins.getQueue()).thenReturn(queue);

    Item item = Mockito.mock(Item.class);
    Item [] items = {item};
    Mockito.when(queue.getItems()).thenReturn(items);
    Mockito.when(mesosCloud.canProvision(null)).thenReturn(true);

    SchedulerDriver driver = Mockito.mock(SchedulerDriver.class);
    Mockito.when(mesosCloud.getDeclineOfferDurationDouble()).thenReturn((double) 120000);
    jenkinsScheduler.resourceOffers(driver, offers);
    Mockito.verify(driver).declineOffer(offer.getId());
    Mockito.verify(driver, Mockito.never()).declineOffer(offer.getId(), Protos.Filters.newBuilder().setRefuseSeconds(120000).build());
}
项目:gearman-plugin    文件:GearmanProxy.java   
public CauseOfBlockage canTake(Node node,
                               Queue.BuildableItem item) {
    // Ask the AvailabilityMonitor for this node if it's okay to
    // run this build.
    ExecutorWorkerThread workerThread = null;

    synchronized(gewtHandles) {
        Computer computer = node.toComputer();
        for (ExecutorWorkerThread t : gewtHandles) {
            if (t.getComputer() == computer) {
                workerThread = t;
                break;
            }
        }
    }

    if (workerThread != null) {
        if (workerThread.getAvailability().canTake(item)) {
            return null;
        } else {
            return new CauseOfBlockage.BecauseNodeIsBusy(node);
        }
    }
    return null;
}
项目:gearman-plugin    文件:NodeAvailabilityMonitor.java   
public boolean canTake(Queue.BuildableItem item)
{
    // Jenkins calls this from within the scheduler maintenance
    // function (while owning the queue monitor).  If we are
    // locked, only allow the build we are expecting to run.
    logger.debug("AvailabilityMonitor canTake request for " +
                 workerHoldingLock);

    NodeParametersAction param = item.getAction(NodeParametersAction.class);
    if (param != null) {
        logger.debug("AvailabilityMonitor canTake request for UUID " +
                     param.getUuid() + " expecting " + expectedUUID);

        if (expectedUUID == param.getUuid()) {
            return true;
        }
    }
    return (workerHoldingLock == null);
}
项目:codescene-jenkins-plugin    文件:CodeSceneBuilder.java   
/**
 * Populates the list of credentials in the select box in CodeScene API configuration section
 * Inspired by git plugin:
 * https://github.com/jenkinsci/git-plugin/blob/f58648e9005293ab07b2389212603ff9a460b80a/src/main/java/jenkins/plugins/git/GitSCMSource.java#L239
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId) {
    if (context == null || !context.hasPermission(Item.CONFIGURE)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    context instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task)context) : ACL.SYSTEM,
                    context,
                    StandardUsernameCredentials.class,
                    Collections.<DomainRequirement>emptyList(),
                    CredentialsMatchers.always())
            .includeCurrentValue(credentialsId);
}
项目:gitea-plugin    文件:GiteaSCMNavigator.java   
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
                                             @QueryParameter String serverUrl,
                                             @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            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 ?
                    Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
项目:gitea-plugin    文件:GiteaSCMNavigator.java   
public FormValidation doCheckCredentialsId(@AncestorInPath SCMSourceOwner context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value)
        throws IOException, InterruptedException {
    if (context == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            return FormValidation.ok();
        }
    }
    GiteaServer server = GiteaServers.get().findServer(serverUrl);
    if (server == null) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        return FormValidation.ok();
    }
    if (CredentialsProvider.listCredentials(
            StandardCredentials.class,
            context,
            context instanceof Queue.Task ?
                    Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.allOf(
                    CredentialsMatchers.withId(value),
                    AuthenticationTokens.matcher(GiteaAuth.class)

            )).isEmpty()) {
        return FormValidation.error(Messages.GiteaSCMNavigator_selectedCredentialsMissing());
    }
    return FormValidation.ok();
}
项目:gitea-plugin    文件:SSHCheckoutTrait.java   
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String serverUrl,
                                             @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            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.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    result.includeMatchingAs(
            context instanceof Queue.Task ?
                    Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
    return result;
}
项目:gitea-plugin    文件:SSHCheckoutTrait.java   
/**
 * Validation for checkout credentials.
 *
 * @param context   the context.
 * @param serverUrl the server url.
 * @param value     the current selection.
 * @return the validation results
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value) {
    if (context == null
            ? !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        // use agent key
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(SSHUserPrivateKey.class, context, context instanceof Queue.Task
                            ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(StandardUsernameCredentials.class, context, context instanceof Queue.Task
                            ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.error(Messages.SSHCheckoutTrait_incompatibleCredentials());
    }
    return FormValidation.warning(Messages.SSHCheckoutTrait_missingCredentials());
}
项目:gitea-plugin    文件:GiteaSCMSource.java   
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
                                             @QueryParameter String serverUrl,
                                             @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            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 ?
                    Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
项目:gitea-plugin    文件:GiteaSCMSource.java   
public FormValidation doCheckCredentialsId(@AncestorInPath SCMSourceOwner context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value)
        throws IOException, InterruptedException{
    if (context == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            return FormValidation.ok();
        }
    }
    GiteaServer server = GiteaServers.get().findServer(serverUrl);
    if (server == null) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        return FormValidation.ok();
    }
    if (CredentialsProvider.listCredentials(
            StandardCredentials.class,
            context,
            context instanceof Queue.Task ?
                    Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.allOf(
                    CredentialsMatchers.withId(value),
                    AuthenticationTokens.matcher(GiteaAuth.class)

            )).isEmpty()) {
        return FormValidation.error(Messages.GiteaSCMSource_selectedCredentialsMissing());
    }
    return FormValidation.ok();
}
项目:gerrit-plugin    文件:GerritSCMSource.java   
public FormValidation doCheckCredentialsId(
    @AncestorInPath Item context, @QueryParameter String remote, @QueryParameter String value) {
  if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
      || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
    return FormValidation.ok();
  }

  value = Util.fixEmptyAndTrim(value);
  if (value == null) {
    return FormValidation.ok();
  }

  remote = Util.fixEmptyAndTrim(remote);
  if (remote == null)
  // not set, can't check
  {
    return FormValidation.ok();
  }

  for (ListBoxModel.Option o :
      CredentialsProvider.listCredentials(
          StandardUsernameCredentials.class,
          context,
          context instanceof Queue.Task
              ? Tasks.getAuthenticationOf((Queue.Task) context)
              : ACL.SYSTEM,
          URIRequirementBuilder.fromUri(remote).build(),
          GitClient.CREDENTIALS_MATCHER)) {
    if (StringUtils.equals(value, o.value)) {
      // TODO check if this type of credential is acceptable to the Git client or does it merit warning
      // NOTE: we would need to actually lookup the credential to do the check, which may require
      // fetching the actual credential instance from a remote credentials store. Perhaps this is
      // not required
      return FormValidation.ok();
    }
  }
  // no credentials available, can't check
  return FormValidation.warning("Cannot find any credentials with id " + value);
}
项目:openshift-sync-plugin    文件:JenkinsUtils.java   
public static void cancelQueuedBuilds(WorkflowJob job, String bcUid) {
    Queue buildQueue = Jenkins.getActiveInstance().getQueue();
    for (Queue.Item item : buildQueue.getItems()) {
        for (Cause cause : item.getCauses()) {
            if (cause instanceof BuildCause) {
                BuildCause buildCause = (BuildCause) cause;
                if (buildCause.getBuildConfigUid().equals(bcUid)) {
                    Build build = new BuildBuilder().withNewMetadata().withNamespace(buildCause.getNamespace())
                            .withName(buildCause.getName()).and().build();
                    cancelQueuedBuild(job, build);
                }
            }
        }
    }
}
项目:hyper-slaves-plugin    文件:ProvisionQueueListener.java   
/**
 * If item is canceled, remove the executor we created for it.
 */
@Override
public void onLeft(Queue.LeftItem item) {
    if (item.isCancelled()) {
        HyperSlaveAssignmentAction action = item.getAction(HyperSlaveAssignmentAction.class);
        if (action == null) return;
        Node slave = action.getAssignedNodeName();
        if (slave == null) return;
        try {
            Jenkins.getActiveInstance().removeNode(slave);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failure to remove One-Shot Slave", e);
        }
    }
}
项目:sumologic-jenkins-plugin    文件:ModelFactory.java   
public static JenkinsModel createJenkinsModel(Jenkins jenkins) {
  Queue queue = jenkins.getQueue();
  final Queue.Item[] items = queue.getItems();
  int queueLength = items.length;
  long maxwait = 0, averagewait = 0, now = System.currentTimeMillis();
  for(Queue.Item item : items){
    long waiting = now - item.getInQueueSince();
    maxwait = maxwait > waiting ? maxwait : waiting;
    averagewait += waiting;
  }
  if (queueLength > 0 ) {
    averagewait = averagewait / queueLength;
  }

  QueueModel queueModel = new QueueModel(queueLength,queueLength - queue.countBuildableItems(), maxwait, averagewait);

  int numFreeExecutors=0;

  for (Computer computer : jenkins.getComputers()) {
    if (computer.isOnline()){
      numFreeExecutors += computer.countIdle();
    }

  }
  SlaveModel slaveModel = new SlaveModel(jenkins.getComputers().length - 1, jenkins.getNumExecutors(), numFreeExecutors);

  return new JenkinsModel(queueModel, slaveModel, jenkins.getDescription());
}
项目:fabric8-jenkins-workflow-steps    文件:Steps.java   
public static Run<?, ?> $build(FlowExecution execution) throws IOException {
    if (execution != null) {
        FlowExecutionOwner owner = execution.getOwner();
        if (owner != null) {
            Queue.Executable qe = owner.getExecutable();
            if (qe instanceof Run) {
                return (Run) qe;
            }
        }
    }
    return null;
}
项目:yet-another-docker-plugin    文件:DockerSlave.java   
@Override
public CauseOfBlockage canTake(Queue.BuildableItem item) {
    // hack for some core issue
    if (item.task instanceof Queue.FlyweightTask) {
        return new FlyweightCauseOfBlockage();
    }
    return super.canTake(item);
}
项目:yet-another-docker-plugin    文件:DockerComputer.java   
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
    LOG.debug("Computer {} taskCompleted", this);

    // May take the slave offline and remove it, in which case getNode()
    // above would return null and we'd not find our DockerSlave anymore.
    super.taskCompleted(executor, task, durationMS);
}
项目:yet-another-docker-plugin    文件:TaskBuildStep.java   
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath filePath, @Nonnull Launcher launcher,
                    @Nonnull TaskListener taskListener) throws InterruptedException, IOException {
    taskListener.getLogger().println("Entering task producer");
    Queue.getInstance().schedule(new DockerTask(), 0);
    taskListener.getLogger().println("Task scheduled? sleep");
    Thread.sleep(MINUTES.toMillis(10));
    taskListener.getLogger().println("end of sleep");
}
项目:jenkins-kubernetes-plugin    文件:KubernetesComputer.java   
@Override
public void taskCompleted(Executor executor, Queue.Task task, long durationMS) {
    LOGGER.log(Level.FINE, " Computer " + this + " taskCompleted");

    // May take the agent offline and remove it, in which case getNode()
    // above would return null and we'd not find our DockerSlave anymore.
    super.taskCompleted(executor, task, durationMS);
}
项目:jenkins-docker-build-plugin    文件:DockerJobLoadBalancer.java   
@Override
public MappingWorksheet.Mapping map(Queue.Task task, MappingWorksheet worksheet) {
    LOG.log(FINER, "map({0}, {1}])", new Object[]{task.getFullDisplayName(), worksheet.works.size()});

    if (task instanceof AbstractProject) {
        return map((AbstractProject) task, worksheet);
    } else {
        return _fallback.map(task, worksheet);
    }
}
项目:bitbucket-pullrequest-builder-plugin    文件:BitbucketBuildTrigger.java   
private void cancelPreviousJobsInQueueThatMatch(@Nonnull BitbucketCause bitbucketCause) {
    logger.fine("Looking for queued jobs that match PR ID: " + bitbucketCause.getPullRequestId());
    Queue queue = getInstance().getQueue();

    for (Queue.Item item : queue.getItems()) {
        if (hasCauseFromTheSamePullRequest(item.getCauses(), bitbucketCause)) {
            logger.fine("Canceling item in queue: " + item);
            queue.cancel(item);
        }
    }
}
项目:deployer-framework-plugin    文件:DeployNowSlave.java   
@Override
public CauseOfBlockage canTake(Queue.BuildableItem item) {
    if (item.task instanceof DeployNowTask) {
        return null;
    }
    return CauseOfBlockage.fromMessage(Messages._DeployNowSlave_OnlyAcceptsDeployNowTasks());
}
项目:deployer-framework-plugin    文件:DeployNowComputer.java   
@Override
public synchronized long check(final DeployNowComputer c) {
    if (!c.isIdle()) {
        return 1;
    }
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        for (Queue.Item t : jenkins.getQueue().getItems()) {
            if (t.task instanceof DeployNowTask) {
                return 1;
            }
        }
    }
    if (!c.offline) {
        c.offline = true;
        try {
            if (jenkins != null) {
                Slave node = c.getNode();
                if (node != null) {
                    jenkins.removeNode(node);
                }
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return 1;
}
项目:deployer-framework-plugin    文件:DeployNowRunAction.java   
/**
 * Returns true if the log file is still being updated.
 */
public boolean isLogUpdated() {
    if (deployer != null) {
        return true;
    }
    for (Queue.Item item : Hudson.getInstance().getQueue().getItems()) {
        if (item.task instanceof DeployNowTask && owner.equals(DeployNowTask.class.cast(item.task).getBuild())) {
            return true;
        }
    }
    return false;
}
项目:p4-jenkins    文件:ReviewAction.java   
public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {

        project.checkPermission(AbstractProject.BUILD);

        List<ParameterValue> values = new ArrayList<ParameterValue>();
        List<ParameterDefinition> defs = new ArrayList<ParameterDefinition>();

        Enumeration<?> names = req.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            defs.add(new StringParameterDefinition(name, null));
        }

        for (ParameterDefinition d : defs) {
            StringParameterValue value = (StringParameterValue) d.createValue(req);
            if (value != null && value.value != null && !value.value.isEmpty()) {
                values.add(value);
            }
        }

        // Schedule build
        TimeDuration delay = new TimeDuration(project.getQuietPeriod());
        CauseAction cause = new CauseAction(new Cause.UserIdCause());

        List<ParameterValue> internalParams = extractAndRemoveInternalParameters(values);
        ParametersAction params = new SafeParametersAction(values, internalParams);

        Jenkins j = Jenkins.getInstance();
        if (j != null) {
            Queue queue = j.getQueue();
            queue.schedule(project, delay.getTime(), params, cause);

            // send the user back to the job top page.
            rsp.sendRedirect("../");
        }
    }
项目:metrics-plugin    文件:JenkinsMetricProviderImpl.java   
@Override
public boolean shouldSchedule(Queue.Task p, List<Action> actions) {
    JenkinsMetricProviderImpl instance = instance();
    if (instance != null && instance.jenkinsJobScheduleRate != null) {
        instance.jenkinsJobScheduleRate.mark();
    }
    return true;
}
项目:metrics-plugin    文件:JenkinsMetricProviderImpl.java   
public void onLeft(Queue.LeftItem li) {
    long millisecondsInQueue = System.currentTimeMillis() - li.getInQueueSince();
    JenkinsMetricProviderImpl instance = JenkinsMetricProviderImpl.instance();
    if (instance != null && instance.jenkinsJobQueueTime != null) {
        instance.jenkinsJobQueueTime.update(millisecondsInQueue, TimeUnit.MILLISECONDS);
    }
    if (li.outcome != null) {
        synchronized (actions) {
            actions.put(li.outcome, new TimeInQueueAction(millisecondsInQueue));
        }
    }
}
项目:metrics-plugin    文件:JenkinsMetricProviderImpl.java   
@Override
public void onEnterBlocked(Queue.BlockedItem bi) {
    JenkinsMetricProviderImpl instance = JenkinsMetricProviderImpl.instance();
    if (instance != null && instance.jenkinsJobBlockedTime != null) {
        synchronized (blocked) {
            if (!blocked.containsKey(bi)) {
                blocked.put(bi, instance.jenkinsJobBlockedTime.time());
            }
        }
    }
}
项目:metrics-plugin    文件:JenkinsMetricProviderImpl.java   
@Override
public void onLeaveBlocked(Queue.BlockedItem bi) {
    synchronized (blocked) {
        Timer.Context context = blocked.remove(bi);
        if (context != null) {
            context.stop();
        }
    }
}