org.csanchez.jenkins.plugins.kubernetes.PodTemplate Java Examples

The following examples show how to use org.csanchez.jenkins.plugins.kubernetes.PodTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Issue("JENKINS-60517")
@Test
public void runInDynamicallyCreatedContainer() throws Exception {
    List<PodTemplate> templates = cloud.getTemplates();
    while (templates.isEmpty()) {
        LOGGER.log(Level.INFO, "Waiting for template to be created");
        templates = cloud.getTemplates();
        Thread.sleep(1000);
    }
    assertFalse(templates.isEmpty());
    PodTemplate template = templates.get(0);
    assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogContains("whoami", b);
    r.assertLogContains("root", b);
}
 
Example #2
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void podTemplateWithMultipleLabels() throws Exception {
    PodTemplate pt = new PodTemplate();
    pt.setName("podTemplate");
    pt.setLabel("label1 label2");
    ContainerTemplate jnlp = new ContainerTemplate("jnlp", "jenkins/jnlp-slave:3.35-5-alpine");
    pt.setContainers(Collections.singletonList(jnlp));
    cloud.addTemplate(pt);
    SemaphoreStep.waitForStart("pod/1", b);
    Map<String, String> labels = getLabels(cloud, this, name);
    labels.put("jenkins/label","label1_label2");
    KubernetesSlave node = r.jenkins.getNodes().stream()
            .filter(KubernetesSlave.class::isInstance)
            .map(KubernetesSlave.class::cast)
            .findAny().get();
    assertTrue(node.getAssignedLabels().containsAll(Label.parse("label1 label2")));
    PodList pods = cloud.connect().pods().withLabels(labels).list();
    assertThat(
            "Expected one pod with labels " + labels + " but got: "
                    + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
            pods.getItems(), hasSize(1));
    SemaphoreStep.success("pod/1", null);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
 
Example #3
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Issue("JENKINS-57893")
@Test
public void runInPodFromYaml() throws Exception {
    List<PodTemplate> templates = cloud.getTemplates();
    while (templates.isEmpty()) {
        LOGGER.log(Level.INFO, "Waiting for template to be created");
        templates = cloud.getTemplates();
        Thread.sleep(1000);
    }
    assertFalse(templates.isEmpty());
    PodTemplate template = templates.get(0);
    assertEquals(Integer.MAX_VALUE, template.getInstanceCap());
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogContains("script file contents: ", b);
    r.assertLogNotContains(CONTAINER_ENV_VAR_FROM_SECRET_VALUE, b);
    r.assertLogContains("INSIDE_CONTAINER_ENV_VAR_FROM_SECRET = ******** or " + CONTAINER_ENV_VAR_FROM_SECRET_VALUE.toUpperCase(Locale.ROOT) + "\n", b);
    assertFalse("There are pods leftover after test execution, see previous logs",
            deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
 
Example #4
Source File: WorkspaceVolumeCasCTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule r, String configContent) {
    KubernetesCloud cloud = r.j.jenkins.clouds.get(KubernetesCloud.class);
    assertNotNull(cloud);
    List<PodTemplate> templates = cloud.getTemplates();
    assertNotNull(templates);
    assertEquals(1, templates.size());
    PodTemplate podTemplate = templates.get(0);
    strategy.verify(podTemplate.getWorkspaceVolume());

}
 
Example #5
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void configureCloud() throws Exception {
    cloud = setupCloud(this, name);
    client = cloud.connect();
    deletePods(client, getLabels(this, name), false);

    String image = "busybox";
    Container c = new ContainerBuilder().withName(image).withImagePullPolicy("IfNotPresent").withImage(image)
            .withCommand("cat").withTty(true).build();
    Container d = new ContainerBuilder().withName(image + "1").withImagePullPolicy("IfNotPresent").withImage(image)
            .withCommand("cat").withTty(true).withWorkingDir("/home/jenkins/agent1").build();
    String podName = "test-command-execution-" + RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
    pod = client.pods().create(new PodBuilder().withNewMetadata().withName(podName)
            .withLabels(getLabels(this, name)).endMetadata().withNewSpec().withContainers(c, d).withNodeSelector(Collections.singletonMap("kubernetes.io/os", "linux")).withTerminationGracePeriodSeconds(0L).endSpec().build());

    System.out.println("Created pod: " + pod.getMetadata().getName());

    PodTemplate template = new PodTemplate();
    template.setName(pod.getMetadata().getName());
    agent = mock(KubernetesSlave.class);
    when(agent.getNamespace()).thenReturn(client.getNamespace());
    when(agent.getPodName()).thenReturn(pod.getMetadata().getName());
    doReturn(cloud).when(agent).getKubernetesCloud();
    when(agent.getPod()).thenReturn(Optional.of(pod));
    StepContext context = mock(StepContext.class);
    when(context.get(Node.class)).thenReturn(agent);

    decorator = new ContainerExecDecorator();
    decorator.setNodeContext(new KubernetesNodeContext(context));
    decorator.setContainerName(image);
}
 
Example #6
Source File: AbstractKubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private static void setEnvVariables(PodTemplate podTemplate) {
    TemplateEnvVar podSecretEnvVar = new SecretEnvVar("POD_ENV_VAR_FROM_SECRET", "pod-secret", SECRET_KEY, false);
    TemplateEnvVar podSimpleEnvVar = new KeyValueEnvVar("POD_ENV_VAR", POD_ENV_VAR_VALUE);
    podTemplate.setEnvVars(asList(podSecretEnvVar, podSimpleEnvVar));
    TemplateEnvVar containerEnvVariable = new KeyValueEnvVar("CONTAINER_ENV_VAR", CONTAINER_ENV_VAR_VALUE);
    TemplateEnvVar containerEnvVariableLegacy = new ContainerEnvVar("CONTAINER_ENV_VAR_LEGACY",
            CONTAINER_ENV_VAR_VALUE);
    TemplateEnvVar containerSecretEnvVariable = new SecretEnvVar("CONTAINER_ENV_VAR_FROM_SECRET",
                                                                 "container-secret", SECRET_KEY, false);
    podTemplate.getContainers().get(0)
            .setEnvVars(asList(containerEnvVariable, containerEnvVariableLegacy, containerSecretEnvVariable));
}
 
Example #7
Source File: AbstractKubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private PodTemplate buildBusyboxTemplate(String label) {
    // Create a busybox template
    PodTemplate podTemplate = new PodTemplate();
    podTemplate.setLabel(label);
    podTemplate.setTerminationGracePeriodSeconds(0L);

    ContainerTemplate containerTemplate = new ContainerTemplate("busybox", "busybox", "cat", "");
    containerTemplate.setTtyEnabled(true);
    podTemplate.getContainers().add(containerTemplate);
    setEnvVariables(podTemplate);
    return podTemplate;
}
 
Example #8
Source File: RestartPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private PodTemplate buildBusyboxTemplate(String label) {
    // Create a busybox template
    PodTemplate podTemplate = new PodTemplate();
    podTemplate.setLabel(label);
    podTemplate.setTerminationGracePeriodSeconds(0L);

    ContainerTemplate containerTemplate = new ContainerTemplate("busybox", "busybox", "cat", "");
    containerTemplate.setTtyEnabled(true);
    podTemplate.getContainers().add(containerTemplate);
    setEnvVariables(podTemplate);
    return podTemplate;
}
 
Example #9
Source File: RestartPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private static void setEnvVariables(PodTemplate podTemplate) {
    TemplateEnvVar podSecretEnvVar = new SecretEnvVar("POD_ENV_VAR_FROM_SECRET", "pod-secret", SECRET_KEY, false);
    TemplateEnvVar podSimpleEnvVar = new KeyValueEnvVar("POD_ENV_VAR", POD_ENV_VAR_VALUE);
    podTemplate.setEnvVars(asList(podSecretEnvVar, podSimpleEnvVar));
    TemplateEnvVar containerEnvVariable = new KeyValueEnvVar("CONTAINER_ENV_VAR", CONTAINER_ENV_VAR_VALUE);
    TemplateEnvVar containerEnvVariableLegacy = new ContainerEnvVar("CONTAINER_ENV_VAR_LEGACY",
            CONTAINER_ENV_VAR_VALUE);
    TemplateEnvVar containerSecretEnvVariable = new SecretEnvVar("CONTAINER_ENV_VAR_FROM_SECRET",
                                                                 "container-secret", SECRET_KEY, false);
    podTemplate.getContainers().get(0)
            .setEnvVars(asList(containerEnvVariable, containerEnvVariableLegacy, containerSecretEnvVariable));
}
 
Example #10
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void runWithActiveDeadlineSeconds() throws Exception {
    SemaphoreStep.waitForStart("podTemplate/1", b);
    PodTemplate deadlineTemplate = cloud.getAllTemplates().stream().filter(x -> name.getMethodName().equals(x.getLabel())).findAny().orElse(null);
    assertNotNull(deadlineTemplate);
    SemaphoreStep.success("podTemplate/1", null);
    assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds());
    b.getExecutor().interrupt();
    r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
}
 
Example #11
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void runIn2Pods() throws Exception {
    SemaphoreStep.waitForStart("podTemplate1/1", b);
    String label1 = name.getMethodName() + "-1";
    PodTemplate template1 = podTemplatesWithLabel(label1, cloud.getAllTemplates()).get(0);
    SemaphoreStep.success("podTemplate1/1", null);
    assertEquals(Integer.MAX_VALUE, template1.getInstanceCap());
    assertThat(template1.getLabelsMap(), hasEntry("jenkins/label", label1));
    SemaphoreStep.waitForStart("pod1/1", b);
    Map<String, String> labels1 = getLabels(cloud, this, name);
    labels1.put("jenkins/label",label1);
    PodList pods = cloud.connect().pods().withLabels(labels1).list();
    assertTrue(!pods.getItems().isEmpty());
    SemaphoreStep.success("pod1/1", null);

    SemaphoreStep.waitForStart("podTemplate2/1", b);
    String label2 = name.getMethodName() + "-2";
    PodTemplate template2 = podTemplatesWithLabel(label2, cloud.getAllTemplates()).get(0);
    SemaphoreStep.success("podTemplate2/1", null);
    assertEquals(Integer.MAX_VALUE, template2.getInstanceCap());
    assertThat(template2.getLabelsMap(), hasEntry("jenkins/label", label2));
    assertNull(label2 + " should not inherit from anything", template2.getInheritFrom());
    SemaphoreStep.waitForStart("pod2/1", b);
    Map<String, String> labels2 = getLabels(cloud, this, name);
    labels1.put("jenkins/label", label2);
    PodList pods2 = cloud.connect().pods().withLabels(labels2).list();
    assertTrue(!pods2.getItems().isEmpty());
    SemaphoreStep.success("pod2/1", null);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogContains("script file contents: ", b);
    r.assertLogContains("Started container jnlp", b);
    assertFalse("There are pods leftover after test execution, see previous logs",
            deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
 
Example #12
Source File: VolumeCasCTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule r, String configContent) {
    KubernetesCloud cloud = r.j.jenkins.clouds.get(KubernetesCloud.class);
    assertNotNull(cloud);
    List<PodTemplate> templates = cloud.getTemplates();
    assertNotNull(templates);
    assertEquals(1, templates.size());
    PodTemplate podTemplate = templates.get(0);
    List<PodVolume> volumes = podTemplate.getVolumes();
    assertEquals(1, volumes.size());
    strategy.verify(volumes.get(0));

}
 
Example #13
Source File: EnvVarCasCTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule r, String configContent) {
    KubernetesCloud cloud = r.j.jenkins.clouds.get(KubernetesCloud.class);
    assertNotNull(cloud);
    List<PodTemplate> templates = cloud.getTemplates();
    assertNotNull(templates);
    assertEquals(1, templates.size());
    PodTemplate podTemplate = templates.get(0);
    List<TemplateEnvVar> envVars = podTemplate.getEnvVars();
    assertEquals(1, envVars.size());
    strategy._verify(envVars.get(0));

}
 
Example #14
Source File: PodTemplateMap.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a template for the corresponding cloud instance.
 * @param cloud The cloud instance.
 * @param podTemplate The pod template to add.
 */
public void addTemplate(@Nonnull KubernetesCloud cloud, @Nonnull PodTemplate podTemplate) {
    synchronized (this.map) {
        List<PodTemplate> list = getOrCreateTemplateList(cloud);
        list.add(podTemplate);
        map.put(cloud.name, list);
    }
}
 
Example #15
Source File: WithPodStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start() throws Exception {
    StepContext context = getContext();
    podName = step.getName() + "-" + UUID.randomUUID().toString();
    final AtomicBoolean podAlive = new AtomicBoolean(false);
    final CountDownLatch podStarted = new CountDownLatch(1);
    final CountDownLatch podFinished = new CountDownLatch(1);

    //The body is executed async. so we can't use try with resource here.
    final KubernetesFacade kubernetes = new KubernetesFacade();

    PodTemplate newTemplate = new PodTemplate();
    newTemplate.setName(podName);
    newTemplate.setLabel(step.getName());
    newTemplate.setVolumes(step.getVolumes());
    newTemplate.setContainers(step.getContainers());
    newTemplate.setNodeSelector(step.getNodeSelector());
    newTemplate.setServiceAccount(step.getServiceAccount());

    //Get host using env vars and fallback to computer name (integration point with kubernetes-plugin).
    String hostname = env.get(Constants.HOSTNAME, computer.getName());
    String jobname = env.get(Constants.JOB_NAME, computer.getName());

    kubernetes.createPod(hostname, jobname, newTemplate, workspace.getRemote(), step.getLabels());
    kubernetes.watch(podName, podAlive, podStarted, podFinished, true);
    podStarted.await();

    String containerName = step.getContainers().get(step.getContainers().size() - 1).getName();

    context.newBodyInvoker()
            .withContext(BodyInvoker
                    .mergeLauncherDecorators(getContext().get(LauncherDecorator.class), new PodExecDecorator(kubernetes, podName, containerName, podAlive, podStarted, podFinished)))
                    .withCallback(new PodCallback(podName))
            .start();
    return false;
}
 
Example #16
Source File: CasCTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule r, String configContent) {
    KubernetesCloud cloud = r.j.jenkins.clouds.get(KubernetesCloud.class);
    assertNotNull(cloud);
    assertEquals(10,cloud.getContainerCap());
    assertEquals("http://jenkinshost:8080/jenkins/", cloud.getJenkinsUrl());
    assertEquals(32, cloud.getMaxRequestsPerHost());
    assertEquals("kubernetes", cloud.name);
    List<PodTemplate> templates = cloud.getTemplates();
    assertNotNull(templates);
    assertEquals(3, templates.size());
    PodTemplate podTemplate = templates.get(0);
    assertEquals(false, podTemplate.isHostNetwork());
    assertEquals("java", podTemplate.getLabel());
    assertEquals("default-java", podTemplate.getName());
    assertEquals(10, podTemplate.getInstanceCap());
    assertEquals(123, podTemplate.getSlaveConnectTimeout());
    assertEquals(5, podTemplate.getIdleMinutes());
    assertEquals(66, podTemplate.getActiveDeadlineSeconds());
    assertThat(podTemplate.getYamlMergeStrategy(), isA(Overrides.class));
    podTemplate = templates.get(1);
    assertEquals(false, podTemplate.isHostNetwork());
    assertEquals("dynamic-pvc", podTemplate.getLabel());
    assertEquals("dynamic-pvc", podTemplate.getName());
    assertThat(podTemplate.getYamlMergeStrategy(), isA(Overrides.class));
    WorkspaceVolume workspaceVolume = podTemplate.getWorkspaceVolume();
    assertNotNull(workspaceVolume);
    assertThat(workspaceVolume, isA(DynamicPVCWorkspaceVolume.class));
    DynamicPVCWorkspaceVolume dynamicPVCVolume = (DynamicPVCWorkspaceVolume) workspaceVolume;
    assertEquals("ReadWriteOnce", dynamicPVCVolume.getAccessModes());
    assertEquals("1",dynamicPVCVolume.getRequestsSize());
    assertEquals("hostpath",dynamicPVCVolume.getStorageClassName());
    podTemplate = templates.get(2);
    assertEquals(false, podTemplate.isHostNetwork());
    assertEquals("test", podTemplate.getLabel());
    assertEquals("test", podTemplate.getName());
    assertThat(podTemplate.getYamlMergeStrategy(), isA(Merge.class));
    List<ContainerTemplate> containers = podTemplate.getContainers();
    assertNotNull(containers);
    assertEquals(1, containers.size());
    ContainerTemplate container = containers.get(0);
    assertEquals("cat", container.getArgs());
    assertEquals("/bin/sh -c", container.getCommand());
    assertEquals("maven:3.6.3-jdk-8", container.getImage());
    ContainerLivenessProbe livenessProbe = container.getLivenessProbe();
    assertEquals(1, livenessProbe.getFailureThreshold());
    assertEquals(2, livenessProbe.getInitialDelaySeconds());
    assertEquals(3, livenessProbe.getPeriodSeconds());
    assertEquals(4, livenessProbe.getSuccessThreshold());
    assertEquals(5, livenessProbe.getTimeoutSeconds());
    assertEquals("maven",container.getName());
    assertEquals(true, container.isTtyEnabled());
    assertEquals("/src", container.getWorkingDir());

}
 
