io.fabric8.kubernetes.api.model.EnvVar Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.EnvVar. 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: EntityUserOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityUserOperatorEnvVarValidityAndRenewal() {
    int validity = 100;
    int renewal = 42;
    Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas,
            image, healthDelay, healthTimeout, singletonMap("animal", "wombat"), singletonMap("foo", "bar"), emptyMap()))
            .editSpec()
            .withNewClientsCa()
            .withRenewalDays(renewal)
            .withValidityDays(validity)
            .endClientsCa()
            .withNewEntityOperator()
            .withNewUserOperator()
            .endUserOperator()
            .endEntityOperator()
            .endSpec()
            .build();

    EntityUserOperator f = EntityUserOperator.fromCrd(kafkaAssembly);
    List<EnvVar> envvar = f.getEnvVars();
    assertThat(Integer.parseInt(envvar.stream().filter(a -> a.getName().equals(EntityUserOperator.ENV_VAR_CLIENTS_CA_VALIDITY)).findFirst().get().getValue()), is(validity));
    assertThat(Integer.parseInt(envvar.stream().filter(a -> a.getName().equals(EntityUserOperator.ENV_VAR_CLIENTS_CA_RENEWAL)).findFirst().get().getValue()), is(renewal));
}
 
Example #2
Source File: KafkaConnectClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidExternalConfigurationEnvs() {
    ExternalConfigurationEnv env = new ExternalConfigurationEnvBuilder()
            .withName("MY_ENV_VAR")
            .withNewValueFrom()
                .withConfigMapKeyRef(new ConfigMapKeySelectorBuilder().withName("my-map").withKey("my-key").withOptional(false).build())
                .withSecretKeyRef(new SecretKeySelectorBuilder().withName("my-secret").withKey("my-key").withOptional(false).build())
            .endValueFrom()
            .build();

    KafkaConnect resource = new KafkaConnectBuilder(this.resource)
            .editSpec()
            .withNewExternalConfiguration()
            .withEnv(env)
            .endExternalConfiguration()
            .endSpec()
            .build();
    KafkaConnectCluster kc = KafkaConnectCluster.fromCrd(resource, VERSIONS);

    // Check Deployment
    Deployment dep = kc.generateDeployment(emptyMap(), true, null, null);
    List<EnvVar> envs = dep.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv();
    List<EnvVar> selected = envs.stream().filter(var -> var.getName().equals("MY_ENV_VAR")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #3
Source File: EnvVarsTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(dataProvider = "detectReferencesTestValues")
public void shouldDetectReferences(String value, Set<EnvVar> expected, String caseName) {
  assertEquals(
      extractReferencedVariables(var("name", value)), expected, caseName + ": just value");
  assertEquals(
      extractReferencedVariables(var("name", "v" + value)),
      expected,
      caseName + ": value with prefix");
  assertEquals(
      extractReferencedVariables(var("name", "v" + value + "v")),
      expected,
      caseName + ": value with prefix and postfix");
  assertEquals(
      extractReferencedVariables(var("name", value + "v")),
      expected,
      caseName + ": value with postfix");
}
 
Example #4
Source File: DefaultContainerFactoryTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void create() {
	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();
	DefaultContainerFactory defaultContainerFactory = new DefaultContainerFactory(
			kubernetesDeployerProperties);

	AppDefinition definition = new AppDefinition("app-test", null);
	Resource resource = getResource();
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.limits.memory", "128Mi");
	props.put("spring.cloud.deployer.kubernetes.environment-variables",
			"JAVA_OPTIONS=-Xmx64m,KUBERNETES_NAMESPACE=test-space");
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition,
			resource, props);

	ContainerConfiguration containerConfiguration = new ContainerConfiguration("app-test", appDeploymentRequest);
	Container container = defaultContainerFactory.create(containerConfiguration);
	assertNotNull(container);
	assertEquals(3, container.getEnv().size());
	EnvVar envVar1 = container.getEnv().get(0);
	EnvVar envVar2 = container.getEnv().get(1);
	assertEquals("JAVA_OPTIONS", envVar1.getName());
	assertEquals("-Xmx64m", envVar1.getValue());
	assertEquals("KUBERNETES_NAMESPACE", envVar2.getName());
	assertEquals("test-space", envVar2.getValue());
}
 
Example #5
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 #6
Source File: DockerimageComponentToWorkspaceApplier.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private List<HasMetadata> createComponentObjects(
    ComponentImpl dockerimageComponent, String machineName) {
  List<HasMetadata> componentObjects = new ArrayList<>();
  Deployment deployment =
      buildDeployment(
          machineName,
          dockerimageComponent.getImage(),
          dockerimageComponent.getMemoryLimit(),
          dockerimageComponent.getCpuRequest(),
          dockerimageComponent.getCpuLimit(),
          dockerimageComponent
              .getEnv()
              .stream()
              .map(e -> new EnvVar(e.getName(), e.getValue(), null))
              .collect(Collectors.toCollection(ArrayList::new)),
          dockerimageComponent.getCommand(),
          dockerimageComponent.getArgs());
  componentObjects.add(deployment);

  return componentObjects;
}
 
Example #7
Source File: KafkaMirrorMaker2ClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidExternalConfigurationEnvs() {
    ExternalConfigurationEnv env = new ExternalConfigurationEnvBuilder()
            .withName("MY_ENV_VAR")
            .withNewValueFrom()
                .withConfigMapKeyRef(new ConfigMapKeySelectorBuilder().withName("my-map").withKey("my-key").withOptional(false).build())
                .withSecretKeyRef(new SecretKeySelectorBuilder().withName("my-secret").withKey("my-key").withOptional(false).build())
            .endValueFrom()
            .build();

    KafkaMirrorMaker2 resource = new KafkaMirrorMaker2Builder(this.resource)
            .editSpec()
            .withNewExternalConfiguration()
            .withEnv(env)
            .endExternalConfiguration()
            .endSpec()
            .build();
    KafkaMirrorMaker2Cluster kmm2 = KafkaMirrorMaker2Cluster.fromCrd(resource, VERSIONS);

    // Check Deployment
    Deployment dep = kmm2.generateDeployment(emptyMap(), true, null, null);
    List<EnvVar> envs = getContainer(dep).getEnv();
    List<EnvVar> selected = envs.stream().filter(var -> var.getName().equals("MY_ENV_VAR")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #8
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidExternalConfigurationEnvs() {
    ExternalConfigurationEnv env = new ExternalConfigurationEnvBuilder()
            .withName("MY_ENV_VAR")
            .withNewValueFrom()
                .withConfigMapKeyRef(new ConfigMapKeySelectorBuilder().withName("my-map").withKey("my-key").withOptional(false).build())
                .withSecretKeyRef(new SecretKeySelectorBuilder().withName("my-secret").withKey("my-key").withOptional(false).build())
            .endValueFrom()
            .build();

    KafkaConnectS2I resource = new KafkaConnectS2IBuilder(this.resource)
            .editSpec()
                .withNewExternalConfiguration()
                    .withEnv(env)
                .endExternalConfiguration()
            .endSpec()
            .build();
    KafkaConnectS2ICluster kc = KafkaConnectS2ICluster.fromCrd(resource, VERSIONS);

    // Check Deployment
    DeploymentConfig dep = kc.generateDeploymentConfig(Collections.EMPTY_MAP, true, null, null);
    List<EnvVar> envs = dep.getSpec().getTemplate().getSpec().getContainers().get(0).getEnv();
    List<EnvVar> selected = envs.stream().filter(var -> var.getName().equals("MY_ENV_VAR")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #9
Source File: KafkaConnectClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testJvmOptions() {
    Map<String, String> xx = new HashMap<>(2);
    xx.put("UseG1GC", "true");
    xx.put("MaxGCPauseMillis", "20");

    KafkaConnect resource = new KafkaConnectBuilder(this.resource)
            .editSpec()
                .withNewJvmOptions()
                    .withNewXms("512m")
                    .withNewXmx("1024m")
                    .withNewServer(true)
                    .withXx(xx)
                .endJvmOptions()
            .endSpec()
            .build();
    KafkaConnectCluster kc = KafkaConnectCluster.fromCrd(resource, VERSIONS);

    Deployment dep = kc.generateDeployment(Collections.EMPTY_MAP, true, null, null);
    Container cont = dep.getSpec().getTemplate().getSpec().getContainers().get(0);
    assertThat(cont.getEnv().stream().filter(env -> "KAFKA_JVM_PERFORMANCE_OPTS".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").contains("-server"), is(true));
    assertThat(cont.getEnv().stream().filter(env -> "KAFKA_JVM_PERFORMANCE_OPTS".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").contains("-XX:+UseG1GC"), is(true));
    assertThat(cont.getEnv().stream().filter(env -> "KAFKA_JVM_PERFORMANCE_OPTS".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").contains("-XX:MaxGCPauseMillis=20"), is(true));
    assertThat(cont.getEnv().stream().filter(env -> "KAFKA_HEAP_OPTS".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").contains("-Xmx1024m"), is(true));
    assertThat(cont.getEnv().stream().filter(env -> "KAFKA_HEAP_OPTS".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").contains("-Xms512m"), is(true));
}
 
Example #10
Source File: KafkaMirrorMaker2ClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testExternalConfigurationConfigEnvs() {
    ExternalConfigurationEnv env = new ExternalConfigurationEnvBuilder()
            .withName("MY_ENV_VAR")
            .withNewValueFrom()
                .withConfigMapKeyRef(new ConfigMapKeySelectorBuilder().withName("my-map").withKey("my-key").withOptional(false).build())
            .endValueFrom()
            .build();

    KafkaMirrorMaker2 resource = new KafkaMirrorMaker2Builder(this.resource)
            .editSpec()
            .withNewExternalConfiguration()
                .withEnv(env)
            .endExternalConfiguration()
            .endSpec()
            .build();
    KafkaMirrorMaker2Cluster kmm2 = KafkaMirrorMaker2Cluster.fromCrd(resource, VERSIONS);

    // Check Deployment
    Deployment dep = kmm2.generateDeployment(emptyMap(), true, null, null);
    List<EnvVar> envs = getContainer(dep).getEnv();
    List<EnvVar> selected = envs.stream().filter(var -> var.getName().equals("MY_ENV_VAR")).collect(Collectors.toList());
    assertThat(selected.size(), is(1));
    assertThat(selected.get(0).getName(), is("MY_ENV_VAR"));
    assertThat(selected.get(0).getValueFrom().getConfigMapKeyRef(), is(env.getValueFrom().getConfigMapKeyRef()));
}
 
Example #11
Source File: ZookeeperCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Override
protected List<EnvVar> getEnvVars() {
    List<EnvVar> varList = new ArrayList<>();
    varList.add(buildEnvVar(ENV_VAR_ZOOKEEPER_METRICS_ENABLED, String.valueOf(isMetricsEnabled)));
    varList.add(buildEnvVar(ENV_VAR_ZOOKEEPER_SNAPSHOT_CHECK_ENABLED, String.valueOf(isSnapshotCheckEnabled)));
    varList.add(buildEnvVar(ENV_VAR_STRIMZI_KAFKA_GC_LOG_ENABLED, String.valueOf(gcLoggingEnabled)));
    if (javaSystemProperties != null) {
        varList.add(buildEnvVar(ENV_VAR_STRIMZI_JAVA_SYSTEM_PROPERTIES, ModelUtils.getJavaSystemPropertiesToString(javaSystemProperties)));
    }

    heapOptions(varList, 0.75, 2L * 1024L * 1024L * 1024L);
    jvmPerformanceOptions(varList);
    varList.add(buildEnvVar(ENV_VAR_ZOOKEEPER_CONFIGURATION, configuration.getConfiguration()));

    // Add shared environment variables used for all containers
    varList.addAll(getSharedEnvVars());

    addContainerEnvsToExistingEnvs(varList, templateZookeeperContainerEnvVars);

    return varList;
}
 
Example #12
Source File: KafkaMirrorMakerClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
protected List<EnvVar> getExpectedEnvVars() {

        List<EnvVar> expected = new ArrayList<>();

        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_CONFIGURATION_CONSUMER).withValue(expectedConsumerConfiguration).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_CONFIGURATION_PRODUCER).withValue(expectedProducerConfiguration).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_METRICS_ENABLED).withValue("true").build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_BOOTSTRAP_SERVERS_CONSUMER).withValue(consumerBootstrapServers).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_BOOTSTRAP_SERVERS_PRODUCER).withValue(producerBootstrapServers).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_WHITELIST).withValue(whitelist).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_GROUPID_CONSUMER).withValue(groupId).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_NUMSTREAMS).withValue(Integer.toString(numStreams)).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_OFFSET_COMMIT_INTERVAL).withValue(Integer.toString(offsetCommitInterval)).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_ABORT_ON_SEND_FAILURE).withValue(Boolean.toString(abortOnSendFailure)).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_STRIMZI_KAFKA_GC_LOG_ENABLED).withValue(Boolean.toString(AbstractModel.DEFAULT_JVM_GC_LOGGING_ENABLED)).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_HEAP_OPTS).withValue(kafkaHeapOpts).build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_STRIMZI_LIVENESS_PERIOD).withValue("10").build());
        expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_STRIMZI_READINESS_PERIOD).withValue("10").build());

        return expected;
    }
 
