Java Code Examples for io.fabric8.kubernetes.api.model.Container#getEnv()

The following examples show how to use io.fabric8.kubernetes.api.model.Container#getEnv() . 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: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static void ensureHasEnv(Container container, EnvVar envVar) {
    List<EnvVar> envVars = container.getEnv();
    if (envVars == null) {
        envVars = new ArrayList<>();
        container.setEnv(envVars);
    }
    for (EnvVar var : envVars) {
        if (Objects.equals(var.getName(), envVar.getName())) {
            // lets replace the object so that we can update the value or valueFrom
            envVars.remove(var);
            envVars.add(envVar);
            return;
        }
    }
    envVars.add(envVar);
}
 
Example 3
Source File: GoCDContainerDetails.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
public static GoCDContainerDetails fromContainer(Container container, ContainerStatus containerStatus) {
    GoCDContainerDetails containerDetails = new GoCDContainerDetails();

    containerDetails.name = container.getName();
    containerDetails.image = container.getImage();
    containerDetails.imagePullPolicy = container.getImagePullPolicy();

    containerDetails.command = container.getCommand();
    containerDetails.env = new ArrayList<>();
    for (EnvVar var : container.getEnv()) {
        containerDetails.env.add(new EnvironmentVariable(var.getName(), var.getValue()));
    }
    if (containerStatus != null) {
        containerDetails.ready = containerStatus.getReady();
        containerDetails.restartCount = containerStatus.getRestartCount();
    }
    else {
        containerDetails.ready = false;
        containerDetails.restartCount = 0;
    }

    return containerDetails;
}
 
Example 4
Source File: ModelUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * @param pod The StatefulSet
 * @param containerName The name of the container whoes environment variables are to be retrieved
 * @param envVarName Name of the environment variable which we should get
 * @return The environment of the Kafka container in the sts.
 */