Example #17
Source File: KubernetesCloudTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithReadme("kubernetes/README.md")
public void configure_kubernetes_cloud() throws Exception {
    final KubernetesCloud cloud = j.jenkins.clouds.get(KubernetesCloud.class);
    assertNotNull(cloud);
    assertEquals("advanced-k8s-config", cloud.name);
    assertEquals("https://avanced-k8s-config:443", cloud.getServerUrl());
    assertEquals("serverCertificate", cloud.getServerCertificate());
    assertTrue(cloud.isSkipTlsVerify());
    assertEquals("default", cloud.getNamespace());
    assertEquals("http://jenkins/", cloud.getJenkinsUrl());
    assertEquals("advanced-k8s-credentials", cloud.getCredentialsId());
    assertEquals("jenkinsTunnel", cloud.getJenkinsTunnel());
    assertEquals(42, cloud.getContainerCap());
    assertEquals(5, cloud.getRetentionTimeout());
    assertEquals(10, cloud.getConnectTimeout());
    assertEquals(20, cloud.getReadTimeout());
    assertEquals("64", cloud.getMaxRequestsPerHostStr());

    final List<PodTemplate> templates = cloud.getTemplates();
    assertEquals(2, templates.size());
    final PodTemplate template = templates.get(0);
    assertEquals("test", template.getName());
    assertEquals("serviceAccount", template.getServiceAccount());
    assertEquals(1234, template.getInstanceCap());
    assertEquals("label", template.getLabel());

    final List<PodVolume> volumes = template.getVolumes();
    assertEquals(1, volumes.size());
    final PodVolume volume = volumes.get(0);
    assertTrue(volume instanceof HostPathVolume);
    assertEquals("mountPath", volume.getMountPath());
    assertEquals("hostPath", ((HostPathVolume)volume).getHostPath());

    final List<TemplateEnvVar> envVars = template.getEnvVars();
    assertEquals(1, envVars.size());
    final KeyValueEnvVar envVar = (KeyValueEnvVar) envVars.get(0);
    assertEquals("FOO", envVar.getKey());
    assertEquals("BAR", envVar.getValue());

    final PodTemplate template1 = templates.get(1);
    assertEquals("k8s-slave", template1.getName());
    assertEquals("default", template1.getNamespace());
    assertEquals(Mode.EXCLUSIVE, template1.getNodeUsageMode());
}
 
