下面列出了怎么用hudson.model.Queue的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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);
}
});
}
}
}
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) {
}
}
});
});
}
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;
}
@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);
}
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();
}
}
}
}
}
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)))));
}
@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.");
}
}
/**
* 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;
}
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));
}
/**
* 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);
}
}
}
}
}
@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);
}
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)))));
}
/**
* 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)
);
}
/**
* 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
);
}
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);
}
@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();
}
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;
}
@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.get().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
? ((Queue.Task) context).getDefaultAuthentication()
: ACL.SYSTEM,
context,
StandardUsernameCredentials.class,
URIRequirementBuilder.fromUri(serverUrl).build(),
CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
);
return result;
}
public SwarmQueueItem(final Queue.BuildableItem item) {
this.name = item.task.getFullDisplayName();
this.label = item.task.getAssignedLabel().getName();
this.labelConfig = DockerSwarmCloud.get().getLabelConfiguration(this.label);
this.inQueueSince = item.getInQueueForString();
this.agentInfo = item.getAction(DockerSwarmAgentInfo.class); // this should never be null
final DockerSwarmLabelAssignmentAction lblAssignmentAction = item
.getAction(DockerSwarmLabelAssignmentAction.class);
if (lblAssignmentAction != null) {
final String computerName = lblAssignmentAction.getLabel().getName();
this.provisionedComputer = Jenkins.getInstance().getComputer(computerName);
}
}
public DockerSwarmComputerLauncher(final Queue.BuildableItem bi) {
super(DockerSwarmCloud.get().getTunnel(), null, new RemotingWorkDirSettings(false, "/tmp", null, false));
this.bi = bi;
this.label = bi.task.getAssignedLabel().getName();
this.jobName = bi.task instanceof AbstractProject ? ((AbstractProject) bi.task).getFullName()
: bi.task.getName();
}
private void done(Executor executor) {
final DockerSwarmComputer c = (DockerSwarmComputer) 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);
}
@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");
}
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();
}
}
private void cancel(Queue.Item item, Queue queue, String branch) {
try {
LOGGER.log(Level.INFO, "Cancelling job {0} for branch {1}", LoggerUtil.toArray(item.task.getName(), branch));
queue.cancel(item);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error cancelling queued build", e);
}
}
@Override
public CauseOfBlockage canTake(final Queue.BuildableItem item) {
final Label l = item.getAssignedLabel();
if (l != null && this.name.equals(l.getName())) {
return null;
}
return super.canTake(item);
}
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;
};
}
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;
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
@QueryParameter String serverUrl,
@QueryParameter String credentialsId) {
StandardListBoxModel result = new StandardListBoxModel();
if (context == null) {
if (!Jenkins.get().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 ?
((Queue.Task) context).getDefaultAuthentication()
: ACL.SYSTEM,
context,
StandardCredentials.class,
URIRequirementBuilder.fromUri(serverUrl).build(),
AuthenticationTokens.matcher(GiteaAuth.class)
);
return result;
}
@Override
public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
try(final DockerClient client = api.getClient()) {
client.inspectContainerCmd(containerId).exec();
} catch (NotFoundException e) {
// Container has been removed
Queue.withLock(() -> {
DockerTransientNode node = (DockerTransientNode) computer.getNode();
node.terminate(listener);
});
return;
}
super.launch(computer, listener);
}