Search in sources :

Example 11 with ServiceName

use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.

the class ServicesAssert method service.

/**
 * Asserts that the given service name exist
 *
 * @return the assertion object on the given service
 */
public ServicePodsAssert service(String serviceName) {
    Service service = null;
    for (Service aService : actual) {
        String name = getName(aService);
        if (Objects.equals(name, serviceName)) {
            service = aService;
        }
    }
    assertThat(service).describedAs("No service could be found for name: " + serviceName).isNotNull();
    return new ServicePodsAssert(client, service);
}
Also used : Service(io.fabric8.kubernetes.api.model.Service)

Example 12 with ServiceName

use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.

the class Fabric8Extension method onInjectionPoint.

public <T, X> void onInjectionPoint(@Observes ProcessInjectionPoint<T, X> event, BeanManager beanManager) {
    final InjectionPoint injectionPoint = event.getInjectionPoint();
    if (isServiceInjectionPoint(injectionPoint)) {
        Annotated annotated = injectionPoint.getAnnotated();
        ServiceName name = annotated.getAnnotation(ServiceName.class);
        Protocol protocol = annotated.getAnnotation(Protocol.class);
        PortName port = annotated.getAnnotation(PortName.class);
        Path path = annotated.getAnnotation(Path.class);
        Alias alias = annotated.getAnnotation(Alias.class);
        Endpoint endpoint = annotated.getAnnotation(Endpoint.class);
        External external = annotated.getAnnotation(External.class);
        String serviceName = name.value();
        String serviceProtocol = protocol != null ? protocol.value() : null;
        String servicePort = port != null ? port.value() : null;
        String servicePath = path != null ? path.value() : null;
        String serviceAlias = alias != null ? alias.value() : null;
        Boolean serviceExternal = external != null ? external.value() : false;
        Boolean serviceEndpoint = endpoint != null ? endpoint.value() : false;
        Type type = annotated.getBaseType();
        if (type instanceof ParameterizedType && Instance.class.equals(((ParameterizedType) type).getRawType())) {
            type = ((ParameterizedType) type).getActualTypeArguments()[0];
        }
        if (type.equals(String.class)) {
            ServiceUrlBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal);
        } else if (isGenericOf(type, List.class, String.class)) {
            ServiceUrlCollectionBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, Types.LIST_OF_STRINGS);
        } else if (isGenericOf(type, List.class, null)) {
        // TODO: Integrate with Factories(?)
        } else if (isGenericOf(type, Set.class, String.class)) {
            ServiceUrlCollectionBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, Types.SET_OF_STRINGS);
        } else if (isGenericOf(type, Set.class, null)) {
        // TODO: Integrate with Factories(?)
        } else if (type instanceof Class) {
            ServiceBean.getBean(serviceName, serviceProtocol, servicePort, servicePath, serviceAlias, serviceEndpoint, serviceExternal, type);
        } else {
            throw new RuntimeException(String.format(INJECTION_POINT_UNKNOWN_TYPE, injectionPoint.getBean().getBeanClass(), type));
        }
        if (protocol == null) {
            setDefaultProtocol(event);
        }
        if (port == null) {
            setDefaultPort(event);
        }
        if (path == null) {
            setDefaultPath(event);
        }
        if (endpoint == null) {
            setDefaultEndpoint(event);
        }
        if (external == null) {
            setDefaultExternal(event);
        }
    } else if (isConfigurationInjectionPoint(injectionPoint)) {
        Annotated annotated = injectionPoint.getAnnotated();
        Configuration configuration = annotated.getAnnotation(Configuration.class);
        Type type = injectionPoint.getType();
        String configurationId = configuration.value();
        ConfigurationBean.getBean(configurationId, type);
    }
}
Also used : Path(io.fabric8.annotations.Path) Utils.getFactoryMethodPath(io.fabric8.cdi.Utils.getFactoryMethodPath) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Configuration(io.fabric8.annotations.Configuration) ProcessInjectionPoint(javax.enterprise.inject.spi.ProcessInjectionPoint) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) Instance(javax.enterprise.inject.Instance) PortName(io.fabric8.annotations.PortName) ParameterizedType(java.lang.reflect.ParameterizedType) Annotated(javax.enterprise.inject.spi.Annotated) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Endpoint(io.fabric8.annotations.Endpoint) ServiceName(io.fabric8.annotations.ServiceName) Alias(io.fabric8.annotations.Alias) External(io.fabric8.annotations.External) ArrayList(java.util.ArrayList) List(java.util.List) Utils.getFactoryMethodProtocol(io.fabric8.cdi.Utils.getFactoryMethodProtocol) Protocol(io.fabric8.annotations.Protocol)

