Search in sources :

Example 6 with NetClient

use of io.vertx.core.net.NetClient in project gravitee-management-rest-api by gravitee-io.

the class ManagementApiProbe method check.

@Override
public Future<Result> check() {
    Future<Result> future = Future.future();
    NetClientOptions options = new NetClientOptions().setConnectTimeout(500);
    NetClient client = vertx.createNetClient(options);
    client.connect(port, host, res -> {
        if (res.succeeded()) {
            future.complete(Result.healthy());
        } else {
            future.complete(Result.unhealthy(res.cause()));
        }
        client.close();
    });
    return future;
}
Also used : NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) Result(io.gravitee.management.services.healthcheck.Result)

Example 7 with NetClient

use of io.vertx.core.net.NetClient in project okapi by folio-org.

the class ProcessModuleHandle method tryConnect.

private void tryConnect(Handler<AsyncResult<Void>> startFuture, int count) {
    NetClientOptions options = new NetClientOptions().setConnectTimeout(MILLISECONDS);
    NetClient c = vertx.createNetClient(options);
    logger.debug("ProcessModuleHandle.tryConnect() port " + port + " count " + count);
    c.connect(port, "localhost", res -> {
        if (res.succeeded()) {
            logger.info("Connected to service at port " + port + " count " + count);
            NetSocket socket = res.result();
            socket.close();
            try {
                p.getErrorStream().close();
            } catch (Exception e) {
                logger.error("Closing streams failed: " + e);
            }
            startFuture.handle(Future.succeededFuture());
        } else if (!p.isAlive() && p.exitValue() != 0) {
            logger.warn("Service returned with exit code " + p.exitValue());
            startFuture.handle(Future.failedFuture("Service returned with exit code " + p.exitValue()));
        } else if (count < maxIterations) {
            vertx.setTimer((long) (count + 1) * MILLISECONDS, id -> tryConnect(startFuture, count + 1));
        } else {
            startFuture.handle(Future.failedFuture("Deployment failed. " + "Could not connect to port " + port + ": " + res.cause().getMessage()));
        }
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) IOException(java.io.IOException)

Example 8 with NetClient

use of io.vertx.core.net.NetClient in project okapi by folio-org.

the class ProcessModuleHandle method waitPortToClose.

private void waitPortToClose(Handler<AsyncResult<Void>> stopFuture, int iter) {
    if (port > 0) {
        // fail if port is already in use
        NetClientOptions options = new NetClientOptions().setConnectTimeout(50);
        NetClient c = vertx.createNetClient(options);
        c.connect(port, "localhost", res -> {
            if (res.succeeded()) {
                NetSocket socket = res.result();
                socket.close();
                if (iter > 0) {
                    vertx.setTimer(100, x -> waitPortToClose(stopFuture, iter - 1));
                } else {
                    stopFuture.handle(Future.failedFuture("port " + port + " not shut down"));
                }
            } else {
                stopFuture.handle(Future.succeededFuture());
            }
        });
    } else {
        stopFuture.handle(Future.succeededFuture());
    }
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient)

Example 9 with NetClient

use of io.vertx.core.net.NetClient in project gravitee-gateway by gravitee-io.

the class GatewayProbe method check.

@Override
public CompletableFuture<Result> check() {
    VertxCompletableFuture<Result> result = new VertxCompletableFuture<>(vertx);
    NetClientOptions options = new NetClientOptions().setConnectTimeout(500);
    NetClient client = vertx.createNetClient(options);
    client.connect(port, host, res -> {
        if (res.succeeded()) {
            result.complete(Result.healthy());
        } else {
            result.complete(Result.unhealthy(res.cause()));
        }
        client.close();
    });
    return result;
}
Also used : NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) VertxCompletableFuture(io.gravitee.gateway.services.healthcheck.vertx.VertxCompletableFuture) Result(io.gravitee.gateway.services.healthcheck.Result)

Example 10 with NetClient

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

the class HttpProxy method start.

/**
 * Start the server.
 *
 * @param vertx
 *          Vertx instance to use for creating the server and client
 */
@Override
public HttpProxy start(Vertx vertx) throws Exception {
    HttpServerOptions options = new HttpServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createHttpServer(options);
    server.requestHandler(request -> {
        HttpMethod method = request.method();
        String uri = request.uri();
        if (username != null) {
            String auth = request.getHeader("Proxy-Authorization");
            String expected = "Basic " + Base64.getEncoder().encodeToString((username + ":" + username).getBytes());
            if (auth == null || !auth.equals(expected)) {
                request.response().setStatusCode(407).end("proxy authentication failed");
                return;
            }
        }
        lastRequestHeaders = HttpHeaders.headers().addAll(request.headers());
        if (error != 0) {
            request.response().setStatusCode(error).end("proxy request failed");
        } else if (method == HttpMethod.CONNECT) {
            if (!uri.contains(":")) {
                request.response().setStatusCode(403).end("invalid request");
            } else {
                lastUri = uri;
                lastMethod = HttpMethod.CONNECT;
                if (forceUri != null) {
                    uri = forceUri;
                }
                String[] split = uri.split(":");
                String host = split[0];
                int port;
                try {
                    port = Integer.parseInt(split[1]);
                } catch (NumberFormatException ex) {
                    port = 443;
                }
                // this will deny access to e.g. smtp port 25 to avoid spammers
                if (port == 8080 || port < 1024 && port != 443) {
                    request.response().setStatusCode(403).end("access to port denied");
                    return;
                }
                NetClientOptions netOptions = new NetClientOptions();
                NetClient netClient = vertx.createNetClient(netOptions);
                netClient.connect(port, host, ar1 -> {
                    if (ar1.succeeded()) {
                        request.toNetSocket().onComplete(ar2 -> {
                            if (ar2.succeeded()) {
                                NetSocket serverSocket = ar2.result();
                                NetSocket clientSocket = ar1.result();
                                serverSocket.closeHandler(v -> clientSocket.close());
                                clientSocket.closeHandler(v -> serverSocket.close());
                                Pump.pump(serverSocket, clientSocket).start();
                                Pump.pump(clientSocket, serverSocket).start();
                            } else {
                            // Not handled
                            }
                        });
                    } else {
                        request.response().setStatusCode(403).end("request failed");
                    }
                });
            }
        } else if (method == HttpMethod.GET) {
            lastUri = uri;
            lastMethod = HttpMethod.GET;
            if (forceUri != null) {
                uri = forceUri;
            }
            HttpClient client = vertx.createHttpClient();
            RequestOptions opts = new RequestOptions();
            opts.setAbsoluteURI(uri);
            client.request(opts).compose(req -> {
                for (String name : request.headers().names()) {
                    if (!name.equals("Proxy-Authorization")) {
                        req.putHeader(name, request.headers().get(name));
                    }
                }
                return req.send();
            }).onComplete(ar1 -> {
                if (ar1.succeeded()) {
                    HttpClientResponse resp = ar1.result();
                    for (String name : resp.headers().names()) {
                        request.response().putHeader(name, resp.headers().getAll(name));
                    }
                    resp.body(ar2 -> {
                        if (ar2.succeeded()) {
                            request.response().end(ar2.result());
                        } else {
                            request.response().setStatusCode(500).end(ar2.cause().toString() + " on client request");
                        }
                    });
                } else {
                    Throwable e = ar1.cause();
                    log.debug("exception", e);
                    int status;
                    if (e instanceof UnknownHostException) {
                        status = 504;
                    } else {
                        status = 400;
                    }
                    request.response().setStatusCode(status).end(e.toString() + " on client request");
                }
            });
        } else {
            request.response().setStatusCode(405).end("method not supported");
        }
    });
    CompletableFuture<Void> fut = new CompletableFuture<>();
    server.listen(ar -> {
        if (ar.succeeded()) {
            fut.complete(null);
        } else {
            fut.completeExceptionally(ar.cause());
        }
    });
    fut.get(10, TimeUnit.SECONDS);
    return this;
}
Also used : Logger(io.vertx.core.impl.logging.Logger) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) MultiMap(io.vertx.core.MultiMap) Vertx(io.vertx.core.Vertx) CompletableFuture(java.util.concurrent.CompletableFuture) UnknownHostException(java.net.UnknownHostException) io.vertx.core.http(io.vertx.core.http) NetClientOptions(io.vertx.core.net.NetClientOptions) TimeUnit(java.util.concurrent.TimeUnit) Base64(java.util.Base64) Pump(io.vertx.core.streams.Pump) NetClient(io.vertx.core.net.NetClient) NetSocket(io.vertx.core.net.NetSocket) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) UnknownHostException(java.net.UnknownHostException) CompletableFuture(java.util.concurrent.CompletableFuture) NetClient(io.vertx.core.net.NetClient)

Aggregations

NetClient (io.vertx.core.net.NetClient)52 NetSocket (io.vertx.core.net.NetSocket)35 Test (org.junit.Test)34 NetServerOptions (io.vertx.core.net.NetServerOptions)24 Vertx (io.vertx.core.Vertx)23 JsonObject (io.vertx.core.json.JsonObject)21 Async (io.vertx.ext.unit.Async)20 Handler (io.vertx.core.Handler)19 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)19 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 NetClientOptions (io.vertx.core.net.NetClientOptions)17 BridgeOptions (io.vertx.ext.bridge.BridgeOptions)16 PermittedOptions (io.vertx.ext.bridge.PermittedOptions)16 Before (org.junit.Before)16 Message (io.vertx.core.eventbus.Message)15 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)15 FrameHelper (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameHelper)15 TestContext (io.vertx.ext.unit.TestContext)15 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 After (org.junit.After)15