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

The following examples show how to use io.fabric8.kubernetes.api.model.Pod#getSpec() . 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: VerifyIntegrationTestAction.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve log messages from given pod.
 * @param pod
 * @return
 */
private String getIntegrationPodLogs(Pod pod) {
    PodResource<Pod, DoneablePod> podRes = client.pods()
            .inNamespace(CamelKHelper.namespace())
            .withName(pod.getMetadata().getName());

    String containerName = null;
    if (pod.getSpec() != null && pod.getSpec().getContainers() != null && pod.getSpec().getContainers().size() > 1) {
        containerName = pod.getSpec().getContainers().get(0).getName();
    }

    String logs;
    if (containerName != null) {
        logs = podRes.inContainer(containerName).getLog();
    } else {
        logs = podRes.getLog();
    }
    return logs;
}
 
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: 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 4
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 5
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 6
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 7
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 8
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 9
Source File: Diagnostics.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public <T extends HasMetadata> void display(T resource) {
 logger.info("Diagnostics for kind: [" + resource.getKind() + "] with name : [" + resource.getMetadata().getName() + "].");
  try {
    PodList podList = pods.list(resource);
    if (podList == null) {
      return;
    }
    for (Pod pod : podList.getItems()) {
      // That should only happen in tests.
      if (pod.getSpec() == null || pod.getSpec().getContainers() == null) {
        continue;
      }

      events(pod);
      for (Container container : pod.getSpec().getContainers()) {
        log(pod, container);
      }
    }
  } catch (Throwable t) {
    // ignore
  }
}
 
