Search in sources :

Example 1 with NodeSpec

use of io.fabric8.kubernetes.api.model.NodeSpec in project fabric8 by jboss-fuse.

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 2 with NodeSpec

use of io.fabric8.kubernetes.api.model.NodeSpec 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 3 with NodeSpec

use of io.fabric8.kubernetes.api.model.NodeSpec 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 4 with NodeSpec

use of io.fabric8.kubernetes.api.model.NodeSpec in project onos by opennetworkinglab.

the class KubevirtNodeUtil method buildKubevirtNode.

/**
 * Returns the kubevirt node from the node.
 *
 * @param node a raw node object returned from a k8s client
 * @return kubevirt node
 */
public static KubevirtNode buildKubevirtNode(Node node) {
    String hostname = node.getMetadata().getName();
    IpAddress managementIp = null;
    IpAddress dataIp = null;
    for (NodeAddress nodeAddress : node.getStatus().getAddresses()) {
        if (nodeAddress.getType().equals(INTERNAL_IP)) {
            managementIp = IpAddress.valueOf(nodeAddress.getAddress());
            dataIp = IpAddress.valueOf(nodeAddress.getAddress());
        }
    }
    Set<String> rolesFull = node.getMetadata().getLabels().keySet().stream().filter(l -> l.contains(K8S_ROLE)).collect(Collectors.toSet());
    KubevirtNode.Type nodeType = WORKER;
    for (String roleStr : rolesFull) {
        String role = roleStr.split("/")[1];
        if (MASTER.name().equalsIgnoreCase(role)) {
            nodeType = MASTER;
            break;
        }
    }
    // start to parse kubernetes annotation
    Map<String, String> annots = node.getMetadata().getAnnotations();
    String physnetConfig = annots.get(PHYSNET_CONFIG_KEY);
    String gatewayConfig = annots.get(GATEWAY_CONFIG_KEY);
    String dataIpStr = annots.get(DATA_IP_KEY);
    Set<KubevirtPhyInterface> phys = new HashSet<>();
    String gatewayBridgeName = null;
    try {
        if (physnetConfig != null) {
            JSONArray configJson = new JSONArray(physnetConfig);
            for (int i = 0; i < configJson.length(); i++) {
                JSONObject object = configJson.getJSONObject(i);
                String network = object.getString(NETWORK_KEY);
                String intf = object.getString(INTERFACE_KEY);
                if (network != null && intf != null) {
                    phys.add(DefaultKubevirtPhyInterface.builder().network(network).intf(intf).build());
                }
            }
        }
        if (dataIpStr != null) {
            dataIp = IpAddress.valueOf(dataIpStr);
        }
        if (gatewayConfig != null) {
            JsonNode jsonNode = new ObjectMapper().readTree(gatewayConfig);
            nodeType = GATEWAY;
            gatewayBridgeName = jsonNode.get(GATEWAY_BRIDGE_NAME).asText();
        }
    } catch (JSONException | JsonProcessingException e) {
        log.error("Failed to parse physnet config or gateway config object", e);
    }
    // if the node is taint with kubevirt.io key configured,
    // we mark this node as OTHER type, and do not add it into the cluster
    NodeSpec spec = node.getSpec();
    if (spec.getTaints() != null) {
        for (Taint taint : spec.getTaints()) {
            String effect = taint.getEffect();
            String key = taint.getKey();
            String value = taint.getValue();
            if (StringUtils.equals(effect, NO_SCHEDULE_EFFECT) && StringUtils.equals(key, KUBEVIRT_IO_KEY) && StringUtils.equals(value, DRAINING_VALUE)) {
                nodeType = OTHER;
            }
        }
    }
    return DefaultKubevirtNode.builder().hostname(hostname).managementIp(managementIp).dataIp(dataIp).type(nodeType).state(KubevirtNodeState.ON_BOARDED).phyIntfs(phys).gatewayBridgeName(gatewayBridgeName).build();
}
Also used : Address(org.xbill.DNS.Address) StringUtils(org.apache.commons.lang.StringUtils) OvsdbNodeId(org.onosproject.ovsdb.controller.OvsdbNodeId) GATEWAY(org.onosproject.kubevirtnode.api.KubevirtNode.Type.GATEWAY) DeviceService(org.onosproject.net.device.DeviceService) LoggerFactory(org.slf4j.LoggerFactory) DefaultKubevirtNode(org.onosproject.kubevirtnode.api.DefaultKubevirtNode) KubevirtApiConfig(org.onosproject.kubevirtnode.api.KubevirtApiConfig) NodeSpec(io.fabric8.kubernetes.api.model.NodeSpec) DefaultKubevirtPhyInterface(org.onosproject.kubevirtnode.api.DefaultKubevirtPhyInterface) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) JSONException(org.json.JSONException) WORKER(org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER) JSONObject(org.json.JSONObject) OvsdbController(org.onosproject.ovsdb.controller.OvsdbController) OTHER(org.onosproject.kubevirtnode.api.KubevirtNode.Type.OTHER) NodeAddress(io.fabric8.kubernetes.api.model.NodeAddress) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) Node(io.fabric8.kubernetes.api.model.Node) IpAddress(org.onlab.packet.IpAddress) KubevirtNode(org.onosproject.kubevirtnode.api.KubevirtNode) Tools.get(org.onlab.util.Tools.get) Logger(org.slf4j.Logger) Device(org.onosproject.net.Device) Taint(io.fabric8.kubernetes.api.model.Taint) BridgeName(org.onosproject.net.behaviour.BridgeName) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) MASTER(org.onosproject.kubevirtnode.api.KubevirtNode.Type.MASTER) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) KubevirtPhyInterface(org.onosproject.kubevirtnode.api.KubevirtPhyInterface) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) List(java.util.List) SONA_PROJECT_DOMAIN(org.onosproject.kubevirtnode.api.Constants.SONA_PROJECT_DOMAIN) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) OvsdbClientService(org.onosproject.ovsdb.controller.OvsdbClientService) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) KubevirtNodeState(org.onosproject.kubevirtnode.api.KubevirtNodeState) JSONArray(org.json.JSONArray) Dictionary(java.util.Dictionary) BridgeConfig(org.onosproject.net.behaviour.BridgeConfig) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JsonNode(com.fasterxml.jackson.databind.JsonNode) Taint(io.fabric8.kubernetes.api.model.Taint) Taint(io.fabric8.kubernetes.api.model.Taint) DefaultKubevirtNode(org.onosproject.kubevirtnode.api.DefaultKubevirtNode) KubevirtNode(org.onosproject.kubevirtnode.api.KubevirtNode) JSONObject(org.json.JSONObject) DefaultKubevirtPhyInterface(org.onosproject.kubevirtnode.api.DefaultKubevirtPhyInterface) KubevirtPhyInterface(org.onosproject.kubevirtnode.api.KubevirtPhyInterface) NodeSpec(io.fabric8.kubernetes.api.model.NodeSpec) IpAddress(org.onlab.packet.IpAddress) NodeAddress(io.fabric8.kubernetes.api.model.NodeAddress) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 HTTPIngressPath (io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath)3 HTTPIngressRuleValue (io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue)3 Ingress (io.fabric8.kubernetes.api.model.extensions.Ingress)3 IngressBackend (io.fabric8.kubernetes.api.model.extensions.IngressBackend)3 IngressList (io.fabric8.kubernetes.api.model.extensions.IngressList)3 IngressRule (io.fabric8.kubernetes.api.model.extensions.IngressRule)3 IngressSpec (io.fabric8.kubernetes.api.model.extensions.IngressSpec)3 IngressTLS (io.fabric8.kubernetes.api.model.extensions.IngressTLS)3 Route (io.fabric8.openshift.api.model.Route)3 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)3 IOException (java.io.IOException)3 UnknownHostException (java.net.UnknownHostException)3 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 Node (io.fabric8.kubernetes.api.model.Node)2 NodeAddress (io.fabric8.kubernetes.api.model.NodeAddress)2 NodeSpec (io.fabric8.kubernetes.api.model.NodeSpec)2 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)2