Example #13
Source File: ProxySettingsProvisioner.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Traced
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity)
    throws InfrastructureException {

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

  if (!proxyEnvVars.isEmpty()) {
    k8sEnv
        .getPodsData()
        .entrySet()
        .stream()
        // JWTProxy container doesn't need proxy settings since it never does any outbound
        // requests, and setting of it may fail accessing internal addresses.
        .filter(entry -> !entry.getKey().equals(JWT_PROXY_POD_NAME))
        .flatMap(
            entry ->
                Stream.concat(
                    entry.getValue().getSpec().getContainers().stream(),
                    entry.getValue().getSpec().getInitContainers().stream()))
        .forEach(
            container ->
                proxyEnvVars.forEach((k, v) -> container.getEnv().add(new EnvVar(k, v, null))));
  }
}
 
Example #14
Source File: ProxySettingsProvisionerTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNotApplyProxySettingsToJWTProxyContainer() throws Exception {

  Map<String, Pod> pods = new HashMap<>();
  pods.put(JWT_PROXY_POD_NAME, buildPod(JWT_PROXY_POD_NAME, buildContainers(2)));

  KubernetesEnvironment k8sEnv = KubernetesEnvironment.builder().setPods(pods).build();
  provisioner.provision(k8sEnv, runtimeId);

  assertTrue(
      k8sEnv
          .getPodsData()
          .values()
          .stream()
          .filter(pod -> pod.getMetadata().getName().equals(JWT_PROXY_POD_NAME))
          .flatMap(pod -> pod.getSpec().getContainers().stream())
          .noneMatch(
              container ->
                  container.getEnv().contains(new EnvVar(HTTP_PROXY, HTTP_PROXY_VALUE, null))
                      || container
                          .getEnv()
                          .contains(new EnvVar(HTTPS_PROXY, HTTPS_PROXY_VALUE, null))
                      || container
                          .getEnv()
                          .contains(new EnvVar(NO_PROXY, NO_PROXY_VALUE, null))));
}
 
