Java Code Examples for io.fabric8.kubernetes.api.model.PodSpec#getContainers()

The following examples show how to use io.fabric8.kubernetes.api.model.PodSpec#getContainers() . 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: 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 2
Source File: DockerImageWatcher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private boolean updateImageName(HasMetadata entity, PodTemplateSpec template, String imagePrefix, String imageName) {
    boolean answer = false;
    PodSpec spec = template.getSpec();
    if (spec != null) {
        List<Container> containers = spec.getContainers();
        if (containers != null) {
            for (Container container : containers) {
                String image = container.getImage();
                if (image != null && image.startsWith(imagePrefix)) {
                    container.setImage(imageName);
                    log.info("Updating " + KubernetesHelper.getKind(entity) + " " + KubernetesHelper.getName(entity) + " to use image: " + imageName);
                    answer = true;
                }
            }
        }
    }
    return answer;
}
 
Example 3
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 4
Source File: GitConfigProvisioner.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void mountConfigFile(PodSpec podSpec, String gitConfigMapName, boolean addVolume) {
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(CONFIG_MAP_VOLUME_NAME)
                .withConfigMap(
                    new ConfigMapVolumeSourceBuilder().withName(gitConfigMapName).build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(CONFIG_MAP_VOLUME_NAME)
                .withMountPath(GIT_CONFIG_PATH)
                .withSubPath(GIT_CONFIG)
                .withReadOnly(false)
                .withNewReadOnly(false)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example 5
Source File: BrokerEnvironmentFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNameContainersAfterMetadataPluginBrokerImage() throws Exception {
  // given
  Collection<PluginFQN> pluginFQNs = singletonList(new PluginFQN(null, "id"));
  ArgumentCaptor<BrokersConfigs> captor = ArgumentCaptor.forClass(BrokersConfigs.class);

  // when
  factory.createForMetadataBroker(pluginFQNs, runtimeId);

  // then
  verify(factory).doCreate(captor.capture());
  BrokersConfigs brokersConfigs = captor.getValue();
  PodSpec brokerPodSpec = brokersConfigs.pods.values().iterator().next().getSpec();

  List<Container> containers = brokerPodSpec.getContainers();
  assertEquals(containers.size(), 1);
  assertEquals(containers.get(0).getName(), "metadata-image");
}
 
Example 6
Source File: BrokerEnvironmentFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNameContainersAfterArtifactsPluginBrokerImage() throws Exception {
  // given
  Collection<PluginFQN> pluginFQNs = singletonList(new PluginFQN(null, "id"));
  ArgumentCaptor<BrokersConfigs> captor = ArgumentCaptor.forClass(BrokersConfigs.class);

  // when
  factory.createForArtifactsBroker(pluginFQNs, runtimeId);

  // then
  verify(factory).doCreate(captor.capture());
  BrokersConfigs brokersConfigs = captor.getValue();
  PodSpec brokerPodSpec = brokersConfigs.pods.values().iterator().next().getSpec();

  List<Container> containers = brokerPodSpec.getContainers();
  assertEquals(containers.size(), 1);
  assertEquals(containers.get(0).getName(), "artifacts-image");
}
 
Example 7
Source File: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isLocalCustomisation(PodSpec podSpec) {
    List<Container> containers = podSpec.getContainers() != null ? podSpec.getContainers() : Collections.<Container>emptyList();
    for (Container container : containers) {
        if (StringUtils.isNotBlank(container.getImage())) {
            return false;
        }
    }
    return true;
}
 
Example 8
Source File: DebugEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private boolean enableDebugging(HasMetadata entity, PodTemplateSpec template) {
    if (template != null) {
        PodSpec podSpec = template.getSpec();
        if (podSpec != null) {
            List<Container> containers = podSpec.getContainers();
            if (!containers.isEmpty()) {
                Container container = containers.get(0);
                List<EnvVar> env = container.getEnv();
                if (env == null) {
                    env = new ArrayList<>();
                }
                String remoteDebugPort =
                    KubernetesHelper.getEnvVar(env, ENV_VAR_JAVA_DEBUG_PORT, ENV_VAR_JAVA_DEBUG_PORT_DEFAULT);
                boolean enabled = false;
                if (KubernetesHelper.setEnvVar(env, ENV_VAR_JAVA_DEBUG, "true")) {
                    container.setEnv(env);
                    enabled = true;
                }
                List<ContainerPort> ports = container.getPorts();
                if (ports == null) {
                    ports = new ArrayList<>();
                }
                if (KubernetesResourceUtil.addPort(ports, remoteDebugPort, "debug", log)) {
                    container.setPorts(ports);
                    enabled = true;
                }
                if (enabled) {
                    log.info("Enabling debug on " + KubernetesHelper.getKind(entity) + " " + KubernetesHelper.getName(
                        entity) + " due to the property: " + ENABLE_DEBUG_MAVEN_PROPERTY);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 9
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<Container> getContainers(PodSpec podSpec) {
    if (podSpec != null) {
        return podSpec.getContainers();
    }
    return Collections.EMPTY_LIST;
}
 
Example 10
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 11
Source File: ServersConverter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@Traced
public void provision(T k8sEnv, RuntimeIdentity identity) throws InfrastructureException {

  TracingTags.WORKSPACE_ID.set(identity::getWorkspaceId);

  SecureServerExposer<T> secureServerExposer =
      secureServerExposerFactoryProvider.get(k8sEnv).create(identity);

  for (PodData podConfig : k8sEnv.getPodsData().values()) {
    final PodSpec podSpec = podConfig.getSpec();
    for (Container containerConfig : podSpec.getContainers()) {
      String machineName = Names.machineName(podConfig, containerConfig);
      InternalMachineConfig machineConfig = k8sEnv.getMachines().get(machineName);
      if (!machineConfig.getServers().isEmpty()) {
        KubernetesServerExposer kubernetesServerExposer =
            new KubernetesServerExposer<>(
                externalServerExposer,
                secureServerExposer,
                machineName,
                podConfig,
                containerConfig,
                k8sEnv);
        kubernetesServerExposer.expose(machineConfig.getServers());
      }
    }
  }
}
 
Example 12
Source File: SshKeysProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void mountSshKeySecret(String secretName, PodSpec podSpec, boolean addVolume) {
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(secretName)
                .withSecret(
                    new SecretVolumeSourceBuilder()
                        .withSecretName(secretName)
                        .withDefaultMode(0600)
                        .build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(secretName)
                .withNewReadOnly(true)
                .withReadOnly(true)
                .withMountPath(SSH_PRIVATE_KEYS_PATH)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example 13
Source File: SshKeysProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void mountConfigFile(PodSpec podSpec, String sshConfigMapName, boolean addVolume) {
  String configMapVolumeName = "ssshkeyconfigvolume";
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(configMapVolumeName)
                .withConfigMap(
                    new ConfigMapVolumeSourceBuilder().withName(sshConfigMapName).build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(configMapVolumeName)
                .withMountPath(SSH_CONFIG_PATH)
                .withSubPath(SSH_CONFIG)
                .withReadOnly(true)
                .withNewReadOnly(true)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example 14
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")));
}
 
Example 15
Source File: DebugMojo.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private boolean enableDebugging(HasMetadata entity, PodTemplateSpec template) {
    if (template != null) {
        PodSpec podSpec = template.getSpec();
        if (podSpec != null) {
            List<Container> containers = podSpec.getContainers();
            boolean enabled = false;
            for (int i = 0; i < containers.size(); i++) {
                Container container = containers.get(i);
                List<EnvVar> env = container.getEnv();
                if (env == null) {
                    env = new ArrayList<>();
                }
                remoteDebugPort = KubernetesHelper.getEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_PORT, DebugConstants.ENV_VAR_JAVA_DEBUG_PORT_DEFAULT);
                if (KubernetesHelper.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG, "true")) {
                    container.setEnv(env);
                    enabled = true;
                }
                if (KubernetesHelper.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SUSPEND, String.valueOf(debugSuspend))) {
                    container.setEnv(env);
                    enabled = true;
                }
                List<ContainerPort> ports = container.getPorts();
                if (ports == null) {
                    ports = new ArrayList<>();
                }
                if (KubernetesResourceUtil.addPort(ports, remoteDebugPort, "debug", log)) {
                    container.setPorts(ports);
                    enabled = true;
                }
                if (debugSuspend) {
                    // Setting a random session value to force pod restart
                    this.debugSuspendValue = String.valueOf(new Random().nextLong());
                    KubernetesHelper.setEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SESSION, this.debugSuspendValue);
                    container.setEnv(env);
                    if (container.getReadinessProbe() != null) {
                        log.info("Readiness probe will be disabled on " + KubernetesHelper.getKind(entity) + " " + getName(entity) + " to allow attaching a remote debugger during suspension");
                        container.setReadinessProbe(null);
                    }
                    enabled = true;
                } else {
                    if (KubernetesHelper.removeEnvVar(env, DebugConstants.ENV_VAR_JAVA_DEBUG_SESSION)) {
                        container.setEnv(env);
                        enabled = true;
                    }
                }
            }
            if (enabled) {
                log.info("Enabling debug on " + KubernetesHelper.getKind(entity) + " " + getName(entity));
                return true;
            }
        }
    }
    return false;
}
 
Example 16
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());
            }
        }
    }
}