Example 13 with ServiceName

use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.

the class J4pClientProvider method lookup.

@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
    KubernetesClient client = this.clientInstance.get();
    Session session = this.sessionInstance.get();
    JolokiaClients jolokiaClients = new JolokiaClients(client);
    String serviceName = getServiceName(qualifiers);
    String podName = getPodName(qualifiers);
    String replicationControllerName = getReplicationControllerName(qualifiers);
    if (Strings.isNotBlank(serviceName)) {
        Service service = client.services().inNamespace(session.getNamespace()).withName(serviceName).get();
        if (service != null) {
            return jolokiaClients.clientForService(service);
        }
    }
    if (Strings.isNotBlank(podName)) {
        Pod pod = client.pods().inNamespace(session.getNamespace()).withName(serviceName).get();
        if (pod != null) {
            return jolokiaClients.clientForPod(pod);
        }
    }
    if (Strings.isNotBlank(replicationControllerName)) {
        ReplicationController replicationController = client.replicationControllers().inNamespace(session.getNamespace()).withName(replicationControllerName).get();
        if (replicationController != null) {
            return jolokiaClients.clientForReplicationController(replicationController);
        }
    }
    return null;
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Pod(io.fabric8.kubernetes.api.model.Pod) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) Service(io.fabric8.kubernetes.api.model.Service) JolokiaClients(io.fabric8.kubernetes.jolokia.JolokiaClients) Session(io.fabric8.arquillian.kubernetes.Session)

Example 14 with ServiceName

use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.

the class KubernetesHelper method getServiceURLInCurrentNamespace.

/**
 * 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 getServiceURLInCurrentNamespace(KubernetesClient client, String serviceName, 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);
    // 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 {
        srv = client.services().withName(serviceName).get();
    }
    if (srv == null) {
        throw new IllegalArgumentException("No kubernetes service could be found for name: " + serviceName);
    }
    if (Strings.isNullOrBlank(servicePortName) && isOpenShift(client)) {
        OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
        RouteList routeList = openShiftClient.routes().list();
        for (Route route : routeList.getItems()) {
            if (route.getSpec().getTo().getName().equals(serviceName)) {
                return (serviceProto + "://" + route.getSpec().getHost()).toLowerCase();
            }
        }
    }
    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 current namespace is head-less. Search for endpoints instead.");
    }
    return (serviceProto + "://" + clusterIP + ":" + port.getPort()).toLowerCase();
}
Also used : DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) RouteList(io.fabric8.openshift.api.model.RouteList) Route(io.fabric8.openshift.api.model.Route)

Example 15 with ServiceName

use of io.fabric8.annotations.ServiceName 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)

Aggregations

Service (io.fabric8.kubernetes.api.model.Service)13 ArrayList (java.util.ArrayList)7 ServiceBuilder (io.fabric8.kubernetes.api.model.ServiceBuilder)6 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)6 ServicePort (io.fabric8.kubernetes.api.model.ServicePort)5 Ingress (io.fabric8.kubernetes.api.model.extensions.Ingress)5 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)5 ServiceSpec (io.fabric8.kubernetes.api.model.ServiceSpec)4 HTTPIngressPath (io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath)4 Route (io.fabric8.openshift.api.model.Route)4 List (java.util.List)4 ServicePortBuilder (io.fabric8.kubernetes.api.model.ServicePortBuilder)3 BaseOperation (io.fabric8.kubernetes.client.dsl.base.BaseOperation)3 Map (java.util.Map)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Alias (io.fabric8.annotations.Alias)2 External (io.fabric8.annotations.External)2 PortName (io.fabric8.annotations.PortName)2 Protocol (io.fabric8.annotations.Protocol)2 ServiceName (io.fabric8.annotations.ServiceName)2