Example #15
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void deployWithEnvironmentWithMultipleCommaDelimitedValue() throws Exception {
	AppDefinition definition = new AppDefinition("app-test", null);
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.environmentVariables",
			"JAVA_TOOL_OPTIONS='thing1,thing2',OPTS='thing3, thing4'");

	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	deployer = new KubernetesAppDeployer(bindDeployerProperties(), null);
	PodSpec podSpec = deployer.createPodSpec(appDeploymentRequest);

	assertThat(podSpec.getContainers().get(0).getEnv())
			.contains(
				new EnvVar("JAVA_TOOL_OPTIONS", "thing1,thing2", null),
				new EnvVar("OPTS", "thing3, thing4", null));
}
 
Example #16
Source File: PodTemplateBuilderTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
private void validateJnlpContainer(Container jnlp, KubernetesSlave slave, boolean directConnection) {
    assertThat(jnlp.getCommand(), empty());
    List<EnvVar> envVars = Lists.newArrayList();
    if (slave != null) {
        assertThat(jnlp.getArgs(), empty());
        if(directConnection) {
          envVars.add(new EnvVar("JENKINS_PROTOCOLS", JENKINS_PROTOCOLS, null));
          envVars.add(new EnvVar("JENKINS_DIRECT_CONNECTION", "localhost:" + Jenkins.get().getTcpSlaveAgentListener().getAdvertisedPort(), null));
          envVars.add(new EnvVar("JENKINS_INSTANCE_IDENTITY", Jenkins.get().getTcpSlaveAgentListener().getIdentityPublicKey(), null));
        } else {
          envVars.add(new EnvVar("JENKINS_URL", JENKINS_URL, null));
        }
        envVars.add(new EnvVar("JENKINS_SECRET", AGENT_SECRET, null));
        envVars.add(new EnvVar("JENKINS_NAME", AGENT_NAME, null));
        envVars.add(new EnvVar("JENKINS_AGENT_NAME", AGENT_NAME, null));
        envVars.add(new EnvVar("JENKINS_AGENT_WORKDIR", ContainerTemplate.DEFAULT_WORKING_DIR, null));
    } else {
        assertThat(jnlp.getArgs(), empty());
    }
    assertThat(jnlp.getEnv(), containsInAnyOrder(envVars.toArray(new EnvVar[envVars.size()])));
}
 
