code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
private static void ensureSkipTlsVerifyInFipsMode(boolean skipTlsVerify) {
if (FIPS140.useCompliantAlgorithms() && skipTlsVerify) {
throw new IllegalArgumentException(Messages.KubernetesCloud_skipTlsVerifyNotAllowedInFIPSMode());
}
}
|
Checks if TLS verification is being skipped, which is not allowed in FIPS mode
Continues if not being skipped or not in FIPS mode, throws an {@link IllegalArgumentException} if not.
@param skipTlsVerify value to check
|
ensureSkipTlsVerifyInFipsMode
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
public PodTemplate getUnwrappedTemplate(PodTemplate podTemplate) {
return PodTemplateUtils.unwrap(podTemplate, getDefaultsProviderTemplate(), getAllTemplates());
}
|
Unwraps the given pod template.
@param podTemplate the pod template to unwrap.
@return the unwrapped pod template
|
getUnwrappedTemplate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
@Deprecated
public ArrayList<PodTemplate> getMatchingTemplates(@CheckForNull Label label) {
return new ArrayList<>(getTemplatesFor(label));
}
|
Gets all PodTemplates that have the matching {@link Label}.
@param label label to look for in templates
@return list of matching templates
@deprecated Use {@link #getTemplatesFor(Label)} instead.
|
getMatchingTemplates
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
public List<PodTemplate> getTemplatesFor(@CheckForNull Label label) {
return PodTemplateFilter.applyAll(this, getAllTemplates(), label);
}
|
Gets all PodTemplates that have the matching {@link Label}.
@param label label to look for in templates
@return list of matching templates
|
getTemplatesFor
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
@Override
public void addTemplate(PodTemplate t) {
this.checkManagePermission();
this.templates.add(t);
// t.parent = this;
}
|
Add a new template to the cloud
@param t docker template
|
addTemplate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
public void addDynamicTemplate(PodTemplate t) {
PodTemplateMap.get().addTemplate(this, t);
}
|
Add a dynamic pod template. Won't be displayed in UI, and persisted separately from the cloud instance.
@param t the template to add
|
addDynamicTemplate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloud.java
|
Apache-2.0
|
public static ExtensionList<KubernetesComputerFactory> all() {
return ExtensionList.lookup(KubernetesComputerFactory.class);
}
|
Returns all registered implementations of {@link KubernetesComputerFactory}.
@return all registered implementations of {@link KubernetesComputerFactory}.
|
all
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesComputerFactory.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesComputerFactory.java
|
Apache-2.0
|
public static KubernetesComputer createInstance(KubernetesSlave slave) {
for (KubernetesComputerFactory factory : all()) {
KubernetesComputer kubernetesComputer = factory.newInstance(slave);
if (kubernetesComputer != null) {
return kubernetesComputer;
}
}
return new KubernetesComputer(slave);
}
|
Returns a new instance of {@link KubernetesComputer}.
@return a new instance of {@link KubernetesComputer}.
|
createInstance
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesComputerFactory.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesComputerFactory.java
|
Apache-2.0
|
private void logLastLines(
@CheckForNull List<ContainerStatus> containers,
String podId,
String namespace,
KubernetesSlave slave,
Map<String, Integer> errors,
KubernetesClient client) {
if (containers != null) {
for (ContainerStatus containerStatus : containers) {
String containerName = containerStatus.getName();
String log = client.pods()
.inNamespace(namespace)
.withName(podId)
.inContainer(containerStatus.getName())
.tailingLines(30)
.getLog();
if (!StringUtils.isBlank(log)) {
String msg =
errors != null ? String.format(" exited with error %s", errors.get(containerName)) : "";
LOGGER.log(
Level.SEVERE,
"Error in provisioning; agent={0}, template={1}. Container {2}{3}. Logs: {4}",
new Object[] {slave, slave.getTemplateOrNull(), containerName, msg, log});
}
}
}
}
|
Log the last lines of containers logs
|
logLastLines
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesLauncher.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesLauncher.java
|
Apache-2.0
|
public synchronized boolean register(
@NonNull KubernetesCloud cloud, @NonNull PodTemplate podTemplate, int numExecutors) {
initInstance();
int newGlobalCount = getGlobalCount(cloud.name) + numExecutors;
if (newGlobalCount <= cloud.getContainerCap()) {
int newPodTemplateCount = getPodTemplateCount(podTemplate.getId()) + numExecutors;
if (newPodTemplateCount <= podTemplate.getInstanceCap()) {
cloudCounts.put(cloud.name, newGlobalCount);
LOGGER.log(
Level.FINEST,
() -> cloud.name + " global limit: " + newGlobalCount + "/" + cloud.getContainerCap());
podTemplateCounts.put(podTemplate.getId(), newPodTemplateCount);
LOGGER.log(
Level.FINEST,
() -> podTemplate.getName() + " template limit: " + newPodTemplateCount + "/"
+ podTemplate.getInstanceCap());
return true;
} else {
LOGGER.log(
Level.FINEST,
() -> podTemplate.getName() + " template limit reached: "
+ getPodTemplateCount(podTemplate.getId()) + "/" + podTemplate.getInstanceCap()
+ ". Cannot add " + numExecutors + " more!");
Metrics.metricRegistry().counter(MetricNames.REACHED_POD_CAP).inc();
}
} else {
LOGGER.log(
Level.FINEST,
() -> cloud.name + " global limit reached: " + getGlobalCount(cloud.name) + "/"
+ cloud.getContainerCap() + ". Cannot add " + numExecutors + " more!");
Metrics.metricRegistry().counter(MetricNames.REACHED_GLOBAL_CAP).inc();
}
return false;
}
|
Register executors
@param cloud the kubernetes cloud the executors will be on
@param podTemplate the pod template used to schedule the agent
@param numExecutors the number of executors (pretty much always 1)
|
register
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesProvisioningLimits.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesProvisioningLimits.java
|
Apache-2.0
|
@NonNull
public TaskListener getRunListener() {
PodTemplate podTemplate = getTemplateOrNull();
if (podTemplate != null) {
TaskListener listener = podTemplate.getListenerOrNull();
if (listener != null) {
return listener;
}
}
Computer c = toComputer();
if (c != null) {
for (Executor executor : c.getExecutors()) {
Queue.Executable executable = executor.getCurrentExecutable();
// If this executor hosts a PlaceholderExecutable, send to the owning build log.
if (executable != null) {
Queue.Executable parentExecutable = executable.getParentExecutable();
if (parentExecutable instanceof FlowExecutionOwner.Executable) {
FlowExecutionOwner flowExecutionOwner =
((FlowExecutionOwner.Executable) parentExecutable).asFlowExecutionOwner();
if (flowExecutionOwner != null) {
try {
return flowExecutionOwner.getListener();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}
}
// TODO handle freestyle and similar if executable instanceof Run, by capturing a TaskListener from
// RunListener.onStarted
}
}
return TaskListener.NULL;
}
|
Makes a best effort to find the build log corresponding to this agent.
|
getRunListener
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
@Deprecated
public Cloud getCloud() {
return Jenkins.getInstance().getCloud(getCloudName());
}
|
@deprecated Please use the strongly typed getKubernetesCloud() instead.
|
getCloud
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Optional<Pod> getPod() {
Pod p = pod;
if (p == null) {
// if jenkins restarts the transient pod reference may not be available
try {
p = getKubernetesCloud()
.getPodResource(getNamespace(), getPodName())
.get();
if (p != null) {
assignPod(p);
return Optional.of(p);
} else {
return Optional.empty();
}
} catch (KubernetesAuthException | IOException | IllegalStateException e) {
LOGGER.log(
Level.WARNING,
e,
() -> String.format(
"Failed to connect to cloud %s to get pod %s/%s",
getCloudName(), getNamespace(), getPodName()));
return Optional.empty();
}
} else {
return Optional.of(p);
}
}
|
Get {@link Pod} reference for this agent. If it hasn't been assigned yet
or the reference was lost due to restart, it will be looked up.
@return assigned pod, or empty if not assigned or no longer exists
|
getPod
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder name(String name) {
this.name = name;
return this;
}
|
@param name The name of the future {@link KubernetesSlave}
@return the current instance for method chaining
|
name
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder nodeDescription(String nodeDescription) {
this.nodeDescription = nodeDescription;
return this;
}
|
@param nodeDescription The node description of the future {@link KubernetesSlave}
@return the current instance for method chaining
|
nodeDescription
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder podTemplate(PodTemplate podTemplate) {
this.podTemplate = podTemplate;
return this;
}
|
@param podTemplate The pod template the future {@link KubernetesSlave} has been created from
@return the current instance for method chaining
|
podTemplate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder cloud(KubernetesCloud cloud) {
this.cloud = cloud;
return this;
}
|
@param cloud The cloud that is provisioning the {@link KubernetesSlave} instance.
@return the current instance for method chaining
|
cloud
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder label(String label) {
this.label = label;
return this;
}
|
@param label The label the {@link KubernetesSlave} has.
@return the current instance for method chaining
|
label
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public Builder computerLauncher(ComputerLauncher computerLauncher) {
this.computerLauncher = computerLauncher;
return this;
}
|
@param computerLauncher The computer launcher to use to launch the {@link KubernetesSlave} instance.
@return the current instance for method chaining
|
computerLauncher
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesSlave.java
|
Apache-2.0
|
public boolean register(@NonNull PodTemplate podTemplate, int numExecutors) {
var result = new Result(
KubernetesProvisioningLimits.get().register(cloud, podTemplate, numExecutors),
podTemplate,
numExecutors);
results.add(result);
return result.success;
}
|
Register a slot for the given pod template and number of executors.
@return true is the registration was successful
|
register
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/LimitRegistrationResults.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/LimitRegistrationResults.java
|
Apache-2.0
|
public KubernetesCloud getCloud() {
return cloud;
}
|
Returns the {@link KubernetesCloud}.
@return the {@link KubernetesCloud}.
|
getCloud
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
Apache-2.0
|
public PlannedNodeBuilder cloud(KubernetesCloud cloud) {
this.cloud = cloud;
return this;
}
|
@param cloud the {@link KubernetesCloud} instance to use.
@return the current builder.
|
cloud
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
Apache-2.0
|
public PlannedNodeBuilder template(PodTemplate template) {
this.template = template;
return this;
}
|
@param template the {@link PodTemplate} instance to use.
@return the current builder.
|
template
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
Apache-2.0
|
public PlannedNodeBuilder label(Label label) {
this.label = label;
return this;
}
|
@param label the {@link Label} to use.
@return the current builder.
|
label
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
Apache-2.0
|
public PlannedNodeBuilder numExecutors(int numExecutors) {
this.numExecutors = numExecutors;
return this;
}
|
@param numExecutors the number of executors.
@return the current builder.
|
numExecutors
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilder.java
|
Apache-2.0
|
public static ExtensionList<PlannedNodeBuilderFactory> all() {
return ExtensionList.lookup(PlannedNodeBuilderFactory.class);
}
|
Returns all registered implementations of {@link PlannedNodeBuilderFactory}.
@return all registered implementations of {@link PlannedNodeBuilderFactory}.
|
all
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilderFactory.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilderFactory.java
|
Apache-2.0
|
public static PlannedNodeBuilder createInstance() {
for (PlannedNodeBuilderFactory factory : all()) {
PlannedNodeBuilder plannedNodeBuilder = factory.newInstance();
if (plannedNodeBuilder != null) {
return plannedNodeBuilder;
}
}
return new StandardPlannedNodeBuilder();
}
|
Returns a new instance of {@link PlannedNodeBuilder}.
@return a new instance of {@link PlannedNodeBuilder}.
|
createInstance
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilderFactory.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PlannedNodeBuilderFactory.java
|
Apache-2.0
|
@NonNull
public static List<PodContainerSource> all() {
return ExtensionList.lookup(PodContainerSource.class);
}
|
Lookup all {@link PodContainerSource} extensions.
@return pod container source extension list
|
all
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
Apache-2.0
|
public static Optional<String> lookupContainerWorkingDir(@NonNull Pod pod, @NonNull String containerName) {
return all().stream()
.map(cs -> cs.getContainerWorkingDir(pod, containerName))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
|
Lookup pod container working dir. Searches all {@link PodContainerSource} extensions and returns
the first non-empty result.
@param pod pod to inspect
@param containerName container to search for
@return optional working dir if container found and working dir, possibly empty
|
lookupContainerWorkingDir
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
Apache-2.0
|
public static Optional<ContainerStatus> lookupContainerStatus(Pod pod, String containerName) {
return PodContainerSource.all().stream()
.map(cs -> cs.getContainerStatus(pod, containerName))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
|
Lookup container status (either main container or ephemeral container).
@param pod pod resource to inspect
@param containerName container to locate
@return container status if found
|
lookupContainerStatus
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodContainerSource.java
|
Apache-2.0
|
@NonNull
static Map<String, String> toMap(@NonNull Iterable<PodLabel> labels) {
Map<String, String> builder = new HashMap<>();
for (PodLabel podLabel : labels) {
builder.put(podLabel.getKey(), substituteEnv(podLabel.getValue()));
}
return Collections.unmodifiableMap(builder);
}
|
Create map from collection of labels. Values that environment variables placeholders will be resolved.
@see PodTemplateUtils#substituteEnv(String)
@param labels collection of pod labels to convert to a map
@return immutable map of pod labels
|
toMap
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodLabel.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodLabel.java
|
Apache-2.0
|
protected static MessageDigest getLabelDigestFunction() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// will never happen, SHA-1 support required on every Java implementation
e.printStackTrace();
// throw error to allow variable to be set as final
throw new AssertionError(e);
}
}
|
Digest function that is used to compute the kubernetes label "jenkins/label-digest"
Not used for security.
|
getLabelDigestFunction
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplate.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplate.java
|
Apache-2.0
|
public Pod build(KubernetesSlave slave) {
return new PodTemplateBuilder(this, slave).build();
}
|
Build a Pod object from a PodTemplate
@param slave
|
build
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplate.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplate.java
|
Apache-2.0
|
public static ExtensionList<PodTemplateFilter> all() {
return ExtensionList.lookup(PodTemplateFilter.class);
}
|
Returns a list of all implementations of {@link PodTemplateFilter}.
@return a list of all implementations of {@link PodTemplateFilter}.
|
all
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateFilter.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateFilter.java
|
Apache-2.0
|
public static List<PodTemplate> applyAll(
@NonNull KubernetesCloud cloud, @NonNull List<PodTemplate> podTemplates, @CheckForNull Label label) {
List<PodTemplate> result = new ArrayList<>();
for (PodTemplate t : podTemplates) {
PodTemplate output = t;
for (PodTemplateFilter f : all()) {
output = f.transform(cloud, output, label);
if (output == null) {
break;
}
}
if (output != null) {
result.add(output);
}
}
return result;
}
|
Pass the given pod templates list into all filters implementations.
@param cloud The cloud instance the pod templates are getting considered for
@param podTemplates The initial list of pod templates
@param label The label that was requested for provisioning
@return The pod template list after filtering
|
applyAll
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateFilter.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateFilter.java
|
Apache-2.0
|
default boolean hasManagePermission() {
return Jenkins.get().hasPermission(getManagePermission());
}
|
@return {@code true} if the current {@link Authentication} has permissions to add / replace / remove templates.
|
hasManagePermission
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateGroup.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateGroup.java
|
Apache-2.0
|
@Override
protected PodTemplate transform(
@NonNull KubernetesCloud cloud, @NonNull PodTemplate podTemplate, @CheckForNull Label label) {
if ((label == null && podTemplate.getNodeUsageMode() == Node.Mode.NORMAL)
|| (label != null && label.matches(podTemplate.getLabelSet()))) {
return podTemplate;
}
return null;
}
|
Implementation of {@link PodTemplateFilter} filtering pod templates matching the right label.
|
transform
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateLabelFilter.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateLabelFilter.java
|
Apache-2.0
|
public static ContainerTemplate combine(
@CheckForNull ContainerTemplate parent, @NonNull ContainerTemplate template) {
if (template == null) {
throw new IllegalArgumentException("Container template should not be null");
}
if (parent == null) {
return template;
}
Map<String, PortMapping> ports =
parent.getPorts().stream().collect(Collectors.toMap(PortMapping::getName, Function.identity()));
template.getPorts().forEach(p -> ports.put(p.getName(), p));
var h = new HierarchyResolver<>(parent, template);
ContainerTemplate combined = new ContainerTemplate(
template.getName(), h.resolve(ContainerTemplate::getImage, PodTemplateUtils::isNullOrEmpty));
combined.setAlwaysPullImage(h.resolve(ContainerTemplate::isAlwaysPullImage, v -> !v));
combined.setCommand(h.resolve(ContainerTemplate::getCommand, PodTemplateUtils::isNullOrEmpty));
combined.setArgs(h.resolve(ContainerTemplate::getArgs, PodTemplateUtils::isNullOrEmpty));
combined.setTtyEnabled(h.resolve(ContainerTemplate::isTtyEnabled, v -> !v));
combined.setResourceLimitCpu(
h.resolve(ContainerTemplate::getResourceLimitCpu, PodTemplateUtils::isNullOrEmpty));
combined.setResourceLimitMemory(
h.resolve(ContainerTemplate::getResourceLimitMemory, PodTemplateUtils::isNullOrEmpty));
combined.setResourceLimitEphemeralStorage(
h.resolve(ContainerTemplate::getResourceLimitEphemeralStorage, PodTemplateUtils::isNullOrEmpty));
combined.setResourceRequestCpu(
h.resolve(ContainerTemplate::getResourceRequestCpu, PodTemplateUtils::isNullOrEmpty));
combined.setResourceRequestMemory(
h.resolve(ContainerTemplate::getResourceRequestMemory, PodTemplateUtils::isNullOrEmpty));
combined.setResourceRequestEphemeralStorage(
h.resolve(ContainerTemplate::getResourceRequestEphemeralStorage, PodTemplateUtils::isNullOrEmpty));
combined.setShell(h.resolve(ContainerTemplate::getShell, PodTemplateUtils::isNullOrEmpty));
combined.setWorkingDir(h.resolve(ContainerTemplate::getWorkingDir, PodTemplateUtils::isNullOrEmpty));
combined.setPrivileged(h.resolve(ContainerTemplate::isPrivileged, v -> !v));
combined.setRunAsUser(h.resolve(ContainerTemplate::getRunAsUser, Objects::isNull));
combined.setRunAsGroup(h.resolve(ContainerTemplate::getRunAsGroup, Objects::isNull));
combined.setEnvVars(combineEnvVars(parent, template));
combined.setPorts(new ArrayList<>(ports.values()));
combined.setLivenessProbe(h.resolve(ContainerTemplate::getLivenessProbe, Objects::isNull));
return combined;
}
|
Combines a {@link ContainerTemplate} with its parent.
@param parent The parent container template (nullable).
@param template The actual container template
@return The combined container template.
|
combine
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
public static Pod combine(List<Pod> pods) {
Pod result = null;
for (Pod p : pods) {
if (result != null) {
result = combine(result, p);
} else {
result = p;
}
}
return result;
}
|
Combines all given pods together in order.
@param pods the pods to combine
|
combine
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
public static PodTemplate combine(PodTemplate parent, PodTemplate template) {
if (template == null) {
throw new IllegalArgumentException("Pod template should not be null");
}
if (parent == null) {
return template;
}
LOGGER.log(Level.FINEST, () -> "Combining pod templates, parent: " + parent + ", template: " + template);
String name = template.getName();
String label = template.getLabel();
Set<PodAnnotation> podAnnotations = new LinkedHashSet<>();
podAnnotations.addAll(template.getAnnotations());
podAnnotations.addAll(parent.getAnnotations());
Set<PodImagePullSecret> imagePullSecrets = new LinkedHashSet<>();
imagePullSecrets.addAll(parent.getImagePullSecrets());
imagePullSecrets.addAll(template.getImagePullSecrets());
Map<String, ContainerTemplate> combinedContainers = new HashMap<>();
Map<String, PodVolume> combinedVolumes = new HashMap<>();
// Containers
Map<String, ContainerTemplate> parentContainers =
parent.getContainers().stream().collect(toMap(ContainerTemplate::getName, c -> c));
combinedContainers.putAll(parentContainers);
combinedContainers.putAll(template.getContainers().stream()
.collect(toMap(ContainerTemplate::getName, c -> combine(parentContainers.get(c.getName()), c))));
// Volumes
Map<String, PodVolume> parentVolumes =
parent.getVolumes().stream().collect(toMap(PodVolume::getMountPath, v -> v));
combinedVolumes.putAll(parentVolumes);
combinedVolumes.putAll(template.getVolumes().stream().collect(toMap(PodVolume::getMountPath, v -> v)));
WorkspaceVolume workspaceVolume =
WorkspaceVolume.merge(parent.getWorkspaceVolume(), template.getWorkspaceVolume());
// Tool location node properties
List<NodeProperty<?>> nodeProperties = new ArrayList<>(parent.getNodeProperties());
nodeProperties.addAll(template.getNodeProperties());
PodTemplate podTemplate = new PodTemplate(template.getId());
var h = new HierarchyResolver<>(parent, template);
podTemplate.setName(name);
podTemplate.setNamespace(h.resolve(PodTemplate::getNamespace, PodTemplateUtils::isNullOrEmpty));
podTemplate.setLabel(label);
podTemplate.setNodeSelector(h.resolve(PodTemplate::getNodeSelector, PodTemplateUtils::isNullOrEmpty));
podTemplate.setServiceAccount(h.resolve(PodTemplate::getServiceAccount, PodTemplateUtils::isNullOrEmpty));
podTemplate.setSchedulerName(h.resolve(PodTemplate::getSchedulerName, PodTemplateUtils::isNullOrEmpty));
podTemplate.setEnvVars(combineEnvVars(parent, template));
podTemplate.setContainers(new ArrayList<>(combinedContainers.values()));
podTemplate.setWorkspaceVolume(workspaceVolume);
podTemplate.setVolumes(new ArrayList<>(combinedVolumes.values()));
podTemplate.setImagePullSecrets(new ArrayList<>(imagePullSecrets));
podTemplate.setAnnotations(new ArrayList<>(podAnnotations));
podTemplate.setNodeProperties(nodeProperties);
podTemplate.setNodeUsageMode(
template.getNodeUsageMode() == null ? parent.getNodeUsageMode() : template.getNodeUsageMode());
podTemplate.setYamlMergeStrategy(h.resolve(
PodTemplate::getYamlMergeStrategy,
childValue -> childValue == null && parent.isInheritYamlMergeStrategy()));
podTemplate.setInheritYamlMergeStrategy(parent.isInheritYamlMergeStrategy());
podTemplate.setInheritFrom(h.resolve(PodTemplate::getInheritFrom, PodTemplateUtils::isNullOrEmpty));
podTemplate.setInstanceCap(h.resolve(PodTemplate::getInstanceCap, i -> Objects.equals(i, Integer.MAX_VALUE)));
podTemplate.setSlaveConnectTimeout(h.resolve(
PodTemplate::getSlaveConnectTimeout,
i -> Objects.equals(i, PodTemplate.DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT)));
podTemplate.setIdleMinutes(h.resolve(PodTemplate::getIdleMinutes, i -> Objects.equals(i, 0)));
podTemplate.setActiveDeadlineSeconds(
h.resolve(PodTemplate::getActiveDeadlineSeconds, i -> Objects.equals(i, 0)));
podTemplate.setServiceAccount(h.resolve(PodTemplate::getServiceAccount, PodTemplateUtils::isNullOrEmpty));
podTemplate.setSchedulerName(h.resolve(PodTemplate::getSchedulerName, PodTemplateUtils::isNullOrEmpty));
podTemplate.setPodRetention(template.getPodRetention());
podTemplate.setShowRawYaml(h.resolve(PodTemplate::isShowRawYaml, v -> v));
podTemplate.setRunAsUser(h.resolve(PodTemplate::getRunAsUser, Objects::isNull));
podTemplate.setRunAsGroup(h.resolve(PodTemplate::getRunAsGroup, Objects::isNull));
podTemplate.setSupplementalGroups(h.resolve(PodTemplate::getSupplementalGroups, Objects::isNull));
podTemplate.setAgentContainer(h.resolve(PodTemplate::getAgentContainer, PodTemplateUtils::isNullOrEmpty));
podTemplate.setAgentInjection(h.resolve(PodTemplate::isAgentInjection, v -> !v));
if (template.isHostNetworkSet()) {
podTemplate.setHostNetwork(template.isHostNetwork());
} else if (parent.isHostNetworkSet()) {
podTemplate.setHostNetwork(parent.isHostNetwork());
}
List<String> yamls = new ArrayList<>(parent.getYamls());
yamls.addAll(template.getYamls());
podTemplate.setYamls(yamls);
podTemplate.setListener(template.getListener());
LOGGER.log(Level.FINEST, "Pod templates combined: {0}", podTemplate);
return podTemplate;
}
|
Combines a {@link PodTemplate} with its parent.
@param parent The parent container template (nullable).
@param template The actual container template
@return The combined container template.
|
combine
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
<T> T resolve(Function<P, T> getter, Predicate<T> isDefaultValue) {
var childValue = getter.apply(child);
return !isDefaultValue.test(childValue) ? childValue : getter.apply(parent);
}
|
<p>Resolves a pod template field according to hierarchy.
<p>If the child pod template uses a non-default value, then it is used.
<p>Otherwise the parent value is used.
@param getter the getter function to obtain the field value
@param isDefaultValue A function to determine if the value is the default value
@return The value for the field taking into account the hierarchy.
@param <T> The field type
|
resolve
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
static PodTemplate unwrap(PodTemplate template, Collection<PodTemplate> allTemplates) {
return unwrap(template, null, allTemplates);
}
|
Unwraps the hierarchy of the PodTemplate.
@param template The template to unwrap.
@param allTemplates A collection of all the known templates
@return
|
unwrap
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
@CheckForNull
public static PodTemplate getTemplateByLabel(@CheckForNull Label label, Collection<PodTemplate> templates) {
for (PodTemplate t : templates) {
if ((label == null && t.getNodeUsageMode() == Node.Mode.NORMAL)
|| (label != null && label.matches(t.getLabelSet()))) {
return t;
}
}
return null;
}
|
Gets the {@link PodTemplate} by {@link Label}.
@param label The label.
@param templates The list of all templates.
@return The first pod template from the collection that has a matching label.
|
getTemplateByLabel
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
public static PodTemplate getTemplateByName(@CheckForNull String name, Collection<PodTemplate> templates) {
for (PodTemplate t : templates) {
if (name != null && name.equals(t.getName())) {
return t;
}
}
return null;
}
|
Gets the {@link PodTemplate} by name.
@param name The name.
@param templates The list of all templates.
@return The first pod template from the collection that has a matching name.
|
getTemplateByName
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
@Deprecated
public static String substituteEnv(String s) {
return SUBSTITUTE_ENV ? replaceMacro(s, System.getenv()) : s;
}
|
Substitutes a placeholder with a value found in the environment.
@param s The placeholder. Should be use the format: ${placeholder}.
@return The substituted value if found, or the input value otherwise.
@deprecated Potentially insecure; a no-op by default.
|
substituteEnv
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
@Deprecated
public static String substitute(String s, Map<String, String> properties) {
return replaceMacro(s, properties);
}
|
Substitutes a placeholder with a value found in the specified map.
@deprecated use {@link Util#replaceMacro(String, Map)}
@param s The placeholder. Should be use the format: ${placeholder}.
@param properties The map with the key value pairs to use for substitution.
@return The substituted value if found, or the input value otherwise.
|
substitute
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
public static boolean validateImage(String image) {
return image != null && image.matches("\\S+");
}
|
TODO perhaps enforce https://docs.docker.com/engine/reference/commandline/tag/#extended-description
|
validateImage
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
public static @Nullable List<String> splitCommandLine(@Nullable String commandLine) {
if (commandLine == null || commandLine.isEmpty()) {
return null;
}
String[] args = Commandline.translateCommandline(commandLine);
if (SUBSTITUTE_ENV) {
for (int i = 0; i < args.length; i++) {
args[i] = substituteEnv(args[i]);
}
}
return Arrays.asList(args);
}
|
Split a command in the parts that Docker need
@param commandLine docker command to parse
@return command split by arguments, {@code null} if {@code commandLine} is {@code null} or empty
|
splitCommandLine
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodTemplateUtils.java
|
Apache-2.0
|
@NonNull
public static List<ContainerStatus> getContainerStatus(@NonNull Pod pod) {
PodStatus podStatus = pod.getStatus();
if (podStatus == null) {
return Collections.emptyList();
}
return podStatus.getContainerStatuses();
}
|
Get all container statuses (does not include ephemeral or init containers).
@param pod pod to get container statuses for
@return list of statuses, possibly empty, never null
|
getContainerStatus
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
Apache-2.0
|
public static List<ContainerStatus> getContainers(@NonNull Pod pod, @NonNull Predicate<ContainerStatus> predicate) {
return getContainerStatus(pod).stream().filter(predicate).collect(Collectors.toList());
}
|
Get pod container statuses (does not include ephemeral or init containers) that match the given filter.
@param pod pod to get container statuses for
@param predicate container status predicate
@return list of statuses, possibly empty, never null
|
getContainers
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
Apache-2.0
|
@NonNull
public static String generateRandomSuffix() {
return RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
}
|
Generate a random string to be used as the suffix for dynamic resource names.
@return random string suitable for kubernetes resources
|
generateRandomSuffix
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
Apache-2.0
|
@NonNull
public static String createNameWithRandomSuffix(@NonNull String name) {
String suffix = generateRandomSuffix();
// no spaces
name = name.replaceAll("[ _]", "-").toLowerCase(Locale.getDefault());
// keep it under 63 chars (62 is used to account for the '-')
name = name.substring(0, Math.min(name.length(), 62 - suffix.length()));
return String.join("-", name, suffix);
}
|
Create kubernetes resource name with a random suffix appended to the given base name. This method
performs some basic transforms to make the base name compliant (i.e. spaces and underscores). The
returned string will also be truncated to a max of 63 characters.
@param name base name to append to
@return resource name with random suffix and maximum length of 63 characters
|
createNameWithRandomSuffix
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
Apache-2.0
|
public static boolean isValidName(@NonNull String name) {
return PodUtils.NAME_PATTERN.matcher(name).matches();
}
|
Check if the given name is a valid pod resource name. Does not validate string length.
@param name name to check
@return true if the given string contains valid pod resource name characters
|
isValidName
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodUtils.java
|
Apache-2.0
|
@Deprecated
public static boolean volumeMountExists(String path, List<VolumeMount> existingMounts) {
return PodVolume.volumeMountExists(path, existingMounts);
}
|
@deprecated Use {@link PodVolume#volumeMountExists(String, List)} instead
|
volumeMountExists
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodVolumes.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodVolumes.java
|
Apache-2.0
|
@Deprecated
public static boolean podVolumeExists(String path, List<PodVolume> existingVolumes) {
for (PodVolume podVolume : existingVolumes) {
if (podVolume.getMountPath().equals(path)) {
return true;
}
}
return false;
}
|
@deprecated Use {@link PodVolume#podVolumeExists(String,List)} instead
|
podVolumeExists
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodVolumes.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/PodVolumes.java
|
Apache-2.0
|
@Override
public NodeProvisioner.PlannedNode build() {
KubernetesCloud cloud = getCloud();
PodTemplate t = getTemplate();
CompletableFuture f;
String displayName;
try {
KubernetesSlave agent = KubernetesSlave.builder()
.podTemplate(t.isUnwrapped() ? t : cloud.getUnwrappedTemplate(t))
.cloud(cloud)
.build();
displayName = agent.getDisplayName();
f = CompletableFuture.completedFuture(agent);
} catch (IOException | Descriptor.FormException e) {
displayName = null;
f = new CompletableFuture();
f.completeExceptionally(e);
}
return new NodeProvisioner.PlannedNode(Util.fixNull(displayName), f, getNumExecutors());
}
|
The default {@link PlannedNodeBuilder} implementation, in case there is other registered.
|
build
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/StandardPlannedNodeBuilder.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/StandardPlannedNodeBuilder.java
|
Apache-2.0
|
@Override
public void finished(StepContext context) {
closeQuietly(context, closeables);
}
|
This class has been replaced but is not deleted to prevent {@code ClassNotFoundException}.
See <a href="https://issues.jenkins.io/browse/JENKINS-75720">JENKINS-75720</a>
@deprecated replaced {@link Resources#closeQuietlyCallback(Closeable...)}
|
finished
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/ContainerStepExecution.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/ContainerStepExecution.java
|
Apache-2.0
|
@NonNull
public String getPodName() {
return podName;
}
|
Kubernetes Pod name.
@return pod name, never {@code null}
|
getPodName
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
Apache-2.0
|
@Nullable
public String getNamespace() {
return namespace;
}
|
Kubernetes namespace Pod is running in.
@return kubernetes namespace or {@code null}
|
getNamespace
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
Apache-2.0
|
@NonNull
public final KubernetesSlave getKubernetesSlave() throws IOException, InterruptedException {
Node node = context.get(Node.class);
if (!(node instanceof KubernetesSlave)) {
throw new AbortException(
String.format("Node is not a Kubernetes node: %s", node != null ? node.getNodeName() : null));
}
return (KubernetesSlave) node;
}
|
Get {@link Node} from the {@link StepContext}. If the context instance is instance of
{@link KubernetesSlave} it will be returned otherwise an exception is thrown.
@return kubernetes slave node context, never {@code null}
@throws IOException if IO exception
@throws InterruptedException if interrupted
@throws AbortException if {@link Node} context is not instance of {@link KubernetesSlave}
|
getKubernetesSlave
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesNodeContext.java
|
Apache-2.0
|
public static PodTemplateMap get() {
return ExtensionList.lookupSingleton(PodTemplateMap.class);
}
|
A map of {@link KubernetesCloud} -> List of {@link PodTemplate} instances.
|
get
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/PodTemplateMap.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/PodTemplateMap.java
|
Apache-2.0
|
public static void closeQuietly(@NonNull StepContext context, @NonNull Closeable... closeables) {
for (Closeable c : closeables) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
try {
TaskListener listener = context.get(TaskListener.class);
if (listener != null) {
listener.error("Error while closing: [" + c + "]");
}
} catch (IOException | InterruptedException e1) {
LOGGER.log(Level.WARNING, "Error writing to task listener", e);
}
}
}
}
}
|
Close each {@link Closeable}, capturing and ignoring any {@link IOException} thrown.
@param context step context
@param closeables list of closable resources to close
|
closeQuietly
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/Resources.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/Resources.java
|
Apache-2.0
|
@NonNull
public static BodyExecutionCallback closeQuietlyCallback(@NonNull Closeable... closeables) {
return new CloseQuietlyBodyExecutionCallback(closeables);
}
|
Factory method for a {@link BodyExecutionCallback} that closes each {@link Closeable} when
execution is finished.
@param closeables list of closable resources
@return new body execution callback, never null
|
closeQuietlyCallback
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/Resources.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/Resources.java
|
Apache-2.0
|
@NonNull
@Override
public Pod decorate(@NonNull KubernetesCloud kubernetesCloud, @NonNull Pod pod) {
// default OS: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
if (pod.getSpec().getRuntimeClassName() == null
&& (pod.getSpec().getNodeSelector() == null
|| pod.getSpec().getNodeSelector().isEmpty())
&& (pod.getSpec().getAffinity() == null
|| pod.getSpec().getAffinity().getNodeAffinity() == null)) {
pod.getSpec().setNodeSelector(Collections.singletonMap("kubernetes.io/os", "linux"));
}
return pod;
}
|
Sets the default node selector to linux if it hasn't been set explicitly in the pod before.
|
decorate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/DefaultNodeSelector.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/DefaultNodeSelector.java
|
Apache-2.0
|
@NonNull
@Override
public Pod decorate(@NonNull KubernetesCloud kubernetesCloud, @NonNull Pod pod) {
if (StringUtils.isBlank(pod.getSpec().getRestartPolicy())) {
pod.getSpec().setRestartPolicy("Never");
}
return pod;
}
|
Sets the restart policy to Never.
|
decorate
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/DefaultRestartPolicy.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/DefaultRestartPolicy.java
|
Apache-2.0
|
@NonNull
static Pod decorateAll(@NonNull KubernetesCloud kubernetesCloud, @NonNull Pod pod) throws PodDecoratorException {
for (PodDecorator decorator : ExtensionList.lookup(PodDecorator.class)) {
pod = decorator.decorate(kubernetesCloud, pod);
}
return pod;
}
|
Goes through all the {@link PodDecorator} extensions and decorates the pod.
@param kubernetesCloud The cloud this pod will be scheduled as context.
@param pod the initial pod definition before decoration.
@return The modified pod definition.
@throws PodDecoratorException Should any of the decorators fail to decorate the pod.
|
decorateAll
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/PodDecorator.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/decorator/PodDecorator.java
|
Apache-2.0
|
public static PodRetention getKubernetesCloudDefault() {
return new Never();
}
|
Returns the default <code>PodRetention</code> for a <code>KubernetesCloud</code> instance.
@return the {@link Never} <code>PodRetention</code> strategy.
|
getKubernetesCloudDefault
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
Apache-2.0
|
public static PodRetention getPodTemplateDefault() {
return new Default();
}
|
Returns the default <code>PodRetention</code> for a <code>PodTemplate</code> instance.
@return the {@link Default} <code>PodRetention</code> strategy.
|
getPodTemplateDefault
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
Apache-2.0
|
@Override
public String toString() {
return getClass().getSimpleName();
}
|
Determines if a agent pod should be deleted after the Jenkins build completes.
@param cloud - the {@link KubernetesCloud} the agent pod belongs to.
@param pod - the {@link Pod} running the Jenkins build.
@return <code>true</code> if the agent pod should be deleted.
|
toString
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/PodRetention.java
|
Apache-2.0
|
private void reapAgents() {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins != null) {
for (Node n : new ArrayList<>(jenkins.getNodes())) {
if (!(n instanceof KubernetesSlave)) {
continue;
}
KubernetesSlave ks = (KubernetesSlave) n;
if (ks.getLauncher().isLaunchSupported()) {
// Being launched, don't touch it.
continue;
}
String ns = ks.getNamespace();
String name = ks.getPodName();
try {
// TODO more efficient to do a single (or paged) list request, but tricky since there may be
// multiple clouds,
// and even within a single cloud an agent pod is permitted to use a nondefault namespace,
// yet we do not want to do an unnamespaced pod list for RBAC reasons.
// Could use a hybrid approach: first list all pods in the configured namespace for all clouds;
// then go back and individually check any unmatched agents with their configured namespace.
KubernetesCloud cloud = ks.getKubernetesCloud();
if (cloud.connect().pods().inNamespace(ns).withName(name).get() == null) {
LOGGER.info(() -> ns + "/" + name
+ " seems to have been deleted, so removing corresponding Jenkins agent");
jenkins.removeNode(ks);
} else {
LOGGER.fine(() -> ns + "/" + name + " still seems to exist, OK");
}
} catch (KubernetesAuthException | IOException | RuntimeException x) {
LOGGER.log(Level.WARNING, x, () -> "failed to do initial reap check for " + ns + "/" + name);
}
}
}
}
|
Remove any {@link KubernetesSlave} nodes that reference Pods that don't exist.
|
reapAgents
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
private void watchClouds() {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins != null) {
Set<String> cloudNames = new HashSet<>(this.watchers.keySet());
for (KubernetesCloud kc : jenkins.clouds.getAll(KubernetesCloud.class)) {
watchCloud(kc);
cloudNames.remove(kc.name);
}
// close any cloud watchers that have been removed
cloudNames.stream().map(this.watchers::get).filter(Objects::nonNull).forEach(cpw -> {
LOGGER.info(() -> "stopping pod watcher for deleted kubernetes cloud " + cpw.cloudName);
cpw.stop();
});
}
}
|
Create watchers for each configured {@link KubernetesCloud} in Jenkins and remove any existing watchers
for clouds that have been removed. If a {@link KubernetesCloud} client configuration property has been
updated a new watcher will be created to replace the existing one.
|
watchClouds
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
private void watchCloud(@NonNull KubernetesCloud kc) {
// can't use ConcurrentHashMap#computeIfAbsent because CloudPodWatcher will remove itself from the watchers
// map on close. If an error occurs when creating the watch it would create a deadlock situation.
CloudPodWatcher watcher = new CloudPodWatcher(kc);
if (!isCloudPodWatcherActive(watcher)) {
try {
KubernetesClient client = kc.connect();
watcher.watch = client.pods().inNamespace(client.getNamespace()).watch(watcher);
CloudPodWatcher old = watchers.put(kc.name, watcher);
// if another watch slipped in then make sure it stopped
if (old != null) {
old.stop();
}
LOGGER.info(() -> "set up watcher on " + kc.getDisplayName());
} catch (KubernetesAuthException | IOException | RuntimeException x) {
LOGGER.log(Level.WARNING, x, () -> "failed to set up watcher on " + kc.getDisplayName());
}
}
}
|
Register {@link CloudPodWatcher} for the given cloud if one does not exist or if the existing watcher
is no longer valid.
@param kc kubernetes cloud to watch
|
watchCloud
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
@Override
public void eventReceived(Action action, Pod pod) {
// don't send bookmark event to listeners as they don't represent change in pod state
if (action == Action.BOOKMARK) {
// TODO future enhancement might be to keep track of bookmarks for better reconnect behavior. Would
// likely have to track based on cloud address/namespace in case cloud was renamed or namespace
// is changed.
return;
}
// If there was a non-success http response code from watch request
// or the api returned a Status object the watch manager notifies with
// an error action and null resource.
if (action == Action.ERROR && pod == null) {
return;
}
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return;
}
String ns = pod.getMetadata().getNamespace();
String name = pod.getMetadata().getName();
Optional<KubernetesSlave> optionalNode = resolveNode(jenkins, ns, name);
if (!optionalNode.isPresent()) {
return;
}
Listeners.notify(Listener.class, true, listener -> {
try {
Set<String> terminationReasons = Reaper.this.terminationReasons.get(
optionalNode.get().getNodeName());
listener.onEvent(
action,
optionalNode.get(),
pod,
terminationReasons != null ? terminationReasons : Collections.emptySet());
} catch (Exception x) {
LOGGER.log(Level.WARNING, "Listener " + listener + " failed for " + ns + "/" + name, x);
}
});
}
|
Kubernetes pod event watcher for a Kubernetes Cloud. Notifies {@link Listener}
extensions on Pod events. The default Kubernetes client watch manager will
attempt to reconnect on connection errors. If the watch api returns "410 Gone"
then the Watch will close itself with a WatchException and this watcher will
deregister itself.
|
eventReceived
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
@NonNull
public Set<String> terminationReasons(@NonNull String node) {
synchronized (terminationReasons) {
return new HashSet<>(terminationReasons.get(node));
}
}
|
Get any reason(s) why a node was terminated by a listener.
@param node a {@link Node#getNodeName}
@return a possibly empty set of {@link ContainerStateTerminated#getReason} or {@link PodStatus#getReason}
|
terminationReasons
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
@Override
public void onChange(Saveable o, XmlFile file) {
if (o instanceof Jenkins) {
Reaper reaper = Reaper.getInstance();
// only update if reaper has been activated to avoid hitting api server if not in use
if (reaper.activated.get()) {
Reaper.getInstance().watchClouds();
}
}
}
|
{@link SaveableListener} that will update cloud watchers when Jenkins configuration is updated.
|
onChange
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/Reaper.java
|
Apache-2.0
|
default Volume buildEphemeralVolume(String volumeName) {
return new VolumeBuilder()
.withName(volumeName)
.withNewEphemeral()
.withNewVolumeClaimTemplate()
.withNewSpec()
.withAccessModes(getAccessModesOrDefault())
.withStorageClassName(getStorageClassNameOrDefault())
.withNewResources()
.withRequests(getResourceMap())
.endResources()
.endSpec()
.endVolumeClaimTemplate()
.endEphemeral()
.build();
}
|
Interface containing common code between {@link GenericEphemeralVolume} and {@link org.csanchez.jenkins.plugins.kubernetes.volumes.workspace.GenericEphemeralWorkspaceVolume}.
|
buildEphemeralVolume
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/volumes/EphemeralVolume.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/volumes/EphemeralVolume.java
|
Apache-2.0
|
public PersistentVolumeClaim createVolume(KubernetesClient client, ObjectMeta podMetaData) {
return null;
}
|
Create the workspace volume
@param client Kubernetes client
@param podMetaData Kubernetes pod metadata
@return the created persistent volume claim
|
createVolume
|
java
|
jenkinsci/kubernetes-plugin
|
src/main/java/org/csanchez/jenkins/plugins/kubernetes/volumes/workspace/WorkspaceVolume.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/main/java/org/csanchez/jenkins/plugins/kubernetes/volumes/workspace/WorkspaceVolume.java
|
Apache-2.0
|
public static Map<String, String> getLabels(KubernetesCloud cloud, Object o, TestName name) {
Map<String, String> l = new HashMap<>();
l.put("BRANCH_NAME", BRANCH_NAME == null ? "undefined" : BRANCH_NAME);
l.put("BUILD_NUMBER", BUILD_NUMBER == null ? "undefined" : BUILD_NUMBER);
if (cloud != null) {
l.putAll(cloud.getPodLabelsMap());
}
l.put("class", o.getClass().getSimpleName());
l.put("test", name.getMethodName());
return l;
}
|
Labels to add to the pods so we can match them to a specific build run, test class and method
|
getLabels
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesTestUtil.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesTestUtil.java
|
Apache-2.0
|
protected final WorkflowRun createJobThenScheduleRun() throws Exception {
return createJobThenScheduleRun(null);
}
|
Creates a pipeline job using <methodName>.groovy as pipeline definition,
then schedule it and wait for it to start.
Resolves $NAME to the method name in order to avoid any hard-coded reference
to the method name within the pipeline definition.
@return The scheduled pipeline run
|
createJobThenScheduleRun
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/AbstractKubernetesPipelineTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/AbstractKubernetesPipelineTest.java
|
Apache-2.0
|
@Test
public void runWithStepOverriddenNamespace() throws Exception {
String overriddenNamespace = testingNamespace + "-overridden-namespace";
String stepNamespace = testingNamespace + "-overridden-namespace2";
cloud.setNamespace(overriddenNamespace);
// Run in our own testing namespace
createNamespaceIfNotExist(cloud.connect(), stepNamespace);
Map<String, String> env = new HashMap<>();
env.put("OVERRIDDEN_NAMESPACE", stepNamespace);
assertNotNull(createJobThenScheduleRun(env));
SemaphoreStep.waitForStart("pod/1", b);
for (KubernetesComputer c : getKubernetesComputers()) {
assertEquals(stepNamespace, c.getNode().getPod().get().getMetadata().getNamespace());
}
SemaphoreStep.success("pod/1", null);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains(stepNamespace, b);
}
|
Step namespace should have priority over anything else.
|
runWithStepOverriddenNamespace
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesPipelineOverridenNamespaceTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesPipelineOverridenNamespaceTest.java
|
Apache-2.0
|
@Override
public void run(JenkinsRule r) throws Throwable {
KubernetesCloud cloud = new KubernetesCloud("kubernetes");
cloud.setWebSocket(websocket);
r.jenkins.clouds.add(cloud);
// Agents running in Kubernetes (minikube) need to connect to this server, so localhost does not work
URL url = new URL(JenkinsLocationConfiguration.get().getUrl());
System.err.println("Calling home to address: " + hostAddress);
URL nonLocalhostUrl = new URL(url.getProtocol(), hostAddress, url.getPort(), url.getFile());
cloud.setJenkinsUrl(nonLocalhostUrl.toString());
if (agentPort != null) {
r.jenkins.setSlaveAgentPort(agentPort);
}
r.jenkins.save();
}
|
Sets up a Kubernetes cloud instance named kubernetes.
|
run
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/steps/SetupCloud.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pipeline/steps/SetupCloud.java
|
Apache-2.0
|
private CapturedRequests kubeClientRequests() throws InterruptedException {
int count = server.getKubernetesMockServer().getRequestCount();
List<RecordedRequest> requests = new LinkedList<>();
while (count-- > 0) {
RecordedRequest rr = server.getKubernetesMockServer().takeRequest(1, TimeUnit.SECONDS);
if (rr != null) {
requests.add(rr);
}
}
return new CapturedRequests(requests);
}
|
Get all the requests made to the kube client so far. Drains the captured requests. Next
call to this method will only return newly captured requests.
@return captured kube client requests so far
@throws InterruptedException interrupted exception
|
kubeClientRequests
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
Apache-2.0
|
private CapturedRequests waitForKubeClientRequests(int count) throws InterruptedException {
List<RecordedRequest> requests = new LinkedList<>();
while (count-- > 0) {
requests.add(server.getKubernetesMockServer().takeRequest());
}
return new CapturedRequests(requests);
}
|
Wait until the specified number of kube client requests are captured.
@param count number of requests to wait for
@return captured requests
@throws InterruptedException interrupted exception
|
waitForKubeClientRequests
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
Apache-2.0
|
private synchronized CapturingReaperListener waitForEventsOnJenkinsExtensionInstance()
throws InterruptedException {
while (CAPTURED_EVENTS.isEmpty()) {
wait();
}
return this;
}
|
Test should use {@link #waitForEvents()}, not this method
|
waitForEventsOnJenkinsExtensionInstance
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
Apache-2.0
|
public CapturingReaperListener waitForEvents() throws InterruptedException {
// find the instance that Jenkins created and wait on that one
CapturingReaperListener l =
Jenkins.get().getExtensionList(Reaper.Listener.class).get(CapturingReaperListener.class);
if (l == null) {
throw new RuntimeException("CapturingReaperListener not registered in Jenkins");
}
return l.waitForEventsOnJenkinsExtensionInstance();
}
|
Tests should use this method to wait for events to be processed by the Reaper cloud watcher.
@return jenkins extension instance
@throws InterruptedException if wait was interrupted
|
waitForEvents
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
Apache-2.0
|
public synchronized void expectEvent(Watcher.Action action, KubernetesSlave node) {
boolean found = CAPTURED_EVENTS.stream().anyMatch(e -> e.action == action && e.node == node);
assertTrue("expected event: " + action + ", " + node, found);
}
|
Verify that the watcher received an event of the given action and target node.
@param action action to match
@param node target node
|
expectEvent
|
java
|
jenkinsci/kubernetes-plugin
|
src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
https://github.com/jenkinsci/kubernetes-plugin/blob/master/src/test/java/org/csanchez/jenkins/plugins/kubernetes/pod/retention/ReaperTest.java
|
Apache-2.0
|
public static int stringtoint(String input) {
try {
return Integer.parseInt(input);
} catch (Exception e) {
return -1;
}
}
|
string to int
@param input
@return
|
stringtoint
|
java
|
FreddyChen/NettyChat
|
app/src/main/java/com/freddy/chat/utils/StringUtil.java
|
https://github.com/FreddyChen/NettyChat/blob/master/app/src/main/java/com/freddy/chat/utils/StringUtil.java
|
Apache-2.0
|
public static long stringtolong(String input) {
try {
return Long.parseLong(input);
} catch (Exception e) {
return 0l;
}
}
|
string to long
@param input
@return
|
stringtolong
|
java
|
FreddyChen/NettyChat
|
app/src/main/java/com/freddy/chat/utils/StringUtil.java
|
https://github.com/FreddyChen/NettyChat/blob/master/app/src/main/java/com/freddy/chat/utils/StringUtil.java
|
Apache-2.0
|
public static <T> List<T> copyListProperties(List<?> source, Class<T> targetClass) {
if (CollectionUtils.isEmpty(source)) {
return new ArrayList<>();
}
List<T> target = new ArrayList<T>();
for (Object obj : source) {
T targetObject;
try {
// targetObject = targetClass.newInstance();
targetObject = targetClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
copyProperties(obj, targetObject);
target.add(targetObject);
}
return target;
}
|
@param source
@param targetClass
@throws Exception
|
copyListProperties
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/BeanCopierUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/BeanCopierUtil.java
|
Apache-2.0
|
public static <T extends BaseDsConfig> T toDsConfig(String propsYml, Class<T> targetClass) {
if (StringUtils.isEmpty(propsYml)) {
throw new DatasourceException(ErrorEnum.DATASOURCE_PROPS_EMPTY);
}
try {
return YamlUtil.loadAs(propsYml, targetClass);
} catch (JsonSyntaxException e) {
throw new DatasourceException(ErrorEnum.DATASOURCE_PROPS_CONVERT_ERROR);
}
}
|
https://stackabuse.com/reading-and-writing-yaml-files-in-java-with-snakeyaml/
@param propsYml
@param targetClass
@param <T>
@return
|
toDsConfig
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/DsUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/DsUtil.java
|
Apache-2.0
|
public static long calculateHowManySecondsHavePassed(Date date) {
long subTime = System.currentTimeMillis() - date.getTime();
if (subTime < 0) {
return 0;
}
return subTime / NewTimeUtil.SECOND_TIME;
}
|
Calculate how many seconds
@param date
@return
|
calculateHowManySecondsHavePassed
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/NewTimeUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/NewTimeUtil.java
|
Apache-2.0
|
public static String getFingerprint(String publicKey) {
String fingerprint = "-";
if (StringUtils.isNotEmpty(publicKey)) {
if (publicKey.contains("ssh-")) {
publicKey = publicKey.substring(publicKey.indexOf("ssh-"));
} else if (publicKey.contains("ecdsa-")) {
publicKey = publicKey.substring(publicKey.indexOf("ecdsa-"));
}
try {
KeyPair keyPair = KeyPair.load(new JSch(), null, publicKey.getBytes());
if (keyPair != null) {
fingerprint = keyPair.getFingerPrint();
}
} catch (JSchException ignored) {
}
}
return fingerprint;
}
|
https://github.com/bastillion-io/Bastillion/blob/master/src/main/java/io/bastillion/manage/util/SSHUtil.java
returns public key fingerprint
@param publicKey public key
@return fingerprint of public key
|
getFingerprint
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/SSHUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/SSHUtil.java
|
Apache-2.0
|
public static String getKeyType(String publicKey) {
String keyType = null;
if (StringUtils.isNotEmpty(publicKey)) {
if (publicKey.contains("ssh-")) {
publicKey = publicKey.substring(publicKey.indexOf("ssh-"));
} else if (publicKey.contains("ecdsa-")) {
publicKey = publicKey.substring(publicKey.indexOf("ecdsa-"));
}
try {
KeyPair keyPair = KeyPair.load(new JSch(), null, publicKey.getBytes());
if (keyPair != null) {
int type = keyPair.getKeyType();
if (KeyPair.DSA == type) {
keyType = "DSA";
} else if (KeyPair.RSA == type) {
keyType = "RSA";
} else if (KeyPair.ECDSA == type) {
keyType = "ECDSA";
} else if (KeyPair.ED25519 == type) {
keyType = "ED25519";
} else if (KeyPair.UNKNOWN == type) {
keyType = "UNKNOWN";
} else if (KeyPair.ERROR == type) {
keyType = "ERROR";
}
}
} catch (JSchException ex) {
log.error(ex.toString(), ex);
}
}
return keyType;
}
|
returns public key type
@param publicKey public key
@return fingerprint of public key
|
getKeyType
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/SSHUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/SSHUtil.java
|
Apache-2.0
|
public static <T> T loadAs(String loadYaml, Class<T> targetClass) throws JsonSyntaxException {
Representer representer = new Representer(new DumperOptions());
representer.getPropertyUtils().setSkipMissingProperties(true);
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setTagInspector(tag -> true);
Constructor constructor = new Constructor(targetClass, loaderOptions);
Yaml yaml = new Yaml(constructor, representer);
return yaml.loadAs(loadYaml, targetClass);
}
|
2.0
@param loadYaml
@param targetClass
@param <T>
@return
@throws JsonSyntaxException
|
loadAs
|
java
|
ixrjog/opscloud4
|
opscloud-common/src/main/java/com/baiyi/opscloud/common/util/YamlUtil.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/YamlUtil.java
|
Apache-2.0
|
public List<ListNamespaceResponse.NamespacesItem> listNamespace(String regionId, AliyunConfig.Aliyun aliyun, String instanceId) throws ClientException {
ListNamespaceRequest request = new ListNamespaceRequest();
request.setSysRegionId(regionId);
request.setInstanceId(instanceId);
request.setNamespaceStatus(Query.NORMAL);
request.setPageSize(Query.PAGE_SIZE);
int total = 0;
int pageNo = 1;
List<ListNamespaceResponse.NamespacesItem> namespacesItems = Lists.newArrayList();
while (total == 0 || total == namespacesItems.size()) {
request.setPageNo(pageNo);
ListNamespaceResponse response = aliyunClient.getAcsResponse(regionId, aliyun, request);
List<ListNamespaceResponse.NamespacesItem> nowData = response.getNamespaces();
if (CollectionUtils.isEmpty(nowData)) {
break;
} else {
namespacesItems.addAll(nowData);
}
if (total == 0) {
total = Integer.parseInt(response.getTotalCount());
}
pageNo++;
}
return namespacesItems;
}
|
{
"defaultRepoType":"PRIVATE",
"namespaceStatus":"NORMAL",
"namespaceId":"crn-g0h399e0ayt6ax00",
"autoCreateRepo":true,
"instanceId":"cri-4v9b8l2gc3en0x34",
"namespaceName":"daily"
}
@param regionId
@param aliyun
@param instanceId
@return
@throws ClientException
|
listNamespace
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aliyun-acr/src/main/java/com/baiyi/opscloud/datasource/aliyun/acr/driver/AliyunAcrInstanceDriver.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aliyun-acr/src/main/java/com/baiyi/opscloud/datasource/aliyun/acr/driver/AliyunAcrInstanceDriver.java
|
Apache-2.0
|
@Override
public AssetContainer toAssetContainer(DatasourceInstance dsInstance) {
DatasourceInstanceAsset asset = DatasourceInstanceAsset.builder()
.instanceUuid(dsInstance.getUuid())
.assetId(this.namespaceId)
.name(this.namespaceName)
.assetKey(this.namespaceId)
.assetKey2(this.instanceId)
.kind("namespace")
.regionId(regionId)
.assetType(DsAssetTypeConstants.ACR_NAMESPACE.name())
.isActive(true)
.build();
return AssetContainerBuilder.newBuilder()
.paramAsset(asset)
.paramProperty("defaultRepoType", this.defaultRepoType)
.paramProperty("namespaceStatus", this.namespaceStatus)
.paramProperty("autoCreateRepo", this.autoCreateRepo)
.build();
}
|
{
"defaultRepoType":"PRIVATE",
"namespaceStatus":"NORMAL",
"namespaceId":"crn-g0h399e0ayt6ax00",
"autoCreateRepo":true,
"instanceId":"cri-4v9b8l2gc3en0x34",
"namespaceName":"daily"
}
|
toAssetContainer
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aliyun-acr/src/main/java/com/baiyi/opscloud/datasource/aliyun/acr/entity/AliyunAcr.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aliyun-acr/src/main/java/com/baiyi/opscloud/datasource/aliyun/acr/entity/AliyunAcr.java
|
Apache-2.0
|
public void createGroup(String regionId, AliyunConfig.Aliyun aliyun, OnsGroupV5.Group group) throws Exception {
CreateConsumerGroupRequest.CreateConsumerGroupRequestConsumeRetryPolicy policy = new CreateConsumerGroupRequest.CreateConsumerGroupRequestConsumeRetryPolicy()
.setRetryPolicy(group.getConsumeRetryPolicy().getRetryPolicy())
.setMaxRetryTimes(group.getConsumeRetryPolicy().getMaxRetryTimes())
.setDeadLetterTargetTopic(group.getConsumeRetryPolicy().getDeadLetterTargetTopic());
CreateConsumerGroupRequest request = new CreateConsumerGroupRequest()
.setRemark(group.getRemark())
.setDeliveryOrderType(group.getDeliveryOrderType())
.setConsumeRetryPolicy(policy);
Client client = AliyunOnsV5Client.buildClient(regionId, aliyun);
client.createConsumerGroup(group.getInstanceId(), group.getConsumerGroupId(), request);
}
|
https://help.aliyun.com/zh/apsaramq-for-rocketmq/cloud-message-queue-rocketmq-5-x-series/developer-reference/api-rocketmq-2022-08-01-createconsumergroup?spm=a2c4g.11186623.0.0.7ee7c4b4JkXAgI
|
createGroup
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aliyun-ons/src/main/java/com/baiyi/opscloud/datasource/aliyun/ons/driver/AliyunOnsGroupV5Driver.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aliyun-ons/src/main/java/com/baiyi/opscloud/datasource/aliyun/ons/driver/AliyunOnsGroupV5Driver.java
|
Apache-2.0
|
public void attachUserPolicy(AwsConfig.Aws config, String userName, IamPolicy.Policy policy) {
AttachUserPolicyRequest request = new AttachUserPolicyRequest();
request.setUserName(userName);
request.setPolicyArn(policy.getArn());
buildAmazonIdentityManagement(config).attachUserPolicy(request);
}
|
https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html
@param config
@param userName
@param policy
|
attachUserPolicy
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aws-iam/src/main/java/com/baiyi/opscloud/datasource/aws/iam/driver/AmazonIdentityManagementPolicyDriver.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aws-iam/src/main/java/com/baiyi/opscloud/datasource/aws/iam/driver/AmazonIdentityManagementPolicyDriver.java
|
Apache-2.0
|
public IamUser.User createUser(AwsConfig.Aws config,
com.baiyi.opscloud.domain.generator.opscloud.User user,
boolean createLoginProfile) {
CreateUserRequest request = new CreateUserRequest();
request.setUserName(user.getUsername());
CreateUserResult result = buildAmazonIdentityManagement(config).createUser(request);
if (createLoginProfile) {
try {
this.createLoginProfile(config, user, NO_PASSWORD_RESET_REQUIRED);
} catch (PasswordPolicyViolationException e) {
throw new CreateUserException(e.getMessage());
}
}
return BeanCopierUtil.copyProperties(result.getUser(), IamUser.User.class);
}
|
https://docs.aws.amazon.com/zh_cn/IAM/latest/APIReference/API_CreateUser.html
@param config
|
createUser
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aws-iam/src/main/java/com/baiyi/opscloud/datasource/aws/iam/driver/AmazonIdentityManagementUserDriver.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aws-iam/src/main/java/com/baiyi/opscloud/datasource/aws/iam/driver/AmazonIdentityManagementUserDriver.java
|
Apache-2.0
|
public String createQueue(AwsConfig.Aws config, String regionId, String queueName, Map<String, String> attributes) {
CreateQueueRequest request = new CreateQueueRequest();
request.setQueueName(queueName);
if (!CollectionUtils.isEmpty(attributes)) {
request.setAttributes(attributes);
}
CreateQueueResult result = AmazonSQSService.buildAmazonSQS(config, regionId).createQueue(request);
return result.getQueueUrl();
}
|
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html
@param config
@param regionId
@param queueName
@param attributes queueUrl
@return
|
createQueue
|
java
|
ixrjog/opscloud4
|
opscloud-datasource-aws-sqs/src/main/java/com/baiyi/opscloud/datasource/aws/sqs/driver/AmazonSimpleQueueServiceDriver.java
|
https://github.com/ixrjog/opscloud4/blob/master/opscloud-datasource-aws-sqs/src/main/java/com/baiyi/opscloud/datasource/aws/sqs/driver/AmazonSimpleQueueServiceDriver.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.