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

The following examples show how to use io.fabric8.kubernetes.api.model.EnvVarBuilder. 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: ContainerHandler.java    From jkube with Eclipse Public License 2.0 7 votes vote down vote up
private List<EnvVar> getEnvVars(ResourceConfig config) {
    List<EnvVar> envVars = KubernetesHelper.convertToEnvVarList(config.getEnv());

    // TODO: This should go into an extra enricher so that this behaviour can be switched on / off
    envVars.removeIf(obj -> obj.getName().equals("KUBERNETES_NAMESPACE"));
    envVars.add(0,
        new EnvVarBuilder()
            .withName("KUBERNETES_NAMESPACE")
            .withNewValueFrom()
              .withNewFieldRef()
                 .withFieldPath("metadata.namespace")
              .endFieldRef()
            .endValueFrom()
            .build());

    return envVars;
}
 
Example #2
Source File: KafkaBridgeClusterTest.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(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_METRICS_ENABLED).withValue(String.valueOf(true)).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_STRIMZI_GC_LOG_ENABLED).withValue(String.valueOf(AbstractModel.DEFAULT_JVM_GC_LOGGING_ENABLED)).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_BOOTSTRAP_SERVERS).withValue(bootstrapServers).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_CONSUMER_CONFIG).withValue(defaultConsumerConfiguration).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_PRODUCER_CONFIG).withValue(defaultProducerConfiguration).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_ID).withValue(cluster).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_HTTP_ENABLED).withValue(String.valueOf(true)).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_HTTP_HOST).withValue(KafkaBridgeHttpConfig.HTTP_DEFAULT_HOST).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_HTTP_PORT).withValue(String.valueOf(KafkaBridgeHttpConfig.HTTP_DEFAULT_PORT)).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_CORS_ENABLED).withValue(String.valueOf(false)).build());
        expected.add(new EnvVarBuilder().withName(KafkaBridgeCluster.ENV_VAR_KAFKA_BRIDGE_AMQP_ENABLED).withValue(String.valueOf(false)).build());
        return expected;
    }
 
Example #3
Source File: ImageEnricher.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void mergeEnvVariables(Container container) {
    Optional.ofNullable(getConfiguration().getResource()).map(ResourceConfig::getEnv).ifPresent(resourceEnv -> {
        List<EnvVar> containerEnvVars = container.getEnv();
        if (containerEnvVars == null) {
            containerEnvVars = new LinkedList<>();
            container.setEnv(containerEnvVars);
        }

        for (Map.Entry<String, String> resourceEnvEntry : resourceEnv.entrySet()) {
            EnvVar newEnvVar =
                new EnvVarBuilder()
                    .withName(resourceEnvEntry.getKey())
                    .withValue(resourceEnvEntry.getValue())
                    .build();
            if (!hasEnvWithName(containerEnvVars, newEnvVar.getName())) {
                containerEnvVars.add(newEnvVar);
            } else {
                log.warn(
                    "Environment variable %s will not be overridden: trying to set the value %s, but its actual value is %s",
                    newEnvVar.getName(), newEnvVar.getValue(), getEnvValue(containerEnvVars, newEnvVar.getName()));
            }
        }
    });
}
 
