Search in sources :

Example 21 with ProxyOptions

use of io.vertx.core.net.ProxyOptions in project vert.x by eclipse.

the class NetClientImpl method connectInternal.

public void connectInternal(ProxyOptions proxyOptions, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, boolean useAlpn, boolean registerWriteHandlers, Promise<NetSocket> connectHandler, ContextInternal context, int remainingAttempts) {
    checkClosed();
    EventLoop eventLoop = context.nettyEventLoop();
    if (eventLoop.inEventLoop()) {
        Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
        vertx.transport().configure(options, remoteAddress.isDomainSocket(), bootstrap);
        ChannelProvider channelProvider = new ChannelProvider(bootstrap, sslHelper, context).proxyOptions(proxyOptions);
        channelProvider.handler(ch -> connected(context, ch, connectHandler, remoteAddress, channelProvider.applicationProtocol(), registerWriteHandlers));
        io.netty.util.concurrent.Future<Channel> fut = channelProvider.connect(remoteAddress, peerAddress, serverName, ssl, useAlpn);
        fut.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) future -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                boolean connectError = cause instanceof ConnectException || cause instanceof FileNotFoundException;
                if (connectError && (remainingAttempts > 0 || remainingAttempts == -1)) {
                    context.emit(v -> {
                        log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                        vertx.setTimer(options.getReconnectInterval(), tid -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                    });
                } else {
                    failed(context, null, cause, connectHandler);
                }
            }
        });
    } else {
        eventLoop.execute(() -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts));
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) Channel(io.netty.channel.Channel) FileNotFoundException(java.io.FileNotFoundException) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) ConnectException(java.net.ConnectException)

Example 22 with ProxyOptions

use of io.vertx.core.net.ProxyOptions in project vert.x by eclipse.

the class ProxyOptionsTest method testDefaultOptionsJson.

@Test
public void testDefaultOptionsJson() {
    ProxyOptions def = new ProxyOptions();
    ProxyOptions options = new ProxyOptions(new JsonObject());
    assertEquals(def.getType(), options.getType());
    assertEquals(def.getPort(), options.getPort());
    assertEquals(def.getHost(), options.getHost());
    assertEquals(def.getUsername(), options.getUsername());
    assertEquals(def.getPassword(), options.getPassword());
}
Also used : ProxyOptions(io.vertx.core.net.ProxyOptions) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 23 with ProxyOptions

use of io.vertx.core.net.ProxyOptions in project vert.x by eclipse.

the class ProxyOptionsTest method testCopyProxyOptions.

@Test
public void testCopyProxyOptions() {
    ProxyOptions options = new ProxyOptions();
    options.setType(randType);
    options.setHost(randHost);
    options.setPort(randPort);
    options.setUsername(randUsername);
    options.setPassword(randPassword);
    ProxyOptions copy = new ProxyOptions(options);
    assertEquals(randType, copy.getType());
    assertEquals(randPort, copy.getPort());
    assertEquals(randHost, copy.getHost());
    assertEquals(randUsername, copy.getUsername());
    assertEquals(randPassword, copy.getPassword());
}
Also used : ProxyOptions(io.vertx.core.net.ProxyOptions) Test(org.junit.Test)

Example 24 with ProxyOptions

use of io.vertx.core.net.ProxyOptions in project vert.x by eclipse.

the class HttpClientImpl method webSocket.

private void webSocket(WebSocketConnectOptions connectOptions, PromiseInternal<WebSocket> promise) {
    ProxyOptions proxyOptions = getProxyOptions(connectOptions.getProxyOptions());
    int port = getPort(connectOptions);
    String host = getHost(connectOptions);
    SocketAddress addr = SocketAddress.inetSocketAddress(port, host);
    if (proxyFilter != null) {
        if (!proxyFilter.test(addr)) {
            proxyOptions = null;
        }
    }
    EndpointKey key = new EndpointKey(connectOptions.isSsl() != null ? connectOptions.isSsl() : options.isSsl(), proxyOptions, addr, addr);
    ContextInternal ctx = promise.context();
    EventLoopContext eventLoopContext;
    if (ctx instanceof EventLoopContext) {
        eventLoopContext = (EventLoopContext) ctx;
    } else {
        eventLoopContext = vertx.createEventLoopContext(ctx.nettyEventLoop(), ctx.workerPool(), ctx.classLoader());
    }
    webSocketCM.getConnection(eventLoopContext, key, ar -> {
        if (ar.succeeded()) {
            Http1xClientConnection conn = (Http1xClientConnection) ar.result();
            conn.toWebSocket(ctx, connectOptions.getURI(), connectOptions.getHeaders(), connectOptions.getAllowOriginHeader(), connectOptions.getVersion(), connectOptions.getSubProtocols(), HttpClientImpl.this.options.getMaxWebSocketFrameSize(), promise);
        } else {
            promise.fail(ar.cause());
        }
    });
}
Also used : ProxyOptions(io.vertx.core.net.ProxyOptions) ContextInternal(io.vertx.core.impl.ContextInternal) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopContext(io.vertx.core.impl.EventLoopContext) Endpoint(io.vertx.core.net.impl.pool.Endpoint)