Example #17
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 #18
Source File: KafkaMirrorMakerCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the consumer related environment variables in the provided List.
 *
 * @param varList   List with environment variables
 */
private void addConsumerEnvVars(List<EnvVar> varList) {
    if (consumer.getTls() != null) {
        varList.add(buildEnvVar(ENV_VAR_KAFKA_MIRRORMAKER_TLS_CONSUMER, "true"));

        if (consumer.getTls().getTrustedCertificates() != null && consumer.getTls().getTrustedCertificates().size() > 0) {
            StringBuilder sb = new StringBuilder();
            boolean separator = false;
            for (CertSecretSource certSecretSource : consumer.getTls().getTrustedCertificates()) {
                if (separator) {
                    sb.append(";");
                }
                sb.append(certSecretSource.getSecretName() + "/" + certSecretSource.getCertificate());
                separator = true;
            }
            varList.add(buildEnvVar(ENV_VAR_KAFKA_MIRRORMAKER_TRUSTED_CERTS_CONSUMER, sb.toString()));
        }
    }

    AuthenticationUtils.configureClientAuthenticationEnvVars(consumer.getAuthentication(), varList, name -> ENV_VAR_PREFIX + name + "_CONSUMER");
}
 
Example #19
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
private void testEnvironmentVariables(KubernetesSchedulerProperties kubernetesSchedulerProperties,
		Map<String, String> schedulerProperties, EnvVar[] expectedVars) {
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, schedulerProperties,
			null, getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);

	assertTrue("Environment variables should not be empty", !container.getEnv().isEmpty());

	assertThat(container.getEnv()).contains(expectedVars);

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #20
Source File: EnvVars.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Looks at the value of the provided environment variable and returns a set of environment
 * variable references in the Kubernetes convention of {@literal $(VAR_NAME)}.
 *
 * <p>See <a
 * href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/#envvar-v1-core">API
 * docs</a> and/or <a
 * href="https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/#using-environment-variables-inside-of-your-config">documentation</a>.
 *
 * @param var the environment variable to analyze
 * @return a set of variable references, never null
 */