Example #4
Source File: EntityUserOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private List<EnvVar> getExpectedEnvVars() {
    List<EnvVar> expected = new ArrayList<>();
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_ZOOKEEPER_CONNECT).withValue(String.format("%s:%d", "localhost", EntityUserOperatorSpec.DEFAULT_ZOOKEEPER_PORT)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_KAFKA_BOOTSTRAP_SERVERS).withValue(String.format("%s:%d", "foo-kafka-bootstrap", EntityUserOperatorSpec.DEFAULT_BOOTSTRAP_SERVERS_PORT)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_WATCHED_NAMESPACE).withValue(uoWatchedNamespace).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_RESOURCE_LABELS).withValue(ModelUtils.defaultResourceLabels(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_FULL_RECONCILIATION_INTERVAL_MS).withValue(String.valueOf(uoReconciliationInterval * 1000)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_ZOOKEEPER_SESSION_TIMEOUT_MS).withValue(String.valueOf(uoZookeeperSessionTimeout * 1000)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLIENTS_CA_KEY_SECRET_NAME).withValue(KafkaCluster.clientsCaKeySecretName(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLIENTS_CA_CERT_SECRET_NAME).withValue(KafkaCluster.clientsCaCertSecretName(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLIENTS_CA_NAMESPACE).withValue(namespace).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLUSTER_CA_CERT_SECRET_NAME).withValue(KafkaCluster.clusterCaCertSecretName(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_EO_KEY_SECRET_NAME).withValue(EntityOperator.secretName(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_STRIMZI_GC_LOG_ENABLED).withValue(Boolean.toString(AbstractModel.DEFAULT_JVM_GC_LOGGING_ENABLED)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLIENTS_CA_VALIDITY).withValue(Integer.toString(CertificateAuthority.DEFAULT_CERTS_VALIDITY_DAYS)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_CLIENTS_CA_RENEWAL).withValue(Integer.toString(CertificateAuthority.DEFAULT_CERTS_RENEWAL_DAYS)).build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_STRIMZI_JAVA_OPTS).withValue("-Xmx256m").build());
    expected.add(new EnvVarBuilder().withName(EntityUserOperator.ENV_VAR_STRIMZI_JAVA_SYSTEM_PROPERTIES).withValue("-Djavax.net.debug=verbose -Dsomething.else=42").build());

    return expected;
}
 
Example #5
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static boolean setEnvVar(List<EnvVar> envVarList, String name, String value) {
    for (EnvVar envVar : envVarList) {
        String envVarName = envVar.getName();
        if (Objects.equals(name, envVarName)) {
            String oldValue = envVar.getValue();
            if (Objects.equals(value, oldValue)) {
                return false;
            } else {
                envVar.setValue(value);
                return true;
            }
        }
    }
    EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build();
    envVarList.add(env);
    return true;
}
 
Example #6
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 #7
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 #8
Source File: SystemtestsKubernetesApps.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static Deployment getMessagingAppDeploymentResource() {
    return new DeploymentBuilder()
            .withNewMetadata()
            .withName(MESSAGING_CLIENTS)
            .endMetadata()
            .withNewSpec()
            .withNewSelector()
            .addToMatchLabels("app", MESSAGING_CLIENTS)
            .endSelector()
            .withReplicas(1)
            .withNewTemplate()
            .withNewMetadata()
            .addToLabels("app", MESSAGING_CLIENTS)
            .endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName(MESSAGING_CLIENTS)
            .withImage("quay.io/enmasse/systemtests-clients:latest")
            .withImagePullPolicy(env.getImagePullPolicy())
            .withCommand("sleep")
            .withArgs("infinity")
            .withEnv(new EnvVarBuilder().withName("PN_TRACE_FRM").withValue("true").build())
            .endContainer()
            .endSpec()
            .endTemplate()
            .endSpec()
            .build();
}
 
Example #9
Source File: KafkaConnectClusterTest.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(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_CONFIGURATION).withValue(expectedConfiguration.asPairs()).build());
        expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_METRICS_ENABLED).withValue(String.valueOf(true)).build());
        expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_BOOTSTRAP_SERVERS).withValue(bootstrapServers).build());
        expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.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());
        return expected;
    }
 
