Skip to content

[JENKINS-48149] Add Pod Retention policies #354

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ Either way it provides access to the following fields:
* **annotations** Annotations to apply to the pod.
* **inheritFrom** List of one or more pod templates to inherit from *(more details below)*.
* **slaveConnectTimeout** Timeout in seconds for an agent to be online.
* **activeDeadlineSeconds** Pod is deleted after this deadline is passed.
* **podRetention** Controls the behavior of keeping slave pods. Can be 'never()', 'onFailure()', 'always()', or 'default()' - if empty will default to deleting the pod after `activeDeadlineSeconds` has passed.
* **activeDeadlineSeconds** If `podRetention` is set to 'never()' or 'onFailure()', pod is deleted after this deadline is passed.
* **idleMinutes** Allows the Pod to remain active for reuse until the configured number of minutes has passed since the last step was executed on it.

The `containerTemplate` is a template of container that will be added to the pod. Again, its configurable via the user interface or via pipeline and allows you to set the following fields:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.csanchez.jenkins.plugins.kubernetes.pipeline.PodTemplateMap;
import org.csanchez.jenkins.plugins.kubernetes.pod.retention.Default;
import org.csanchez.jenkins.plugins.kubernetes.pod.retention.PodRetention;
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl;
Expand All @@ -43,8 +45,6 @@
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.ctc.wstx.util.StringUtil;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;