public static Set<String> extractReferencedVariables(EnvVar var) {
  String val = var.getValue();

  Matcher matcher = REFERENCE_PATTERN.matcher(val);

  // let's just keep the initial size small, because usually there are not that many references
  // present.
  Set<String> ret = new HashSet<>(2);

  while (matcher.find()) {
    int start = matcher.start();

    // the variable reference can be escaped using a double $, e.g. $$(VAR) is not a reference
    if (start > 0 && val.charAt(start - 1) == '$') {
      continue;
    }

    // extract the variable name out of the reference $(NAME) -> NAME
    String refName = matcher.group().substring(2, matcher.group().length() - 1);
    ret.add(refName);
  }

  return ret;
}
 
Example #21
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomEnvironmentVariablesOverrideGlobal() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	kubernetesSchedulerProperties.setEnvironmentVariables(new String[] { "MYVAR1=MYVAL1", "MYVAR2=MYVAL2" });

	String prefix = KubernetesSchedulerProperties.KUBERNETES_SCHEDULER_PROPERTIES_PREFIX;

	Map<String, String> schedulerProperties = new HashMap<>(getSchedulerProperties());
	schedulerProperties.put(prefix + ".environmentVariables", "MYVAR2=OVERRIDE");

	EnvVar[] expectedVars = new EnvVar[] { new EnvVar("MYVAR1", "MYVAL1", null),
			new EnvVar("MYVAR2", "OVERRIDE", null) };

	testEnvironmentVariables(kubernetesSchedulerProperties, schedulerProperties, expectedVars);
}
 