Example #10
Source File: CruiseControlTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private List<EnvVar> getExpectedEnvVars() {
    List<EnvVar> expected = new ArrayList<>();
    expected.add(new EnvVarBuilder().withName(CruiseControl.ENV_VAR_STRIMZI_KAFKA_BOOTSTRAP_SERVERS).withValue(CruiseControl.defaultBootstrapServers(cluster)).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(CruiseControl.ENV_VAR_MIN_INSYNC_REPLICAS).withValue(minInsyncReplicas).build());
    expected.add(new EnvVarBuilder().withName(ENV_VAR_BROKER_DISK_MIB_CAPACITY).withValue(Double.toString(DEFAULT_BROKER_DISK_MIB_CAPACITY)).build());
    expected.add(new EnvVarBuilder().withName(ENV_VAR_BROKER_CPU_UTILIZATION_CAPACITY).withValue(Integer.toString(DEFAULT_BROKER_CPU_UTILIZATION_CAPACITY)).build());
    expected.add(new EnvVarBuilder().withName(ENV_VAR_BROKER_INBOUND_NETWORK_KIB_PER_SECOND_CAPACITY).withValue(Double.toString(DEFAULT_BROKER_INBOUND_NETWORK_KIB_PER_SECOND_CAPACITY)).build());
    expected.add(new EnvVarBuilder().withName(ENV_VAR_BROKER_OUTBOUND_NETWORK_KIB_PER_SECOND_CAPACITY).withValue(Double.toString(DEFAULT_BROKER_OUTBOUND_NETWORK_KIB_PER_SECOND_CAPACITY)).build());
    expected.add(new EnvVarBuilder().withName(KafkaMirrorMakerCluster.ENV_VAR_KAFKA_HEAP_OPTS).withValue(kafkaHeapOpts).build());
    expected.add(new EnvVarBuilder().withName(CruiseControl.ENV_VAR_CRUISE_CONTROL_CONFIGURATION).withValue(configuration.getConfiguration()).build());

    return expected;
}
 
Example #11
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;
}
 
Example #12
Source File: KafkaConnectS2IClusterTest.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<EnvVar>();
    expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_CONFIGURATION).withValue(expectedConfiguration.asPairs()).build());
    expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_METRICS_ENABLED).withValue(String.valueOf(true)).build());
    expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_BOOTSTRAP_SERVERS).withValue(bootstrapServers).build());
    expected.add(new EnvVarBuilder().withName(KafkaConnectCluster.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());
    return expected;
}
 
Example #13
Source File: KafkaExporterTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private List<EnvVar> getExpectedEnvVars() {
    List<EnvVar> expected = new ArrayList<>();
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_LOGGING).withValue(exporterOperatorLogging).build());
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_KAFKA_VERSION).withValue(version).build());
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_GROUP_REGEX).withValue(groupRegex).build());
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_TOPIC_REGEX).withValue(topicRegex).build());
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_KAFKA_SERVER).withValue("foo-kafka-bootstrap:" + KafkaCluster.REPLICATION_PORT).build());
    expected.add(new EnvVarBuilder().withName(KafkaExporter.ENV_VAR_KAFKA_EXPORTER_ENABLE_SARAMA).withValue("true").build());
    return expected;
}
 
Example #14
Source File: InitJobManagerDecorator.java    From flink with Apache License 2.0 5 votes vote down vote up
private List<EnvVar> getCustomizedEnvs() {
	return kubernetesJobManagerParameters.getEnvironments()
		.entrySet()
		.stream()
		.map(kv -> new EnvVarBuilder()
				.withName(kv.getKey())
				.withValue(kv.getValue())
				.build())
		.collect(Collectors.toList());
}
 
Example #15
Source File: UniqueNamesProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void rewritePodConfigMapEnv() throws Exception {
  when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);

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

  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);

  String newConfigMapName = configMap.getMetadata().getName();
  EnvVar newEnvVar = container.getEnv().iterator().next();
  assertEquals(newEnvVar.getValueFrom().getConfigMapKeyRef().getName(), newConfigMapName);
}
 
Example #16
Source File: SecretEnvVar.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public EnvVar buildEnvVar() {
    return new EnvVarBuilder() //
            .withName(getKey()) //
            .withValueFrom(new EnvVarSourceBuilder() //
                    .withSecretKeyRef(
                         (new SecretKeySelectorBuilder()
                              .withKey(secretKey)
                              .withName(secretName)
                              .withOptional(optional)
                              .build())) //
                    .build()) //
            .build();
}
 
