Java Code Examples for io.fabric8.kubernetes.api.model.Pod#getMetadata()

The following examples show how to use io.fabric8.kubernetes.api.model.Pod#getMetadata() . 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: KubernetesServerExposerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  container = new ContainerBuilder().withName("main").build();
  Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName("pod")
          .endMetadata()
          .withNewSpec()
          .withContainers(container)
          .endSpec()
          .build();

  kubernetesEnvironment =
      KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();

  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  this.serverExposer =
      new KubernetesServerExposer<>(
          externalServerExposer,
          secureServerExposer,
          MACHINE_NAME,
          podData,
          container,
          kubernetesEnvironment);
}
 
Example 2
Source File: KubernetesEnvironmentPodsValidatorTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = ValidationException.class,
    expectedExceptionsMessageRegExp =
        "Container 'main' in pod 'pod1' contains volume mount that references missing volume 'non-existing'")
public void shouldThrowExceptionWhenContainerHasVolumeMountThatReferencesMissingPodVolume()
    throws Exception {
  // given
  String podName = "pod1";
  Pod pod = createPod("pod1", "main");
  pod.getSpec()
      .getContainers()
      .get(0)
      .getVolumeMounts()
      .add(new VolumeMountBuilder().withName("non-existing").withMountPath("/tmp/data").build());
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  when(kubernetesEnvironment.getPodsData()).thenReturn(ImmutableMap.of(podName, podData));
  when(kubernetesEnvironment.getMachines())
      .thenReturn(ImmutableMap.of(podName + "/main", mock(InternalMachineConfig.class)));

  // when
  podsValidator.validate(kubernetesEnvironment);
}
 
Example 3
Source File: KubernetesEnvironmentPodsValidatorTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = ValidationException.class,
    expectedExceptionsMessageRegExp =
        "Pod 'pod1' contains volume 'user-data' with PVC sources that references missing PVC 'non-existing'")
public void shouldThrowExceptionWhenPodHasVolumeThatReferencesMissingPVC() throws Exception {
  // given
  String podName = "pod1";
  Pod pod = createPod("pod1", "main");
  pod.getSpec()
      .getVolumes()
      .add(
          new VolumeBuilder()
              .withName("user-data")
              .withNewPersistentVolumeClaim()
              .withClaimName("non-existing")
              .endPersistentVolumeClaim()
              .build());
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  when(kubernetesEnvironment.getPodsData()).thenReturn(ImmutableMap.of(podName, podData));
  when(kubernetesEnvironment.getMachines())
      .thenReturn(ImmutableMap.of(podName + "/main", mock(InternalMachineConfig.class)));

  // when
  podsValidator.validate(kubernetesEnvironment);
}
 
Example 4
Source File: KubernetesEnvironmentPodsValidatorTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = ValidationException.class,
    expectedExceptionsMessageRegExp =
        "Environment contains machines that are missing in recipe: pod1/db")
public void shouldThrowExceptionWhenMachineIsDeclaredButThereIsNotContainerInKubernetesRecipe()
    throws Exception {
  // given
  String podName = "pod1";
  Pod pod = createPod("pod1", "main");
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  when(kubernetesEnvironment.getPodsData()).thenReturn(ImmutableMap.of(podName, podData));
  when(kubernetesEnvironment.getMachines())
      .thenReturn(ImmutableMap.of(podName + "/db", mock(InternalMachineConfig.class)));

  // when
  podsValidator.validate(kubernetesEnvironment);
}
 
Example 5
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void doesNotRewritePodConfigMapVolumesWhenNoConfigMap() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  Volume volume =
      new VolumeBuilder().withNewConfigMap().withName(CONFIGMAP_NAME).endConfigMap().build();
  Pod pod = newPod();
  pod.getSpec().setVolumes(ImmutableList.of(volume));
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  Volume newVolume = pod.getSpec().getVolumes().iterator().next();
  assertEquals(newVolume.getConfigMap().getName(), CONFIGMAP_NAME);
}
 
Example 6
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rewritePodConfigMapVolumes() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  ConfigMap configMap = newConfigMap();
  doReturn(ImmutableMap.of(CONFIGMAP_NAME, configMap)).when(k8sEnv).getConfigMaps();

  Volume volume =
      new VolumeBuilder().withNewConfigMap().withName(CONFIGMAP_NAME).endConfigMap().build();
  Pod pod = newPod();
  pod.getSpec().setVolumes(ImmutableList.of(volume));
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  String newConfigMapName = configMap.getMetadata().getName();
  Volume newVolume = pod.getSpec().getVolumes().iterator().next();
  assertEquals(newVolume.getConfigMap().getName(), newConfigMapName);
}
 
