Java源码示例:io.fabric8.kubernetes.api.model.PodSecurityContext

示例1
@Test
public void testPodSecurityContextProperty() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534, fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
示例2
@Test
public void testPodSecurityContextGlobalProperty() {
	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), null);

	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();

	KubernetesDeployerProperties.PodSecurityContext securityContext = new KubernetesDeployerProperties.PodSecurityContext();
	securityContext.setFsGroup(65534L);
	securityContext.setRunAsUser(65534L);

	kubernetesDeployerProperties.setPodSecurityContext(securityContext);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
示例3
@Test
public void testPodSecurityContextUIDOnly() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertNull("Unexpected fs group", podSecurityContext.getFsGroup());
}
 
示例4
@Test
public void testPodSecurityContextFsGroupOnly() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertNull("Unexpected run as user", podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
示例5
@Test
public void testPodSecurityContextPropertyOverrideGlobal() {
	Map<String, String> props = new HashMap<>();
	props.put("spring.cloud.deployer.kubernetes.podSecurityContext", "{runAsUser: 65534, fsGroup: 65534}");

	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), props);

	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();

	KubernetesDeployerProperties.PodSecurityContext securityContext = new KubernetesDeployerProperties.PodSecurityContext();
	securityContext.setFsGroup(1000L);
	securityContext.setRunAsUser(1000L);

	kubernetesDeployerProperties.setPodSecurityContext(securityContext);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
示例6
@Test
public void shouldAssignSecurityContextSharedByPods() throws Exception {
  // given
  PodSpec podSpec1 =
      new PodSpecBuilder()
          .withSecurityContext(new PodSecurityContextBuilder().withRunAsUser(42L).build())
          .build();
  podSpec1.setAdditionalProperty("add1", 1L);
  PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());

  PodSpec podSpec2 =
      new PodSpecBuilder()
          .withSecurityContext(new PodSecurityContextBuilder().withRunAsUser(42L).build())
          .build();
  podSpec2.setAdditionalProperty("add2", 2L);
  PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());

  // when
  Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));

  // then
  PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
  PodSecurityContext sc = podTemplate.getSpec().getSecurityContext();
  assertEquals(sc.getRunAsUser(), (Long) 42L);
}
 
示例7
PodSecurityContext getPodSecurityContext(Map<String, String> kubernetesDeployerProperties) {
	PodSecurityContext podSecurityContext = null;

	KubernetesDeployerProperties deployerProperties = bindProperties(kubernetesDeployerProperties,
			this.propertyPrefix + ".podSecurityContext", "podSecurityContext");

	if (deployerProperties.getPodSecurityContext() != null) {
		podSecurityContext = new PodSecurityContextBuilder()
				.withRunAsUser(deployerProperties.getPodSecurityContext().getRunAsUser())
				.withFsGroup(deployerProperties.getPodSecurityContext().getFsGroup())
				.build();
	}
	else {
		String runAsUser = PropertyParserUtils.getDeploymentPropertyValue(kubernetesDeployerProperties,
				this.propertyPrefix + ".podSecurityContext.runAsUser");

		String fsGroup = PropertyParserUtils.getDeploymentPropertyValue(kubernetesDeployerProperties,
				this.propertyPrefix + ".podSecurityContext.fsGroup");

		if (!StringUtils.isEmpty(runAsUser) && !StringUtils.isEmpty(fsGroup)) {
			podSecurityContext = new PodSecurityContextBuilder()
					.withRunAsUser(Long.valueOf(runAsUser))
					.withFsGroup(Long.valueOf(fsGroup))
					.build();
		}
		else if (this.properties.getPodSecurityContext() != null) {
			podSecurityContext = new PodSecurityContextBuilder()
					.withRunAsUser(this.properties.getPodSecurityContext().getRunAsUser())
					.withFsGroup(this.properties.getPodSecurityContext().getFsGroup())
					.build();
		}
	}

	return podSecurityContext;
}
 
示例8
@Test
public void testPodSecurityContextFromYaml() throws Exception {
	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource(), null);

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

	PodSecurityContext podSecurityContext = podSpec.getSecurityContext();

	assertNotNull("Pod security context should not be null", podSecurityContext);

	assertEquals("Unexpected run as user", Long.valueOf("65534"), podSecurityContext.getRunAsUser());
	assertEquals("Unexpected fs group", Long.valueOf("65534"), podSecurityContext.getFsGroup());
}
 
示例9
@Test
public void shouldProvisionSecurityContextIfItIsConfigured() throws Exception {
  // given
  securityContextProvisioner = new SecurityContextProvisioner("1", "2");

  // when
  securityContextProvisioner.provision(kubernetesEnvironment, runtimeIdentity);

  // then
  PodSecurityContext securityContext = pod.getSpec().getSecurityContext();
  assertNotNull(securityContext);

  assertEquals(securityContext.getRunAsUser(), new Long(1));
  assertEquals(securityContext.getFsGroup(), new Long(2));
}
 