Example #17
Source File: LoadAsTemplateTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private void assertListIsProcessed(KubernetesList list) {
  assertNotNull(list);
  assertNotNull(list.getItems());
  assertEquals(1, list.getItems().size());

  final AtomicBoolean userIsRoot = new AtomicBoolean(false);
  final AtomicBoolean passwordIsNotNull = new AtomicBoolean(false);
  final AtomicBoolean requiredIsSet = new AtomicBoolean(false);
  final AtomicBoolean optionalIsEmpty = new AtomicBoolean(false);
  new KubernetesListBuilder(list).accept(new TypedVisitor<EnvVarBuilder>() {

    @Override
    public void visit(EnvVarBuilder element) {
      if (element.getName().equals("USERNAME")) {
        userIsRoot.set(element.getValue().equals("root"));
      } else if (element.getName().equals("PASSWORD")) {
        passwordIsNotNull.set(Utils.isNotNullOrEmpty(element.getValue()));
      } else if (element.getName().equals("REQUIRED")) {
        requiredIsSet.set(Utils.isNotNullOrEmpty(element.getValue()));
      } else if (element.getName().equals("OPTIONAL")) {
        optionalIsEmpty.set(element.getValue().isEmpty());
      }
    }
  }).build();

  assertTrue(userIsRoot.get());
  assertTrue(passwordIsNotNull.get());
  assertTrue(requiredIsSet.get());
  assertTrue(optionalIsEmpty.get());
}
 
Example #18
Source File: PodPresetExamples.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
  String master = "https://192.168.42.193:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  Config config = new ConfigBuilder().withMasterUrl(master).build();
  try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
    String namespace = "default";
    log("namespace", namespace);
    Pod pod = client.pods().inNamespace(namespace).load(PodPresetExamples.class.getResourceAsStream("/pod-preset-example.yml")).get();
    log("Pod created");
    client.pods().inNamespace(namespace).create(pod);

    PodPreset podPreset = new PodPresetBuilder()
      .withNewMetadata().withName("allow-database").endMetadata()
      .withNewSpec()
      .withNewSelector().withMatchLabels(Collections.singletonMap("role", "frontend")).endSelector()
      .withEnv(new EnvVarBuilder().withName("DB_PORT").withValue("6379").build())
      .withVolumeMounts(new VolumeMountBuilder().withMountPath("/cache").withName("cache-volume").build())
      .withVolumes(new VolumeBuilder().withName("cache-volume").withEmptyDir(new EmptyDirVolumeSourceBuilder().build()).build())
      .endSpec()
      .build();

    log("Creating Pod Preset : " + podPreset.getMetadata().getName());
    client.settings().podPresets().inNamespace(namespace).create(podPreset);

    pod = client.pods().inNamespace(namespace).withName(pod.getMetadata().getName()).get();
    log("Updated pod: ");
    log(SerializationUtils.dumpAsYaml(pod));
  } catch (Exception e) {
    log("Exception occurred: ", e.getMessage());
    e.printStackTrace();
  }
}
 
Example #19
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Build an environment variable instance with the provided name from a field reference
 * using the Downward API
 *
 * @param name The name of the environment variable
 * @param field The field path from which the value is set
 *
 * @return The environment variable object
 */
protected static EnvVar buildEnvVarFromFieldRef(String name, String field) {

    EnvVarSource envVarSource = new EnvVarSourceBuilder()
            .withNewFieldRef()
                .withFieldPath(field)
            .endFieldRef()
            .build();

    return new EnvVarBuilder()
            .withName(name)
            .withValueFrom(envVarSource)
            .build();
}
 
Example #20
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Build an environment variable which will use a value from a secret
 *
 * @param name The name of the environment variable
 * @param secret The name of the secret where the value is stored
 * @param key The key under which the value is stored in the secret
 *
 * @return The environment variable object
 */
protected static EnvVar buildEnvVarFromSecret(String name, String secret, String key) {
    return new EnvVarBuilder()
            .withName(name)
            .withNewValueFrom()
                .withNewSecretKeyRef()
                    .withName(secret)
                    .withKey(key)
                .endSecretKeyRef()
            .endValueFrom()
            .build();
}
 