Example 7
Source File: RestartPolicyRewriterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rewritesRestartPolicyWhenItsDifferentWithDefaultOne() throws Exception {
  Pod pod = newPod(TEST_POD_NAME, ALWAYS_RESTART_POLICY);
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  when(k8sEnv.getPodsData()).thenReturn(singletonMap(TEST_POD_NAME, podData));

  restartPolicyRewriter.provision(k8sEnv, runtimeIdentity);

  assertEquals(pod.getSpec().getRestartPolicy(), DEFAULT_RESTART_POLICY);
  verifyWarnings(
      new WarningImpl(
          RESTART_POLICY_SET_TO_NEVER_WARNING_CODE,
          format(
              "Restart policy '%s' for pod '%s' is rewritten with %s",
              ALWAYS_RESTART_POLICY, TEST_POD_NAME, DEFAULT_RESTART_POLICY)));
}
 
Example 8
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void doesNotRewritePodConfigMapEnvFromWhenNoConfigMap() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  EnvFromSource envFrom =
      new EnvFromSourceBuilder()
          .withNewConfigMapRef()
          .withName(CONFIGMAP_NAME)
          .endConfigMapRef()
          .build();
  Container container = new ContainerBuilder().withEnvFrom(envFrom).build();
  Pod pod = newPod();
  pod.getSpec().setContainers(ImmutableList.of(container));
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  EnvFromSource newEnvFromSource = container.getEnvFrom().iterator().next();
  assertEquals(newEnvFromSource.getConfigMapRef().getName(), CONFIGMAP_NAME);
}
 
Example 9
Source File: PodTemplateUtils.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
public static Pod parseFromYaml(String yaml) {
    String s = yaml;
    try (KubernetesClient client = new DefaultKubernetesClient()) {
        // JENKINS-57116
        if (StringUtils.isBlank(s)) {
            LOGGER.log(Level.WARNING, "[JENKINS-57116] Trying to parse invalid yaml: \"{0}\"", yaml);
            s = "{}";
        }
        Pod podFromYaml;
        try (InputStream is = new ByteArrayInputStream(s.getBytes(UTF_8))) {
            podFromYaml = client.pods().load(is).get();
        } catch (IOException | KubernetesClientException e) {
            throw new RuntimeException(String.format("Failed to parse yaml: \"%s\"", yaml), e);
        }
        LOGGER.finest(() -> "Parsed pod template from yaml: " + Serialization.asYaml(podFromYaml));
        // yaml can be just a fragment, avoid NPEs
        if (podFromYaml.getMetadata() == null) {
            podFromYaml.setMetadata(new ObjectMeta());
        }
        if (podFromYaml.getSpec() == null) {
            podFromYaml.setSpec(new PodSpec());
        }
        return podFromYaml;
    }
}
 
Example 10
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void doesNotRewritePodConfigMapEnvWhenNoConfigMap() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  EnvVar envVar =
      new EnvVarBuilder()
          .withNewValueFrom()
          .withNewConfigMapKeyRef()
          .withName(CONFIGMAP_NAME)
          .withKey(CONFIGMAP_KEY)
          .endConfigMapKeyRef()
          .endValueFrom()
          .build();
  Container container = new ContainerBuilder().withEnv(envVar).build();
  Pod pod = newPod();
  pod.getSpec().setContainers(ImmutableList.of(container));
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  EnvVar newEnvVar = container.getEnv().iterator().next();
  assertEquals(newEnvVar.getValueFrom().getConfigMapKeyRef().getName(), CONFIGMAP_NAME);
}
 
Example 11
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rewritePodConfigMapEnvFrom() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  ConfigMap configMap = newConfigMap();
  doReturn(ImmutableMap.of(CONFIGMAP_NAME, configMap)).when(k8sEnv).getConfigMaps();

  EnvFromSource envFrom =
      new EnvFromSourceBuilder()
          .withNewConfigMapRef()
          .withName(CONFIGMAP_NAME)
          .endConfigMapRef()
          .build();
  Container container = new ContainerBuilder().withEnvFrom(envFrom).build();
  Pod pod = newPod();
  pod.getSpec().setContainers(ImmutableList.of(container));
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  String newConfigMapName = configMap.getMetadata().getName();
  EnvFromSource newEnvFromSource = container.getEnvFrom().iterator().next();
  assertEquals(newEnvFromSource.getConfigMapRef().getName(), newConfigMapName);
}
 
Example 12
Source File: PodsVolumesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() {
  Pod pod =
      newPod(POD_1_NAME)
          .withContainers(
              newContainer(CONTAINER_1_NAME).build(), newContainer(CONTAINER_2_NAME).build())
          .build();
  podData = new PodData(pod.getSpec(), pod.getMetadata());

  podsVolumes = new PodsVolumes();
}
 
