Skip to content
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

[JENKINS-51610] Allow setting namespace from Pod yaml #405

Merged
merged 7 commits into from
Dec 24, 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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import javax.annotation.CheckForNull;

import hudson.Extension;
import hudson.model.Computer;
import hudson.model.Label;
import hudson.model.Node;

Expand All @@ -16,9 +17,10 @@ public class DefaultInProvisioning extends InProvisioning {
private static final Logger LOGGER = Logger.getLogger(DefaultInProvisioning.class.getName());

private static boolean isNotAcceptingTasks(Node n) {
return n.toComputer().isLaunchSupported() // Launcher hasn't been called yet
|| !n.isAcceptingTasks() // node is not ready yet
;
Computer computer = n.toComputer();
return computer != null && (computer.isLaunchSupported() // Launcher hasn't been called yet
|| !n.isAcceptingTasks()) // node is not ready yet
;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
Expand Down Expand Up @@ -99,7 +100,12 @@ public void launch(SlaveComputer computer, TaskListener listener) {
Pod pod = getPodTemplate(client, slave, unwrappedTemplate);

String podId = pod.getMetadata().getName();
String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace());

String namespace = Arrays.asList( //
pod.getMetadata() != null ? pod.getMetadata().getNamespace() : null,
unwrappedTemplate.getNamespace(), client.getNamespace()) //
.stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null);
slave.setNamespace(namespace);

LOGGER.log(Level.FINE, "Creating Pod: {0} in namespace {1}", new Object[]{podId, namespace});
pod = client.pods().inNamespace(namespace).create(pod);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public class KubernetesSlave extends AbstractCloudSlave {
private static final ResourceBundleHolder HOLDER = ResourceBundleHolder.get(Messages.class);

private final String cloudName;
private final String namespace;
private String namespace;
private final PodTemplate template;
private transient Set<Queue.Executable> executables = new HashSet<>();

Expand Down Expand Up @@ -129,22 +129,18 @@ protected KubernetesSlave(String name, PodTemplate template, String nodeDescript
template.getNodeProperties());

this.cloudName = cloudName;
this.namespace = determineNamespace(getKubernetesCloud(cloudName), Util.fixEmpty(template.getNamespace()));
this.template = template;
}

private static String determineNamespace(KubernetesCloud cloud, String namespace) throws IOException {
try {
return namespace == null ? cloud.connect().getNamespace() : namespace;
} catch (UnrecoverableKeyException|NoSuchAlgorithmException|KeyStoreException|CertificateEncodingException e) {
throw new IOException(e);
}
}

public String getCloudName() {
return cloudName;
}

public void setNamespace(@Nonnull String namespace) {
this.namespace = namespace;
}

@Nonnull
public String getNamespace() {
return namespace;
}
Expand Down Expand Up @@ -294,24 +290,23 @@ protected void _terminate(TaskListener listener) throws IOException, Interrupted
}

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();
Boolean deleted = client.pods().inNamespace(getNamespace()).withName(name).delete();
if (!Boolean.TRUE.equals(deleted)) {
String msg = String.format("Failed to delete pod for agent %s/%s: not found", actualNamespace, name);
String msg = String.format("Failed to delete pod for agent %s/%s: not found", getNamespace(), name);
LOGGER.log(Level.WARNING, msg);
listener.error(msg);
return;
}
} catch (KubernetesClientException e) {
String msg = String.format("Failed to delete pod for agent %s/%s: %s", actualNamespace, name,
String msg = String.format("Failed to delete pod for agent %s/%s: %s", getNamespace(), name,
e.getMessage());
LOGGER.log(Level.WARNING, msg, e);
listener.error(msg);
return;
}

String msg = String.format("Terminated Kubernetes instance for agent %s/%s", actualNamespace, name);
String msg = String.format("Terminated Kubernetes instance for agent %s/%s", getNamespace(), name);
LOGGER.log(Level.INFO, msg);
listener.getLogger().println(msg);
}
Expand All @@ -330,15 +325,13 @@ public boolean equals(Object o) {
KubernetesSlave that = (KubernetesSlave) o;

if (cloudName != null ? !cloudName.equals(that.cloudName) : that.cloudName != null) return false;
if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) return false;
return template != null ? template.equals(that.template) : that.template == null;
}

@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (cloudName != null ? cloudName.hashCode() : 0);
result = 31 * result + (namespace != null ? namespace.hashCode() : 0);
result = 31 * result + (template != null ? template.hashCode() : 0);
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,8 @@ private void setupEnvironmentVariable(EnvVars vars, ExecWatch watch) throws IOEx
}

private void waitUntilContainerIsReady() throws IOException {
LOGGER.log(Level.FINEST, "Waiting until container is ready: {0}/{1}",
new String[] { namespace, podName });
try {
Pod pod = client.pods().inNamespace(namespace).withName(podName)
.waitUntilReady(CONTAINER_READY_TIMEOUT, TimeUnit.MINUTES);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ public void declarativeFromYaml() throws Exception {
r.assertLogContains("BUSYBOX_CONTAINER_ENV_VAR = busybox\n", b);
}

@Issue("JENKINS-51610")
@Test
public void declarativeFromYamlWithNamespace() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "job with dir");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("declarativeWithNamespaceFromYaml.groovy"), true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains("Apache Maven 3.3.9", b);
r.assertLogContains("OUTSIDE_CONTAINER_ENV_VAR = jnlp\n", b);
r.assertLogContains("MAVEN_CONTAINER_ENV_VAR = maven\n", b);
r.assertLogContains("BUSYBOX_CONTAINER_ENV_VAR = busybox\n", b);
}

@Issue("JENKINS-52259")
@Test
public void declarativeFromYamlFile() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
pipeline {
agent {
kubernetes {
label 'declarativefromyaml-pod'
yaml """
metadata:
namespace: kubernetes-plugin-test-overridden-namespace
labels:
some-label: some-label-value
class: KubernetesDeclarativeAgentTest
spec:
containers:
- name: jnlp
env:
- name: CONTAINER_ENV_VAR
value: jnlp
- name: maven
image: maven:3.3.9-jdk-8-alpine
command:
- cat
tty: true
env:
- name: CONTAINER_ENV_VAR
value: maven
- name: busybox
image: busybox
command:
- cat
tty: true
env:
- name: CONTAINER_ENV_VAR
value: busybox
"""
}
}
stages {
stage('Run maven') {
steps {
sh 'set'
sh "echo OUTSIDE_CONTAINER_ENV_VAR = ${CONTAINER_ENV_VAR}"
container('maven') {
sh 'echo MAVEN_CONTAINER_ENV_VAR = ${CONTAINER_ENV_VAR}'
sh 'mvn -version'
}
container('busybox') {
sh 'echo BUSYBOX_CONTAINER_ENV_VAR = ${CONTAINER_ENV_VAR}'
sh '/bin/busybox'
}
}
}
}
}