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

The following examples show how to use io.fabric8.kubernetes.api.model.VolumeMount. 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: FlinkConfMountDecoratorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoratedFlinkPodWithoutLog4jAndLogback() {
	final FlinkPod resultFlinkPod = flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod);

	final List<KeyToPath> expectedKeyToPaths = Collections.singletonList(
		new KeyToPathBuilder()
			.withKey(FLINK_CONF_FILENAME)
			.withPath(FLINK_CONF_FILENAME)
			.build());
	final List<Volume> expectedVolumes = Collections.singletonList(
		new VolumeBuilder()
			.withName(Constants.FLINK_CONF_VOLUME)
			.withNewConfigMap()
				.withName(getFlinkConfConfigMapName(CLUSTER_ID))
				.withItems(expectedKeyToPaths)
				.endConfigMap()
			.build());
	assertEquals(expectedVolumes, resultFlinkPod.getPod().getSpec().getVolumes());

	final List<VolumeMount> expectedVolumeMounts = Collections.singletonList(
		new VolumeMountBuilder()
			.withName(Constants.FLINK_CONF_VOLUME)
			.withMountPath(FLINK_CONF_DIR_IN_POD)
		.build());
	assertEquals(expectedVolumeMounts, resultFlinkPod.getMainContainer().getVolumeMounts());
}
 
Example #2
Source File: KubernetesDockerRunnerPodResourceTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotHaveSecretsMountIfNoSecret() {
  Pod pod = createPod(
      WORKFLOW_INSTANCE,
      DockerRunner.RunSpec.simple("eid", "busybox"), EMPTY_SECRET_SPEC);

  List<Volume> volumes = pod.getSpec().getVolumes();
  List<Container> containers = pod.getSpec().getContainers();
  assertThat(volumes.size(), is(0));
  assertThat(containers.size(), is(2));
  assertThat(containers.get(0).getName(), is(MAIN_CONTAINER_NAME));

  Container container = containers.get(0);
  List<VolumeMount> volumeMounts = container.getVolumeMounts();
  assertThat(volumeMounts.size(), is(0));
}
 
Example #3
Source File: AuthenticationUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Generates volume mounts needed for certificates needed to connect to OAuth server.
 * This is used in both OAuth servers and clients.
 *
 * @param volumeNamePrefix   Prefix which was used to name the secret volumes
 * @param trustedCertificates   List of certificates which should be mounted
 * @param baseVolumeMount   The Base volume into which the certificates should be mounted
 *
 * @return List of new VolumeMounts
 */
public static List<VolumeMount> configureOauthCertificateVolumeMounts(String volumeNamePrefix, List<CertSecretSource> trustedCertificates, String baseVolumeMount)   {
    List<VolumeMount> newVolumeMounts = new ArrayList<>();

    if (trustedCertificates != null && trustedCertificates.size() > 0) {
        int i = 0;

        for (CertSecretSource certSecretSource : trustedCertificates) {
            String volumeName = String.format("%s-%d", volumeNamePrefix, i);
            newVolumeMounts.add(VolumeUtils.createVolumeMount(volumeName, String.format("%s/%s-%d", baseVolumeMount, certSecretSource.getSecretName(), i)));
            i++;
        }
    }

    return newVolumeMounts;
}
 
