Skip to content

Commit

Permalink
Merge pull request #221 from tanskann/master
Browse files Browse the repository at this point in the history
add activeDeadlineSeconds to Pod template
  • Loading branch information
carlossg authored Oct 16, 2017
2 parents 9ea798d + cc110e7 commit 72ecd23
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 7 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ 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 a slave to be online.
* **activeDeadlineSeconds** Pod is deleted after this deadline is passed.

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 @@ -40,6 +40,7 @@
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodFluent;
import io.fabric8.kubernetes.api.model.Probe;
import io.fabric8.kubernetes.api.model.ProbeBuilder;
import io.fabric8.kubernetes.api.model.Quantity;
Expand Down Expand Up @@ -271,23 +272,33 @@ private Pod getPodTemplate(KubernetesSlave slave, PodTemplate template) {

List<LocalObjectReference> imagePullSecrets = template.getImagePullSecrets().stream()
.map((x) -> x.toLocalObjectReference()).collect(Collectors.toList());
return new PodBuilder()

PodFluent.SpecNested<PodBuilder> builder = new PodBuilder()
.withNewMetadata()
.withName(substituteEnv(slave.getNodeName()))
.withLabels(slave.getKubernetesCloud().getLabelsMap(template.getLabelSet()))
.withAnnotations(getAnnotationsMap(template.getAnnotations()))
.endMetadata()
.withNewSpec()
.withVolumes(volumes)
.withNewSpec();

if(template.getActiveDeadlineSeconds() > 0) {
builder = builder.withActiveDeadlineSeconds(Long.valueOf(template.getActiveDeadlineSeconds()));
}

Pod pod = builder.withVolumes(volumes)
.withServiceAccount(substituteEnv(template.getServiceAccount()))
.withImagePullSecrets(imagePullSecrets)
.withContainers(containers.values().toArray(new Container[containers.size()]))
.withNodeSelector(getNodeSelectorMap(template.getNodeSelector()))
.withRestartPolicy("Never")
.endSpec()
.build();

return pod;

}