Example #18
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
private List<PodTemplate> podTemplatesWithLabel(String label, List<PodTemplate> templates) {
    return templates.stream().filter(t -> label.equals(t.getLabel())).collect(Collectors.toList());
}
 
Example #19
Source File: PodTemplateMap.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public List<PodTemplate> getList(@Nonnull KubernetesCloud cloud) {
    return PodTemplateMap.get().getTemplates(cloud);
}
 
Example #20
Source File: PodTemplateMap.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
public void removeTemplate(@Nonnull KubernetesCloud cloud, @Nonnull PodTemplate podTemplate) {
    synchronized (this.map) {
        getOrCreateTemplateList(cloud).remove(podTemplate);
    }
}
 
Example #21
Source File: PodTemplateMap.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
private List<PodTemplate> getOrCreateTemplateList(@Nonnull KubernetesCloud cloud) {
    List<PodTemplate> podTemplates = map.get(cloud.name);
    return podTemplates == null ? new CopyOnWriteArrayList<>() : podTemplates;
}
 
Example #22
Source File: PodTemplateStepExecution.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
private PodTemplateCallback(PodTemplate podTemplate) {
    this.podTemplate = podTemplate;
}
 
Example #23
Source File: PodTemplateStepExecution.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean start() throws Exception {
    KubernetesCloud cloud = resolveCloud();

    Run<?, ?> run = getContext().get(Run.class);
    if (cloud.isUsageRestricted()) {
        checkAccess(run, cloud);
    }

    PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
    String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;

    String label = step.getLabel();
    if (label == null) {
        label = labelify(run.getExternalizableId());
    }

    //Let's generate a random name based on the user specified to make sure that we don't have
    //issues with concurrent builds, or messing with pre-existing configuration
    String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
    String stepName = step.getName();
    if (stepName == null) {
        stepName = label;
    }
    String name = String.format(NAME_FORMAT, stepName, randString);
    String namespace = checkNamespace(cloud, podTemplateContext);

    newTemplate = new PodTemplate();
    newTemplate.setName(name);
    newTemplate.setNamespace(namespace);

    if (step.getInheritFrom() == null) {
        newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates));
    } else {
        newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom()));
    }
    newTemplate.setInstanceCap(step.getInstanceCap());
    newTemplate.setIdleMinutes(step.getIdleMinutes());
    newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
    newTemplate.setLabel(label);
    newTemplate.setEnvVars(step.getEnvVars());
    newTemplate.setVolumes(step.getVolumes());
    if (step.getWorkspaceVolume() != null) {
        newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
    }
    newTemplate.setContainers(step.getContainers());
    newTemplate.setNodeSelector(step.getNodeSelector());
    newTemplate.setNodeUsageMode(step.getNodeUsageMode());
    newTemplate.setServiceAccount(step.getServiceAccount());
    newTemplate.setRunAsUser(step.getRunAsUser());
    newTemplate.setRunAsGroup(step.getRunAsGroup());
    if (step.getHostNetwork() != null) {
        newTemplate.setHostNetwork(step.getHostNetwork());
    }
    newTemplate.setAnnotations(step.getAnnotations());
    newTemplate.setListener(getContext().get(TaskListener.class));
    newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
    if(run!=null) {
        String url = cloud.getJenkinsUrlOrNull();
        if(url != null) {
            newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
            newTemplate.getAnnotations().add(new PodAnnotation("runUrl", run.getUrl()));
        }
    }
    newTemplate.setImagePullSecrets(
            step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
    newTemplate.setYaml(step.getYaml());
    if (step.isShowRawYamlSet()) {
        newTemplate.setShowRawYaml(step.isShowRawYaml());
    }
    newTemplate.setPodRetention(step.getPodRetention());

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

    for (ContainerTemplate container : newTemplate.getContainers()) {
        if (!PodTemplateUtils.validateContainerName(container.getName())) {
            throw new AbortException(Messages.RFC1123_error(container.getName()));
        }
    }
    Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
    if (!errors.isEmpty()) {
        throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
    }

    // Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
    if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
        throw new AbortException(Messages.label_error(newTemplate.getLabel()));
    }

    cloud.addDynamicTemplate(newTemplate);
    BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
    if (step.getLabel() == null) {
        invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
    }
    invoker.start();

    return false;
}
 
Example #24
Source File: PodTemplateMap.java    From kubernetes-plugin with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a read-only view of the templates available for the corresponding cloud instance.
 * @param cloud The kubernetes cloud instance for which templates are needed
 * @return a read-only view of the templates available for the corresponding cloud instance.
 */
@Nonnull
public List<PodTemplate> getTemplates(@Nonnull KubernetesCloud cloud) {
    return Collections.unmodifiableList(getOrCreateTemplateList(cloud));
}