use of io.fabric8.knative.serving.v1.Route 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);
}
}
use of io.fabric8.knative.serving.v1.Route in project fabric8-maven-plugin by fabric8io.
the class AbstractLiveEnricher method getExternalServiceURL.
/**
* Returns the external access to the given service name
*
* @param serviceName name of the service
* @param protocol URL protocol such as <code>http</code>
*/
protected String getExternalServiceURL(String serviceName, String protocol) {
if (!isOnline()) {
getLog().info("Not looking for service " + serviceName + " as we are in offline mode");
return null;
} else {
try {
KubernetesClient kubernetes = getKubernetes();
String ns = kubernetes.getNamespace();
if (StringUtils.isBlank(ns)) {
ns = getNamespace();
}
Service service = kubernetes.services().inNamespace(ns).withName(serviceName).get();
return service != null ? ServiceUrlUtil.getServiceURL(kubernetes, serviceName, ns, protocol, true) : null;
} catch (Throwable e) {
Throwable cause = e;
boolean notFound = false;
boolean connectError = false;
Stack<Throwable> stack = unfoldExceptions(e);
while (!stack.isEmpty()) {
Throwable t = stack.pop();
if (t instanceof ConnectException || "No route to host".equals(t.getMessage())) {
getLog().warn("Cannot connect to Kubernetes to find URL for service %s : %s", serviceName, cause.getMessage());
return null;
} else if (t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().matches("^No.*found.*$")) {
getLog().warn("%s", cause.getMessage());
return null;
}
;
}
getLog().warn("Cannot find URL for service %s : %s", serviceName, cause.getMessage());
return null;
}
}
}
use of io.fabric8.knative.serving.v1.Route 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();
}
use of io.fabric8.knative.serving.v1.Route in project fabric8-maven-plugin by fabric8io.
the class ResourceMojo method writeResourcesIndividualAndComposite.
public static File writeResourcesIndividualAndComposite(KubernetesList resources, File resourceFileBase, ResourceFileType resourceFileType, Logger log) throws MojoExecutionException {
// Creating a new items list. This will be used to generate openshift.yml
List<HasMetadata> newItemList = new ArrayList<>();
// entity is object which will be sent to writeResource for openshift.yml
// if generateRoute is false, this will be set to resources with new list
// otherwise it will be set to resources with old list.
Object entity = resources;
// if the list contains a single Template lets unwrap it
// in resources already new or old as per condition is set.
// no need to worry about this for dropping Route.
Template template = getSingletonTemplate(resources);
if (template != null) {
entity = template;
}
File file = writeResource(resourceFileBase, entity, resourceFileType);
// write separate files, one for each resource item
// resources passed to writeIndividualResources is also new one.
writeIndividualResources(resources, resourceFileBase, resourceFileType, log);
return file;
}
use of io.fabric8.knative.serving.v1.Route in project che-server by eclipse-che.
the class RouteServerResolverTest method testResolvingServersWhenThereIsMatchedRouteForMachineAndServerPathIsNull.
@Test
public void testResolvingServersWhenThereIsMatchedRouteForMachineAndServerPathIsNull() {
Route route = createRoute("matched", "machine", singletonMap("http-server", new ServerConfigImpl("3054", "http", null, ATTRIBUTES_MAP)));
RouteServerResolver serverResolver = new RouteServerResolver(emptyList(), singletonList(route));
Map<String, ServerImpl> resolved = serverResolver.resolve("machine");
assertEquals(resolved.size(), 1);
assertEquals(resolved.get("http-server"), new ServerImpl().withUrl("http://localhost").withStatus(UNKNOWN).withAttributes(defaultAttributeAnd(Constants.SERVER_PORT_ATTRIBUTE, "3054", ServerConfig.ENDPOINT_ORIGIN, "/")));
}
Aggregations