Java Code Examples for io.fabric8.kubernetes.api.model.Container

The following examples show how to use io.fabric8.kubernetes.api.model.Container. These examples are extracted from open source projects. 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
@Test
public void testGenerateDeploymentConfigWithTls() {
    KafkaConnectS2I resource = new KafkaConnectS2IBuilder(this.resource)
            .editSpec()
            .editOrNewTls()
            .addToTrustedCertificates(new CertSecretSourceBuilder().withSecretName("my-secret").withCertificate("cert.crt").build())
            .addToTrustedCertificates(new CertSecretSourceBuilder().withSecretName("my-secret").withCertificate("new-cert.crt").build())
            .addToTrustedCertificates(new CertSecretSourceBuilder().withSecretName("my-another-secret").withCertificate("another-cert.crt").build())
            .endTls()
            .endSpec()
            .build();
    KafkaConnectS2ICluster kc = KafkaConnectS2ICluster.fromCrd(resource, VERSIONS);
    DeploymentConfig dep = kc.generateDeploymentConfig(Collections.EMPTY_MAP, true, null, null);

    assertThat(dep.getSpec().getTemplate().getSpec().getVolumes().get(1).getName(), is("my-secret"));
    assertThat(dep.getSpec().getTemplate().getSpec().getVolumes().get(2).getName(), is("my-another-secret"));

    List<Container> containers = dep.getSpec().getTemplate().getSpec().getContainers();

    assertThat(containers.get(0).getVolumeMounts().get(1).getMountPath(), is(KafkaConnectCluster.TLS_CERTS_BASE_VOLUME_MOUNT + "my-secret"));
    assertThat(containers.get(0).getVolumeMounts().get(2).getMountPath(), is(KafkaConnectCluster.TLS_CERTS_BASE_VOLUME_MOUNT + "my-another-secret"));

    assertThat(AbstractModel.containerEnvVars(containers.get(0)).get(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_TRUSTED_CERTS),
            is("my-secret/cert.crt;my-secret/new-cert.crt;my-another-secret/another-cert.crt"));
    assertThat(AbstractModel.containerEnvVars(containers.get(0)).get(KafkaConnectCluster.ENV_VAR_KAFKA_CONNECT_TLS), is("true"));
}
 
Example 2
Source Project: che   Source File: ContainerSearchTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldFindAllContainersIfNotRestricted() {
  ContainerSearch search = new ContainerSearch(null, null, null);

  List<Container> results = search.search(testList);

  Assert.assertEquals(results.size(), 12);
  assertContainsContainer(results, "container1");
  assertContainsContainer(results, "container2");
  assertContainsContainer(results, "container3");
  assertContainsContainer(results, "container4");
  assertContainsContainer(results, "container5");
  assertContainsContainer(results, "container6");
  assertContainsContainer(results, "container7");
  assertContainsContainer(results, "container8");
  assertContainsContainer(results, "container9");
  assertContainsContainer(results, "container10");
  assertContainsContainer(results, "container11");
  assertContainsContainer(results, "container12");
}
 