private Container createContainer(KubernetesSlave slave, ContainerTemplate containerTemplate, Collection<TemplateEnvVar> globalEnvVars, Collection<VolumeMount> volumeMounts) {
// Last-write wins map of environment variable names to values
HashMap<String, String> env = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ public class PodTemplate extends AbstractDescribableImpl<PodTemplate> implements

private int idleMinutes;

private int activeDeadlineSeconds;

private String label;

private String serviceAccount;
Expand Down Expand Up @@ -118,6 +120,7 @@ public PodTemplate(PodTemplate from) {
this.setNodeUsageMode(from.getNodeUsageMode());
this.setServiceAccount(from.getServiceAccount());
this.setSlaveConnectTimeout(from.getSlaveConnectTimeout());
this.setActiveDeadlineSeconds(from.getActiveDeadlineSeconds());
this.setVolumes(from.getVolumes());
this.setWorkspaceVolume(from.getWorkspaceVolume());
}
Expand Down Expand Up @@ -282,6 +285,14 @@ public int getIdleMinutes() {
return idleMinutes;
}

public void setActiveDeadlineSeconds(int i) {
this.activeDeadlineSeconds = i;
}

public int getActiveDeadlineSeconds() {
return activeDeadlineSeconds;
}

@DataBoundSetter
public void setIdleMinutesStr(String idleMinutes) {
if (StringUtils.isBlank(idleMinutes)) {
Expand All @@ -299,6 +310,23 @@ public String getIdleMinutesStr() {
}
}

@DataBoundSetter
public void setActiveDeadlineSecondsStr(String activeDeadlineSeconds) {
if (StringUtils.isBlank(activeDeadlineSeconds)) {
setActiveDeadlineSeconds(0);
} else {
setActiveDeadlineSeconds(Integer.parseInt(activeDeadlineSeconds));
}
}

public String getActiveDeadlineSecondsStr() {
if (getActiveDeadlineSeconds() == 0) {
return "";
} else {
return String.valueOf(activeDeadlineSeconds);
}
}

public Set<LabelAtom> getLabelSet() {
return Label.parse(label);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class KubernetesDeclarativeAgent extends DeclarativeAgent<KubernetesDecla
private String serviceAccount;
private String nodeSelector;
private String workingDir;
private int activeDeadlineSeconds;

private ContainerTemplate containerTemplate;

Expand Down Expand Up @@ -94,6 +95,13 @@ public ContainerTemplate getContainerTemplate() {
return containerTemplate;
}

public int getActiveDeadlineSeconds() {
return activeDeadlineSeconds;
}

@DataBoundSetter
public void setActiveDeadlineSeconds(int activeDeadlineSeconds) { this.activeDeadlineSeconds = activeDeadlineSeconds; }

public Map<String,Object> getAsArgs() {
Map<String,Object> argMap = new TreeMap<>();

Expand All @@ -116,6 +124,10 @@ public Map<String,Object> getAsArgs() {
if (!StringUtils.isEmpty(workingDir)) {
argMap.put("workingDir", workingDir);
}
if (activeDeadlineSeconds != 0) {
argMap.put("activeDeadlineSeconds", activeDeadlineSeconds);
}

if (instanceCap > 0) {
argMap.put("instanceCap", instanceCap);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class PodTemplateStep extends Step implements Serializable {
private int instanceCap = Integer.MAX_VALUE;
private int idleMinutes;
private int slaveConnectTimeout = PodTemplate.DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
private int activeDeadlineSeconds;

private String serviceAccount;
private String nodeSelector;
Expand Down Expand Up @@ -162,10 +163,17 @@ public void setSlaveConnectTimeout(int slaveConnectTimeout) {
this.slaveConnectTimeout = slaveConnectTimeout;
}

public String getServiceAccount() {
return serviceAccount;
public int getActiveDeadlineSeconds() {
return activeDeadlineSeconds;
}

@DataBoundSetter
public void setActiveDeadlineSeconds(int activeDeadlineSeconds) {
this.activeDeadlineSeconds = activeDeadlineSeconds;
}

public String getServiceAccount() { return serviceAccount; }

@DataBoundSetter
public void setServiceAccount(String serviceAccount) {
this.serviceAccount = serviceAccount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.logging.Logger;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud;
import org.csanchez.jenkins.plugins.kubernetes.PodImagePullSecret;
import org.csanchez.jenkins.plugins.kubernetes.PodTemplate;
Expand Down Expand Up @@ -78,6 +79,10 @@ public boolean start() throws Exception {
newTemplate.setImagePullSecrets(
step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));

if(step.getActiveDeadlineSeconds() != 0) {
newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
}

kubernetesCloud.addTemplate(newTemplate);
getContext().newBodyInvoker().withContext(step).withCallback(new PodTemplateCallback(newTemplate)).start();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
<f:textbox/>
</f:entry>

<f:entry field="activeDeadlineSecondsStr" title="${%Time in seconds for Pod deadline}">
<f:number/>
</f:entry>

<f:entry field="slaveConnectTimeoutStr" title="${%Timeout in seconds for Jenkins connection}">
<f:textbox/>
</f:entry>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Specify time in seconds time after which Kubernetes will kill the pod if it has not completed.
Value should be a positive integer, default being empty which means no activeDeadlineSeconds will be specified.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
</f:entry>
<f:entry field="idleMinutes" title="${%Time in minutes to retain slave when idle}">
<f:textbox default="0"/>
</f:entry>
<f:entry field="activeDeadlineSeconds" title="${%Time in seconds for Pod deadline}">
<f:number/>
</f:entry>
<f:entry field="serviceAccount" title="The service account">
<f:textbox/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,5 +93,8 @@ private void assertPodTemplates(List<PodTemplate> templates) {
assertEquals("/host", hostPathVolume.getMountPath());
assertEquals("/mnt/host", hostPathVolume.getHostPath());
assertEquals(HostPathVolume.class.getName(), hostPathVolume.getClass().getName());

assertEquals(0, podTemplate.getActiveDeadlineSeconds());

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,5 +144,4 @@ private static List<String> print(FilterWatchListDeletable<Pod, PodList, Boolean
.map(pod -> String.format("%s (%s)", pod.getMetadata().getName(), pod.getStatus().getPhase()))
.collect(Collectors.toList());
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import static org.junit.Assert.*;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -285,4 +286,21 @@ public void evaluate() throws Throwable {
});
}

@Test
public void runWithActiveDeadlineSeconds() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "Deadline");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithActiveDeadlineSeconds.groovy")
, true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);

r.waitForMessage("podTemplate", b);

PodTemplate deadlineTemplate = cloud.getTemplates().stream().filter(x -> x.getLabel() == "deadline").findAny().get();

assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds());
assertNotNull(deadlineTemplate);
r.assertLogNotContains("Hello from container!", b);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
podTemplate(label: 'deadline', activeDeadlineSeconds: 10, containers: [
containerTemplate(name: 'busybox', image: 'busybox', ttyEnabled: true, command: '/bin/cat'),
]) {

node ('deadline') {
stage('Run') {
container('busybox') {
sh """
echo "Hello from container!"
"""
}
}
}
}

0 comments on commit 72ecd23

Please sign in to comment.