Search in sources :

Example 1 with Ingress

use of io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress in project fabric8-maven-plugin by fabric8io.

the class ApplyService method applyEntity.

/**
 * Applies the given DTOs onto the Kubernetes master
 */
private void applyEntity(Object dto, String sourceName) throws Exception {
    if (dto instanceof Pod) {
        applyPod((Pod) dto, sourceName);
    } else if (dto instanceof ReplicationController) {
        applyReplicationController((ReplicationController) dto, sourceName);
    } else if (dto instanceof Service) {
        applyService((Service) dto, sourceName);
    } else if (dto instanceof Route) {
        applyRoute((Route) dto, sourceName);
    } else if (dto instanceof BuildConfig) {
        applyBuildConfig((BuildConfig) dto, sourceName);
    } else if (dto instanceof DeploymentConfig) {
        DeploymentConfig resource = (DeploymentConfig) dto;
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient != null) {
            applyResource(resource, sourceName, openShiftClient.deploymentConfigs());
        } else {
            log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof RoleBinding) {
        applyRoleBinding((RoleBinding) dto, sourceName);
    } else if (dto instanceof Role) {
        Role resource = (Role) dto;
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient != null) {
            applyResource(resource, sourceName, openShiftClient.rbac().roles());
        } else {
            log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof ImageStream) {
        applyImageStream((ImageStream) dto, sourceName);
    } else if (dto instanceof OAuthClient) {
        applyOAuthClient((OAuthClient) dto, sourceName);
    } else if (dto instanceof Template) {
        applyTemplate((Template) dto, sourceName);
    } else if (dto instanceof ServiceAccount) {
        applyServiceAccount((ServiceAccount) dto, sourceName);
    } else if (dto instanceof Secret) {
        applySecret((Secret) dto, sourceName);
    } else if (dto instanceof ConfigMap) {
        applyResource((ConfigMap) dto, sourceName, kubernetesClient.configMaps());
    } else if (dto instanceof DaemonSet) {
        applyResource((DaemonSet) dto, sourceName, kubernetesClient.apps().daemonSets());
    } else if (dto instanceof Deployment) {
        applyResource((Deployment) dto, sourceName, kubernetesClient.extensions().deployments());
    } else if (dto instanceof ReplicaSet) {
        applyResource((ReplicaSet) dto, sourceName, kubernetesClient.extensions().replicaSets());
    } else if (dto instanceof StatefulSet) {
        applyResource((StatefulSet) dto, sourceName, kubernetesClient.apps().statefulSets());
    } else if (dto instanceof Ingress) {
        applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
    } else if (dto instanceof PersistentVolumeClaim) {
        applyPersistentVolumeClaim((PersistentVolumeClaim) dto, sourceName);
    } else if (dto instanceof CustomResourceDefinition) {
        applyCustomResourceDefinition((CustomResourceDefinition) dto, sourceName);
    } else if (dto instanceof Job) {
        applyJob((Job) dto, sourceName);
    } else if (dto instanceof HasMetadata) {
        HasMetadata entity = (HasMetadata) dto;
        try {
            log.info("Applying " + getKind(entity) + " " + getName(entity) + " from " + sourceName);
            kubernetesClient.resource(entity).inNamespace(getNamespace(entity)).createOrReplace();
        } catch (Exception e) {
            onApplyError("Failed to create " + getKind(entity) + " from " + sourceName + ". " + e, e);
        }
    } else {
        throw new IllegalArgumentException("Unknown entity type " + dto);
    }
}
Also used : ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) DoneableImageStream(io.fabric8.openshift.api.model.DoneableImageStream) ImageStream(io.fabric8.openshift.api.model.ImageStream) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Template(io.fabric8.openshift.api.model.Template) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) RoleBinding(io.fabric8.kubernetes.api.model.rbac.RoleBinding) Job(io.fabric8.kubernetes.api.model.batch.Job) ReplicaSet(io.fabric8.kubernetes.api.model.apps.ReplicaSet) Route(io.fabric8.openshift.api.model.Route) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Pod(io.fabric8.kubernetes.api.model.Pod) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Role(io.fabric8.kubernetes.api.model.rbac.Role) Secret(io.fabric8.kubernetes.api.model.Secret) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) DaemonSet(io.fabric8.kubernetes.api.model.apps.DaemonSet) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet)