Example 3
Source Project: jkube   Source File: KubernetesResourceUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static boolean podHasContainerImage(Pod pod, String imageName) {
    if (pod != null) {
        PodSpec spec = pod.getSpec();
        if (spec != null) {
            List<Container> containers = spec.getContainers();
            if (containers != null) {
                for (Container container : containers) {
                    if (Objects.equals(imageName, container.getImage())) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example 4
Source Project: jkube   Source File: KubernetesResourceUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private static void ensureHasEnv(Container container, EnvVar envVar) {
    List<EnvVar> envVars = container.getEnv();
    if (envVars == null) {
        envVars = new ArrayList<>();
        container.setEnv(envVars);
    }
    for (EnvVar var : envVars) {
        if (Objects.equals(var.getName(), envVar.getName())) {
            // lets replace the object so that we can update the value or valueFrom
            envVars.remove(var);
            envVars.add(envVar);
            return;
        }
    }
    envVars.add(envVar);
}
 
Example 5
Source Project: flink   Source File: FlinkConfMountDecorator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) {
	final Pod mountedPod = decoratePod(flinkPod.getPod());

	final Container mountedMainContainer = new ContainerBuilder(flinkPod.getMainContainer())
		.addNewVolumeMount()
			.withName(FLINK_CONF_VOLUME)
			.withMountPath(kubernetesComponentConf.getFlinkConfDirInPod())
			.endVolumeMount()
		.build();

	return new FlinkPod.Builder(flinkPod)
		.withPod(mountedPod)
		.withMainContainer(mountedMainContainer)
		.build();
}
 
Example 6
Source Project: jkube   Source File: InitContainerHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public void appendInitContainer(PodTemplateSpecBuilder builder, Container initContainer) {
    String name = initContainer.getName();
    Container existing = getInitContainer(builder, name);
    if (existing != null) {
        if (existing.equals(initContainer)) {
            log.warn("Trying to add init-container %s a second time. Ignoring ....", name);
            return;
        } else {
            throw new IllegalArgumentException(
                String.format("PodSpec %s already contains a different init container with name %s but can not add a second one with the same name. " +
                              "Please choose a different name for the init container",
                              builder.build().getMetadata().getName(), name));
        }
    }

    ensureSpec(builder);
    builder.editSpec().addToInitContainers(initContainer).endSpec();
}
 
Example 7
Source Project: che   Source File: BrokerEnvironmentFactoryTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNameContainersAfterArtifactsPluginBrokerImage() throws Exception {
  // given
  Collection<PluginFQN> pluginFQNs = singletonList(new PluginFQN(null, "id"));
  ArgumentCaptor<BrokersConfigs> captor = ArgumentCaptor.forClass(BrokersConfigs.class);

  // when
  factory.createForArtifactsBroker(pluginFQNs, runtimeId);

  // then
  verify(factory).doCreate(captor.capture());
  BrokersConfigs brokersConfigs = captor.getValue();
  PodSpec brokerPodSpec = brokersConfigs.pods.values().iterator().next().getSpec();

  List<Container> containers = brokerPodSpec.getContainers();
  assertEquals(containers.size(), 1);
  assertEquals(containers.get(0).getName(), "artifacts-image");
}
 
Example 8
public static GoCDContainerDetails fromContainer(Container container, ContainerStatus containerStatus) {
    GoCDContainerDetails containerDetails = new GoCDContainerDetails();

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

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

    return containerDetails;
}
 
Example 9
@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 10
@BeforeMethod
public void setUp() throws Exception {
  Container container = new ContainerBuilder().withName("main").build();
  Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName("pod")
          .endMetadata()
          .withNewSpec()
          .withContainers(container)
          .endSpec()
          .build();

  kubernetesEnvironment =
      KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();
  externalServerExposer =
      new ExternalServerExposer<>(
          new MultiHostExternalServiceExposureStrategy(DOMAIN, MULTI_HOST_STRATEGY),
          emptyMap(),
          "%s");
}
 
Example 11
Source Project: che   Source File: K8sContainerResolver.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void provisionCpuLimit(Container container, CheContainer cheContainer)
    throws InfrastructureException {
  String cpuLimit = cheContainer.getCpuLimit();
  if (isNullOrEmpty(cpuLimit)) {
    return;
  }
  try {
    KubernetesSize.toCores(cpuLimit);
  } catch (IllegalArgumentException e) {
    throw new InfrastructureException(
        format(
            "Sidecar CPU limit field contains illegal value '%s'. Error: '%s'",
            cpuLimit, e.getMessage()));
  }
  Containers.addCpuLimit(container, cpuLimit);
}
 
Example 12
Source Project: che   Source File: K8sContainerResolver.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void provisionMemoryRequest(Container container, CheContainer cheContainer)
    throws InfrastructureException {
  String memoryRequest = cheContainer.getMemoryRequest();
  if (isNullOrEmpty(memoryRequest)) {
    return;
  }
  try {
    KubernetesSize.toBytes(memoryRequest);
  } catch (IllegalArgumentException e) {
    throw new InfrastructureException(
        format(
            "Sidecar memory request field contains illegal value '%s'. Error: '%s'",
            memoryRequest, e.getMessage()));
  }
  Containers.addRamRequest(container, memoryRequest);
}
 
Example 13
@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 14
@Test
public void testImagePullPolicyDefault() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	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, getSchedulerProperties(),
			getDeploymentProperties(), getCommandLineArgs(), randomName(), testApplication());

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

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

	assertEquals("Unexpected default image pull policy", ImagePullPolicy.IfNotPresent,
			ImagePullPolicy.relaxedValueOf(container.getImagePullPolicy()));

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example 15
@Test
public void testGenerateDeploymentWithProducerOAuthWithAccessToken() {
    KafkaMirrorMaker resource = new KafkaMirrorMakerBuilder(this.resource)
            .editSpec()
                .editProducer()
                    .withAuthentication(
                            new KafkaClientAuthenticationOAuthBuilder()
                                    .withNewAccessToken()
                                        .withSecretName("my-token-secret")
                                        .withKey("my-token-key")
                                    .endAccessToken()
                                    .build())
                .endProducer()
            .endSpec()
            .build();

    KafkaMirrorMakerCluster kc = KafkaMirrorMakerCluster.fromCrd(resource, VERSIONS);
    Deployment dep = kc.generateDeployment(emptyMap(), true, null, null);
    Container cont = dep.getSpec().getTemplate().getSpec().getContainers().get(0);

    assertThat(cont.getEnv().stream().filter(var -> KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_SASL_MECHANISM_PRODUCER.equals(var.getName())).findFirst().orElse(null).getValue(), is("oauth"));
    assertThat(cont.getEnv().stream().filter(var -> KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_OAUTH_ACCESS_TOKEN_PRODUCER.equals(var.getName())).findFirst().orElse(null).getValueFrom().getSecretKeyRef().getName(), is("my-token-secret"));
    assertThat(cont.getEnv().stream().filter(var -> KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_OAUTH_ACCESS_TOKEN_PRODUCER.equals(var.getName())).findFirst().orElse(null).getValueFrom().getSecretKeyRef().getKey(), is("my-token-key"));
    assertThat(cont.getEnv().stream().filter(var -> KafkaMirrorMakerCluster.ENV_VAR_KAFKA_MIRRORMAKER_OAUTH_CONFIG_PRODUCER.equals(var.getName())).findFirst().orElse(null).getValue().isEmpty(), is(true));
}
 
Example 16
@Test
public void testProbeHeadersWithoutAuth() throws Exception {
	AppDefinition definition = new AppDefinition("app-test", null);
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition, getResource());

	ContainerConfiguration containerConfiguration = new ContainerConfiguration("app-test", appDeploymentRequest)
			.withExternalPort(8080);

	ContainerFactory containerFactory = new DefaultContainerFactory(new KubernetesDeployerProperties());
	Container container = containerFactory.create(containerConfiguration);

	assertTrue("Liveness probe should not contain any HTTP headers",
			container.getLivenessProbe().getHttpGet().getHttpHeaders().isEmpty());
	assertTrue("Readiness probe should not contain any HTTP headers",
			container.getReadinessProbe().getHttpGet().getHttpHeaders().isEmpty());
}
 
Example 17
Source Project: module-ballerina-kubernetes   Source File: Sample12Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void validateDeployment() {
    Assert.assertNotNull(deployment);
    Assert.assertEquals(deployment.getMetadata().getName(), "hello-world-copy-file-deployment");
    Assert.assertEquals(deployment.getSpec().getReplicas().intValue(), 1);
    Assert.assertEquals(deployment.getSpec().getTemplate().getSpec().getVolumes().size(), 1);
    Assert.assertEquals(deployment.getMetadata().getLabels().get(KubernetesConstants
            .KUBERNETES_SELECTOR_KEY), "hello_world_copy_file");
    Assert.assertEquals(deployment.getSpec().getTemplate().getSpec().getContainers().size(), 1);

    // Assert Containers
    Container container = deployment.getSpec().getTemplate().getSpec().getContainers().get(0);
    Assert.assertEquals(container.getVolumeMounts().size(), 1);
    Assert.assertEquals(container.getImage(), DOCKER_IMAGE);
    Assert.assertEquals(container.getImagePullPolicy(), KubernetesConstants.ImagePullPolicy.IfNotPresent.name());
    Assert.assertEquals(container.getPorts().size(), 1);
}
 
Example 18
@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 19
Source Project: che   Source File: BrokerEnvironmentFactoryTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldNameContainersAfterMetadataPluginBrokerImage() throws Exception {
  // given
  Collection<PluginFQN> pluginFQNs = singletonList(new PluginFQN(null, "id"));
  ArgumentCaptor<BrokersConfigs> captor = ArgumentCaptor.forClass(BrokersConfigs.class);

  // when
  factory.createForMetadataBroker(pluginFQNs, runtimeId);

  // then
  verify(factory).doCreate(captor.capture());
  BrokersConfigs brokersConfigs = captor.getValue();
  PodSpec brokerPodSpec = brokersConfigs.pods.values().iterator().next().getSpec();

  List<Container> containers = brokerPodSpec.getContainers();
  assertEquals(containers.size(), 1);
  assertEquals(containers.get(0).getName(), "metadata-image");
}
 
Example 20
Source Project: module-ballerina-kubernetes   Source File: Sample10Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void validatePizzaDeployment() {
    Assert.assertNotNull(pizzaDeployment);
    Assert.assertEquals(pizzaDeployment.getMetadata().getName(), "foodstore");
    Assert.assertEquals(pizzaDeployment.getSpec().getReplicas().intValue(), 3);
    Assert.assertEquals(pizzaDeployment.getSpec().getTemplate().getSpec().getVolumes().size(), 0);
    Assert.assertEquals(pizzaDeployment.getMetadata().getLabels().get(KubernetesConstants
            .KUBERNETES_SELECTOR_KEY), PIZZA_SELECTOR);
    Assert.assertEquals(pizzaDeployment.getSpec().getTemplate().getSpec().getContainers().size(), 1);

    // Assert Containers
    Container container = pizzaDeployment.getSpec().getTemplate().getSpec().getContainers().get(0);
    Assert.assertEquals(container.getVolumeMounts().size(), 0);
    Assert.assertEquals(container.getImage(), PIZZA_DOCKER_IMAGE);
    Assert.assertEquals(container.getImagePullPolicy(), KubernetesConstants.ImagePullPolicy.IfNotPresent.name());
    Assert.assertEquals(container.getPorts().size(), 1);
    Assert.assertEquals(container.getEnv().size(), 2);
}
 
Example 21
@BeforeMethod
public void setup() {
  resourceProvisioner = new ContainerResourceProvisioner(1024, 512, "500m", "100m");
  container = new Container();
  container.setName(CONTAINER_NAME);
  when(k8sEnv.getMachines()).thenReturn(of(MACHINE_NAME, internalMachineConfig));
  when(internalMachineConfig.getAttributes())
      .thenReturn(
          of(
              MEMORY_LIMIT_ATTRIBUTE,
              RAM_LIMIT_VALUE,
              MEMORY_REQUEST_ATTRIBUTE,
              RAM_REQUEST_VALUE,
              CPU_LIMIT_ATTRIBUTE,
              CPU_LIMIT_VALUE,
              CPU_REQUEST_ATTRIBUTE,
              CPU_REQUEST_VALUE));
  final ObjectMeta podMetadata = mock(ObjectMeta.class);
  when(podMetadata.getName()).thenReturn(POD_NAME);
  final PodSpec podSpec = mock(PodSpec.class);
  when(podSpec.getContainers()).thenReturn(Collections.singletonList(container));
  when(k8sEnv.getPodsData()).thenReturn(of(POD_NAME, new PodData(podSpec, podMetadata)));
}
 
Example 22
Source Project: che   Source File: SubPathPrefixesTest.java    License: 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 23
Source Project: flink   Source File: JavaCmdJobManagerDecoratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testStartCommandWithoutLog4jAndLogback() {
	final Container resultMainContainer =
			javaCmdJobManagerDecorator.decorateFlinkPod(baseFlinkPod).getMainContainer();

	assertEquals(Collections.singletonList(KUBERNETES_ENTRY_PATH), resultMainContainer.getCommand());

	final String expectedCommand = getJobManagerExpectedCommand("", "");
	final List<String> expectedArgs = Arrays.asList("/bin/bash", "-c", expectedCommand);

	assertEquals(expectedArgs, resultMainContainer.getArgs());
}
 
Example 24
Source Project: che   Source File: Containers.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the RAM request in bytes, if it is present in given container otherwise 0 will be
 * returned.
 */
public static long getRamRequest(Container container) {
  final ResourceRequirements resources = container.getResources();
  final Quantity quantity;
  if (resources != null
      && resources.getRequests() != null
      && (quantity = resources.getRequests().get("memory")) != null
      && quantity.getAmount() != null) {
    return Quantity.getAmountInBytes(quantity).longValue();
  }
  return 0;
}
 
Example 25
@Test
public void createCustomLivenessPortFromProperties() {
	int defaultPort = 8080;
	int livenessPort = 8090;

	KubernetesDeployerProperties kubernetesDeployerProperties = new KubernetesDeployerProperties();
	kubernetesDeployerProperties.setLivenessProbePort(livenessPort);
	DefaultContainerFactory defaultContainerFactory = new DefaultContainerFactory(
			kubernetesDeployerProperties);

	AppDefinition definition = new AppDefinition("app-test", null);
	Resource resource = getResource();
	Map<String, String> props = new HashMap<>();
	AppDeploymentRequest appDeploymentRequest = new AppDeploymentRequest(definition,
			resource, props);

	ContainerConfiguration containerConfiguration = new ContainerConfiguration("app-test", appDeploymentRequest)
			.withExternalPort(defaultPort)
			.withHostNetwork(true);
	Container container = defaultContainerFactory.create(containerConfiguration);
	assertNotNull(container);

	List<ContainerPort> containerPorts = container.getPorts();
	assertNotNull(containerPorts);

	assertTrue("Only two container ports should be set", containerPorts.size() == 2);
	assertTrue(8080 == containerPorts.get(0).getContainerPort());
	assertTrue(8080 == containerPorts.get(0).getHostPort());
	assertTrue(8090 == containerPorts.get(1).getContainerPort());
	assertTrue(8090 == containerPorts.get(1).getHostPort());
	assertTrue(8090 == container.getLivenessProbe().getHttpGet().getPort().getIntVal());
}
 
Example 26
Source Project: rabbitmq-operator   Source File: RabbitMQContainers.java    License: Apache License 2.0 5 votes vote down vote up
public Container buildContainer(
        final String namespace,
        final String rabbitName,
        final String rabbitMQImage,
        final RabbitMQComputeResources resources,
        final double highWatermark
) {
    final String discoveryServiceName = RabbitMQServices.getDiscoveryServiceName(rabbitName);
    final String adminSecretName = RabbitMQSecrets.getClusterSecretName(rabbitName);
    final String erlangCookieSecretName = RabbitMQSecrets.getErlangCookieSecretName(rabbitName);

    return new ContainerBuilder()
            .addNewPort().withName("epmd").withContainerPort(EPMD_PORT).withProtocol("TCP").endPort()
            .addNewPort().withName("amqp").withContainerPort(AMQP_PORT).withProtocol("TCP").endPort()
            .addNewPort().withName("management").withContainerPort(MANAGEMENT_PORT).withProtocol("TCP").endPort()
            .withImage(rabbitMQImage)
            .withName(rabbitName)
            .withNewResources()
                .withRequests(resources.asResourceRequestQuantityMap())
                .withLimits(resources.asResourceLimitQuantityMap())
            .endResources()
            .addNewEnv().withName("MY_POD_NAME").withNewValueFrom().withNewFieldRef().withFieldPath("metadata.name").endFieldRef().endValueFrom().endEnv()
            .addNewEnv().withName("RABBITMQ_VM_MEMORY_HIGH_WATERMARK").withValue(highWatermark > 0 ? String.valueOf(highWatermark) : "0Mib").endEnv()
            .addNewEnv().withName("RABBITMQ_ERLANG_COOKIE").withNewValueFrom().withNewSecretKeyRef(Constants.Secrets.ERLANG_COOKIE_KEY, erlangCookieSecretName, false).endValueFrom().endEnv()
            .addNewEnv().withName("RABBITMQ_DEFAULT_USER").withNewValueFrom().withNewSecretKeyRef(Constants.Secrets.USERNAME_KEY, adminSecretName, false).endValueFrom().endEnv()
            .addNewEnv().withName("RABBITMQ_DEFAULT_PASS").withNewValueFrom().withNewSecretKeyRef(Constants.Secrets.PASSWORD_KEY, adminSecretName, false).endValueFrom().endEnv()
            .addNewEnv().withName("K8S_SERVICE_NAME").withValue(discoveryServiceName).endEnv()
            .addNewEnv().withName("RABBITMQ_USE_LONGNAME").withValue("true").endEnv()
            .addNewEnv().withName("RABBITMQ_NODENAME").withValue(String.format("[email protected]$(MY_POD_NAME).%s.%s.svc.cluster.local", discoveryServiceName, namespace)).endEnv()
            .addNewEnv().withName("K8S_HOSTNAME_SUFFIX").withValue(String.format(".%s.%s.svc.cluster.local", discoveryServiceName, namespace)).endEnv()
            .addNewVolumeMount().withName("config").withMountPath("/etc/rabbitmq").endVolumeMount()
            .addNewVolumeMount().withName(RABBITMQ_STORAGE_NAME).withMountPath("/var/lib/rabbitmq").endVolumeMount()
            .addNewVolumeMount().withName("probes").withMountPath("/probes").endVolumeMount()
            .addNewVolumeMount().withName("startup-scripts").withMountPath("/startup-scripts").endVolumeMount()
            .withReadinessProbe(buildReadinessProbe())
            .withLifecycle(buildLifeCycle())
            .build();
}
 
Example 27
Source Project: flink   Source File: KubernetesJobManagerFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPodSpec() {
	final PodSpec resultPodSpec =
		this.kubernetesJobManagerSpecification.getDeployment().getSpec().getTemplate().getSpec();

	assertEquals(1, resultPodSpec.getContainers().size());
	assertEquals(SERVICE_ACCOUNT_NAME, resultPodSpec.getServiceAccountName());
	assertEquals(1, resultPodSpec.getVolumes().size());

	final Container resultedMainContainer = resultPodSpec.getContainers().get(0);
	assertEquals(KubernetesJobManagerParameters.JOB_MANAGER_MAIN_CONTAINER_NAME, resultedMainContainer.getName());
	assertEquals(CONTAINER_IMAGE, resultedMainContainer.getImage());
	assertEquals(CONTAINER_IMAGE_PULL_POLICY.name(), resultedMainContainer.getImagePullPolicy());

	assertEquals(3, resultedMainContainer.getEnv().size());
	assertTrue(resultedMainContainer.getEnv()
			.stream()
			.anyMatch(envVar -> envVar.getName().equals("key1")));

	assertEquals(3, resultedMainContainer.getPorts().size());

	final Map<String, Quantity> requests = resultedMainContainer.getResources().getRequests();
	assertEquals(Double.toString(JOB_MANAGER_CPU), requests.get("cpu").getAmount());
	assertEquals(String.valueOf(JOB_MANAGER_MEMORY), requests.get("memory").getAmount());

	assertEquals(1, resultedMainContainer.getCommand().size());
	assertEquals(3, resultedMainContainer.getArgs().size());

	assertEquals(1, resultedMainContainer.getVolumeMounts().size());
}
 
Example 28
Source Project: che   Source File: EnvVars.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Applies the specified env vars list to the specified containers.
 *
 * <p>If a container does not have the corresponding env - it will be provisioned, if it has - the
 * value will be overridden.
 *
 * @param container pod to supply env vars
 * @param toApply env vars to apply
 */
public void apply(Container container, List<? extends Env> toApply) {
  List<EnvVar> targetEnv = container.getEnv();
  if (targetEnv == null) {
    targetEnv = new ArrayList<>();
    container.setEnv(targetEnv);
  }

  for (Env env : toApply) {
    apply(targetEnv, env);
  }
}
 
Example 29
Source Project: kubernetes-plugin   Source File: PodTemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFilterOutEnvFromSourcesWithNullOrEmptyKey() {
    EnvFromSource noSource = new EnvFromSource(null, null, null);
    EnvFromSource noConfigMapKey = new EnvFromSource(new ConfigMapEnvSource(null, false), null, null);
    EnvFromSource emptyConfigMapKey = new EnvFromSource(new ConfigMapEnvSource("", false), null, null);
    EnvFromSource noSecretKey = new EnvFromSource(null, null, new SecretEnvSource(null, false));
    EnvFromSource emptySecretKey = new EnvFromSource(null, null, new SecretEnvSource("", false));

    Container container = new Container();
    container.setEnvFrom(asList(noSource, noConfigMapKey, emptyConfigMapKey, noSecretKey, emptySecretKey));

    Container result = combine(container, new Container());

    assertEquals(0, result.getEnvFrom().size());
}
 
Example 30
Source Project: strimzi-kafka-operator   Source File: CruiseControlTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProbeConfiguration()   {
    CruiseControlSpec cruiseControlSpec = new CruiseControlSpecBuilder()
            .withImage(ccImage)
            .withNewLivenessProbe()
                    .withInitialDelaySeconds(healthDelay)
                    .withTimeoutSeconds(healthTimeout)
            .endLivenessProbe()
            .withNewReadinessProbe()
                   .withInitialDelaySeconds(healthDelay)
                   .withTimeoutSeconds(healthTimeout)
            .endReadinessProbe()
            .build();

    Kafka resource =
            new KafkaBuilder(ResourceUtils.createKafkaCluster(namespace, cluster, replicas, image, healthDelay, healthTimeout))
            .editSpec()
                .editKafka()
                    .withVersion(version)
                .endKafka()
                .withCruiseControl(cruiseControlSpec)
            .endSpec()
            .build();

    CruiseControl cc = CruiseControl.fromCrd(resource, VERSIONS);
    Deployment dep = cc.generateDeployment(true, null, null, null);
    List<Container> containers = dep.getSpec().getTemplate().getSpec().getContainers();

    // checks on the main Cruise Control container
    Container ccContainer = containers.stream().filter(container -> ccImage.equals(container.getImage())).findFirst().get();
    assertThat(ccContainer.getImage(), is(cc.image));
    assertThat(ccContainer.getLivenessProbe().getInitialDelaySeconds(), is(new Integer(healthDelay)));
    assertThat(ccContainer.getLivenessProbe().getTimeoutSeconds(), is(new Integer(healthTimeout)));
    assertThat(ccContainer.getReadinessProbe().getInitialDelaySeconds(), is(new Integer(healthDelay)));
    assertThat(ccContainer.getReadinessProbe().getTimeoutSeconds(), is(new Integer(healthTimeout)));
}