示例10
/**
 * Create PodSpec for the given {@link AppDeploymentRequest}

 * @param appDeploymentRequest the app deployment request to use to create the PodSpec
 * @return the PodSpec
 */
PodSpec createPodSpec(AppDeploymentRequest appDeploymentRequest) {

	String appId = createDeploymentId(appDeploymentRequest);

	Map<String, String>  deploymentProperties = (appDeploymentRequest instanceof ScheduleRequest) ?
			((ScheduleRequest) appDeploymentRequest).getSchedulerProperties() : appDeploymentRequest.getDeploymentProperties();

	PodSpecBuilder podSpec = new PodSpecBuilder();

	String imagePullSecret = this.deploymentPropertiesResolver.getImagePullSecret(deploymentProperties);

	if (imagePullSecret != null) {
		podSpec.addNewImagePullSecret(imagePullSecret);
	}

	boolean hostNetwork = this.deploymentPropertiesResolver.getHostNetwork(deploymentProperties);

	ContainerConfiguration containerConfiguration = new ContainerConfiguration(appId, appDeploymentRequest)
			.withProbeCredentialsSecret(getProbeCredentialsSecret(deploymentProperties))
			.withHostNetwork(hostNetwork);

	if (KubernetesAppDeployer.class.isAssignableFrom(this.getClass())) {
		containerConfiguration.withExternalPort(getExternalPort(appDeploymentRequest));
	}

	Container container = containerFactory.create(containerConfiguration);

	// add memory and cpu resource limits
	ResourceRequirements req = new ResourceRequirements();
	req.setLimits(this.deploymentPropertiesResolver.deduceResourceLimits(deploymentProperties));
	req.setRequests(this.deploymentPropertiesResolver.deduceResourceRequests(deploymentProperties));
	container.setResources(req);
	ImagePullPolicy pullPolicy = this.deploymentPropertiesResolver.deduceImagePullPolicy(deploymentProperties);
	container.setImagePullPolicy(pullPolicy.name());

	Map<String, String> nodeSelectors = this.deploymentPropertiesResolver.getNodeSelectors(deploymentProperties);
	if (nodeSelectors.size() > 0) {
		podSpec.withNodeSelector(nodeSelectors);
	}

	podSpec.withTolerations(this.deploymentPropertiesResolver.getTolerations(deploymentProperties));

	// only add volumes with corresponding volume mounts
	podSpec.withVolumes(this.deploymentPropertiesResolver.getVolumes(deploymentProperties).stream()
			.filter(volume -> container.getVolumeMounts().stream()
					.anyMatch(volumeMount -> volumeMount.getName().equals(volume.getName())))
			.collect(Collectors.toList()));

	if (hostNetwork) {
		podSpec.withHostNetwork(true);
	}
	podSpec.addToContainers(container);

	podSpec.withRestartPolicy(this.deploymentPropertiesResolver.getRestartPolicy(deploymentProperties).name());

	String deploymentServiceAcccountName = this.deploymentPropertiesResolver.getDeploymentServiceAccountName(deploymentProperties);

	if (deploymentServiceAcccountName != null) {
		podSpec.withServiceAccountName(deploymentServiceAcccountName);
	}

	PodSecurityContext podSecurityContext = this.deploymentPropertiesResolver.getPodSecurityContext(deploymentProperties);
	if (podSecurityContext != null) {
		podSpec.withSecurityContext(podSecurityContext);
	}

	Affinity affinity = this.deploymentPropertiesResolver.getAffinityRules(deploymentProperties);
	// Make sure there is at least some rule.
	if (affinity.getNodeAffinity() != null
			|| affinity.getPodAffinity() != null
			|| affinity.getPodAntiAffinity() != null) {
		podSpec.withAffinity(affinity);
	}

	Container initContainer = this.deploymentPropertiesResolver.getInitContainer(deploymentProperties);
	if (initContainer != null) {
		podSpec.addToInitContainers(initContainer);
	}

	return podSpec.build();
}
 