Example 2 with Ingress

use of io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress in project fabric8-maven-plugin by fabric8io.

the class ServiceUrlUtil method getServiceURL.

/**
 * Returns the URL to access the service; using the environment variables, routes
 * or service clusterIP address
 *
 * @throws IllegalArgumentException if the URL cannot be found for the serviceName and namespace
 */
public static String getServiceURL(KubernetesClient client, String serviceName, String serviceNamespace, String serviceProtocol, boolean serviceExternal) {
    Service srv = null;
    String serviceHost = serviceToHostOrBlank(serviceName);
    String servicePort = serviceToPortOrBlank(serviceName);
    String serviceProto = serviceProtocol != null ? serviceProtocol : serviceToProtocol(serviceName, servicePort);
    // Use specified or fallback namespace.
    String actualNamespace = StringUtils.isNotBlank(serviceNamespace) ? serviceNamespace : client.getNamespace();
    // 1. Inside Kubernetes: Services as ENV vars
    if (!serviceExternal && StringUtils.isNotBlank(serviceHost) && StringUtils.isNotBlank(servicePort) && StringUtils.isNotBlank(serviceProtocol)) {
        return serviceProtocol + "://" + serviceHost + ":" + servicePort;
    // 2. Anywhere: When namespace is passed System / Env var. Mostly needed for integration tests.
    } else if (StringUtils.isNotBlank(actualNamespace)) {
        srv = client.services().inNamespace(actualNamespace).withName(serviceName).get();
    }
    if (srv == null) {
        // lets try use environment variables
        String hostAndPort = getServiceHostAndPort(serviceName, "", "");
        if (!hostAndPort.startsWith(":")) {
            return serviceProto + "://" + hostAndPort;
        }
    }
    if (srv == null) {
        throw new IllegalArgumentException("No kubernetes service could be found for name: " + serviceName + " in namespace: " + actualNamespace);
    }
    String answer = KubernetesHelper.getOrCreateAnnotations(srv).get(Fabric8Annotations.SERVICE_EXPOSE_URL.toString());
    if (StringUtils.isNotBlank(answer)) {
        return answer;
    }
    if (OpenshiftHelper.isOpenShift(client)) {
        OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
        Route route = openShiftClient.routes().inNamespace(actualNamespace).withName(serviceName).get();
        if (route != null) {
            return (serviceProto + "://" + route.getSpec().getHost()).toLowerCase();
        }
    }
    ServicePort port = findServicePortByName(srv, null);
    if (port == null) {
        throw new RuntimeException("Couldn't find port: " + null + " for service:" + serviceName);
    }
    String clusterIP = srv.getSpec().getClusterIP();
    if ("None".equals(clusterIP)) {
        throw new IllegalStateException("Service: " + serviceName + " in namespace:" + serviceNamespace + "is head-less. Search for endpoints instead.");
    }
    Integer portNumber = port.getPort();
    if (StringUtils.isBlank(clusterIP)) {
        IngressList ingresses = client.extensions().ingresses().inNamespace(serviceNamespace).list();
        if (ingresses != null) {
            List<Ingress> items = ingresses.getItems();
            if (items != null) {
                for (Ingress item : items) {
                    String ns = KubernetesHelper.getNamespace(item);
                    if (Objects.equal(serviceNamespace, ns)) {
                        IngressSpec spec = item.getSpec();
                        if (spec != null) {
                            List<IngressRule> rules = spec.getRules();
                            List<IngressTLS> tls = spec.getTls();
                            if (rules != null) {
                                for (IngressRule rule : rules) {
                                    HTTPIngressRuleValue http = rule.getHttp();
                                    if (http != null) {
                                        List<HTTPIngressPath> paths = http.getPaths();
                                        if (paths != null) {
                                            for (HTTPIngressPath path : paths) {
                                                IngressBackend backend = path.getBackend();
                                                if (backend != null) {
                                                    String backendServiceName = backend.getServiceName();
                                                    if (serviceName.equals(backendServiceName) && portsMatch(port, backend.getServicePort())) {
                                                        String pathPostfix = path.getPath();
                                                        if (tls != null) {
                                                            for (IngressTLS tlsHost : tls) {
                                                                List<String> hosts = tlsHost.getHosts();
                                                                if (hosts != null) {
                                                                    for (String host : hosts) {
                                                                        if (StringUtils.isNotBlank(host)) {
                                                                            return String.format("https://%s/%s", host, preparePath(pathPostfix));
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        answer = rule.getHost();
                                                        if (StringUtils.isNotBlank(answer)) {
                                                            return String.format("http://%s/%s", answer, preparePath(pathPostfix));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // lets try use the status on GKE
        ServiceStatus status = srv.getStatus();
        if (status != null) {
            LoadBalancerStatus loadBalancerStatus = status.getLoadBalancer();
            if (loadBalancerStatus != null) {
                List<LoadBalancerIngress> loadBalancerIngresses = loadBalancerStatus.getIngress();
                if (loadBalancerIngresses != null) {
                    for (LoadBalancerIngress loadBalancerIngress : loadBalancerIngresses) {
                        String ip = loadBalancerIngress.getIp();
                        if (StringUtils.isNotBlank(ip)) {
                            clusterIP = ip;
                            break;
                        }
                    }
                }
            }
        }
    }
    if (StringUtils.isBlank(clusterIP)) {
        // on vanilla kubernetes we can use nodePort to access things externally
        boolean found = false;
        Integer nodePort = port.getNodePort();
        if (nodePort != null) {
            NodeList nodeList = client.nodes().list();
            if (nodeList != null) {
                List<Node> items = nodeList.getItems();
                if (items != null) {
                    for (Node item : items) {
                        NodeStatus status = item.getStatus();
                        if (!found && status != null) {
                            List<NodeAddress> addresses = status.getAddresses();
                            if (addresses != null) {
                                for (NodeAddress address : addresses) {
                                    String ip = address.getAddress();
                                    if (StringUtils.isNotBlank(ip)) {
                                        clusterIP = ip;
                                        portNumber = nodePort;
                                        found = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!found) {
                            NodeSpec spec = item.getSpec();
                            if (spec != null) {
                                clusterIP = spec.getExternalID();
                                if (StringUtils.isNotBlank(clusterIP)) {
                                    portNumber = nodePort;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return (serviceProto + "://" + clusterIP + ":" + portNumber).toLowerCase();
}
Also used : ServicePort(io.fabric8.kubernetes.api.model.ServicePort) Node(io.fabric8.kubernetes.api.model.Node) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) IngressList(io.fabric8.kubernetes.api.model.extensions.IngressList) HTTPIngressPath(io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath) IngressSpec(io.fabric8.kubernetes.api.model.extensions.IngressSpec) IngressRule(io.fabric8.kubernetes.api.model.extensions.IngressRule) LoadBalancerIngress(io.fabric8.kubernetes.api.model.LoadBalancerIngress) HTTPIngressRuleValue(io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue) ServiceStatus(io.fabric8.kubernetes.api.model.ServiceStatus) NodeAddress(io.fabric8.kubernetes.api.model.NodeAddress) Route(io.fabric8.openshift.api.model.Route) NodeList(io.fabric8.kubernetes.api.model.NodeList) Service(io.fabric8.kubernetes.api.model.Service) LoadBalancerIngress(io.fabric8.kubernetes.api.model.LoadBalancerIngress) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) NodeSpec(io.fabric8.kubernetes.api.model.NodeSpec) IngressTLS(io.fabric8.kubernetes.api.model.extensions.IngressTLS) LoadBalancerStatus(io.fabric8.kubernetes.api.model.LoadBalancerStatus) IngressBackend(io.fabric8.kubernetes.api.model.extensions.IngressBackend) NodeStatus(io.fabric8.kubernetes.api.model.NodeStatus)

Example 3 with Ingress

use of io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress in project fabric8-maven-plugin by fabric8io.

the class IngressEnricher method shouldCreateExternalURLForService.

/**
 * Should we try to create an external URL for the given service?
 * <p/>
 * By default lets ignore the kubernetes services and any service which does not expose ports 80 and 443
 *
 * @return true if we should create an Ingress for this service.
 */
private boolean shouldCreateExternalURLForService(ServiceBuilder service) {
    String serviceName = service.getMetadata().getName();
    if ("kubernetes".equals(serviceName) || "kubernetes-ro".equals(serviceName)) {
        return false;
    }
    ServiceSpec spec = service.getSpec();
    List<ServicePort> ports = spec.getPorts();
    log.debug("Service " + serviceName + " has ports: " + ports);
    if (ports.size() == 1) {
        String type = null;
        if (spec != null) {
            type = spec.getType();
            if (Objects.equals(type, "LoadBalancer")) {
                return true;
            }
        }
        log.info("Not generating Ingress for service " + serviceName + " type is not LoadBalancer: " + type);
        return false;
    } else {
        log.info("Not generating Ingress for service " + serviceName + " as only single port services are supported. Has ports: " + ports);
        return false;
    }
}
Also used : ServicePort(io.fabric8.kubernetes.api.model.ServicePort) ServiceSpec(io.fabric8.kubernetes.api.model.ServiceSpec)

Example 4 with Ingress

use of io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress in project spring-cloud-kubernetes by spring-cloud.

the class Fabric8ClientLoadbalancerIT method deployMockManifests.

private static void deployMockManifests() {
    try {
        Deployment deployment = client.apps().deployments().load(getMockDeployment()).get();
        client.apps().deployments().inNamespace(NAMESPACE).create(deployment);
        mockDeploymentName = deployment.getMetadata().getName();
        Service service = client.services().load(getMockService()).get();
        mockServiceName = service.getMetadata().getName();
        client.services().inNamespace(NAMESPACE).create(service);
        Ingress ingress = client.network().v1().ingresses().load(getMockIngress()).get();
        mockIngressName = ingress.getMetadata().getName();
        Fabric8Utils.waitForDeployment(client, "servicea-wiremock-deployment", NAMESPACE, 2, 600);
        Fabric8Utils.waitForEndpoint(client, "servicea-wiremock", NAMESPACE, 2, 600);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.networking.v1.Ingress) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException)

Example 5 with Ingress

use of io.fabric8.kubernetes.api.model.networking.v1beta1.Ingress in project spring-cloud-kubernetes by spring-cloud.

the class Fabric8ClientLoadbalancerIT method deployPodManifests.

private static void deployPodManifests() {
    try {
        Deployment deployment = client.apps().deployments().load(getPodDeployment()).get();
        String version = K8SUtils.getPomVersion();
        String currentImage = deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getImage();
        deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setImage(currentImage + ":" + version);
        client.apps().deployments().inNamespace(NAMESPACE).create(deployment);
        deploymentName = deployment.getMetadata().getName();
        Service service = client.services().load(getService()).get();
        serviceName = service.getMetadata().getName();
        client.services().inNamespace(NAMESPACE).create(service);
        Ingress ingress = client.network().v1().ingresses().load(getIngress()).get();
        ingressName = ingress.getMetadata().getName();
        client.network().v1().ingresses().inNamespace(NAMESPACE).create(ingress);
        Fabric8Utils.waitForDeployment(client, "spring-cloud-kubernetes-fabric8-client-loadbalancer-deployment", NAMESPACE, 2, 600);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.networking.v1.Ingress) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException)

Aggregations

Ingress (io.fabric8.kubernetes.api.model.networking.v1.Ingress)158 Service (io.fabric8.kubernetes.api.model.Service)73 Test (org.junit.jupiter.api.Test)64 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)38 Test (org.testng.annotations.Test)38 IngressBuilder (io.fabric8.kubernetes.api.model.networking.v1.IngressBuilder)37 IngressRule (io.fabric8.kubernetes.api.model.networking.v1.IngressRule)36 ArrayList (java.util.ArrayList)35 Ingress (io.fabric8.kubernetes.api.model.extensions.Ingress)33 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)32 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)32 HashMap (java.util.HashMap)31 IngressBackend (io.fabric8.kubernetes.api.model.networking.v1.IngressBackend)28 Secret (io.fabric8.kubernetes.api.model.Secret)21 HTTPIngressPath (io.fabric8.kubernetes.api.model.networking.v1.HTTPIngressPath)21 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)19 IngressServiceBackend (io.fabric8.kubernetes.api.model.networking.v1.IngressServiceBackend)18 PlatformFeaturesAvailability (io.strimzi.operator.PlatformFeaturesAvailability)18 KafkaCluster (io.strimzi.operator.cluster.model.KafkaCluster)18 Reconciliation (io.strimzi.operator.common.Reconciliation)18