Search in sources :

Example 11 with Ingress

use of io.fabric8.kubernetes.api.model.extensions.Ingress in project fabric8 by fabric8io.

the class KubernetesHelper 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, String servicePortName, boolean serviceExternal) {
    Service srv = null;
    String serviceHost = KubernetesServices.serviceToHostOrBlank(serviceName);
    String servicePort = KubernetesServices.serviceToPortOrBlank(serviceName, servicePortName);
    String serviceProto = serviceProtocol != null ? serviceProtocol : KubernetesServices.serviceToProtocol(serviceName, servicePort);
    // Use specified or fallback namespace.
    String actualNamespace = Strings.isNotBlank(serviceNamespace) ? serviceNamespace : client.getNamespace();
    // 1. Inside Kubernetes: Services as ENV vars
    if (!serviceExternal && Strings.isNotBlank(serviceHost) && Strings.isNotBlank(servicePort) && Strings.isNotBlank(serviceProtocol)) {
        return serviceProtocol + "://" + serviceHost + ":" + servicePort;
    // 2. Anywhere: When namespace is passed System / Env var. Mostly needed for integration tests.
    } else if (Strings.isNotBlank(actualNamespace)) {
        try {
            srv = client.services().inNamespace(actualNamespace).withName(serviceName).get();
        } catch (Exception e) {
            LOGGER.warn("Could not lookup service:" + serviceName + " in namespace:" + actualNamespace + ", due to: " + e.getMessage());
        }
    }
    if (srv == null) {
        // lets try use environment variables
        String hostAndPort = Systems.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 = getOrCreateAnnotations(srv).get(Annotations.Service.EXPOSE_URL);
    if (Strings.isNotBlank(answer)) {
        return answer;
    }
    try {
        if (Strings.isNullOrBlank(servicePortName) && 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();
            }
        }
    } catch (KubernetesClientException e) {
        if (e.getCode() == 403) {
            LOGGER.warn("Could not lookup route:" + serviceName + " in namespace:" + actualNamespace + ", due to: " + e.getMessage());
        } else {
            throw e;
        }
    }
    ServicePort port = findServicePortByName(srv, servicePortName);
    if (port == null) {
        throw new RuntimeException("Couldn't find port: " + servicePortName + " 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 (Strings.isNullOrBlank(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 = 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 (Strings.isNotBlank(host)) {
                                                                            if (Strings.isNullOrBlank(pathPostfix)) {
                                                                                pathPostfix = "/";
                                                                            }
                                                                            return "https://" + URLUtils.pathJoin(host, pathPostfix);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        answer = rule.getHost();
                                                        if (Strings.isNotBlank(answer)) {
                                                            if (Strings.isNullOrBlank(pathPostfix)) {
                                                                pathPostfix = "/";
                                                            }
                                                            return "http://" + URLUtils.pathJoin(answer, 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 (Strings.isNotBlank(ip)) {
                            clusterIP = ip;
                            break;
                        }
                    }
                }
            }
        }
    }
    if (Strings.isNullOrBlank(clusterIP)) {
        // on vanilla kubernetes we can use nodePort to access things externally
        boolean found = false;
        Integer nodePort = port.getNodePort();
        if (nodePort != null) {
            try {
                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 (Strings.isNotBlank(ip)) {
                                            clusterIP = ip;
                                            portNumber = nodePort;
                                            found = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!found) {
                                NodeSpec spec = item.getSpec();
                                if (spec != null) {
                                    clusterIP = spec.getExternalID();
                                    if (Strings.isNotBlank(clusterIP)) {
                                        portNumber = nodePort;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                // ignore could not find a node!
                LOG.warn("Could not find a node!: " + e, e);
            }
        }
    }
    return (serviceProto + "://" + clusterIP + ":" + portNumber).toLowerCase();
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) 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) HTTPIngressRuleValue(io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue) Route(io.fabric8.openshift.api.model.Route) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) TextParseException(org.xbill.DNS.TextParseException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ParseException(java.text.ParseException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLKeyException(javax.net.ssl.SSLKeyException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) IngressTLS(io.fabric8.kubernetes.api.model.extensions.IngressTLS) IngressBackend(io.fabric8.kubernetes.api.model.extensions.IngressBackend) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 12 with Ingress

use of io.fabric8.kubernetes.api.model.extensions.Ingress in project carbon-apimgt by wso2.

the class KubernetesGatewayImpl method removeContainerBasedGateway.

/**
 * @see ContainerBasedGatewayGenerator#removeContainerBasedGateway(String, API) (String)
 */
@Override
public void removeContainerBasedGateway(String label, API api) throws ContainerBasedGatewayException {
    try {
        client.services().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY, label).delete();
        client.extensions().deployments().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY, label).delete();
        client.extensions().ingresses().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY, label).delete();
        log.info(String.format("Completed deleting the container gateway related %s deployment, service and " + "ingress resources.", cmsType));
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while removing container based gateway", e, ExceptionCodes.CONTAINER_GATEWAY_REMOVAL_FAILED);
    }
}
Also used : ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 13 with Ingress

use of io.fabric8.kubernetes.api.model.extensions.Ingress in project carbon-apimgt by wso2.

the class KubernetesGatewayImplTestCase method testCreateContainerGateway.