Example #21
Source File: EntityTopicOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private List<EnvVar> getExpectedEnvVars() {
    List<EnvVar> expected = new ArrayList<>();
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_RESOURCE_LABELS).withValue(ModelUtils.defaultResourceLabels(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_KAFKA_BOOTSTRAP_SERVERS).withValue(EntityTopicOperator.defaultBootstrapServers(cluster)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_ZOOKEEPER_CONNECT).withValue(String.format("%s:%d", "localhost", EntityTopicOperatorSpec.DEFAULT_ZOOKEEPER_PORT)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_WATCHED_NAMESPACE).withValue(toWatchedNamespace).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_FULL_RECONCILIATION_INTERVAL_MS).withValue(String.valueOf(toReconciliationInterval * 1000)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_ZOOKEEPER_SESSION_TIMEOUT_MS).withValue(String.valueOf(toZookeeperSessionTimeout * 1000)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_TOPIC_METADATA_MAX_ATTEMPTS).withValue(String.valueOf(toTopicMetadataMaxAttempts)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_TLS_ENABLED).withValue(Boolean.toString(true)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_STRIMZI_GC_LOG_ENABLED).withValue(Boolean.toString(AbstractModel.DEFAULT_JVM_GC_LOGGING_ENABLED)).build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_STRIMZI_JAVA_OPTS).withValue("-Xms128m").build());
    expected.add(new EnvVarBuilder().withName(EntityTopicOperator.ENV_VAR_STRIMZI_JAVA_SYSTEM_PROPERTIES).withValue("-Djavax.net.debug=verbose -Dsomething.else=42").build());
    return expected;
}
 
Example #22
Source File: LanderPodFactory.java    From data-highway with Apache License 2.0 5 votes vote down vote up
private EnvVar envFromFieldPath(String name, String fieldPath) {
  EnvVarSource envVarSource = new EnvVarSource();
  envVarSource.setFieldRef(new ObjectFieldSelector());
  ObjectFieldSelector fieldRef = envVarSource.getFieldRef();
  fieldRef.setFieldPath(fieldPath);
  return new EnvVarBuilder().withName(name).withValueFrom(envVarSource).build();
}
 
Example #23
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert a map of env vars to a list of K8s EnvVar objects.
 * @param envVars the name-value map containing env vars
 * @return list of converted env vars
 */
public static List<EnvVar> convertToEnvVarList(Map<String, String> envVars) {
    List<EnvVar> envList = new LinkedList<>();
    for (Map.Entry<String, String> entry : Optional.ofNullable(envVars).orElse(Collections.emptyMap()).entrySet()) {
        String name = entry.getKey();
        String value = entry.getValue();

        if (name != null) {
            EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build();
            envList.add(env);
        }
    }
    return envList;
}
 
Example #24
Source File: KubernetesHelperTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private List<EnvVar> prepareEnvVarList() {
    List<EnvVar> envVarList = new ArrayList<>();
    envVarList.add(new EnvVarBuilder().withName("env1").withValue("value1").build());
    envVarList.add(new EnvVarBuilder().withName("JAVA_OPTIONS").withValue("-Dfoo=bar -Dxyz=abc").build());
    envVarList.add(new EnvVarBuilder().withName("FOO").withValue("BAR").build());

    return envVarList;
}
 
Example #25
Source File: AddImageBuildStepDecorator.java    From dekorate with Apache License 2.0 5 votes vote down vote up
@Override
public void andThenVisit(TaskSpecFluent<?> taskSpec) {
  taskSpec.addNewStep()
        .withName(stepName)
        .withImage(BUILDER_IMAGE_REF)
        .addToEnv(new EnvVarBuilder().withName(DOCKER_CONFIG).withValue(DOCKER_CONFIG_DEFAULT).build())
        .withCommand(KANIKO_CMD)
        .addToArgs(DOCKERFILE_ARG)
        .addToArgs(CONTEXT_ARG)
        .addToArgs(IMAGE_DESTINATION_ARG)
        .addToArgs(VERBOSITY_DEBUG)
        .withWorkingDir(sourcePath(projectName))
    .endStep();
}
 
Example #26
Source File: LanderPodFactory.java    From data-highway with Apache License 2.0 4 votes vote down vote up
private EnvVar env(String name, String value) {
  return new EnvVarBuilder().withName(name).withValue(value).build();
}
 