Example 25 with ProxyOptions

use of io.vertx.core.net.ProxyOptions in project vert.x by eclipse.

the class HttpClientImpl method doRequest.

private void doRequest(RequestOptions request, PromiseInternal<HttpClientRequest> promise) {
    String host = getHost(request);
    int port = getPort(request);
    SocketAddress server = request.getServer();
    if (server == null) {
        server = SocketAddress.inetSocketAddress(port, host);
    }
    ProxyOptions proxyOptions = getProxyOptions(request.getProxyOptions());
    HttpMethod method = request.getMethod();
    String requestURI = request.getURI();
    Boolean ssl = request.isSsl();
    MultiMap headers = request.getHeaders();
    long timeout = request.getTimeout();
    Boolean followRedirects = request.getFollowRedirects();
    Objects.requireNonNull(method, "no null method accepted");
    Objects.requireNonNull(host, "no null host accepted");
    Objects.requireNonNull(requestURI, "no null requestURI accepted");
    boolean useAlpn = this.options.isUseAlpn();
    boolean useSSL = ssl != null ? ssl : this.options.isSsl();
    if (!useAlpn && useSSL && this.options.getProtocolVersion() == HttpVersion.HTTP_2) {
        throw new IllegalArgumentException("Must enable ALPN when using H2");
    }
    checkClosed();
    if (proxyFilter != null) {
        if (!proxyFilter.test(server)) {
            proxyOptions = null;
        }
    }
    if (proxyOptions != null) {
        if (!useSSL && proxyOptions.getType() == ProxyType.HTTP) {
            // If the requestURI is as not absolute URI then we do not recompute one for the proxy
            if (!ABS_URI_START_PATTERN.matcher(requestURI).find()) {
                int defaultPort = 80;
                String addPort = (port != -1 && port != defaultPort) ? (":" + port) : "";
                requestURI = (ssl == Boolean.TRUE ? "https://" : "http://") + host + addPort + requestURI;
            }
            if (proxyOptions.getUsername() != null && proxyOptions.getPassword() != null) {
                if (headers == null) {
                    headers = HttpHeaders.headers();
                }
                headers.add("Proxy-Authorization", "Basic " + Base64.getEncoder().encodeToString((proxyOptions.getUsername() + ":" + proxyOptions.getPassword()).getBytes()));
            }
            server = SocketAddress.inetSocketAddress(proxyOptions.getPort(), proxyOptions.getHost());
            proxyOptions = null;
        }
    }
    String peerHost = host;
    if (peerHost.endsWith(".")) {
        peerHost = peerHost.substring(0, peerHost.length() - 1);
    }
    SocketAddress peerAddress = SocketAddress.inetSocketAddress(port, peerHost);
    doRequest(method, peerAddress, server, host, port, useSSL, requestURI, headers, request.getTraceOperation(), timeout, followRedirects, proxyOptions, promise);
}
Also used : MultiMap(io.vertx.core.MultiMap) ProxyOptions(io.vertx.core.net.ProxyOptions) SocketAddress(io.vertx.core.net.SocketAddress) Endpoint(io.vertx.core.net.impl.pool.Endpoint)

Aggregations

ProxyOptions (io.vertx.core.net.ProxyOptions)28 Test (org.junit.Test)15 HttpClientOptions (io.vertx.core.http.HttpClientOptions)7 SocketAddress (io.vertx.core.net.SocketAddress)5 JsonObject (io.vertx.core.json.JsonObject)4 Handler (io.vertx.core.Handler)3 HttpClientRequest (io.vertx.core.http.HttpClientRequest)3 ProxyType (io.vertx.core.net.ProxyType)3 HttpClientSslOptions (io.gravitee.definition.model.HttpClientSslOptions)2 HttpProxy (io.gravitee.definition.model.HttpProxy)2 HttpClient (io.vertx.core.http.HttpClient)2 ContextInternal (io.vertx.core.impl.ContextInternal)2 Endpoint (io.vertx.core.net.impl.pool.Endpoint)2 SSLCustom (org.apache.servicecomb.foundation.ssl.SSLCustom)2 SSLOption (org.apache.servicecomb.foundation.ssl.SSLOption)2 SSLOptionFactory (org.apache.servicecomb.foundation.ssl.SSLOptionFactory)2 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 HttpStatusCode (io.gravitee.common.http.HttpStatusCode)1 HttpEndpoint (io.gravitee.definition.model.endpoint.HttpEndpoint)1 EndpointRule (io.gravitee.gateway.services.healthcheck.EndpointRule)1