@Test
public void testCreateContainerGateway() throws Exception {
    OpenShiftClient openShiftClient = Mockito.mock(OpenShiftClient.class, Mockito.RETURNS_DEEP_STUBS);
    KubernetesGatewayImpl kubernetesGateway = getKubernetesGatewayImpl(openShiftClient);
    Mockito.when(openShiftClient.load(Mockito.any()).get()).thenReturn(getServiceResources(), getDeploymentResources(), getIngressResources());
    NonNamespaceOperation nonNamespaceOperation = Mockito.mock(NonNamespaceOperation.class);
    ScalableResource scalableResource = Mockito.mock(ScalableResource.class);
    Mockito.when(scalableResource.get()).thenReturn(null);
    Service service = createService(openShiftClient, nonNamespaceOperation);
    Deployment deployment = createDeployment(openShiftClient, nonNamespaceOperation, scalableResource);
    Ingress ingress = createIngress(openShiftClient, nonNamespaceOperation, scalableResource);
    Mockito.when(nonNamespaceOperation.create(Mockito.any())).thenReturn(service, deployment, ingress);
    API api = SampleTestObjectCreator.createDefaultAPI().build();
    kubernetesGateway.createContainerGateway(ContainerBasedGatewayConstants.PRIVATE_JET_API_PREFIX + LABEL_SUFFIX, api);
    Mockito.verify(openShiftClient, Mockito.times(4)).load(Mockito.any());
    Mockito.verify(openShiftClient, Mockito.times(3)).services();
    Mockito.verify(openShiftClient, Mockito.times(6)).extensions();
}
Also used : ScalableResource(io.fabric8.kubernetes.client.dsl.ScalableResource) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Service(io.fabric8.kubernetes.api.model.Service) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) API(org.wso2.carbon.apimgt.core.models.API) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Test(org.junit.Test)

Example 14 with Ingress

use of io.fabric8.kubernetes.api.model.extensions.Ingress in project carbon-apimgt by wso2.

the class ServiceDiscovererKubernetesTestCase method testListServicesOfLoadBalancerTypeWithoutIngress.

@Test(description = "Test .listServices() while the list only has a LoadBalancer type service without any ingress")
public void testListServicesOfLoadBalancerTypeWithoutIngress() throws Exception {
    OpenShiftClient openShiftClient = Mockito.mock(OpenShiftClient.class, Mockito.RETURNS_DEEP_STUBS);
    ServiceDiscovererKubernetes sdKubernetes = new ServiceDiscovererKubernetes();
    sdKubernetes.setClient(openShiftClient);
    // Not include ClusterIPs
    sdKubernetes.setIncludeClusterIP(false);
    // Not include ExternalNames
    sdKubernetes.setIncludeExternalNameTypeServices(false);
    NonNamespaceOperation nonNamespaceOperation = Mockito.mock(NonNamespaceOperation.class);
    Mockito.when(openShiftClient.services().inNamespace(null)).thenReturn(nonNamespaceOperation);
    Mockito.when(nonNamespaceOperation.list()).thenReturn(createMalformedServiceList("http"));
    Mockito.when(openShiftClient.getMasterUrl()).thenReturn(new URL(MASTER_URL));
    List<Endpoint> endpoints = sdKubernetes.listServices();
    Assert.assertEquals(endpoints.size(), 1);
}
Also used : Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) URL(java.net.URL) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 15 with Ingress

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

the class ApplyMojo method createIngress.

protected void createIngress(Controller controller, KubernetesClient kubernetesClient, Collection<HasMetadata> collection) {
    String routeDomainPostfix = this.routeDomain;
    Log log = getLog();
    String namespace = clusterAccess.getNamespace();
    List<Ingress> ingressList = null;
    // lets get the routes first to see if we should bother
    try {
        IngressList ingresses = kubernetesClient.extensions().ingresses().inNamespace(namespace).list();
        if (ingresses != null) {
            ingressList = ingresses.getItems();
        }
    } catch (Exception e) {
        log.warn("Cannot load Ingress instances. Must be an older version of Kubernetes? Error: " + e, e);
        return;
    }
    List<Ingress> ingresses = new ArrayList<>();
    for (Object object : collection) {
        if (object instanceof Service) {
            Service service = (Service) object;
            if (!serviceHasIngressRule(ingressList, service)) {
                Ingress ingress = createIngressForService(routeDomainPostfix, namespace, service);
                if (ingress != null) {
                    ingresses.add(ingress);
                    log.info("Created ingress for " + namespace + ":" + KubernetesHelper.getName(service));
                } else {
                    log.debug("No ingress required for " + namespace + ":" + KubernetesHelper.getName(service));
                }
            } else {
                log.info("Already has ingress for service " + namespace + ":" + KubernetesHelper.getName(service));
            }
        }
    }
    collection.addAll(ingresses);
}
Also used : Log(org.apache.maven.plugin.logging.Log) ArrayList(java.util.ArrayList) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) Service(io.fabric8.kubernetes.api.model.Service) KubernetesHelper.createIntOrString(io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString) IngressList(io.fabric8.kubernetes.api.model.extensions.IngressList) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Aggregations

Ingress (io.fabric8.kubernetes.api.model.extensions.Ingress)12 Service (io.fabric8.kubernetes.api.model.Service)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)5 HTTPIngressPath (io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath)5 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)5 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)5 ArrayList (java.util.ArrayList)5 KubernetesHelper.createIntOrString (io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString)3 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)3 HTTPIngressPathBuilder (io.fabric8.kubernetes.api.model.extensions.HTTPIngressPathBuilder)3 IngressBackend (io.fabric8.kubernetes.api.model.extensions.IngressBackend)3 IngressBuilder (io.fabric8.kubernetes.api.model.extensions.IngressBuilder)3 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2 Namespace (io.fabric8.kubernetes.api.model.Namespace)2 PersistentVolumeClaim (io.fabric8.kubernetes.api.model.PersistentVolumeClaim)2 Pod (io.fabric8.kubernetes.api.model.Pod)2 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)2 Secret (io.fabric8.kubernetes.api.model.Secret)2 ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)2