Example #22
Source File: SimpleRunContainerProviderTest.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
public void validate_all_parameters(){
  final Pod podTemplate = createTemplate(createMap(CloudImageParameters.SOURCE_ID_FIELD, "image1",
                                                        KubeParametersConstants.DOCKER_IMAGE, "jetbrains/teamcity-agent",
                                                        KubeParametersConstants.AGENT_NAME_PREFIX, "prefix"));
  then(podTemplate.getKind()).isEqualTo("Pod");
  final List<Container> containers = podTemplate.getSpec().getContainers();
  then(containers).hasSize(1);
  final Container container = containers.get(0);

  then(container).isNotNull();
  then(container.getImage()).isEqualTo("jetbrains/teamcity-agent");
  then(container.getCommand()).isEmpty();
  then(container.getImagePullPolicy()).isEqualTo(ImagePullPolicy.IfNotPresent.getName());
  then(container.getWorkingDir()).isNull();
  then(container.getEnv()).hasSize(6).containsOnly(
    new EnvVar(KubeContainerEnvironment.SERVER_URL, "server address", null),
    new EnvVar(KubeContainerEnvironment.SERVER_UUID, "SERVER-UUID", null),
    new EnvVar(KubeContainerEnvironment.OFFICIAL_IMAGE_SERVER_URL, "server address", null),
    new EnvVar(KubeContainerEnvironment.IMAGE_NAME, "image1", null),
    new EnvVar(KubeContainerEnvironment.PROFILE_ID, "profile id", null),
    new EnvVar(KubeContainerEnvironment.INSTANCE_NAME, "prefix-1", null)
  );
}
 
Example #23
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 #24
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testGlobalAndCustomEnvironmentVariables() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	kubernetesSchedulerProperties.setEnvironmentVariables(new String[] { "MYVAR1=MYVAL1","MYVAR2=MYVAL2" });

	String prefix = KubernetesSchedulerProperties.KUBERNETES_SCHEDULER_PROPERTIES_PREFIX;

	Map<String, String> schedulerProperties = new HashMap<>(getSchedulerProperties());
	schedulerProperties.put(prefix + ".environmentVariables", "MYVAR3=MYVAL3,MYVAR4=MYVAL4");

	EnvVar[] expectedVars = new EnvVar[] { new EnvVar("MYVAR1", "MYVAL1", null),
			new EnvVar("MYVAR2", "MYVAL2", null), new EnvVar("MYVAR3", "MYVAL3", null),
			new EnvVar("MYVAR4", "MYVAL4", null) };

	testEnvironmentVariables(kubernetesSchedulerProperties, schedulerProperties, expectedVars);
}
 