示例11
protected StatefulSet createStatefulSet(
        Map<String, String> stsAnnotations,
        Map<String, String> podAnnotations,
        List<Volume> volumes,
        List<PersistentVolumeClaim> volumeClaims,
        Affinity affinity,
        List<Container> initContainers,
        List<Container> containers,
        List<LocalObjectReference> imagePullSecrets,
        boolean isOpenShift) {

    PodSecurityContext securityContext = templateSecurityContext;

    // if a persistent volume claim is requested and the running cluster is a Kubernetes one (non-openshift) and we
    // have no user configured PodSecurityContext we set the podSecurityContext.
    // This is to give each pod write permissions under a specific group so that if a pod changes users it does not have permission issues.
    if (ModelUtils.containsPersistentStorage(storage) && !isOpenShift && securityContext == null) {
        securityContext = new PodSecurityContextBuilder()
                .withFsGroup(AbstractModel.DEFAULT_FS_GROUPID)
                .build();
    }

    StatefulSet statefulSet = new StatefulSetBuilder()
            .withNewMetadata()
                .withName(name)
                .withLabels(getLabelsWithStrimziName(name, templateStatefulSetLabels).toMap())
                .withNamespace(namespace)
                .withAnnotations(mergeLabelsOrAnnotations(stsAnnotations, templateStatefulSetAnnotations))
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withPodManagementPolicy(templatePodManagementPolicy.toValue())
                .withUpdateStrategy(new StatefulSetUpdateStrategyBuilder().withType("OnDelete").build())
                .withSelector(new LabelSelectorBuilder().withMatchLabels(getSelectorLabels().toMap()).build())
                .withServiceName(headlessServiceName)
                .withReplicas(replicas)
                .withNewTemplate()
                    .withNewMetadata()
                        .withName(name)
                        .withLabels(getLabelsWithStrimziName(name, templatePodLabels).toMap())
                        .withAnnotations(mergeLabelsOrAnnotations(podAnnotations, templatePodAnnotations))
                    .endMetadata()
                    .withNewSpec()
                        .withServiceAccountName(getServiceAccountName())
                        .withAffinity(affinity)
                        .withInitContainers(initContainers)
                        .withContainers(containers)
                        .withVolumes(volumes)
                        .withTolerations(getTolerations())
                        .withTerminationGracePeriodSeconds(Long.valueOf(templateTerminationGracePeriodSeconds))
                        .withImagePullSecrets(templateImagePullSecrets != null ? templateImagePullSecrets : imagePullSecrets)
                        .withSecurityContext(securityContext)
                        .withPriorityClassName(templatePodPriorityClassName)
                        .withSchedulerName(templatePodSchedulerName != null ? templatePodSchedulerName : "default-scheduler")
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(volumeClaims)
            .endSpec()
            .build();

    return statefulSet;
}
 
示例12
@Description("Configures pod-level security attributes and common container settings.")
@KubeLink(group = "core", version = "v1", kind = "podsecuritycontext")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public PodSecurityContext getSecurityContext() {
    return securityContext;
}
 
示例13
public void setSecurityContext(PodSecurityContext securityContext) {
    this.securityContext = securityContext;
}
 
示例14
public PodSecurityContext getSecurityContext() {
    return securityContext;
}
 
示例15
public void setSecurityContext(PodSecurityContext securityContext) {
    this.securityContext = securityContext;
}
 
示例16
private PodSecurityContext mergeSecurityContexts(
    @Nullable PodSecurityContext a, @Nullable PodSecurityContext b) throws ValidationException {
  return nonNullOrEqual(a, b, "Cannot merge pods with different security contexts: %s, %s");
}
 
示例17
@Test
@TestCaseName("{method}(directConnection={0})")
@Parameters({ "true", "false" })
public void testBuildFromTemplate(boolean directConnection) throws Exception {
    cloud.setDirectConnection(directConnection);
    PodTemplate template = new PodTemplate();
    template.setRunAsUser("1000");
    template.setRunAsGroup("1000");
    template.setSupplementalGroups("5001,5002");

    template.setHostNetwork(false);

    List<PodVolume> volumes = new ArrayList<PodVolume>();
    volumes.add(new HostPathVolume("/host/data", "/container/data"));
    volumes.add(new EmptyDirVolume("/empty/dir", false));
    template.setVolumes(volumes);

    List<ContainerTemplate> containers = new ArrayList<ContainerTemplate>();
    ContainerTemplate busyboxContainer = new ContainerTemplate("busybox", "busybox");
    busyboxContainer.setCommand("cat");
    busyboxContainer.setTtyEnabled(true);
    List<TemplateEnvVar> envVars = new ArrayList<TemplateEnvVar>();
    envVars.add(new KeyValueEnvVar("CONTAINER_ENV_VAR", "container-env-var-value"));
    busyboxContainer.setEnvVars(envVars);
    busyboxContainer.setRunAsUser("2000");
    busyboxContainer.setRunAsGroup("2000");
    containers.add(busyboxContainer);
    template.setContainers(containers);

    setupStubs();
    Pod pod = new PodTemplateBuilder(template).withSlave(slave).build();
    pod.getMetadata().setLabels(ImmutableMap.of("some-label","some-label-value"));
    validatePod(pod, false, directConnection);
    ArrayList<Long> supplementalGroups = new ArrayList<Long>();
    supplementalGroups.add(5001L);
    supplementalGroups.add(5002L);

    Map<String, Container> containersMap = toContainerMap(pod);
    PodSecurityContext securityContext = pod.getSpec().getSecurityContext();
    assertEquals(Long.valueOf(1000L), securityContext.getRunAsUser());
    assertEquals(Long.valueOf(1000L), securityContext.getRunAsGroup());
    assertEquals(supplementalGroups, securityContext.getSupplementalGroups());
    assertEquals(Long.valueOf(2000L), containersMap.get("busybox").getSecurityContext().getRunAsUser());
    assertEquals(Long.valueOf(2000L), containersMap.get("busybox").getSecurityContext().getRunAsGroup());
}