Java Code Examples for org.csanchez.jenkins.plugins.kubernetes.PodTemplate#setLabel()

The following examples show how to use org.csanchez.jenkins.plugins.kubernetes.PodTemplate#setLabel() . 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
@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 2
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 3
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 4
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 5
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;
}