Example #25
Source File: NewIntegrationTestBuildCommand.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    String buildConfigName = buildName.getValue();
    Objects.assertNotNull(buildConfigName, "buildName");
    Map<String, String> labels = BuildConfigs.createBuildLabels(buildConfigName);
    String gitUrlText = getOrFindGitUrl(context, gitUri.getValue());
    String imageText = image.getValue();
    List<EnvVar> envVars = createEnvVars(buildConfigName, gitUrlText, mavenCommand.getValue());
    BuildConfig buildConfig = BuildConfigs.createIntegrationTestBuildConfig(buildConfigName, labels, gitUrlText, imageText, envVars);

    LOG.info("Generated BuildConfig: " + toJson(buildConfig));

    ImageStream imageRepository = BuildConfigs.imageRepository(buildConfigName, labels);

    Controller controller = createController();
    controller.applyImageStream(imageRepository, "generated ImageStream: " + toJson(imageRepository));
    controller.applyBuildConfig(buildConfig, "generated BuildConfig: " + toJson(buildConfig));
    return Results.success("Added BuildConfig: " + Builds.getName(buildConfig) + " to OpenShift at master: " + getKubernetes().getMasterUrl());
}
 
Example #26
Source File: AuthenticationUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Configured environment variables related to authentication in Kafka clients
 *
 * @param authentication    Authentication object with auth configuration
 * @param varList   List where the new environment variables should be added
 * @param envVarNamer   Function for naming the environment variables (ech components is using different names)
 */
public static void configureClientAuthenticationEnvVars(KafkaClientAuthentication authentication, List<EnvVar> varList, Function<String, String> envVarNamer)   {
    if (authentication != null) {

        for (Entry<String, String> entry: getClientAuthenticationProperties(authentication).entrySet()) {
            varList.add(AbstractModel.buildEnvVar(envVarNamer.apply(entry.getKey()), entry.getValue()));
        }
        
        if (authentication instanceof KafkaClientAuthenticationOAuth) {
            KafkaClientAuthenticationOAuth oauth = (KafkaClientAuthenticationOAuth) authentication;

            if (oauth.getClientSecret() != null)    {
                varList.add(AbstractModel.buildEnvVarFromSecret(envVarNamer.apply("OAUTH_CLIENT_SECRET"), oauth.getClientSecret().getSecretName(), oauth.getClientSecret().getKey()));
            }

            if (oauth.getAccessToken() != null)    {
                varList.add(AbstractModel.buildEnvVarFromSecret(envVarNamer.apply("OAUTH_ACCESS_TOKEN"), oauth.getAccessToken().getSecretName(), oauth.getAccessToken().getKey()));
            }

            if (oauth.getRefreshToken() != null)    {
                varList.add(AbstractModel.buildEnvVarFromSecret(envVarNamer.apply("OAUTH_REFRESH_TOKEN"), oauth.getRefreshToken().getSecretName(), oauth.getRefreshToken().getKey()));
            }
        }
    }
}
 
Example #27
Source File: KubernetesDockerRunnerPodResourceTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnableTerminationLoggingWhenTrue() {
  Pod pod = createPod(
      WORKFLOW_INSTANCE,
      DockerRunner.RunSpec.builder()
          .executionId("eid")
          .imageName("busybox")
          .terminationLogging(true)
          .build(),
      EMPTY_SECRET_SPEC);

  Map<String, String> annotations = pod.getMetadata().getAnnotations();
  assertThat(annotations.get(DOCKER_TERMINATION_LOGGING_ANNOTATION), is("true"));

  List<Container> containers = pod.getSpec().getContainers();
  Optional<EnvVar> terminationLogVar = containers.get(0).getEnv().stream()
      .filter(e -> TERMINATION_LOG.equals(e.getName())).findAny();
  assertThat(terminationLogVar.orElseThrow().getValue(), is("/dev/termination-log"));
}
 
