Search in sources :

Example 16 with ContainerPort

use of io.fabric8.kubernetes.api.model.ContainerPort in project che-server by eclipse-che.

the class KubernetesInternalRuntimeTest method mockContainer.

private static Container mockContainer(String name, int... ports) {
    final Container container = mock(Container.class);
    when(container.getName()).thenReturn(name);
    final List<ContainerPort> containerPorts = new ArrayList<>(ports.length);
    for (int port : ports) {
        containerPorts.add(new ContainerPortBuilder().withContainerPort(port).build());
    }
    when(container.getPorts()).thenReturn(containerPorts);
    return container;
}
Also used : Container(io.fabric8.kubernetes.api.model.Container) ContainerPortBuilder(io.fabric8.kubernetes.api.model.ContainerPortBuilder) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) ArrayList(java.util.ArrayList)

Example 17 with ContainerPort

use of io.fabric8.kubernetes.api.model.ContainerPort in project java-operator-sdk by java-operator-sdk.

the class KubernetesResourceStatusUpdateIT method testDeployment.

private Deployment testDeployment() {
    Deployment resource = new Deployment();
    Map<String, String> labels = new HashMap<>();
    labels.put("test", "KubernetesResourceStatusUpdateIT");
    resource.setMetadata(new ObjectMetaBuilder().withName("test-deployment").withLabels(labels).build());
    DeploymentSpec spec = new DeploymentSpec();
    resource.setSpec(spec);
    spec.setReplicas(1);
    var labelSelector = new HashMap<String, String>();
    labelSelector.put("app", "nginx");
    spec.setSelector(new LabelSelector(null, labelSelector));
    PodTemplateSpec podTemplate = new PodTemplateSpec();
    spec.setTemplate(podTemplate);
    podTemplate.setMetadata(new ObjectMeta());
    podTemplate.getMetadata().setLabels(labelSelector);
    podTemplate.setSpec(new PodSpec());
    Container container = new Container();
    container.setName("nginx");
    container.setImage("nginx:1.21.4");
    ContainerPort port = new ContainerPort();
    port.setContainerPort(80);
    container.setPorts(List.of(port));
    podTemplate.getSpec().setContainers(List.of(container));
    return resource;
}
Also used : HashMap(java.util.HashMap) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) DeploymentSpec(io.fabric8.kubernetes.api.model.apps.DeploymentSpec)

Example 18 with ContainerPort

use of io.fabric8.kubernetes.api.model.ContainerPort in project devspaces-images by redhat-developer.

the class KubernetesInternalRuntimeTest method mockContainer.

private static Container mockContainer(String name, int... ports) {
    final Container container = mock(Container.class);
    when(container.getName()).thenReturn(name);
    final List<ContainerPort> containerPorts = new ArrayList<>(ports.length);
    for (int port : ports) {
        containerPorts.add(new ContainerPortBuilder().withContainerPort(port).build());
    }
    when(container.getPorts()).thenReturn(containerPorts);
    return container;
}
Also used : Container(io.fabric8.kubernetes.api.model.Container) ContainerPortBuilder(io.fabric8.kubernetes.api.model.ContainerPortBuilder) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) ArrayList(java.util.ArrayList)

Example 19 with ContainerPort

use of io.fabric8.kubernetes.api.model.ContainerPort in project kubernetes-client by fabric8io.

the class PortForwardExample method main.

public static void main(String[] args) {
    final ConfigBuilder configBuilder = new ConfigBuilder();
    if (args.length > 0) {
        configBuilder.withMasterUrl(args[0]);
        logger.info("Using master with URL: {}", args[0]);
    }
    try (KubernetesClient client = new KubernetesClientBuilder().withConfig(configBuilder.build()).build()) {
        String namespace = "default";
        logger.info("Using namespace: {}", namespace);
        Pod pod = client.pods().inNamespace(namespace).load(PortForwardExample.class.getResourceAsStream("/portforward-example-pod.yml")).get();
        final String podName = pod.getMetadata().getName();
        client.pods().inNamespace(namespace).create(pod);
        logger.info("Pod {} created", podName);
        int containerPort = pod.getSpec().getContainers().get(0).getPorts().get(0).getContainerPort();
        client.pods().inNamespace(namespace).withName(podName).waitUntilReady(10, TimeUnit.SECONDS);
        InetAddress inetAddress = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
        LocalPortForward portForward = client.pods().inNamespace("default").withName("testpod").portForward(containerPort, inetAddress, 8080);
        logger.info("Port forwarded for 60 seconds at http://127.0.0.1:{}", portForward.getLocalPort());
        logger.info("Checking forwarded port:-");
        final ResponseBody responseBody = new OkHttpClient().newCall(new Request.Builder().get().url("http://127.0.0.1:" + portForward.getLocalPort()).build()).execute().body();
        logger.info("Response: \n{}", responseBody != null ? responseBody.string() : "[Empty Body]");
        Thread.sleep(60 * 1000L);
        logger.info("Closing forwarded port");
        portForward.close();
    } catch (Exception e) {
        logger.error("Exception occurred: {}", e.getMessage(), e);
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) LocalPortForward(io.fabric8.kubernetes.client.LocalPortForward) OkHttpClient(okhttp3.OkHttpClient) Pod(io.fabric8.kubernetes.api.model.Pod) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) KubernetesClientBuilder(io.fabric8.kubernetes.client.KubernetesClientBuilder) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) InetAddress(java.net.InetAddress) ResponseBody(okhttp3.ResponseBody)

