use of io.fabric8.kubernetes.api.model.ContainerPort in project elastest-torm by elastest.
the class K8sService method createDaemonSetFromContainerInfo.
public boolean createDaemonSetFromContainerInfo(DockerContainer container, String namespace) {
Boolean created = false;
try {
logger.info("Creating Daemon Set from container name {} in namespace {}", container.getContainerName().get(), namespace);
if (container.getCmd().isPresent()) {
logger.info(String.join(",", container.getCmd().get()));
}
String containerNameWithoutUnderscore = container.getContainerName().get().replace("_", "-");
Map<String, String> k8sPobLabels = container.getLabels().get();
k8sPobLabels.put(LABEL_POD_NAME, container.getContainerName().get());
k8sPobLabels.put(LABEL_COMPONENT, containerNameWithoutUnderscore);
// Create Container
ContainerBuilder containerBuilder = new ContainerBuilder();
containerBuilder.withName(containerNameWithoutUnderscore).withImage(container.getImageId()).withEnv(getEnvVarListFromStringList(container.getEnvs().get()));
// Add ports
if (container.getExposedPorts().isPresent() && !container.getExposedPorts().get().isEmpty()) {
List<ContainerPort> ports = new ArrayList<>();
container.getExposedPorts().get().forEach(port -> {
ContainerPort containerPort = new ContainerPort();
containerPort.setContainerPort(new Integer(port));
ports.add(containerPort);
});
containerBuilder.withPorts(ports);
}
if (container.getCapAdd().isPresent() && !container.getCapAdd().get().isEmpty()) {
SecurityContextBuilder securityContextBuilder = new SecurityContextBuilder();
List<String> stringCapabilities = new ArrayList<>();
container.getCapAdd().get().forEach(cap -> {
stringCapabilities.add(cap);
});
Capabilities capabilities = new CapabilitiesBuilder().withAdd(stringCapabilities).build();
securityContextBuilder.withCapabilities(capabilities);
containerBuilder.withSecurityContext(securityContextBuilder.build());
}
// Add volumes if there are
List<Volume> volumes = new ArrayList<>();
List<VolumeMount> volumeMounts = new ArrayList<>();
if (container.getVolumeBindList().isPresent() && !container.getVolumeBindList().get().isEmpty()) {
int count = 0;
for (Bind dockerVolume : container.getVolumeBindList().get()) {
VolumeMount volumeMount = new VolumeMountBuilder().withName("v-" + count).withMountPath(dockerVolume.to()).build();
volumeMounts.add(volumeMount);
HostPathVolumeSource hostPath = new HostPathVolumeSourceBuilder().withPath(dockerVolume.to()).build();
Volume volume = new VolumeBuilder().withName("v-" + count).withHostPath(hostPath).build();
volumes.add(volume);
count++;
}
containerBuilder.withVolumeMounts(volumeMounts);
}
LabelSelectorBuilder selectorBuilder = new LabelSelectorBuilder();
LabelSelector labelSelector = selectorBuilder.withMatchLabels(Collections.singletonMap(LABEL_COMPONENT, containerNameWithoutUnderscore)).build();
// String dName = "daemonset-" + containerNameWithoutUnderscore;
DaemonSet daemonSet = new DaemonSetBuilder().withNewMetadata().withName(containerNameWithoutUnderscore).withNamespace(namespace).withLabels(k8sPobLabels).endMetadata().withNewSpec().withSelector(labelSelector).withNewTemplate().withNewMetadata().withLabels(k8sPobLabels).endMetadata().withNewSpec().addNewContainerLike(containerBuilder.build()).endContainer().withVolumes(volumes).endSpec().endTemplate().endSpec().build();
client.apps().daemonSets().create(daemonSet);
client.apps().daemonSets().inNamespace(namespace).withName(containerNameWithoutUnderscore).cascading(true);
} catch (Exception e) {
logger.error("Error deploying DaemonSet");
e.printStackTrace();
throw e;
}
return created;
}
use of io.fabric8.kubernetes.api.model.ContainerPort in project kubernetes by ballerinax.
the class DeploymentHandler method generateContainer.
private Container generateContainer(DeploymentModel deploymentModel, List<ContainerPort> containerPorts) throws KubernetesPluginException {
String dockerRegistry = deploymentModel.getRegistry();
String deploymentImageName = deploymentModel.getImage();
if (null != dockerRegistry && !"".equals(dockerRegistry)) {
deploymentImageName = dockerRegistry + REGISTRY_SEPARATOR + deploymentImageName;
}
if (deploymentModel.getBuildExtension() != null) {
if (deploymentModel.getBuildExtension() instanceof OpenShiftBuildExtensionModel) {
OpenShiftBuildExtensionModel openShiftBC = (OpenShiftBuildExtensionModel) deploymentModel.getBuildExtension();
openShiftBC.setName(deploymentModel.getName().replace(DEPLOYMENT_POSTFIX, OPENSHIFT_BUILD_CONFIG_POSTFIX));
dataHolder.setOpenShiftBuildExtensionModel(openShiftBC);
dockerRegistry = deploymentModel.getRegistry();
if (dockerRegistry == null || "".equals(dockerRegistry.trim())) {
throw new KubernetesPluginException("value for 'registry' field in @kubernetes:Deployment{} " + "annotation is required to generate OpenShift Build Configs.");
}
String namespace = dataHolder.getNamespace();
if (namespace == null || "".equals(namespace.trim())) {
throw new KubernetesPluginException("value for 'namespace' field in @kubernetes:Deployment{} " + "annotation is required to generate OpenShift Build Configs. " + "use the value of the OpenShift project name.");
}
deploymentImageName = dockerRegistry + REGISTRY_SEPARATOR + namespace + REGISTRY_SEPARATOR + deploymentModel.getImage();
}
}
return new ContainerBuilder().withName(deploymentModel.getName()).withImage(deploymentImageName).withImagePullPolicy(deploymentModel.getImagePullPolicy()).withPorts(containerPorts).withEnv(populateEnvVar(deploymentModel.getEnv())).withVolumeMounts(populateVolumeMounts(deploymentModel)).withLivenessProbe(generateProbe(deploymentModel.getLivenessProbe())).withReadinessProbe(generateProbe(deploymentModel.getReadinessProbe())).build();
}
use of io.fabric8.kubernetes.api.model.ContainerPort in project kubernetes by ballerinax.
the class PrometheusTest method nodePortPrometheusTest.
/**
* Build bal file with NodePort prometheus settings.
*
* @throws IOException Error when loading the generated yaml.
* @throws InterruptedException Error when compiling the ballerina file.
* @throws KubernetesPluginException Error when deleting the generated artifacts folder.
*/
@Test
public void nodePortPrometheusTest() throws IOException, InterruptedException, KubernetesPluginException, DockerTestException {
Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(BAL_DIRECTORY, "nodeport.bal"), 0);
// Check if docker image exists and correct
validateDockerfile();
validateDockerImage();
// Validate deployment yaml
File deploymentYAML = KUBERNETES_TARGET_PATH.resolve("nodeport_deployment.yaml").toFile();
Assert.assertTrue(deploymentYAML.exists());
Deployment deployment = KubernetesTestUtils.loadYaml(deploymentYAML);
Assert.assertNotNull(deployment.getSpec());
Assert.assertNotNull(deployment.getSpec().getTemplate());
Assert.assertNotNull(deployment.getSpec().getTemplate().getSpec());
Assert.assertTrue(deployment.getSpec().getTemplate().getSpec().getContainers().size() > 0);
final List<ContainerPort> ports = deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getPorts();
Assert.assertEquals(ports.size(), 2);
Assert.assertEquals(ports.get(0).getContainerPort().intValue(), 9090);
Assert.assertEquals(ports.get(1).getContainerPort().intValue(), 9898);
// Validate svc yaml
File svcYAML = KUBERNETES_TARGET_PATH.resolve("nodeport_svc.yaml").toFile();
Assert.assertTrue(svcYAML.exists());
Service svc = KubernetesTestUtils.loadYaml(svcYAML);
Assert.assertEquals(svc.getSpec().getPorts().size(), 1);
final ServicePort servicePort = svc.getSpec().getPorts().get(0);
Assert.assertEquals(servicePort.getPort().intValue(), 9090);
Assert.assertEquals(servicePort.getProtocol(), "TCP");
Assert.assertEquals(servicePort.getTargetPort().getIntVal().intValue(), 9090);
Assert.assertEquals(svc.getSpec().getType(), "ClusterIP");
Assert.assertEquals(svc.getMetadata().getName(), "helloep-svc");
Assert.assertEquals(svc.getSpec().getSelector().get("app"), "nodeport");
// Validate prometheus svc yaml
File svcPrometheusYAML = KUBERNETES_TARGET_PATH.resolve("nodeport_prometheus_svc.yaml").toFile();
Assert.assertTrue(svcPrometheusYAML.exists());
Service svcPrometheus = KubernetesTestUtils.loadYaml(svcPrometheusYAML);
Assert.assertEquals(svcPrometheus.getSpec().getPorts().size(), 1);
final ServicePort prometheusSvcPort = svcPrometheus.getSpec().getPorts().get(0);
Assert.assertEquals(prometheusSvcPort.getPort().intValue(), 9898);
Assert.assertEquals(prometheusSvcPort.getProtocol(), "TCP");
Assert.assertEquals(prometheusSvcPort.getTargetPort().getIntVal().intValue(), 9898);
Assert.assertEquals(svcPrometheus.getSpec().getType(), "NodePort");
Assert.assertEquals(svcPrometheus.getMetadata().getName(), "helloep-svc-prometheus");
Assert.assertEquals(svcPrometheus.getSpec().getSelector().get("app"), "nodeport");
KubernetesUtils.deleteDirectory(KUBERNETES_TARGET_PATH);
KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
KubernetesTestUtils.deleteDockerImage(DOCKER_IMAGE);
}
use of io.fabric8.kubernetes.api.model.ContainerPort in project strimzi by strimzi.
the class KafkaCluster method getContainerPortList.
private List<ContainerPort> getContainerPortList() {
List<ContainerPort> ports = new ArrayList<>(listeners.size() + 3);
ports.add(createContainerPort(CONTROLPLANE_PORT_NAME, CONTROLPLANE_PORT, "TCP"));
ports.add(createContainerPort(REPLICATION_PORT_NAME, REPLICATION_PORT, "TCP"));
for (GenericKafkaListener listener : listeners) {
ports.add(createContainerPort(ListenersUtils.backwardsCompatiblePortName(listener), listener.getPort(), "TCP"));
}
if (isMetricsEnabled) {
ports.add(createContainerPort(METRICS_PORT_NAME, METRICS_PORT, "TCP"));
}
return ports;
}
use of io.fabric8.kubernetes.api.model.ContainerPort in project strimzi by strimzi.
the class KafkaClusterTest method testExternalLoadBalancers.
@ParallelTest
public void testExternalLoadBalancers() {
Kafka kafkaAssembly = new KafkaBuilder(ResourceUtils.createKafka(namespace, cluster, replicas, image, healthDelay, healthTimeout, jmxMetricsConfig, configuration, emptyMap())).editSpec().editKafka().withListeners(new GenericKafkaListenerBuilder().withName("external").withPort(9094).withType(KafkaListenerType.LOADBALANCER).withTls(true).withNewKafkaListenerAuthenticationTlsAuth().endKafkaListenerAuthenticationTlsAuth().build()).endKafka().endSpec().build();
KafkaCluster kc = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafkaAssembly, VERSIONS);
// Check StatefulSet changes
StatefulSet sts = kc.generateStatefulSet(true, null, null, null);
List<ContainerPort> ports = sts.getSpec().getTemplate().getSpec().getContainers().get(0).getPorts();
assertThat(ports.contains(kc.createContainerPort(ListenersUtils.BACKWARDS_COMPATIBLE_EXTERNAL_PORT_NAME, 9094, "TCP")), is(true));
// Check external bootstrap service
Service ext = kc.generateExternalBootstrapServices().get(0);
assertThat(ext.getMetadata().getName(), is(KafkaCluster.externalBootstrapServiceName(cluster)));
assertThat(ext.getMetadata().getFinalizers(), is(emptyList()));
assertThat(ext.getSpec().getType(), is("LoadBalancer"));
assertThat(ext.getSpec().getSelector(), is(kc.getSelectorLabels().toMap()));
assertThat(ext.getSpec().getPorts(), is(Collections.singletonList(kc.createServicePort(ListenersUtils.BACKWARDS_COMPATIBLE_EXTERNAL_PORT_NAME, 9094, 9094, "TCP"))));
assertThat(ext.getSpec().getLoadBalancerIP(), is(nullValue()));
assertThat(ext.getSpec().getExternalTrafficPolicy(), is("Cluster"));
assertThat(ext.getSpec().getLoadBalancerSourceRanges(), is(emptyList()));
checkOwnerReference(kc.createOwnerReference(), ext);
// Check per pod services
for (int i = 0; i < replicas; i++) {
Service srv = kc.generateExternalServices(i).get(0);
assertThat(srv.getMetadata().getName(), is(KafkaCluster.externalServiceName(cluster, i)));
assertThat(srv.getMetadata().getFinalizers(), is(emptyList()));
assertThat(srv.getSpec().getType(), is("LoadBalancer"));
assertThat(srv.getSpec().getSelector().get(Labels.KUBERNETES_STATEFULSET_POD_LABEL), is(KafkaCluster.kafkaPodName(cluster, i)));
assertThat(srv.getSpec().getPorts(), is(Collections.singletonList(kc.createServicePort(ListenersUtils.BACKWARDS_COMPATIBLE_EXTERNAL_PORT_NAME, 9094, 9094, "TCP"))));
assertThat(srv.getSpec().getLoadBalancerIP(), is(nullValue()));
assertThat(srv.getSpec().getExternalTrafficPolicy(), is("Cluster"));
assertThat(srv.getSpec().getLoadBalancerSourceRanges(), is(emptyList()));
checkOwnerReference(kc.createOwnerReference(), srv);
}
}
Aggregations