下面列出了io.fabric8.kubernetes.api.model.EnvVarBuilder#io.fabric8.kubernetes.api.model.ContainerBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
List<Container> getContainers(ResourceConfig config, List<ImageConfiguration> images) {
List<Container> ret = new ArrayList<>();
for (ImageConfiguration imageConfig : images) {
if (imageConfig.getBuildConfiguration() != null) {
Probe livenessProbe = probeHandler.getProbe(config.getLiveness());
Probe readinessProbe = probeHandler.getProbe(config.getReadiness());
Container container = new ContainerBuilder()
.withName(KubernetesResourceUtil.extractContainerName(this.groupArtifactVersion, imageConfig))
.withImage(getImageName(imageConfig))
.withImagePullPolicy(getImagePullPolicy(config))
.withEnv(getEnvVars(config))
.withSecurityContext(createSecurityContext(config))
.withPorts(getContainerPorts(imageConfig))
.withVolumeMounts(getVolumeMounts(config))
.withLivenessProbe(livenessProbe)
.withReadinessProbe(readinessProbe)
.build();
ret.add(container);
}
}
return ret;
}
@Test
public void alreadyExistingInitContainer(@Mocked final ProcessorConfig config) throws Exception {
new Expectations() {{
context.getConfiguration(); result = Configuration.builder().processorConfig(config).build();
}};
PodTemplateBuilder ptb = createEmptyPodTemplate();
addVolume(ptb, "VolumeA");
Container initContainer = new ContainerBuilder()
.withName(VolumePermissionEnricher.ENRICHER_NAME)
.withVolumeMounts(new VolumeMountBuilder().withName("vol-blub").withMountPath("blub").build())
.build();
ptb.editTemplate().editSpec().withInitContainers(Collections.singletonList(initContainer)).endSpec().endTemplate();
KubernetesListBuilder klb = new KubernetesListBuilder().addToPodTemplateItems(ptb.build());
VolumePermissionEnricher enricher = new VolumePermissionEnricher(context);
enricher.enrich(PlatformMode.kubernetes,klb);
List<Container> initS = ((PodTemplate) klb.build().getItems().get(0)).getTemplate().getSpec().getInitContainers();
assertNotNull(initS);
assertEquals(1, initS.size());
Container actualInitContainer = initS.get(0);
assertEquals("blub", actualInitContainer.getVolumeMounts().get(0).getMountPath());
}
private KubernetesListBuilder getPodTemplateList() {
Container container = new ContainerBuilder()
.withName("test-port-enricher")
.withImage("test-image")
.withPorts(new ContainerPortBuilder().withContainerPort(80).withProtocol("TCP").build())
.build();
PodTemplateBuilder ptb = new PodTemplateBuilder()
.withNewMetadata().withName("test-pod")
.endMetadata()
.withNewTemplate()
.withNewSpec()
.withContainers(container)
.endSpec()
.endTemplate();
return new KubernetesListBuilder().addToPodTemplateItems(ptb.build());
}
private Container generateContainer(ServiceModel serviceModel, List<ContainerPort> containerPorts) {
String dockerRegistry = serviceModel.getRegistry();
String deploymentImageName = serviceModel.getImage();
if (null != dockerRegistry && !"".equals(dockerRegistry)) {
deploymentImageName = dockerRegistry + REGISTRY_SEPARATOR + deploymentImageName;
}
return new ContainerBuilder()
.withName(serviceModel.getName())
.withImage(deploymentImageName)
.withPorts(containerPorts)
.withEnv(populateEnvVar(serviceModel.getEnv()))
.withVolumeMounts(populateVolumeMounts(serviceModel))
.withLivenessProbe(generateProbe(serviceModel.getLivenessProbe()))
.withReadinessProbe(generateProbe(serviceModel.getReadinessProbe()))
.build();
}
private List<Container> generateInitContainer(DeploymentModel deploymentModel) throws KubernetesPluginException {
List<Container> initContainers = new ArrayList<>();
for (String dependsOn : deploymentModel.getDependsOn()) {
String serviceName = KubernetesContext.getInstance().getServiceName(dependsOn);
List<String> commands = new ArrayList<>();
commands.add("sh");
commands.add("-c");
commands.add("until nslookup " + serviceName + "; do echo waiting for " + serviceName + "; sleep 2; done;");
initContainers.add(new ContainerBuilder()
.withName("wait-for-" + serviceName)
.withImage("busybox")
.withCommand(commands)
.build());
}
return initContainers;
}
@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();
}
private Container decorateMainContainer(Container container) {
final ResourceRequirements requirements = KubernetesUtils.getResourceRequirements(
kubernetesJobManagerParameters.getJobManagerMemoryMB(),
kubernetesJobManagerParameters.getJobManagerCPU(),
Collections.emptyMap());
return new ContainerBuilder(container)
.withName(kubernetesJobManagerParameters.getJobManagerMainContainerName())
.withImage(kubernetesJobManagerParameters.getImage())
.withImagePullPolicy(kubernetesJobManagerParameters.getImagePullPolicy().name())
.withResources(requirements)
.withPorts(getContainerPorts())
.withEnv(getCustomizedEnvs())
.addNewEnv()
.withName(ENV_FLINK_POD_IP_ADDRESS)
.withValueFrom(new EnvVarSourceBuilder()
.withNewFieldRef(API_VERSION, POD_IP_FIELD_PATH)
.build())
.endEnv()
.build();
}
@Test(
expectedExceptions = InfrastructureException.class,
expectedExceptionsMessageRegExp =
"Unable to mount key 'foo' of secret 'test_secret': It is configured to be mount as a environment variable, but its name was not specified. Please define the 'che.eclipse.org/foo_env-name' annotation on the secret to specify it.")
public void shouldThrowExceptionWhenNoEnvNameSpecifiedMultiValue() throws Exception {
Container container_match = new ContainerBuilder().withName("maven").build();
when(podSpec.getContainers()).thenReturn(ImmutableList.of(container_match));
Secret secret =
new SecretBuilder()
.withData(ImmutableMap.of("foo", "random", "bar", "test"))
.withMetadata(
new ObjectMetaBuilder()
.withName("test_secret")
.withAnnotations(
ImmutableMap.of(ANNOTATION_MOUNT_AS, "env", ANNOTATION_AUTOMOUNT, "true"))
.withLabels(emptyMap())
.build())
.build();
when(secrets.get(any(LabelSelector.class))).thenReturn(singletonList(secret));
secretApplier.applySecret(environment, runtimeIdentity, secret);
}
/**
* For StatefulSets, create an init container to parse ${HOSTNAME} to get the `instance.index` and write it to
* config/application.properties on a shared volume so the main container has it. Using the legacy annotation
* configuration since the current client version does not directly support InitContainers.
*
* Since 1.8 the annotation method has been removed, and the initContainer API is supported since 1.6
*
* @param imageName the image name to use in the init container
* @return a container definition with the above mentioned configuration
*/
private Container createStatefulSetInitContainer(String imageName) {
List<String> command = new LinkedList<>();
String commandString = String
.format("%s && %s", setIndexProperty("INSTANCE_INDEX"), setIndexProperty("spring.application.index"));
command.add("sh");
command.add("-c");
command.add(commandString);
return new ContainerBuilder().withName("index-provider")
.withImage(imageName)
.withImagePullPolicy("IfNotPresent")
.withCommand(command)
.withVolumeMounts(new VolumeMountBuilder().withName("config").withMountPath("/config").build())
.build();
}
@Test(
expectedExceptions = InfrastructureException.class,
expectedExceptionsMessageRegExp =
"Unable to mount secret 'test_secret': It is configured to be mounted as a file but the mount path was not specified. Please define the 'che.eclipse.org/mount-path' annotation on the secret to specify it.")
public void shouldThrowExceptionWhenNoMountPathSpecifiedForFiles() throws Exception {
Container container_match = new ContainerBuilder().withName("maven").build();
PodSpec localSpec =
new PodSpecBuilder().withContainers(ImmutableList.of(container_match)).build();
when(podData.getSpec()).thenReturn(localSpec);
Secret secret =
new SecretBuilder()
.withData(ImmutableMap.of("settings.xml", "random", "another.xml", "freedom"))
.withMetadata(
new ObjectMetaBuilder()
.withName("test_secret")
.withAnnotations(singletonMap(ANNOTATION_MOUNT_AS, "file"))
.withLabels(emptyMap())
.build())
.build();
when(secrets.get(any(LabelSelector.class))).thenReturn(singletonList(secret));
secretApplier.applySecret(environment, runtimeIdentity, secret);
}
@Test
public void shouldGenerateContainerNamesIfCollisionHappened() throws Exception {
// given
PodSpec podSpec1 =
new PodSpecBuilder().withContainers(new ContainerBuilder().withName("c").build()).build();
PodData podData1 = new PodData(podSpec1, new ObjectMetaBuilder().build());
PodSpec podSpec2 =
new PodSpecBuilder().withContainers(new ContainerBuilder().withName("c").build()).build();
PodData podData2 = new PodData(podSpec2, new ObjectMetaBuilder().build());
// when
Deployment merged = podMerger.merge(Arrays.asList(podData1, podData2));
// then
PodTemplateSpec podTemplate = merged.getSpec().getTemplate();
List<Container> containers = podTemplate.getSpec().getContainers();
assertEquals(containers.size(), 2);
Container container1 = containers.get(0);
assertEquals(container1.getName(), "c");
Container container2 = containers.get(1);
assertNotEquals(container2.getName(), "c");
assertTrue(container2.getName().startsWith("c"));
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
return singletonList(new ContainerBuilder()
.withName(USER_OPERATOR_CONTAINER_NAME)
.withImage(getImage())
.withArgs("/opt/strimzi/bin/user_operator_run.sh")
.withEnv(getEnvVars())
.withPorts(singletonList(createContainerPort(HEALTHCHECK_PORT_NAME, HEALTHCHECK_PORT, "TCP")))
.withLivenessProbe(createHttpProbe(livenessPath + "healthy", HEALTHCHECK_PORT_NAME, livenessProbeOptions))
.withReadinessProbe(createHttpProbe(readinessPath + "ready", HEALTHCHECK_PORT_NAME, readinessProbeOptions))
.withResources(getResources())
.withVolumeMounts(getVolumeMounts())
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateContainerSecurityContext)
.build());
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
List<Container> containers = new ArrayList<>(1);
Container container = new ContainerBuilder()
.withName(ZOOKEEPER_NAME)
.withImage(getImage())
.withCommand("/opt/kafka/zookeeper_run.sh")
.withEnv(getEnvVars())
.withVolumeMounts(getVolumeMounts())
.withPorts(getContainerPortList())
.withLivenessProbe(ModelUtils.createExecProbe(Collections.singletonList(livenessPath), livenessProbeOptions))
.withReadinessProbe(ModelUtils.createExecProbe(Collections.singletonList(readinessPath), readinessProbeOptions))
.withResources(getResources())
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateZookeeperContainerSecurityContext)
.build();
containers.add(container);
return containers;
}
@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");
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
List<Container> containers = new ArrayList<>(1);
Container container = new ContainerBuilder()
.withName(name)
.withImage(getImage())
.withCommand("/opt/kafka-exporter/kafka_exporter_run.sh")
.withEnv(getEnvVars())
.withPorts(getContainerPortList())
.withLivenessProbe(ModelUtils.createHttpProbe(livenessPath, METRICS_PORT_NAME, livenessProbeOptions))
.withReadinessProbe(ModelUtils.createHttpProbe(readinessPath, METRICS_PORT_NAME, readinessProbeOptions))
.withResources(getResources())
.withVolumeMounts(VolumeUtils.createVolumeMount(KAFKA_EXPORTER_CERTS_VOLUME_NAME, KAFKA_EXPORTER_CERTS_VOLUME_MOUNT),
VolumeUtils.createVolumeMount(CLUSTER_CA_CERTS_VOLUME_NAME, CLUSTER_CA_CERTS_VOLUME_MOUNT))
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateContainerSecurityContext)
.build();
containers.add(container);
return containers;
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
List<Container> containers = new ArrayList<>(1);
Container container = new ContainerBuilder()
.withName(name)
.withImage(getImage())
.withCommand(getCommand())
.withEnv(getEnvVars())
.withPorts(getContainerPortList())
.withLivenessProbe(createHttpProbe(livenessPath, REST_API_PORT_NAME, livenessProbeOptions))
.withReadinessProbe(createHttpProbe(readinessPath, REST_API_PORT_NAME, readinessProbeOptions))
.withVolumeMounts(getVolumeMounts())
.withResources(getResources())
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateContainerSecurityContext)
.build();
containers.add(container);
return containers;
}
@Override
protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) {
List<Container> containers = new ArrayList<>(1);
Container container = new ContainerBuilder()
.withName(name)
.withImage(getImage())
.withEnv(getEnvVars())
.withReadinessProbe(jmxTransReadinessProbe(readinessProbeOptions, clusterName))
.withResources(getResources())
.withVolumeMounts(getVolumeMounts())
.withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage()))
.withSecurityContext(templateContainerSecurityContext)
.build();
containers.add(container);
return containers;
}
@Test
public void appliesContainerEnvVarToPodTemplate() {
Container actualContainer = new ContainerBuilder()
.withName("foo")
.withEnv(FOO1_ENVVAR, FOO2_ENVAR).build();
Container desiredContainer = new ContainerBuilder()
.withName("foo")
.withEnv(FOO1_UPD_ENVVAR, FOO3_ENVVAR).build();
PodTemplateSpec actual = doApplyContainers(actualContainer, desiredContainer);
Container container = actual.getSpec().getContainers().get(0);
List<EnvVar> probe = container.getEnv();
assertThat(probe.size(), equalTo(3));
assertThat(probe, containsInAnyOrder(FOO1_UPD_ENVVAR, FOO2_ENVAR, FOO3_ENVVAR));
}
@Test
public void appliesInitContainerEnvVarToPodTemplate() {
Container actualContainer = new ContainerBuilder()
.withName("foo")
.withEnv(FOO1_ENVVAR).build();
Container desiredContainer = new ContainerBuilder()
.withName("foo")
.withEnv(FOO1_UPD_ENVVAR).build();
PodTemplateSpec actual = doApplyInitContainers(actualContainer, desiredContainer);
Container container = actual.getSpec().getInitContainers().get(0);
List<EnvVar> probe = container.getEnv();
assertThat(probe.size(), equalTo(1));
assertThat(probe, containsInAnyOrder(FOO1_UPD_ENVVAR));
}
@Test
public void appliesContainerLivenessProbeSettingsToPodTemplate() {
Container actualContainer = new ContainerBuilder()
.withName("foo")
.withLivenessProbe(new ProbeBuilder()
.withInitialDelaySeconds(1)
.withPeriodSeconds(2)
.withFailureThreshold(4).build()).build();
Container desiredContainer = new ContainerBuilder()
.withName("foo")
.withLivenessProbe(new ProbeBuilder()
.withInitialDelaySeconds(10)
.withSuccessThreshold(80).build()).build();
PodTemplateSpec actual = doApplyContainers(actualContainer, desiredContainer);
Container container = actual.getSpec().getContainers().get(0);
Probe probe = container.getLivenessProbe();
assertThat(probe.getInitialDelaySeconds(), equalTo(10));
assertThat(probe.getPeriodSeconds(), equalTo(2));
assertThat(probe.getFailureThreshold(), equalTo(4));
assertThat(probe.getSuccessThreshold(), equalTo(80));
}
@BeforeMethod
public void setUp() throws Exception {
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();
PodData podData = new PodData(pod.getSpec(), pod.getMetadata());
this.serverExposer =
new KubernetesServerExposer<>(
externalServerExposer,
secureServerExposer,
MACHINE_NAME,
podData,
container,
kubernetesEnvironment);
}
@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);
}
@Test
public void rewritePodConfigMapEnvFrom() throws Exception {
when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);
ConfigMap configMap = newConfigMap();
doReturn(ImmutableMap.of(CONFIGMAP_NAME, configMap)).when(k8sEnv).getConfigMaps();
EnvFromSource envFrom =
new EnvFromSourceBuilder()
.withNewConfigMapRef()
.withName(CONFIGMAP_NAME)
.endConfigMapRef()
.build();
Container container = new ContainerBuilder().withEnvFrom(envFrom).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();
EnvFromSource newEnvFromSource = container.getEnvFrom().iterator().next();
assertEquals(newEnvFromSource.getConfigMapRef().getName(), newConfigMapName);
}
@Test
public void doesNotRewritePodConfigMapEnvFromWhenNoConfigMap() throws Exception {
when(runtimeIdentity.getWorkspaceId()).thenReturn(WORKSPACE_ID);
EnvFromSource envFrom =
new EnvFromSourceBuilder()
.withNewConfigMapRef()
.withName(CONFIGMAP_NAME)
.endConfigMapRef()
.build();
Container container = new ContainerBuilder().withEnvFrom(envFrom).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);
EnvFromSource newEnvFromSource = container.getEnvFrom().iterator().next();
assertEquals(newEnvFromSource.getConfigMapRef().getName(), CONFIGMAP_NAME);
}
private Container decorateMainContainer(Container container) {
final ResourceRequirements resourceRequirements = KubernetesUtils.getResourceRequirements(
kubernetesTaskManagerParameters.getTaskManagerMemoryMB(),
kubernetesTaskManagerParameters.getTaskManagerCPU(),
kubernetesTaskManagerParameters.getTaskManagerExternalResources());
return new ContainerBuilder(container)
.withName(kubernetesTaskManagerParameters.getTaskManagerMainContainerName())
.withImage(kubernetesTaskManagerParameters.getImage())
.withImagePullPolicy(kubernetesTaskManagerParameters.getImagePullPolicy().name())
.withResources(resourceRequirements)
.withPorts(new ContainerPortBuilder()
.withName(Constants.TASK_MANAGER_RPC_PORT_NAME)
.withContainerPort(kubernetesTaskManagerParameters.getRPCPort())
.build())
.withEnv(getCustomizedEnvs())
.build();
}
@Test(
expectedExceptions = InfrastructureException.class,
expectedExceptionsMessageRegExp =
"Unable to mount secret 'test_secret': It is configured to be mount as a environment variable, but its name was not specified. Please define the 'che.eclipse.org/env-name' annotation on the secret to specify it.")
public void shouldThrowExceptionWhenNoEnvNameSpecifiedSingleValue() throws Exception {
Container container_match = new ContainerBuilder().withName("maven").build();
when(podSpec.getContainers()).thenReturn(ImmutableList.of(container_match));
Secret secret =
new SecretBuilder()
.withData(singletonMap("foo", "random"))
.withMetadata(
new ObjectMetaBuilder()
.withName("test_secret")
.withAnnotations(
ImmutableMap.of(ANNOTATION_MOUNT_AS, "env", ANNOTATION_AUTOMOUNT, "true"))
.withLabels(emptyMap())
.build())
.build();
when(secrets.get(any(LabelSelector.class))).thenReturn(singletonList(secret));
secretApplier.applySecret(environment, runtimeIdentity, secret);
}
private Container container(String roadName, List<String> args, Map<String, String> config, String truckParkName) {
List<EnvVar> env = ImmutableList
.<EnvVar> builder()
.add(envFromFieldPath("KUBERNETES_NAMESPACE", "metadata.namespace"))
.add(env("POD_NAME", truckParkName))
.add(env("ENVIRONMENT", environment))
.add(env("JVM_ARGS", config.get(JVM_ARGS)))
.add(env("CLOUDWATCH_REGION", config.get(CLOUDWATCH_REGION)))
.add(env("CLOUDWATCH_GROUP", config.get(CLOUDWATCH_GROUP)))
.add(env("CLOUDWATCH_STREAM", "${KUBERNETES_NAMESPACE}-truck-park-" + roadName))
.build();
Map<String, Quantity> limits = ImmutableMap
.<String, Quantity> builder()
.put(CPU, new Quantity(config.get(CPU)))
.put(MEMORY, new Quantity(config.get(MEMORY)))
.build();
return new ContainerBuilder()
.withName(truckParkName)
.withImage(config.get(DOCKER_IMAGE))
.withArgs(args)
.withEnv(env)
.withResources(new ResourceRequirementsBuilder().withLimits(limits).withRequests(limits).build())
.withLivenessProbe(new ProbeBuilder()
.withHttpGet(new HTTPGetActionBuilder().withPath("/").withPort(new IntOrString("http")).build())
.withInitialDelaySeconds(getConfigOrDefault(config, "livenessInitialDelay", 30))
.withPeriodSeconds(getConfigOrDefault(config, "livenessPeriod", 5))
.withSuccessThreshold(getConfigOrDefault(config, "livenessSuccessThreshold", 1))
.withTimeoutSeconds(getConfigOrDefault(config, "livenessTimeout", 5))
.withFailureThreshold(getConfigOrDefault(config, "livenessFailureThreshold", 3))
.build())
.build();
}
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();
}
@BeforeMethod
public void setUp() throws Exception {
// Workspace env setup
ObjectMeta workspacePodMeta =
new ObjectMetaBuilder().withAnnotations(workspacePodAnnotations).build();
workspacePod = new PodBuilder().withMetadata(workspacePodMeta).withSpec(new PodSpec()).build();
Map<String, ConfigMap> workspaceConfigMaps = new HashMap<>();
workspaceEnvironment =
KubernetesEnvironment.builder()
.setPods(ImmutableMap.of(WORKSPACE_POD_NAME, workspacePod))
.setMachines(new HashMap<>())
.setConfigMaps(workspaceConfigMaps)
.build();
// Broker env setup
ObjectMeta brokerPodMeta =
new ObjectMetaBuilder().withAnnotations(brokerPodAnnotations).build();
brokerContainer = new ContainerBuilder().withName(BROKER_CONTAINER_NAME).build();
brokerVolume = new VolumeBuilder().build();
Pod brokerPod =
new PodBuilder()
.withMetadata(brokerPodMeta)
.withNewSpec()
.withContainers(brokerContainer)
.withVolumes(brokerVolume)
.endSpec()
.build();
brokerConfigMap = new ConfigMapBuilder().addToData(brokerConfigMapData).build();
KubernetesEnvironment brokerEnvironment =
KubernetesEnvironment.builder()
.setPods(ImmutableMap.of(BROKER_POD_NAME, brokerPod))
.setConfigMaps(ImmutableMap.of(BROKER_CONFIGMAP_NAME, brokerConfigMap))
.setMachines(ImmutableMap.of(BROKER_MACHINE_NAME, brokerMachine))
.build();
doReturn(brokerEnvironment)
.when(brokerEnvironmentFactory)
.createForArtifactsBroker(any(), any());
applier = new KubernetesArtifactsBrokerApplier<>(brokerEnvironmentFactory);
}
@Before
public void configureCloud() throws Exception {
cloud = setupCloud(this, name);
client = cloud.connect();
deletePods(client, getLabels(this, name), false);
String image = "busybox";
Container c = new ContainerBuilder().withName(image).withImagePullPolicy("IfNotPresent").withImage(image)
.withCommand("cat").withTty(true).build();
Container d = new ContainerBuilder().withName(image + "1").withImagePullPolicy("IfNotPresent").withImage(image)
.withCommand("cat").withTty(true).withWorkingDir("/home/jenkins/agent1").build();
String podName = "test-command-execution-" + RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
pod = client.pods().create(new PodBuilder().withNewMetadata().withName(podName)
.withLabels(getLabels(this, name)).endMetadata().withNewSpec().withContainers(c, d).withNodeSelector(Collections.singletonMap("kubernetes.io/os", "linux")).withTerminationGracePeriodSeconds(0L).endSpec().build());
System.out.println("Created pod: " + pod.getMetadata().getName());
PodTemplate template = new PodTemplate();
template.setName(pod.getMetadata().getName());
agent = mock(KubernetesSlave.class);
when(agent.getNamespace()).thenReturn(client.getNamespace());
when(agent.getPodName()).thenReturn(pod.getMetadata().getName());
doReturn(cloud).when(agent).getKubernetesCloud();
when(agent.getPod()).thenReturn(Optional.of(pod));
StepContext context = mock(StepContext.class);
when(context.get(Node.class)).thenReturn(agent);
decorator = new ContainerExecDecorator();
decorator.setNodeContext(new KubernetesNodeContext(context));
decorator.setContainerName(image);
}