Example 20 with ContainerPort

use of io.fabric8.kubernetes.api.model.ContainerPort in project elastest-torm by elastest.

the class K8sService method deployPod.

public PodInfo deployPod(DockerContainer container, String namespace) throws Exception {
    PodInfo podInfo = new PodInfo();
    Pod pod = null;
    try {
        namespace = namespace != null ? namespace : DEFAULT_NAMESPACE;
        String podName = container.getContainerName().get();
        logger.info("Deploying pod with name {} in namespace {}", podName, namespace);
        if (container.getCmd().isPresent()) {
            logger.info(String.join(",", container.getCmd().get()));
        }
        Map<String, String> k8sPobLabels = container.getLabels().get();
        k8sPobLabels.put(LABEL_POD_NAME, podName);
        String podNameWithoutUnderscore = podName.replace("_", "-");
        k8sPobLabels.put(LABEL_COMPONENT, podNameWithoutUnderscore);
        k8sPobLabels.put(LABEL_COMPONENT_TYPE, getETComponentType(podNameWithoutUnderscore));
        // Create Container
        ContainerBuilder containerBuilder = new ContainerBuilder();
        containerBuilder.withName(podNameWithoutUnderscore).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);
        }
        PodBuilder podBuilder = new PodBuilder();
        // Set Labels if there are
        if (container.getLabels().isPresent() && container.getLabels().get().size() > 0) {
            k8sPobLabels.putAll(container.getLabels().get());
        }
        podBuilder.withNewMetadata().withName(podNameWithoutUnderscore).withLabels(k8sPobLabels).endMetadata().withNewSpec().addNewContainerLike(containerBuilder.build()).endContainer().withVolumes(volumes).endSpec();
        podBuilder.buildSpec().getContainers().get(0);
        pod = client.pods().inNamespace(namespace).createOrReplace(podBuilder.build());
        logger.info("Pod with name {} has been created in namespace {}", podName, namespace);
        logger.info("Waiting for Pod with name {} in namespace {}...", podName, namespace);
        while (!isReady(podNameWithoutUnderscore, namespace)) {
            UtilTools.sleep(1);
        }
        pod = client.pods().inNamespace(namespace).withName(podNameWithoutUnderscore).get();
        if (pod == null) {
            throw new Exception("the pod with name " + podName + " could not be obtained. Is null");
        }
        logger.debug("Pod with name {} ip: {}", podName, pod.getStatus().getPodIP());
    } catch (final KubernetesClientException e) {
        logger.error("Unable to create job", e);
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    podInfo.setPodIp(pod.getStatus().getPodIP());
    podInfo.setPodName(pod.getMetadata().getName());
    return podInfo;
}
Also used : Bind(com.spotify.docker.client.messages.HostConfig.Bind) ArrayList(java.util.ArrayList) VolumeBuilder(io.fabric8.kubernetes.api.model.VolumeBuilder) SecurityContextBuilder(io.fabric8.kubernetes.api.model.SecurityContextBuilder) ContainerBuilder(io.fabric8.kubernetes.api.model.ContainerBuilder) HostPathVolumeSourceBuilder(io.fabric8.kubernetes.api.model.HostPathVolumeSourceBuilder) CapabilitiesBuilder(io.fabric8.kubernetes.api.model.CapabilitiesBuilder) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) HostPathVolumeSource(io.fabric8.kubernetes.api.model.HostPathVolumeSource) Pod(io.fabric8.kubernetes.api.model.Pod) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) VolumeMountBuilder(io.fabric8.kubernetes.api.model.VolumeMountBuilder) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Volume(io.fabric8.kubernetes.api.model.Volume) Capabilities(io.fabric8.kubernetes.api.model.Capabilities) VolumeMount(io.fabric8.kubernetes.api.model.VolumeMount) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Aggregations

ContainerPort (io.fabric8.kubernetes.api.model.ContainerPort)84 ArrayList (java.util.ArrayList)34 ContainerPortBuilder (io.fabric8.kubernetes.api.model.ContainerPortBuilder)31 Container (io.fabric8.kubernetes.api.model.Container)30 Pod (io.fabric8.kubernetes.api.model.Pod)22 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)18 EnvVar (io.fabric8.kubernetes.api.model.EnvVar)17 Test (org.junit.jupiter.api.Test)16 Service (io.fabric8.kubernetes.api.model.Service)13 TopologySpreadConstraint (io.fabric8.kubernetes.api.model.TopologySpreadConstraint)12 HashMap (java.util.HashMap)12 ServicePortBuilder (io.fabric8.kubernetes.api.model.ServicePortBuilder)11 IOException (java.io.IOException)11 LinkedList (java.util.LinkedList)11 PodSpec (io.fabric8.kubernetes.api.model.PodSpec)10 ServiceSpecBuilder (io.fabric8.kubernetes.api.model.ServiceSpecBuilder)10 StatefulSet (io.fabric8.kubernetes.api.model.apps.StatefulSet)10 Kafka (io.strimzi.api.kafka.model.Kafka)10 KafkaBuilder (io.strimzi.api.kafka.model.KafkaBuilder)10 GenericKafkaListenerBuilder (io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder)10