Example 10
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static boolean podHasContainerImage(Pod pod, String imageName) {
    if (pod != null) {
        PodSpec spec = pod.getSpec();
        if (spec != null) {
            List<Container> containers = spec.getContainers();
            if (containers != null) {
                for (Container container : containers) {
                    if (Objects.equals(imageName, container.getImage())) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example 11
Source File: DebugMojo.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private boolean podHasEnvVarValue(Pod pod, String envVarName, String envVarValue) {
    PodSpec spec = pod.getSpec();
    if (spec != null) {
        List<Container> containers = spec.getContainers();
        if (containers != null && !containers.isEmpty()) {
            Container container = containers.get(0);
            List<EnvVar> env = container.getEnv();
            if (env != null) {
                for (EnvVar envVar : env) {
                    if (Objects.equal(envVar.getName(), envVarName) && Objects.equal(envVar.getValue(), envVarValue)) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example 12
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 13
Source File: PodsList.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected TablePrinter podsAsTable(PodList pods) {
    TablePrinter table = new TablePrinter();
    table.columns("id", "image(s)", "host", "labels", "status");
    List<Pod> items = pods.getItems();
    if (items == null) {
        items = Collections.EMPTY_LIST;
    }
    Filter<Pod> filter = KubernetesHelper.createPodFilter(filterText.getValue());
    for (Pod item : items) {
        if (filter.matches(item)) {
            String id = KubernetesHelper.getName(item);
            PodStatus podStatus = item.getStatus();
            String status = "";
            String host = "";
            if (podStatus != null) {
                status = KubernetesHelper.getStatusText(podStatus);
                host = podStatus.getHostIP();
            }
            Map<String, String> labelMap = item.getMetadata().getLabels();
            String labels = KubernetesHelper.toLabelsString(labelMap);
            PodSpec spec = item.getSpec();
            if (spec != null) {
                List<Container> containerList = spec.getContainers();
                for (Container container : containerList) {
                    String image = container.getImage();
                    table.row(id, image, host, labels, status);

                    id = "";
                    host = "";
                    status = "";
                    labels = "";
                }
            }
        }
    }
    return table;
}
 
Example 14
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 15
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 16
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static List<Container> getContainers(Pod pod) {
    if (pod != null) {
        PodSpec podSpec = pod.getSpec();
        return getContainers(podSpec);

    }
    return Collections.EMPTY_LIST;
}
 
Example 17
Source File: PodInfo.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected void executePod(Pod podInfo, String podId) {
    System.out.println("Created: " + podInfo.getMetadata().getCreationTimestamp());
    System.out.println("Labels: ");
    Map<String, String> labels = podInfo.getMetadata().getLabels();
    for (Map.Entry<String, String> entry : labels.entrySet()) {
        System.out.println(indent + entry.getKey() + " = " + entry.getValue());
    }
    PodStatus currentState = podInfo.getStatus();
    if (currentState != null) {
        printValue("Host", currentState.getHostIP());
        printValue("IP", currentState.getPodIP());
        printValue("Status", getStatusText(currentState));
    }
    PodSpec spec = podInfo.getSpec();
    if (spec != null) {
        List<Container> containers = spec.getContainers();
        if (notEmpty(containers)) {
            System.out.println("Containers:");
            indentCount++;
            for (Container container : containers) {
                printValue("Name", container.getName());
                printValue("Image", container.getImage());
                printValue("Working Dir", container.getWorkingDir());
                printValue("Command", container.getCommand());

                List<ContainerPort> ports = container.getPorts();
                if (notEmpty(ports)) {
                    println("Ports:");
                    indentCount++;
                    for (ContainerPort port : ports) {
                        printValue("Name", port.getName());
                        printValue("Protocol", port.getProtocol());
                        printValue("Host Port", port.getHostPort());
                        printValue("Container Port", port.getContainerPort());
                    }
                    indentCount--;
                }

                List<EnvVar> envList = container.getEnv();
                if (notEmpty(envList)) {
                    println("Environment:");
                    indentCount++;
                    for (EnvVar env : envList) {
                        printValue(env.getName(), env.getValue());
                    }
                    indentCount--;
                }
                List<VolumeMount> volumeMounts = container.getVolumeMounts();
                if (notEmpty(volumeMounts)) {
                    println("Volume Mounts:");
                    indentCount++;
                    for (VolumeMount volumeMount : volumeMounts) {
                        printValue("Name", volumeMount.getName());
                        printValue("Mount Path", volumeMount.getMountPath());
                        printValue("Read Only", volumeMount.getReadOnly());
                    }
                    indentCount--;
                }
            }
        }

        List<Volume> volumes = spec.getVolumes();
        if (volumes != null) {
            System.out.println("Volumes: ");
            for (Volume volume : volumes) {
                System.out.println(indent + volume.getName());
            }
        }
    }
}
 
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: KubernetesComponentToWorkspaceApplierTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void shouldChangeEntrypointsOnMatchingContainers() throws Exception {
  // given
  String yamlRecipeContent = getResource("devfile/petclinic.yaml");
  doReturn(toK8SList(yamlRecipeContent).getItems()).when(k8sRecipeParser).parse(anyString());

  List<String> command = asList("teh", "command");
  ComponentImpl component = new ComponentImpl();
  component.setType(KUBERNETES_COMPONENT_TYPE);
  component.setReference(REFERENCE_FILENAME);
  component.setAlias(COMPONENT_NAME);

  EntrypointImpl entrypoint = new EntrypointImpl();
  entrypoint.setParentName("petclinic");
  entrypoint.setCommand(command);
  component.setEntrypoints(singletonList(entrypoint));

  // when
  applier.apply(workspaceConfig, component, s -> yamlRecipeContent);

  // then
  verify(k8sEnvProvisioner).provision(any(), any(), objectsCaptor.capture(), any());
  List<HasMetadata> list = objectsCaptor.getValue();
  for (HasMetadata o : list) {
    if (o instanceof Pod) {
      Pod p = (Pod) o;

      // ignore pods that don't have containers
      if (p.getSpec() == null) {
        continue;
      }

      Container c = p.getSpec().getContainers().get(0);
      if (o.getMetadata().getName().equals("petclinic")) {
        assertEquals(c.getCommand(), command);
      } else {
        assertTrue(c.getCommand() == null || c.getCommand().isEmpty());
      }
    }
  }
}
 
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")));
}