Example 13
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void provideUniquePodsNames() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

  Pod pod = newPod();
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(k8sEnv).getPodsData();

  uniqueNamesProvisioner.provision(k8sEnv, runtimeIdentity);

  ObjectMeta podMetadata = pod.getMetadata();
  assertNotEquals(podMetadata.getName(), POD_NAME);
  assertEquals(podMetadata.getLabels().get(CHE_ORIGINAL_NAME_LABEL), POD_NAME);
}
 
Example 14
Source File: KubernetesDeployments.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Starts the specified Pod via a Deployment.
 *
 * @param pod pod to deploy
 * @return created pod
 * @throws InfrastructureException when any exception occurs
 */
public Pod deploy(Pod pod) throws InfrastructureException {
  putLabel(pod, CHE_WORKSPACE_ID_LABEL, workspaceId);
  // Since we use the pod's metadata as the deployment's metadata
  // This is used to identify the pod in CreateWatcher.
  String originalName = pod.getMetadata().getName();
  putLabel(pod, CHE_DEPLOYMENT_NAME_LABEL, originalName);

  ObjectMeta metadata = pod.getMetadata();
  PodSpec podSpec = pod.getSpec();
  podSpec.setRestartPolicy("Always"); // Only allowable value

  Deployment deployment =
      new DeploymentBuilder()
          .withMetadata(metadata)
          .withNewSpec()
          .withNewSelector()
          .withMatchLabels(metadata.getLabels())
          .endSelector()
          .withReplicas(1)
          .withNewTemplate()
          .withMetadata(metadata)
          .withSpec(podSpec)
          .endTemplate()
          .endSpec()
          .build();
  return createDeployment(deployment, workspaceId);
}
 
Example 15
Source File: KubernetesComputer.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Exported
public List<Event> getPodEvents() throws KubernetesAuthException, IOException {
    if(!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        LOGGER.log(Level.FINE, " Computer {0} getPodEvents, lack of admin permission, returning empty list", this);
        return Collections.emptyList();
    }

    KubernetesSlave slave = getNode();
    if(slave != null) {
        KubernetesCloud cloud = slave.getKubernetesCloud();
        KubernetesClient client = cloud.connect();

        String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace());

        Pod pod = client.pods().inNamespace(namespace).withName(getName()).get();
        if(pod != null) {
            ObjectMeta podMeta = pod.getMetadata();
            String podNamespace = podMeta.getNamespace();

            Map<String, String> fields = new HashMap<>();
            fields.put("involvedObject.uid", podMeta.getUid());
            fields.put("involvedObject.name", podMeta.getName());
            fields.put("involvedObject.namespace", podNamespace);

            EventList eventList = client.events().inNamespace(podNamespace).withFields(fields).list();
            if(eventList != null) {
                return eventList.getItems();
            }
        }
    }

    return Collections.emptyList();
}
 
Example 16
Source File: OpenShiftUniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void provideUniquePodsNames() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);
  Pod pod = newPod();
  PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
  doReturn(ImmutableMap.of(POD_NAME, podData)).when(osEnv).getPodsData();

  uniqueNamesProvisioner.provision(osEnv, runtimeIdentity);

  ObjectMeta podMetadata = pod.getMetadata();
  assertNotEquals(podMetadata.getName(), POD_NAME);
  assertEquals(podMetadata.getLabels().get(CHE_ORIGINAL_NAME_LABEL), POD_NAME);
}
 
Example 17
Source File: LanderPodFactoryTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void podBuildingWithoutAnnotations() {
  when(podNameFactory.newName(any())).thenReturn(TRUCK_PARK_NAME);
  when(configMapSupplier.get()).thenReturn(configMap);
  when(configMap.getData()).thenReturn(ImmutableMap
          .<String, String> builder()
          .put(DOCKER_IMAGE, DOCKER_IMAGE_NAME)
          .put(VERSION, IMAGE_VERSION)
          .put(CPU, "cpu1")
          .put(MEMORY, "mem1")
          .put(JVM_ARGS, "args1")
          .put(CLOUDWATCH_REGION, "region")
          .put(CLOUDWATCH_GROUP, "group")
          .build());

  LanderConfiguration config = new LanderConfiguration(NAME, "topic", emptyMap(), "s3Prefix", false,
          PARTITION_COLUMN_VALUE, false);
  Pod pod = underTest.newInstance(config, singletonList(ARG));

  ObjectMeta metadata = pod.getMetadata();
  assertThat(metadata.getName(), is(TRUCK_PARK_NAME));
  assertThat(metadata.getLabels(),
          is(ImmutableMap
                  .<String, String> builder()
                  .put(APP, TRUCK_PARK)
                  .put(VERSION, IMAGE_VERSION)
                  .put(ROAD, NAME)
                  .build()));
  assertThat(metadata.getAnnotations(),
          is(Collections.emptyMap()));
}
 
