Search in sources :

Example 1 with ConnectTimeoutException

use of io.netty.channel.ConnectTimeoutException in project netty by netty.

the class OioSocketChannel method doConnect.

@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    if (localAddress != null) {
        SocketUtils.bind(socket, localAddress);
    }
    boolean success = false;
    try {
        SocketUtils.connect(socket, remoteAddress, config().getConnectTimeoutMillis());
        activate(socket.getInputStream(), socket.getOutputStream());
        success = true;
    } catch (SocketTimeoutException e) {
        ConnectTimeoutException cause = new ConnectTimeoutException("connection timed out: " + remoteAddress);
        cause.setStackTrace(e.getStackTrace());
        throw cause;
    } finally {
        if (!success) {
            doClose();
        }
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException)

Example 2 with ConnectTimeoutException

use of io.netty.channel.ConnectTimeoutException in project grpc-java by grpc.

the class UtilsTest method testStatusFromThrowable.

@Test
public void testStatusFromThrowable() {
    Status s = Status.CANCELLED.withDescription("msg");
    assertSame(s, Utils.statusFromThrowable(new Exception(s.asException())));
    Throwable t;
    t = new ConnectTimeoutException("msg");
    assertStatusEquals(Status.UNAVAILABLE.withCause(t), Utils.statusFromThrowable(t));
    t = new UnresolvedAddressException();
    assertStatusEquals(Status.UNAVAILABLE.withCause(t), Utils.statusFromThrowable(t));
    t = new Http2Exception(Http2Error.INTERNAL_ERROR, "msg");
    assertStatusEquals(Status.INTERNAL.withCause(t), Utils.statusFromThrowable(t));
    t = new Exception("msg");
    assertStatusEquals(Status.UNKNOWN.withCause(t), Utils.statusFromThrowable(t));
}
Also used : Status(io.grpc.Status) Http2Exception(io.netty.handler.codec.http2.Http2Exception) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) Test(org.junit.Test)

Example 3 with ConnectTimeoutException

use of io.netty.channel.ConnectTimeoutException in project openremote by openremote.

the class NrJavaSerialChannel method doConnect.

@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    NrJavaSerialAddress remote = (NrJavaSerialAddress) remoteAddress;
    final NRSerialPort serial = new NRSerialPort(remote.value(), remote.getBaudRate());
    serial.connect();
    serialPort = serial.getSerialPortInstance();
    if (serialPort == null) {
        // No exception is thrown on connect failure so throw one
        throw new ConnectTimeoutException("Failed to establish connection to COM port: " + remote.value());
    }
    serialPort.enableReceiveTimeout(config().getOption(io.netty.channel.rxtx.RxtxChannelOption.READ_TIMEOUT));
    deviceAddress = remote;
}
Also used : NRSerialPort(gnu.io.NRSerialPort) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException)

Example 4 with ConnectTimeoutException

use of io.netty.channel.ConnectTimeoutException in project fabric8 by jboss-fuse.

the class HttpGatewayHandler method doRouteRequest.