Expand All @@ -55,6 +55,7 @@
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.Label;
import hudson.security.ACL;
import hudson.slaves.Cloud;
Expand Down Expand Up @@ -115,6 +116,8 @@ public class KubernetesCloud extends Cloud {

private transient KubernetesClient client;
private int maxRequestsPerHost;
@CheckForNull
private PodRetention podRetention = PodRetention.getKubernetesCloudDefault();

@DataBoundConstructor
public KubernetesCloud(String name) {
Expand Down Expand Up @@ -143,6 +146,7 @@ public KubernetesCloud(@NonNull String name, @NonNull KubernetesCloud source) {
this.containerCap = source.containerCap;
this.retentionTimeout = source.retentionTimeout;
this.connectTimeout = source.connectTimeout;
this.podRetention = source.podRetention;
}

@Deprecated
Expand Down Expand Up @@ -251,10 +255,12 @@ public String getJenkinsUrl() {
}

@DataBoundSetter
@Deprecated
public void setCapOnlyOnAlivePods(boolean capOnlyOnAlivePods) {
this.capOnlyOnAlivePods = capOnlyOnAlivePods;
}

@Deprecated
public boolean isCapOnlyOnAlivePods() {
return capOnlyOnAlivePods;
}
Expand Down Expand Up @@ -378,6 +384,26 @@ public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}

/**
* Gets the global pod retention policy for the plugin.
*/
public PodRetention getPodRetention() {
return this.podRetention;
}

/**
* Set the global pod retention policy for the plugin.
*
* @param podRetention the pod retention policy for the plugin.
*/
@DataBoundSetter
public void setPodRetention(PodRetention podRetention) {
if (podRetention == null || podRetention instanceof Default) {
podRetention = PodRetention.getKubernetesCloudDefault();
}
this.podRetention = podRetention;
}

/**
* Connects to Kubernetes.
*
Expand Down Expand Up @@ -454,42 +480,30 @@ private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull
}

PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list();
List<Pod> slaveListItems = slaveList.getItems();
List<Pod> allActiveSlavePods = slaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());

Map<String, String> labelsMap = new HashMap<>(this.getLabels());
labelsMap.putAll(template.getLabelsMap());
PodList namedList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
List<Pod> namedListItems = namedList.getItems();

if (this.isCapOnlyOnAlivePods()) {
slaveListItems = slaveListItems.stream()
.filter(x -> x.getStatus()
.getPhase().toLowerCase()
.matches("(running|pending)"))
.collect(Collectors.toList());
}

if (template.isCapOnlyOnAlivePods()) {
namedListItems = namedListItems.stream()
.filter(x -> x.getStatus()
.getPhase().toLowerCase()
.matches("(running|pending)"))
.collect(Collectors.toList());
}
PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
List<Pod> activeTemplateSlavePods = templateSlaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());

if (slaveListItems != null && containerCap <= slaveListItems.size()) {
if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) {
LOGGER.log(Level.INFO,
"Total container cap of {0} reached, not provisioning: {1} running or errored in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, slaveListItems.size(), templateNamespace, getLabels() });
"Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() });
return false;
}

if (namedListItems != null && slaveListItems != null && template.getInstanceCap() <= namedListItems.size()) {
if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) {
LOGGER.log(Level.INFO,
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or errored in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), slaveListItems.size(),
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(),
templateNamespace, label == null ? "" : label.toString(), labelsMap });
return false; // maxed out
return false;
}
return true;
}
Expand Down Expand Up @@ -652,6 +666,24 @@ public FormValidation doCheckMaxRequestsPerHostStr(@QueryParameter String value)
return FormValidation.error("Please supply an integer");
}
}

public List<Descriptor<PodRetention>> getAllowedPodRetentions() {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return new ArrayList<>(0);
}
return DescriptorVisibilityFilter.apply(this, jenkins.getDescriptorList(PodRetention.class));
}

@SuppressWarnings("rawtypes")
public Descriptor getDefaultPodRetention() {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return null;
}
return jenkins.getDescriptor(PodRetention.getKubernetesCloudDefault().getClass());
}

}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.csanchez.jenkins.plugins.kubernetes.pod.retention.PodRetention;
import org.jenkinsci.plugins.durabletask.executors.OnceRetentionStrategy;
import org.jvnet.localizer.Localizable;
import org.jvnet.localizer.ResourceBundleHolder;
Expand All @@ -33,15 +34,19 @@
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.TaskListener;
import hudson.remoting.Engine;
import hudson.remoting.VirtualChannel;
import hudson.slaves.AbstractCloudSlave;
import hudson.slaves.Cloud;
import hudson.slaves.CloudRetentionStrategy;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.OfflineCause;
import hudson.slaves.RetentionStrategy;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;

/**
* @author Carlos Sanchez [email protected]
Expand Down Expand Up @@ -178,10 +183,45 @@ public KubernetesComputer createComputer() {
return new KubernetesComputer(this);
}

public PodRetention getPodRetention(KubernetesCloud cloud) {
PodRetention retentionPolicy = cloud.getPodRetention();
if (template != null) {
retentionPolicy = template.getPodRetention();
}
return retentionPolicy;
}

@Override
protected void _terminate(TaskListener listener) throws IOException, InterruptedException {
LOGGER.log(Level.INFO, "Terminating Kubernetes instance for agent {0}", name);

KubernetesCloud cloud;
try {
cloud = getKubernetesCloud();
} catch (IllegalStateException e) {
e.printStackTrace(listener.fatalError("Unable to terminate agent. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster."));
LOGGER.log(Level.SEVERE, String.format("Unable to terminate agent %s. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster.", name));
return;
}

KubernetesClient client;
try {
client = cloud.connect();
} catch (UnrecoverableKeyException | CertificateEncodingException | NoSuchAlgorithmException
| KeyStoreException e) {
String msg = String.format("Failed to connect to cloud %s. There may be leftover resources on the Kubernetes cluster.", getCloudName());
e.printStackTrace(listener.fatalError(msg));
LOGGER.log(Level.SEVERE, msg);
return;
}

// Prior to termination, determine if we should delete the slave pod based on
// the slave pod's current state and the pod retention policy.
// Healthy slave pods should still have a JNLP agent running at this point.
String actualNamespace = getNamespace() == null ? client.getNamespace() : getNamespace();
Pod pod = client.pods().inNamespace(actualNamespace).withName(name).get();
boolean deletePod = getPodRetention(cloud).shouldDeletePod(cloud, pod);

Computer computer = toComputer();
if (computer == null) {
String msg = String.format("Computer for agent is null: %s", name);
Expand All @@ -190,6 +230,13 @@ protected void _terminate(TaskListener listener) throws IOException, Interrupted
return;
}

// Tell the slave to stop JNLP reconnects.
VirtualChannel ch = computer.getChannel();
if (ch != null) {
ch.call(new SlaveDisconnector());
}

// Disconnect the master from the slave agent
OfflineCause offlineCause = OfflineCause.create(new Localizable(HOLDER, "offline"));

Future<?> disconnected = computer.disconnect(offlineCause);
Expand All @@ -207,24 +254,20 @@ protected void _terminate(TaskListener listener) throws IOException, Interrupted
listener.fatalError(msg);
return;
}
KubernetesCloud cloud;
try {
cloud = getKubernetesCloud();
} catch (IllegalStateException e) {
e.printStackTrace(listener.fatalError("Unable to terminate agent. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster."));
LOGGER.log(Level.SEVERE, String.format("Unable to terminate agent %s. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster.", name));
return;
}
KubernetesClient client;
try {
client = cloud.connect();
} catch (UnrecoverableKeyException | CertificateEncodingException | NoSuchAlgorithmException
| KeyStoreException e) {
String msg = String.format("Failed to connect to cloud %s", getCloudName());
e.printStackTrace(listener.fatalError(msg));
return;

if (deletePod) {
deleteSlavePod(listener, client);
} else {
// Log warning, as the slave pod may still be running
LOGGER.log(Level.WARNING, "Slave pod {0} was not deleted due to retention policy {1}.",
new Object[] { name, getPodRetention(cloud) });
}
String msg = String.format("Disconnected computer %s", name);
LOGGER.log(Level.INFO, msg);
listener.getLogger().println(msg);
}

private void deleteSlavePod(TaskListener listener, KubernetesClient client) throws IOException {
String actualNamespace = getNamespace() == null ? client.getNamespace() : getNamespace();
try {
Boolean deleted = client.pods().inNamespace(actualNamespace).withName(name).delete();
Expand All @@ -245,7 +288,6 @@ protected void _terminate(TaskListener listener) throws IOException, Interrupted
String msg = String.format("Terminated Kubernetes instance for agent %s/%s", actualNamespace, name);
LOGGER.log(Level.INFO, msg);
listener.getLogger().println(msg);
LOGGER.log(Level.INFO, "Disconnected computer {0}", name);
}

@Override
Expand Down Expand Up @@ -424,4 +466,25 @@ public boolean isInstantiable() {
}

}

private static class SlaveDisconnector extends MasterToSlaveCallable<Void, IOException> {

private static final long serialVersionUID = 8683427258340193283L;

private static final Logger LOGGER = Logger.getLogger(SlaveDisconnector.class.getName());

@Override
public Void call() throws IOException {
Engine e = Engine.current();
// No engine, do nothing.
if (e == null) {
return null;
}
// Tell the slave JNLP agent to not attempt further reconnects.
e.setNoReconnect(true);
LOGGER.log(Level.INFO, "Disabled slave engine reconnects.");
return null;
}

}
}
Loading