Example #4
Source File: GitConfigProvisioner.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private void mountConfigFile(PodSpec podSpec, String gitConfigMapName, boolean addVolume) {
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(CONFIG_MAP_VOLUME_NAME)
                .withConfigMap(
                    new ConfigMapVolumeSourceBuilder().withName(gitConfigMapName).build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(CONFIG_MAP_VOLUME_NAME)
                .withMountPath(GIT_CONFIG_PATH)
                .withSubPath(GIT_CONFIG)
                .withReadOnly(false)
                .withNewReadOnly(false)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example #5
Source File: KafkaBridgeCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
protected List<VolumeMount> getVolumeMounts() {
    List<VolumeMount> volumeMountList = new ArrayList<>(1);
    volumeMountList.add(VolumeUtils.createVolumeMount(logAndMetricsConfigVolumeName, logAndMetricsConfigMountPath));

    if (tls != null) {
        List<CertSecretSource> trustedCertificates = tls.getTrustedCertificates();

        if (trustedCertificates != null && trustedCertificates.size() > 0) {
            for (CertSecretSource certSecretSource : trustedCertificates) {
                // skipping if a volume mount with same Secret name was already added
                if (!volumeMountList.stream().anyMatch(vm -> vm.getName().equals(certSecretSource.getSecretName()))) {
                    volumeMountList.add(VolumeUtils.createVolumeMount(certSecretSource.getSecretName(),
                            TLS_CERTS_BASE_VOLUME_MOUNT + certSecretSource.getSecretName()));
                }
            }
        }
    }

    AuthenticationUtils.configureClientAuthenticationVolumeMounts(authentication, volumeMountList, TLS_CERTS_BASE_VOLUME_MOUNT, PASSWORD_VOLUME_MOUNT, OAUTH_TLS_CERTS_BASE_VOLUME_MOUNT, "oauth-certs");

    return volumeMountList;
}
 
Example #6
Source File: KafkaConnectCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
protected List<VolumeMount> getVolumeMounts() {
    List<VolumeMount> volumeMountList = new ArrayList<>(1);
    volumeMountList.add(VolumeUtils.createVolumeMount(logAndMetricsConfigVolumeName, logAndMetricsConfigMountPath));

    if (tls != null) {
        List<CertSecretSource> trustedCertificates = tls.getTrustedCertificates();

        if (trustedCertificates != null && trustedCertificates.size() > 0) {
            for (CertSecretSource certSecretSource : trustedCertificates) {
                // skipping if a volume mount with same Secret name was already added
                if (!volumeMountList.stream().anyMatch(vm -> vm.getName().equals(certSecretSource.getSecretName()))) {
                    volumeMountList.add(VolumeUtils.createVolumeMount(certSecretSource.getSecretName(),
                            TLS_CERTS_BASE_VOLUME_MOUNT + certSecretSource.getSecretName()));
                }
            }
        }
    }

    AuthenticationUtils.configureClientAuthenticationVolumeMounts(authentication, volumeMountList, TLS_CERTS_BASE_VOLUME_MOUNT, PASSWORD_VOLUME_MOUNT, OAUTH_TLS_CERTS_BASE_VOLUME_MOUNT, "oauth-certs");

    volumeMountList.addAll(getExternalConfigurationVolumeMounts());

    return volumeMountList;
}
 
Example #7
Source File: KafkaConnectCluster.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
private List<VolumeMount> getExternalConfigurationVolumeMounts()    {
    List<VolumeMount> volumeMountList = new ArrayList<>(0);

    for (ExternalConfigurationVolumeSource volume : externalVolumes)    {
        String name = volume.getName();

        if (name != null)   {
            if (volume.getConfigMap() != null && volume.getSecret() != null) {
                log.warn("Volume {} with external Kafka Connect configuration has to contain exactly one volume source reference to either ConfigMap or Secret", name);
            } else  if (volume.getConfigMap() != null || volume.getSecret() != null) {
                VolumeMount volumeMount = new VolumeMountBuilder()
                        .withName(EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + name)
                        .withMountPath(EXTERNAL_CONFIGURATION_VOLUME_MOUNT_BASE_PATH + name)
                        .build();

                volumeMountList.add(volumeMount);
            }
        }
    }

    return volumeMountList;
}
 
Example #8
Source File: KafkaConnectClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoExternalConfigurationVolumes() {
    ExternalConfigurationVolumeSource volume = new ExternalConfigurationVolumeSourceBuilder()
            .withName("my-volume")
            .build();

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

    // Check Deployment
    Deployment dep = kc.generateDeployment(emptyMap(), true, null, null);
    List<Volume> volumes = dep.getSpec().getTemplate().getSpec().getVolumes();
    List<Volume> selected = volumes.stream().filter(vol -> vol.getName().equals(KafkaConnectCluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));

    List<VolumeMount> volumeMounths = dep.getSpec().getTemplate().getSpec().getContainers().get(0).getVolumeMounts();
    List<VolumeMount> selectedVolumeMounths = volumeMounths.stream().filter(vol -> vol.getName().equals(KafkaConnectCluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #9
Source File: KafkaMirrorMaker2ClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoExternalConfigurationVolumes() {
    ExternalConfigurationVolumeSource volume = new ExternalConfigurationVolumeSourceBuilder()
            .withName("my-volume")
            .build();

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

    // Check Deployment
    Deployment dep = kmm2.generateDeployment(emptyMap(), true, null, null);
    List<Volume> volumes = dep.getSpec().getTemplate().getSpec().getVolumes();
    List<Volume> selected = volumes.stream().filter(vol -> vol.getName().equals(KafkaMirrorMaker2Cluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));

    List<VolumeMount> volumeMounths = getContainer(dep).getVolumeMounts();
    List<VolumeMount> selectedVolumeMounths = volumeMounths.stream().filter(vol -> vol.getName().equals(KafkaMirrorMaker2Cluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #10
Source File: KafkaConnectS2IClusterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoExternalConfigurationVolumes() {
    ExternalConfigurationVolumeSource volume = new ExternalConfigurationVolumeSourceBuilder()
            .withName("my-volume")
            .build();

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

    // Check Deployment
    DeploymentConfig dep = kc.generateDeploymentConfig(Collections.EMPTY_MAP, true, null, null);
    List<Volume> volumes = dep.getSpec().getTemplate().getSpec().getVolumes();
    List<Volume> selected = volumes.stream().filter(vol -> vol.getName().equals(KafkaConnectCluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));

    List<VolumeMount> volumeMounths = dep.getSpec().getTemplate().getSpec().getContainers().get(0).getVolumeMounts();
    List<VolumeMount> selectedVolumeMounths = volumeMounths.stream().filter(vol -> vol.getName().equals(KafkaConnectCluster.EXTERNAL_CONFIGURATION_VOLUME_NAME_PREFIX + "my-volume")).collect(Collectors.toList());
    assertThat(selected.size(), is(0));
}
 
Example #11
Source File: ContainerHandler.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private List<VolumeMount> getVolumeMounts(ResourceConfig config) {
    List<VolumeConfig> volumeConfigs = config.getVolumes();

    List<VolumeMount> ret = new ArrayList<>();
    if (volumeConfigs != null) {
        for (VolumeConfig volumeConfig : volumeConfigs) {
            List<String> mounts = volumeConfig.getMounts();
            if (mounts != null) {
                for (String mount : mounts) {
                    ret.add(new VolumeMountBuilder()
                                .withName(volumeConfig.getName())
                                .withMountPath(mount)
                                .withReadOnly(false).build());
                }
            }
        }
    }
    return ret;
}
 
Example #12
Source File: SubPathPrefixesTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldPrefixVolumeMountsSubpathsAndUsePvcNameAsVolumeName() {
  // when
  subpathPrefixes.prefixVolumeMountsSubpaths(k8sEnv, WORKSPACE_ID);

  // then
  PodSpec podSpec = k8sEnv.getPodsData().get(POD_1_NAME).getSpec();

  io.fabric8.kubernetes.api.model.Volume userPodVolume = podSpec.getVolumes().get(0);
  assertEquals(userPodVolume.getPersistentVolumeClaim().getClaimName(), USER_DATA_PVC_NAME);
  assertEquals(
      podSpec.getVolumes().get(0).getPersistentVolumeClaim().getClaimName(), USER_DATA_PVC_NAME);

  Container initContainer = podSpec.getInitContainers().get(0);
  VolumeMount initVolumeMount = initContainer.getVolumeMounts().get(0);
  assertEquals(
      initVolumeMount.getSubPath(),
      WORKSPACE_ID + "/" + USER_DATA_PVC_NAME + "/tmp/init/userData");
  assertEquals(initVolumeMount.getName(), userPodVolume.getName());

  Container container = podSpec.getContainers().get(0);
  VolumeMount volumeMount = container.getVolumeMounts().get(0);
  assertEquals(
      volumeMount.getSubPath(), WORKSPACE_ID + "/" + USER_DATA_PVC_NAME + "/home/user/data");
  assertEquals(volumeMount.getName(), userPodVolume.getName());
}
 
Example #13
Source File: SubPathPrefixesTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNotPrefixNotPVCSourcesVolumes() {
  // given
  Volume podVolume = pod.getSpec().getVolumes().get(0);
  podVolume.setPersistentVolumeClaim(null);
  podVolume.setConfigMap(new ConfigMapVolumeSourceBuilder().withName("configMap").build());

  // when
  subpathPrefixes.prefixVolumeMountsSubpaths(k8sEnv, WORKSPACE_ID);

  // then
  PodSpec podSpec = k8sEnv.getPodsData().get(POD_1_NAME).getSpec();

  io.fabric8.kubernetes.api.model.Volume podDataVolume = podSpec.getVolumes().get(0);

  Container initContainer = podSpec.getInitContainers().get(0);
  VolumeMount initVolumeMount = initContainer.getVolumeMounts().get(0);
  assertEquals(initVolumeMount.getSubPath(), "/tmp/init/userData");
  assertEquals(initVolumeMount.getName(), podDataVolume.getName());

  Container container = podSpec.getContainers().get(0);
  VolumeMount volumeMount = container.getVolumeMounts().get(0);
  assertEquals(volumeMount.getSubPath(), "/home/user/data");
  assertEquals(volumeMount.getName(), podDataVolume.getName());
}
 
Example #14
Source File: PodTemplateUtilsTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCombineAllPodMounts() {
    VolumeMount vm1 = new VolumeMountBuilder().withMountPath("/host/mnt1").withName("volume-1").withReadOnly(false)
            .build();
    VolumeMount vm2 = new VolumeMountBuilder().withMountPath("/host/mnt2").withName("volume-2").withReadOnly(false)
            .build();
    VolumeMount vm3 = new VolumeMountBuilder().withMountPath("/host/mnt3").withName("volume-3").withReadOnly(false)
            .build();
    VolumeMount vm4 = new VolumeMountBuilder().withMountPath("/host/mnt1").withName("volume-4").withReadOnly(false)
            .build();
    Container container1 = containerBuilder().withName("jnlp").withVolumeMounts(vm1, vm2).build();
    Pod pod1 = podBuilder().withContainers(container1).endSpec().build();
    Container container2 = containerBuilder().withName("jnlp").withVolumeMounts(vm3, vm4).build();
    Pod pod2 = podBuilder().withContainers(container2).endSpec().build();

    Pod result = combine(pod1, pod2);
    List<Container> containers = result.getSpec().getContainers();
    assertEquals(1, containers.size());
    assertEquals(3, containers.get(0).getVolumeMounts().size());
    assertThat(containers.get(0).getVolumeMounts(), containsInAnyOrder(vm2, vm3, vm4));
}
 
Example #15
Source File: PodTemplateBuilderTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
@Issue("JENKINS-50525")
public void testBuildWithCustomWorkspaceVolume() throws Exception {
    PodTemplate template = new PodTemplate();
    template.setWorkspaceVolume(new EmptyDirWorkspaceVolume(true));
    ContainerTemplate containerTemplate = new ContainerTemplate("name", "image");
    containerTemplate.setWorkingDir("");
    template.getContainers().add(containerTemplate);
    setupStubs();
    Pod pod = new PodTemplateBuilder(template).withSlave(slave).build();
    List<Container> containers = pod.getSpec().getContainers();
    assertEquals(2, containers.size());
    Container container0 = containers.get(0);
    Container container1 = containers.get(1);

    ImmutableList<VolumeMount> volumeMounts = ImmutableList.of(new VolumeMountBuilder()
            .withMountPath("/home/jenkins/agent").withName("workspace-volume").withReadOnly(false).build());

    assertEquals(volumeMounts, container0.getVolumeMounts());
    assertEquals(volumeMounts, container1.getVolumeMounts());
    assertEquals("Memory", pod.getSpec().getVolumes().get(0).getEmptyDir().getMedium());
}
 
Example #16
Source File: PodTemplateBuilderTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildWithDynamicPVCWorkspaceVolume(){
    PodTemplate template = new PodTemplate();
    template.setWorkspaceVolume(new DynamicPVCWorkspaceVolume(
            null, null,null));
    ContainerTemplate containerTemplate = new ContainerTemplate("name", "image");
    containerTemplate.setWorkingDir("");
    template.getContainers().add(containerTemplate);
    setupStubs();
    Pod pod = new PodTemplateBuilder(template).withSlave(slave).build();
    List<Container> containers = pod.getSpec().getContainers();
    assertEquals(2, containers.size());
    Container container0 = containers.get(0);
    Container container1 = containers.get(1);
    ImmutableList<VolumeMount> volumeMounts = ImmutableList.of(new VolumeMountBuilder()
            .withMountPath("/home/jenkins/agent").withName("workspace-volume").withReadOnly(false).build());

    assertEquals(volumeMounts, container0.getVolumeMounts());
    assertEquals(volumeMounts, container1.getVolumeMounts());
    assertNotNull(pod.getSpec().getVolumes().get(0).getPersistentVolumeClaim());
}
 
Example #17
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 #18
Source File: SubPathPrefixesTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldPrefixVolumeMountsSubpathsAndUseVolumeNameStoredInLabels() {
  // given
  String volumeName = "userDataVolume";
  pvc.getMetadata().getLabels().put(CHE_VOLUME_NAME_LABEL, volumeName);

  // when
  subpathPrefixes.prefixVolumeMountsSubpaths(k8sEnv, WORKSPACE_ID);

  // then
  PodSpec podSpec = k8sEnv.getPodsData().get(POD_1_NAME).getSpec();

  io.fabric8.kubernetes.api.model.Volume userPodVolume = podSpec.getVolumes().get(0);
  assertEquals(userPodVolume.getPersistentVolumeClaim().getClaimName(), USER_DATA_PVC_NAME);
  assertEquals(
      podSpec.getVolumes().get(0).getPersistentVolumeClaim().getClaimName(), USER_DATA_PVC_NAME);

  Container initContainer = podSpec.getInitContainers().get(0);
  VolumeMount initVolumeMount = initContainer.getVolumeMounts().get(0);
  assertEquals(
      initVolumeMount.getSubPath(), WORKSPACE_ID + "/" + volumeName + "/tmp/init/userData");
  assertEquals(initVolumeMount.getName(), userPodVolume.getName());

  Container container = podSpec.getContainers().get(0);
  VolumeMount volumeMount = container.getVolumeMounts().get(0);
  assertEquals(volumeMount.getSubPath(), WORKSPACE_ID + "/" + volumeName + "/home/user/data");
  assertEquals(volumeMount.getName(), userPodVolume.getName());
}
 
Example #19
Source File: GitConfigProvisionerTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(dataProvider = "invalidEmailValues")
public void testShouldParseOnlyNameWhenEmailIsNotAString(String json) throws Exception {
  Map<String, String> preferences = singletonMap("theia-user-preferences", json);
  when(preferenceManager.find(eq("id"), eq("theia-user-preferences"))).thenReturn(preferences);
  when(runtimeIdentity.getWorkspaceId()).thenReturn("wksp");

  ObjectMeta podMeta = new ObjectMetaBuilder().withName("wksp").build();
  when(pod.getMetadata()).thenReturn(podMeta);
  when(pod.getSpec()).thenReturn(podSpec);
  when(podSpec.getContainers()).thenReturn(singletonList(container));

  List<VolumeMount> volumeMounts = new ArrayList<>();

  when(container.getVolumeMounts()).thenReturn(volumeMounts);
  k8sEnv.addPod(pod);

  gitConfigProvisioner.provision(k8sEnv, runtimeIdentity);

  assertEquals(volumeMounts.size(), 1);

  VolumeMount mount = volumeMounts.get(0);

  assertEquals(mount.getMountPath(), "/etc/gitconfig");
  assertEquals(mount.getName(), "gitconfigvolume");
  assertFalse(mount.getReadOnly());
  assertEquals(mount.getSubPath(), "gitconfig");

  assertEquals(k8sEnv.getConfigMaps().size(), 1);
  assertTrue(k8sEnv.getConfigMaps().containsKey("wksp-gitconfig"));

  ConfigMap configMap = k8sEnv.getConfigMaps().get("wksp-gitconfig");

  assertEquals(configMap.getData().size(), 1);
  assertTrue(configMap.getData().containsKey("gitconfig"));

  String gitconfig = configMap.getData().get("gitconfig");
  String expectedGitconfig = "[user]\n\tname = user\n";

  assertEquals(gitconfig, expectedGitconfig);
}
 
Example #20
Source File: AbstractJwtProxyProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Pod createJwtProxyPod() {
  String containerName = Names.generateName("che-jwtproxy");
  return new PodBuilder()
      .withNewMetadata()
      .withName(JWT_PROXY_POD_NAME)
      .withAnnotations(Names.createMachineNameAnnotations(containerName, JWT_PROXY_MACHINE_NAME))
      .endMetadata()
      .withNewSpec()
      .withContainers(
          new ContainerBuilder()
              .withImagePullPolicy(imagePullPolicy)
              .withName(containerName)
              .withImage(jwtProxyImage)
              .withVolumeMounts(
                  new VolumeMount(
                      JWT_PROXY_CONFIG_FOLDER + "/",
                      null,
                      "che-jwtproxy-config-volume",
                      false,
                      null,
                      null))
              .withArgs("-config", JWT_PROXY_CONFIG_FOLDER + "/" + JWT_PROXY_CONFIG_FILE)
              .addNewEnv()
              .withName("XDG_CONFIG_HOME")
              .withValue(JWT_PROXY_CONFIG_FOLDER)
              .endEnv()
              .build())
      .withVolumes(
          new VolumeBuilder()
              .withName("che-jwtproxy-config-volume")
              .withNewConfigMap()
              .withName(getConfigMapName())
              .endConfigMap()
              .build())
      .endSpec()
      .build();
}
 
Example #21
Source File: DeploymentPropertiesResolver.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
/**
 * Volume mount deployment properties are specified in YAML format:
 * <p>
 * <code>
 * spring.cloud.deployer.kubernetes.volumeMounts=[{name: 'testhostpath', mountPath: '/test/hostPath'},
 * {name: 'testpvc', mountPath: '/test/pvc'}, {name: 'testnfs', mountPath: '/test/nfs'}]
 * </code>
 * <p>
 * Volume mounts can be specified as deployer properties as well as app deployment properties.
 * Deployment properties override deployer properties.
 *
 * @param deploymentProperties the deployment properties from {@link AppDeploymentRequest}
 * @return the configured volume mounts
 */
List<VolumeMount> getVolumeMounts(Map<String, String> deploymentProperties) {
	List<VolumeMount> volumeMounts = new ArrayList<>();
	String volumeMountDeploymentProperty = PropertyParserUtils.getDeploymentPropertyValue(deploymentProperties,
			this.propertyPrefix + ".volumeMounts");

	if (!StringUtils.isEmpty(volumeMountDeploymentProperty)) {
		try {
			YamlPropertiesFactoryBean properties = new YamlPropertiesFactoryBean();
			String tmpYaml = "{ volume-mounts: " + volumeMountDeploymentProperty + " }";
			properties.setResources(new ByteArrayResource(tmpYaml.getBytes()));
			Properties yaml = properties.getObject();
			MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml);
			KubernetesDeployerProperties deployerProperties = new Binder(source)
					.bind("", Bindable.of(KubernetesDeployerProperties.class)).get();
			volumeMounts.addAll(deployerProperties.getVolumeMounts());
		} catch (Exception e) {
			throw new IllegalArgumentException(
					String.format("Invalid volume mount '%s'", volumeMountDeploymentProperty), e);
		}
	}

	// only add volume mounts that have not already been added, based on the volume mount's name
	// i.e. allow provided deployment volume mounts to override deployer defined volume mounts
	volumeMounts.addAll(this.properties.getVolumeMounts().stream().filter(volumeMount -> volumeMounts.stream()
			.noneMatch(existingVolumeMount -> existingVolumeMount.getName().equals(volumeMount.getName())))
			.collect(Collectors.toList()));

	return volumeMounts;
}
 
Example #22
Source File: KubernetesEnvironmentPodsValidator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void validatePodVolumes(KubernetesEnvironment env) throws ValidationException {
  Set<String> pvcsNames = env.getPersistentVolumeClaims().keySet();
  for (PodData pod : env.getPodsData().values()) {
    Set<String> volumesNames = new HashSet<>();
    for (Volume volume : pod.getSpec().getVolumes()) {
      volumesNames.add(volume.getName());

      PersistentVolumeClaimVolumeSource pvcSource = volume.getPersistentVolumeClaim();
      if (pvcSource != null && !pvcsNames.contains(pvcSource.getClaimName())) {
        throw new ValidationException(
            String.format(
                "Pod '%s' contains volume '%s' with PVC sources that references missing PVC '%s'",
                pod.getMetadata().getName(), volume.getName(), pvcSource.getClaimName()));
      }
    }

    for (Container container : pod.getSpec().getContainers()) {
      for (VolumeMount volumeMount : container.getVolumeMounts()) {
        if (!volumesNames.contains(volumeMount.getName())) {
          throw new ValidationException(
              String.format(
                  "Container '%s' in pod '%s' contains volume mount that references missing volume '%s'",
                  container.getName(), pod.getMetadata().getName(), volumeMount.getName()));
        }
      }
    }
  }
}
 
Example #23
Source File: SshKeysProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void mountConfigFile(PodSpec podSpec, String sshConfigMapName, boolean addVolume) {
  String configMapVolumeName = "ssshkeyconfigvolume";
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(configMapVolumeName)
                .withConfigMap(
                    new ConfigMapVolumeSourceBuilder().withName(sshConfigMapName).build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(configMapVolumeName)
                .withMountPath(SSH_CONFIG_PATH)
                .withSubPath(SSH_CONFIG)
                .withReadOnly(true)
                .withNewReadOnly(true)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example #24
Source File: SshKeysProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void mountSshKeySecret(String secretName, PodSpec podSpec, boolean addVolume) {
  if (addVolume) {
    podSpec
        .getVolumes()
        .add(
            new VolumeBuilder()
                .withName(secretName)
                .withSecret(
                    new SecretVolumeSourceBuilder()
                        .withSecretName(secretName)
                        .withDefaultMode(0600)
                        .build())
                .build());
  }

  List<Container> containers = podSpec.getContainers();
  containers.forEach(
      container -> {
        VolumeMount volumeMount =
            new VolumeMountBuilder()
                .withName(secretName)
                .withNewReadOnly(true)
                .withReadOnly(true)
                .withMountPath(SSH_PRIVATE_KEYS_PATH)
                .build();
        container.getVolumeMounts().add(volumeMount);
      });
}
 
Example #25
Source File: CertificateProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private VolumeMount buildCertVolumeMount() {
  return new VolumeMountBuilder()
      .withName(CHE_SELF_SIGNED_CERT_VOLUME)
      .withNewReadOnly(true)
      .withMountPath(CERT_MOUNT_PATH)
      .build();
}
 
Example #26
Source File: PodTemplateBuilder.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private VolumeMount getDefaultVolumeMount(@CheckForNull String workingDir) {
    String wd = workingDir;
    if (wd == null) {
        wd = ContainerTemplate.DEFAULT_WORKING_DIR;
        LOGGER.log(Level.FINE, "Container workingDir is null, defaulting to {0}", wd);
    }
    return new VolumeMountBuilder().withMountPath(wd).withName(WORKSPACE_VOLUME_NAME).withReadOnly(false).build();
}
 
Example #27
Source File: VcsSslCertificateProvisioner.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private VolumeMount buildCertVolumeMount() {
  return new VolumeMountBuilder()
      .withName(CHE_GIT_SELF_SIGNED_VOLUME)
      .withNewReadOnly(true)
      .withMountPath(CERT_MOUNT_PATH)
      .build();
}
 
Example #28
Source File: PodTemplateBuilder.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
private List<VolumeMount> getContainerVolumeMounts(Collection<VolumeMount> volumeMounts, String workingDir) {
    List<VolumeMount> containerMounts = new ArrayList<>(volumeMounts);
    if (!Strings.isNullOrEmpty(workingDir) && !PodVolume.volumeMountExists(workingDir, volumeMounts)) {
        containerMounts.add(getDefaultVolumeMount(workingDir));
    }
    return containerMounts;
}
 
Example #29
Source File: PodVolume.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
public static boolean volumeMountExists(String path, Iterable<VolumeMount> existingMounts) {
    for (VolumeMount mount : existingMounts) {
        if (mount.getMountPath().equals(path)) {
            return true;
        }
    }
    return false;
}
 
Example #30
Source File: BrokerEnvironmentFactory.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Container newContainer(
    RuntimeIdentity runtimeId,
    List<EnvVar> envVars,
    String image,
    @Nullable String brokerVolumeName) {
  String containerName = generateContainerNameFromImageRef(image);
  final ContainerBuilder cb =
      new ContainerBuilder()
          .withName(containerName)
          .withImage(image)
          .withArgs(
              "-push-endpoint",
              cheWebsocketEndpoint,
              "-runtime-id",
              String.format(
                  "%s:%s:%s",
                  runtimeId.getWorkspaceId(),
                  MoreObjects.firstNonNull(runtimeId.getEnvName(), ""),
                  runtimeId.getOwnerId()),
              "-cacert",
              certProvisioner.isConfigured() ? certProvisioner.getCertPath() : "",
              "--registry-address",
              Strings.nullToEmpty(pluginRegistryUrl))
          .withImagePullPolicy(brokerPullPolicy)
          .withEnv(envVars);
  if (brokerVolumeName != null) {
    cb.withVolumeMounts(
        new VolumeMount(CONF_FOLDER + "/", null, brokerVolumeName, true, null, null));
    cb.addToArgs("-metas", CONF_FOLDER + "/" + CONFIG_FILE);
  }
  Container container = cb.build();
  Containers.addRamLimit(container, "250Mi");
  Containers.addRamRequest(container, "250Mi");
  return container;
}