protected void doRouteRequest(Map<String, MappedServices> mappingRules, final HttpServerRequest request) {
    String uri = request.uri();
    String uri2 = uri;
    if (addMissingTrailingSlashes) {
        uri2 = normalizeUri(uri);
    }
    HttpClient client = null;
    String remaining = null;
    String prefix = null;
    String proxyServiceUrl = null;
    String reverseServiceUrl = null;
    MappedServices mappedServices = null;
    URL clientURL = null;
    Set<Map.Entry<String, MappedServices>> entries = mappingRules.entrySet();
    for (Map.Entry<String, MappedServices> entry : entries) {
        String path = entry.getKey();
        mappedServices = entry.getValue();
        String pathPrefix = path;
        boolean uriMatches = uri.startsWith(pathPrefix);
        boolean uri2Matches = uri2 != null && uri2.startsWith(pathPrefix);
        if (uriMatches || uri2Matches) {
            int pathPrefixLength = pathPrefix.length();
            if (uri2Matches && pathPrefixLength < uri2.length()) {
                remaining = uri2.substring(pathPrefixLength);
            } else if (pathPrefixLength < uri.length()) {
                remaining = uri.substring(pathPrefixLength);
            } else {
                remaining = null;
            }
            // now lets pick a service for this path
            proxyServiceUrl = mappedServices.chooseService(request);
            if (proxyServiceUrl != null) {
                // lets create a client for this request...
                try {
                    clientURL = new URL(proxyServiceUrl);
                    client = createClient(clientURL);
                    prefix = clientURL.getPath();
                    reverseServiceUrl = request.absoluteURI().resolve(pathPrefix).toString();
                    if (reverseServiceUrl.endsWith("/")) {
                        reverseServiceUrl = reverseServiceUrl.substring(0, reverseServiceUrl.length() - 1);
                    }
                    break;
                } catch (MalformedURLException e) {
                    LOG.warn("Failed to parse URL: " + proxyServiceUrl + ". " + e, e);
                }
            }
        }
    }
    if (client != null) {
        String servicePath = prefix != null ? prefix : "";
        // we should usually end the prefix path with a slash for web apps at least
        if (servicePath.length() > 0 && !servicePath.endsWith("/")) {
            servicePath += "/";
        }
        if (remaining != null) {
            servicePath += remaining;
        }
        client.exceptionHandler(new Handler<Throwable>() {

            @Override
            public void handle(Throwable throwable) {
                if (throwable instanceof ConnectTimeoutException) {
                    request.response().setStatusCode(504);
                    request.response().end();
                } else {
                    LOG.error("Unhandled exception", throwable);
                }
            }
        });
        client.setConnectTimeout(connectionTimeout);
        LOG.info("Proxying request {} to service path: {} on service: {} reverseServiceUrl: {}", uri, servicePath, proxyServiceUrl, reverseServiceUrl);
        final HttpClient finalClient = client;
        Handler<HttpClientResponse> responseHandler = new Handler<HttpClientResponse>() {

            public void handle(HttpClientResponse clientResponse) {
                LOG.debug("Proxying response: {}", clientResponse.statusCode());
                request.response().setStatusCode(clientResponse.statusCode());
                request.response().headers().set(clientResponse.headers());
                applyChunkedEncoding(request.response());
                clientResponse.dataHandler(new Handler<Buffer>() {

                    public void handle(Buffer data) {
                        LOG.debug("Proxying response body: {}", data);
                        request.response().write(data);
                    }
                });
                clientResponse.endHandler(new VoidHandler() {

                    public void handle() {
                        request.response().end();
                        finalClient.close();
                    }
                });
            }
        };
        if (mappedServices != null) {
            ProxyMappingDetails proxyMappingDetails = new ProxyMappingDetails(proxyServiceUrl, reverseServiceUrl, servicePath);
            responseHandler = mappedServices.wrapResponseHandlerInPolicies(request, responseHandler, proxyMappingDetails);
        }
        final HttpClientRequest clientRequest = client.request(request.method(), servicePath, responseHandler);
        clientRequest.headers().set(request.headers());
        clientRequest.setChunked(true);
        if (requestTimeout != DEFAULT_REQUEST_TIMEOUT) {
            clientRequest.exceptionHandler(new Handler<Throwable>() {

                @Override
                public void handle(Throwable throwable) {
                    if (throwable instanceof TimeoutException) {
                        request.response().setStatusCode(504);
                        request.response().end();
                    } else {
                        LOG.error("Unhandled exception", throwable);
                    }
                }
            });
            clientRequest.setTimeout(requestTimeout);
        }
        request.dataHandler(new Handler<Buffer>() {

            public void handle(Buffer data) {
                LOG.debug("Proxying request body: {}", data);
                clientRequest.write(data);
            }
        });
        request.endHandler(new VoidHandler() {

            public void handle() {
                LOG.debug("end of the request");
                clientRequest.end();
            }
        });
    } else {
        // lets return a 404
        LOG.info("Could not find matching proxy path for {} from paths: {}", uri, mappingRules.keySet());
        request.response().setStatusCode(404);
        request.response().end();
    }
}
Also used : Buffer(org.vertx.java.core.buffer.Buffer) VoidHandler(org.vertx.java.core.VoidHandler) MalformedURLException(java.net.MalformedURLException) VoidHandler(org.vertx.java.core.VoidHandler) Handler(org.vertx.java.core.Handler) URL(java.net.URL) HttpClientRequest(org.vertx.java.core.http.HttpClientRequest) HttpClient(org.vertx.java.core.http.HttpClient) HttpClientResponse(org.vertx.java.core.http.HttpClientResponse) HashMap(java.util.HashMap) Map(java.util.Map) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException)