public static String getPodEnv(Pod pod, String containerName, String envVarName) {
    if (pod != null) {
        for (Container container : pod.getSpec().getContainers()) {
            if (containerName.equals(container.getName())) {
                if (container.getEnv() != null) {
                    for (EnvVar envVar : container.getEnv()) {
                        if (envVarName.equals(envVar.getName()))    {
                            return envVar.getValue();
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example 5
Source File: KubeUtilTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
public void appliesContainerEnvVarToPodTemplate() {
    Container actualContainer = new ContainerBuilder()
            .withName("foo")
            .withEnv(FOO1_ENVVAR, FOO2_ENVAR).build();
    Container desiredContainer = new ContainerBuilder()
            .withName("foo")
            .withEnv(FOO1_UPD_ENVVAR, FOO3_ENVVAR).build();

    PodTemplateSpec actual = doApplyContainers(actualContainer, desiredContainer);

    Container container = actual.getSpec().getContainers().get(0);
    List<EnvVar> probe = container.getEnv();
    assertThat(probe.size(), equalTo(3));
    assertThat(probe, containsInAnyOrder(FOO1_UPD_ENVVAR, FOO2_ENVAR, FOO3_ENVVAR));
}
 
Example 6
Source File: KubeUtilTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
public void appliesInitContainerEnvVarToPodTemplate() {
    Container actualContainer = new ContainerBuilder()
            .withName("foo")
            .withEnv(FOO1_ENVVAR).build();
    Container desiredContainer = new ContainerBuilder()
            .withName("foo")
            .withEnv(FOO1_UPD_ENVVAR).build();

    PodTemplateSpec actual = doApplyInitContainers(actualContainer, desiredContainer);

    Container container = actual.getSpec().getInitContainers().get(0);
    List<EnvVar> probe = container.getEnv();
    assertThat(probe.size(), equalTo(1));
    assertThat(probe, containsInAnyOrder(FOO1_UPD_ENVVAR));
}
 
Example 7
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 8
Source File: ModelUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * @param sts The StatefulSet
 * @param containerName The name of the container whoes environment variables are to be retrieved
 * @return The environment of the Kafka container in the sts.
 */
public static Map<String, String> getContainerEnv(StatefulSet sts, String containerName) {
    for (Container container : sts.getSpec().getTemplate().getSpec().getContainers()) {
        if (containerName.equals(container.getName())) {
            LinkedHashMap<String, String> map = new LinkedHashMap<>(container.getEnv() == null ? 2 : container.getEnv().size());
            if (container.getEnv() != null) {
                for (EnvVar envVar : container.getEnv()) {
                    map.put(envVar.getName(), envVar.getValue());
                }
            }
            return map;
        }
    }
    throw new KafkaUpgradeException("Could not find '" + containerName + "' container in StatefulSet " + sts.getMetadata().getName());
}
 
Example 9
Source File: CruiseControlTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public String getCapacityConfigurationFromEnvVar(Kafka resource, String envVar) {
    CruiseControl cc = CruiseControl.fromCrd(resource, VERSIONS);
    Deployment dep = cc.generateDeployment(true, null, null, null);
    List<Container> containers = dep.getSpec().getTemplate().getSpec().getContainers();

    // checks on the main Cruise Control container
    Container ccContainer = containers.stream().filter(container -> ccImage.equals(container.getImage())).findFirst().get();
    List<EnvVar> ccEnvVars = ccContainer.getEnv();

    return ccEnvVars.stream().filter(var -> envVar.equals(var.getName())).map(EnvVar::getValue).findFirst().get();
}
 
Example 10
Source File: BaseST.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getImagesFromConfig() {
    Map<String, String> images = new HashMap<>();
    LOGGER.info(ResourceManager.getCoDeploymentName());
    for (Container c : kubeClient().getDeployment(ResourceManager.getCoDeploymentName()).getSpec().getTemplate().getSpec().getContainers()) {
        for (EnvVar envVar : c.getEnv()) {
            images.put(envVar.getName(), envVar.getValue());
        }
    }
    return images;
}
 
Example 11
Source File: KubeUtil.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static void applyDesiredEnvironment(Container actualContainer, Container desiredContainer) {
    List<EnvVar> desiredEnv = desiredContainer.getEnv();
    if (desiredEnv != null && !desiredEnv.isEmpty()) {
        if (actualContainer.getEnv() == null || actualContainer.getEnv().isEmpty()) {
            actualContainer.setEnv(desiredEnv);
        } else {
            Set<String> newNames = desiredEnv.stream().map(EnvVar::getName).collect(Collectors.toSet());
            List<EnvVar> current = new ArrayList<>(actualContainer.getEnv());
            current.removeIf(e -> e.getName() != null && newNames.contains(e.getName()));
            current.addAll(desiredEnv);
            actualContainer.setEnv(current);
        }
    }
}
 
Example 12
Source File: EnvVars.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Applies the specified env vars list to the specified containers.
 *
 * <p>If a container does not have the corresponding env - it will be provisioned, if it has - the
 * value will be overridden.
 *
 * @param container pod to supply env vars
 * @param toApply env vars to apply
 */
public void apply(Container container, List<? extends Env> toApply) {
  List<EnvVar> targetEnv = container.getEnv();
  if (targetEnv == null) {
    targetEnv = new ArrayList<>();
    container.setEnv(targetEnv);
  }

  for (Env env : toApply) {
    apply(targetEnv, env);
  }
}
 
Example 13
Source File: PodTemplateBuilderTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private void validateContainers(Pod pod, KubernetesSlave slave, boolean directConnection) {
    String[] exclusions = new String[] {"JENKINS_URL", "JENKINS_SECRET", "JENKINS_NAME", "JENKINS_AGENT_NAME", "JENKINS_AGENT_WORKDIR"};
    for (Container c : pod.getSpec().getContainers()) {
        if ("jnlp".equals(c.getName())) {
            validateJnlpContainer(c, slave, directConnection);
        } else {
            List<EnvVar> env = c.getEnv();
            assertThat(env.stream().map(EnvVar::getName).collect(toList()), everyItem(not(isIn(exclusions))));
        }
    }
}
 
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());
            }
        }
    }
}