Example #28
Source File: HadoopConfMountDecoratorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testMainContainerWithHadoopConfVolumeMount() throws IOException {
	setHadoopConfDirEnv();
	generateHadoopConfFileItems();
	final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);

	final List<VolumeMount> resultVolumeMounts = resultFlinkPod.getMainContainer().getVolumeMounts();
	assertEquals(1, resultVolumeMounts.size());
	final VolumeMount resultVolumeMount = resultVolumeMounts.get(0);
	assertEquals(Constants.HADOOP_CONF_VOLUME, resultVolumeMount.getName());
	assertEquals(Constants.HADOOP_CONF_DIR_IN_POD, resultVolumeMount.getMountPath());

	final Map<String, String> expectedEnvs = new HashMap<String, String>() {
		{
			put(Constants.ENV_HADOOP_CONF_DIR, Constants.HADOOP_CONF_DIR_IN_POD);
		}
	};
	final Map<String, String> resultEnvs = resultFlinkPod.getMainContainer().getEnv()
		.stream().collect(Collectors.toMap(EnvVar::getName, EnvVar::getValue));
	assertEquals(expectedEnvs, resultEnvs);
}
 
Example #29
Source File: KafkaMirrorMakerClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultProbes() {
    KafkaMirrorMakerCluster mmc = KafkaMirrorMakerCluster.fromCrd(this.resource, VERSIONS);

    Deployment dep = mmc.generateDeployment(Collections.EMPTY_MAP, true, null, null);
    Container cont = dep.getSpec().getTemplate().getSpec().getContainers().get(0);
    Probe livenessProbe = cont.getLivenessProbe();
    Probe readinessProbe = cont.getReadinessProbe();

    assertThat(livenessProbe.getExec().getCommand().get(0), is("/opt/kafka/kafka_mirror_maker_liveness.sh"));
    assertThat(livenessProbe.getInitialDelaySeconds(), is(new Integer(60)));
    assertThat(livenessProbe.getTimeoutSeconds(), is(new Integer(5)));

    assertThat(readinessProbe.getExec().getCommand().size(), is(3));
    assertThat(readinessProbe.getExec().getCommand().get(0), is("test"));
    assertThat(readinessProbe.getExec().getCommand().get(1), is("-f"));
    assertThat(readinessProbe.getExec().getCommand().get(2), is("/tmp/mirror-maker-ready"));
    assertThat(readinessProbe.getInitialDelaySeconds(), is(new Integer(60)));
    assertThat(readinessProbe.getTimeoutSeconds(), is(new Integer(5)));

    assertThat(cont.getEnv().stream().filter(env -> "STRIMZI_READINESS_PERIOD".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").equals("10"), is(true));
    assertThat(cont.getEnv().stream().filter(env -> "STRIMZI_LIVENESS_PERIOD".equals(env.getName())).map(EnvVar::getValue).findFirst().orElse("").equals("10"), is(true));
}
 
Example #30
Source File: KafkaMirrorMaker2ClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
protected List<EnvVar> getExpectedEnvVars() {
    List<EnvVar> expected = new ArrayList<>();
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMaker2Cluster.ENV_VAR_KAFKA_CONNECT_CONFIGURATION).withValue(expectedConfiguration.asPairs()).build());
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMaker2Cluster.ENV_VAR_KAFKA_CONNECT_METRICS_ENABLED).withValue(String.valueOf(true)).build());
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMaker2Cluster.ENV_VAR_KAFKA_CONNECT_BOOTSTRAP_SERVERS).withValue(bootstrapServers).build());
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMaker2Cluster.ENV_VAR_STRIMZI_KAFKA_GC_LOG_ENABLED).withValue(Boolean.toString(AbstractModel.DEFAULT_JVM_GC_LOGGING_ENABLED)).build());
    expected.add(new EnvVarBuilder().withName(AbstractModel.ENV_VAR_KAFKA_HEAP_OPTS).withValue(kafkaHeapOpts).build());
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMaker2Cluster.ENV_VAR_KAFKA_MIRRORMAKER_2_CLUSTERS).withValue(targetClusterAlias).build());
    return expected;
}