Example 5 with ConnectTimeoutException

use of io.netty.channel.ConnectTimeoutException in project gravitee-gateway by gravitee-io.

the class VertxHttpClient method request.

@Override
public ProxyConnection request(ProxyRequest proxyRequest) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient());
    final URI uri = proxyRequest.uri();
    final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80);
    String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath() : uri.getRawPath() + '?' + uri.getRawQuery();
    // Prepare request
    HttpClientRequest clientRequest = httpClient.request(convert(proxyRequest.method()), port, uri.getHost(), relativeUri);
    clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());
    clientRequest.setFollowRedirects(endpoint.getHttpClientOptions().isFollowRedirects());
    VertxProxyConnection proxyConnection = new VertxProxyConnection(proxyRequest, clientRequest);
    clientRequest.handler(clientResponse -> handleClientResponse(proxyConnection, clientResponse));
    clientRequest.connectionHandler(connection -> {
        connection.exceptionHandler(ex -> {
        // I don't want to fill my logs with error
        });
    });
    clientRequest.exceptionHandler(event -> {
        if (!proxyConnection.isCanceled() && !proxyConnection.isTransmitted()) {
            proxyRequest.request().metrics().setMessage(event.getMessage());
            if (proxyConnection.timeoutHandler() != null && (event instanceof ConnectException || event instanceof TimeoutException || event instanceof NoRouteToHostException || event instanceof UnknownHostException)) {
                proxyConnection.handleConnectTimeout(event);
            } else {
                VertxProxyResponse clientResponse = new VertxProxyResponse(((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException)) ? HttpStatusCode.GATEWAY_TIMEOUT_504 : HttpStatusCode.BAD_GATEWAY_502);
                clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);
                proxyConnection.handleResponse(clientResponse);
            }
        }
    });
    return proxyConnection;
}
Also used : UnknownHostException(java.net.UnknownHostException) URI(java.net.URI) NoRouteToHostException(java.net.NoRouteToHostException) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException)

Aggregations

ConnectTimeoutException (io.netty.channel.ConnectTimeoutException)6 HttpEndpoint (io.gravitee.definition.model.endpoint.HttpEndpoint)2 URI (java.net.URI)2 TimeoutException (java.util.concurrent.TimeoutException)2 NRSerialPort (gnu.io.NRSerialPort)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)1 HttpClientSslOptions (io.gravitee.definition.model.HttpClientSslOptions)1 HttpProxy (io.gravitee.definition.model.HttpProxy)1 EndpointRule (io.gravitee.gateway.services.healthcheck.EndpointRule)1 EndpointStatusDecorator (io.gravitee.gateway.services.healthcheck.EndpointStatusDecorator)1 EvaluationException (io.gravitee.gateway.services.healthcheck.eval.EvaluationException)1 AssertionEvaluation (io.gravitee.gateway.services.healthcheck.eval.assertion.AssertionEvaluation)1 EvaluableHttpResponse (io.gravitee.gateway.services.healthcheck.http.el.EvaluableHttpResponse)1 Request (io.gravitee.reporter.api.common.Request)1 Response (io.gravitee.reporter.api.common.Response)1 EndpointStatus (io.gravitee.reporter.api.health.EndpointStatus)1 Step (io.gravitee.reporter.api.health.Step)1 Status (io.grpc.Status)1 Http2Exception (io.netty.handler.codec.http2.Http2Exception)1