Example #27
Source File: PodPresetTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testDelete() {
  server.expect().withPath("/apis/settings.k8s.io/v1alpha1/namespaces/test/podpresets/podpreset1").andReturn(200, new PodPresetBuilder()
    .withNewMetadata().withName("podpreset1").endMetadata()
    .withNewSpec()
    .withNewSelector().withMatchLabels(Collections.singletonMap("app", "website")).endSelector()
    .withEnv(new EnvVarBuilder()
      .withName("DB_PORT")
      .withValue("6379")
      .build())
    .withVolumeMounts(new VolumeMountBuilder()
      .withMountPath("/cache")
      .withName("cache-volume")
      .build())
    .withVolumes(
      new VolumeBuilder()
        .withName("cache-volume")
        .withEmptyDir(new EmptyDirVolumeSourceBuilder().build())
        .build())
    .endSpec()
    .build())
    .once();

  server.expect().withPath("/apis/settings.k8s.io/v1alpha1/namespaces/ns1/podpresets/podpreset2").andReturn(200, new PodPresetBuilder()
    .withNewMetadata().withName("podpreset2").endMetadata()
    .withNewSpec()
    .withNewSelector().withMatchLabels(Collections.singletonMap("app", "website")).endSelector()
    .withEnv(new EnvVarBuilder()
      .withName("DB_PORT")
      .withValue("6379")
      .build())
    .withVolumeMounts(new VolumeMountBuilder()
      .withMountPath("/cache")
      .withName("cache-volume")
      .build())
    .withVolumes(
      new VolumeBuilder()
        .withName("cache-volume")
        .withEmptyDir(new io.fabric8.kubernetes.api.model
          .EmptyDirVolumeSourceBuilder()
          .build())
        .build())
    .endSpec()
    .build())
    .once();

  KubernetesClient client = server.getClient();

  Boolean deleted = client.settings().podPresets().withName("podpreset1").delete();
  assertTrue(deleted);

  deleted = client.settings().podPresets().withName("podpreset2").delete();
  assertFalse(deleted);

  deleted = client.settings().podPresets().inNamespace("ns1").withName("podpreset2").delete();
  assertTrue(deleted);
}
 
Example #28
Source File: PodPresetTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testPodUpdate() {
  try{
    server.expect().withPath("/apis/settings.k8s.io/v1alpha1/namespaces/test/podpresets/podpreset-test").andReturn(200, new PodPresetBuilder()
      .withNewMetadata().withName("podpreset-test").endMetadata()
      .withNewSpec()
      .withNewSelector().withMatchLabels(Collections.singletonMap("app", "website")).endSelector()
      .withEnv(new EnvVarBuilder()
        .withName("DB_PORT")
        .withValue("6379")
        .build())
      .withVolumeMounts(new VolumeMountBuilder()
        .withMountPath("/cache")
        .withName("cache-volume")
        .build())
      .withVolumes(
        new VolumeBuilder()
          .withName("cache-volume")
          .withEmptyDir(new EmptyDirVolumeSourceBuilder().build())
          .build())
      .endSpec()
      .build())
      .once();

    Pod pod = new PodBuilder().withNewMetadata().withName("pod").withNamespace("test").withLabels(Collections.singletonMap("app", "website")).endMetadata()
      .withNewSpec()
      .addToContainers(new ContainerBuilder().withName("website").withImage("nginx").withImagePullPolicy("IfNotPresent").build())
      .endSpec()
      .build();
    server.expect().withPath("/api/v1/namespaces/test/pods/pod").andReturn(200, pod).once();

    KubernetesClient client = server.getClient();
    pod = client.pods().inNamespace("test").withName(pod.getMetadata().getName()).get();
    assertNotNull(pod);
    assertEquals("pod", pod.getMetadata().getName());
    assertNotNull(pod.getSpec().getVolumes().get(0).getName());
    assertEquals("cache-volume", pod.getSpec().getVolumes().get(0).getName());
    PodPreset podpreset = client.settings().podPresets().withName("podpreset-test").get();
    assertNotNull(pod.getSpec().getAdditionalProperties().get("DB_PORT"));
    assertEquals(6379, pod.getSpec().getAdditionalProperties().get("DB_PORT"));
    assertEquals("podpreset-test", podpreset.getMetadata().getName());
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example #29
Source File: KeyValueEnvVar.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public EnvVar buildEnvVar() {
    return new EnvVarBuilder().withName(getKey()).withValue(getValue()).build();
}
 
Example #30
Source File: TeiidOpenShiftClient.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected EnvVar env(String name, String value) {
    return new EnvVarBuilder().withName(name).withValue(value).build();
}