Example 18
Source File: KubernetesEnvironment.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public PodData(Pod pod) {
  this(pod.getSpec(), pod.getMetadata());
}
 
Example 19
Source File: PodOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
private static String getPodUid(Pod resource) {
    if (resource == null || resource.getMetadata() == null) {
        return NO_UID;
    }
    return resource.getMetadata().getUid();
}
 
Example 20
Source File: LanderPodFactoryTest.java    From data-highway with Apache License 2.0 4 votes vote down vote up
@Test
public void simple() {
  when(podNameFactory.newName(any())).thenReturn(TRUCK_PARK_NAME);
  when(configMapSupplier.get()).thenReturn(configMap);
  when(configMap.getData()).thenReturn(ImmutableMap
      .<String, String> builder()
      .put(DOCKER_IMAGE, DOCKER_IMAGE_NAME)
      .put(VERSION, IMAGE_VERSION)
      .put(CPU, "cpu1")
      .put(MEMORY, "mem1")
      .put(JVM_ARGS, "args1")
      .put(CLOUDWATCH_REGION, "region")
      .put(CLOUDWATCH_GROUP, "group")
      .put("annotations", "{\"annotation1\": \"value1\", \"annotation2/slashsomething\": \"value2\"}")
      .build());

  LanderConfiguration config = new LanderConfiguration(NAME, "topic", emptyMap(), "s3Prefix", false,
      PARTITION_COLUMN_VALUE, false);
  Pod pod = underTest.newInstance(config, singletonList(ARG));

  ObjectMeta metadata = pod.getMetadata();
  assertThat(metadata.getName(), is(TRUCK_PARK_NAME));
  assertThat(metadata.getLabels(),
      is(ImmutableMap
          .<String, String> builder()
          .put(APP, TRUCK_PARK)
          .put(VERSION, IMAGE_VERSION)
          .put(ROAD, NAME)
          .build()));
  assertThat(metadata.getAnnotations(),
      is(ImmutableMap
          .<String, String> builder()
          .put("annotation1", "value1")
          .put("annotation2/slashsomething", "value2")
          .build()));

  PodSpec spec = pod.getSpec();
  assertThat(spec.getRestartPolicy(), is(RESTART_POLICY_NEVER));

  List<Container> containers = spec.getContainers();
  assertThat(containers.size(), is(1));

  Container container = containers.get(0);
  assertThat(container.getName(), is(TRUCK_PARK_NAME));
  assertThat(container.getImage(), is(DOCKER_IMAGE_NAME));
  assertThat(container.getArgs(), is(singletonList(ARG)));

  List<EnvVar> env = container.getEnv();
  assertThat(env.size(), is(7));

  EnvVar kubeNamespace = env.get(0);
  assertThat(kubeNamespace.getName(), is("KUBERNETES_NAMESPACE"));
  assertThat(kubeNamespace.getValue(), is(nullValue()));

  EnvVar podNameEnv = env.get(1);
  assertThat(podNameEnv.getName(), is("POD_NAME"));
  assertThat(podNameEnv.getValue(), is(TRUCK_PARK_NAME));

  EnvVar environment = env.get(2);
  assertThat(environment.getName(), is("ENVIRONMENT"));
  assertThat(environment.getValue(), is("lab"));

  EnvVar jvmArgs = env.get(3);
  assertThat(jvmArgs.getName(), is("JVM_ARGS"));
  assertThat(jvmArgs.getValue(), is("args1"));

  EnvVar cloudwatchRegion = env.get(4);
  assertThat(cloudwatchRegion.getName(), is("CLOUDWATCH_REGION"));
  assertThat(cloudwatchRegion.getValue(), is("region"));

  EnvVar cloudwatchGroup = env.get(5);
  assertThat(cloudwatchGroup.getName(), is("CLOUDWATCH_GROUP"));
  assertThat(cloudwatchGroup.getValue(), is("group"));

  EnvVar cloudwatchStream = env.get(6);
  assertThat(cloudwatchStream.getName(), is("CLOUDWATCH_STREAM"));
  assertThat(cloudwatchStream.getValue(), is("${KUBERNETES_NAMESPACE}-truck-park-the_name"));

  ResourceRequirements resources = container.getResources();
  assertThat(resources.getLimits().get(CPU), is(new Quantity("cpu1")));
  assertThat(resources.getLimits().get(MEMORY), is(new Quantity("mem1")));
  assertThat(resources.getRequests().get(CPU), is(new Quantity("cpu1")));
  assertThat(resources.getRequests().get(MEMORY), is(new Quantity("mem1")));
}