Search in sources :

Example 1 with Metrics

use of io.vertx.core.spi.metrics.Metrics in project vert.x by eclipse.

the class HttpServerImpl method listen.

public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestStream.handler() == null && wsStream.handler() == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }
    if (listening) {
        throw new IllegalStateException("Already listening");
    }
    listenContext = vertx.getOrCreateContext();
    listening = true;
    serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
    List<HttpVersion> applicationProtocols = options.getAlpnVersions();
    if (listenContext.isWorkerContext()) {
        applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
    }
    sslHelper.setApplicationProtocols(applicationProtocols);
    synchronized (vertx.sharedHttpServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        HttpServerImpl shared = vertx.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            applyConnectionOptions(bootstrap);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (requestStream.isPaused() || wsStream.isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslHelper.isSSL()) {
                        pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
                        if (options.isUseAlpn()) {
                            pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {

                                @Override
                                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
                                    if (protocol.equals("http/1.1")) {
                                        configureHttp1(pipeline);
                                    } else {
                                        handleHttp2(ch);
                                    }
                                }
                            });
                        } else {
                            configureHttp1(pipeline);
                        }
                    } else {
                        if (DISABLE_HC2) {
                            configureHttp1(pipeline);
                        } else {
                            pipeline.addLast(new Http1xOrHttp2Handler());
                        }
                    }
                }
            });
            addHandlers(this, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.failed()) {
                        vertx.sharedHttpServers().remove(id);
                    } else {
                        Channel serverChannel = res.result();
                        HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
                        serverChannelGroup.add(serverChannel);
                        metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer, listenContext);
            metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
        }
        actualServer.bindFuture.addListener(future -> {
            if (listenHandler != null) {
                final AsyncResult<HttpServer> res;
                if (future.succeeded()) {
                    res = Future.succeededFuture(HttpServerImpl.this);
                } else {
                    res = Future.failedFuture(future.cause());
                    listening = false;
                }
                listenContext.runOnContext((v) -> listenHandler.handle(res));
            } else if (future.failed()) {
                listening = false;
                log.error(future.cause());
            }
        });
    }
    return this;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) VertxException(io.vertx.core.VertxException) HandlerManager(io.vertx.core.net.impl.HandlerManager) ServerWebSocket(io.vertx.core.http.ServerWebSocket) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpServer(io.vertx.core.http.HttpServer) URISyntaxException(java.net.URISyntaxException) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) HttpVersion(io.vertx.core.http.HttpVersion) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) CharsetUtil(io.netty.util.CharsetUtil) ReadStream(io.vertx.core.streams.ReadStream) WebSocketFrameImpl(io.vertx.core.http.impl.ws.WebSocketFrameImpl) URI(java.net.URI) Logger(io.vertx.core.logging.Logger) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) HandlerHolder(io.vertx.core.net.impl.HandlerHolder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) VertxEventLoopGroup(io.vertx.core.net.impl.VertxEventLoopGroup) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) LoggerFactory(io.vertx.core.logging.LoggerFactory) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) ChannelFutureListener(io.netty.channel.ChannelFutureListener) AsyncResult(io.vertx.core.AsyncResult) HttpConnection(io.vertx.core.http.HttpConnection) Metrics(io.vertx.core.spi.metrics.Metrics) HttpContent(io.netty.handler.codec.http.HttpContent) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) AsyncResolveConnectHelper(io.vertx.core.net.impl.AsyncResolveConnectHelper) HttpMethod(io.netty.handler.codec.http.HttpMethod) SSLHelper(io.vertx.core.net.impl.SSLHelper) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ChannelHandler(io.netty.channel.ChannelHandler) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) VertxException(io.vertx.core.VertxException) URISyntaxException(java.net.URISyntaxException) Http2Exception(io.netty.handler.codec.http2.Http2Exception) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) ChannelPipeline(io.netty.channel.ChannelPipeline) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ServerID(io.vertx.core.net.impl.ServerID) HttpServer(io.vertx.core.http.HttpServer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) HttpVersion(io.vertx.core.http.HttpVersion) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 2 with Metrics

use of io.vertx.core.spi.metrics.Metrics in project vert.x by eclipse.

the class NetServerBase method listen.

public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) {
    if (handler == null) {
        throw new IllegalStateException("Set connect handler first");
    }
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    listenContext = vertx.getOrCreateContext();
    registeredHandler = handler;
    synchronized (vertx.sharedNetServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        NetServerBase shared = vertx.sharedNetServers().get(id);
        if (shared == null || port == 0) {
            // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    NetServerBase.this.initChannel(ch.pipeline());
                    pipeline.addLast("handler", new ServerHandler(ch));
                }
            });
            applyConnectionOptions(bootstrap);
            handlerManager.addHandler(handler, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.succeeded()) {
                        Channel ch = res.result();
                        log.trace("Net server listening on " + host + ":" + ch.localAddress());
                        NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host);
                        serverChannelGroup.add(ch);
                        vertx.sharedNetServers().put(id, NetServerBase.this);
                        metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
                    } else {
                        vertx.sharedNetServers().remove(id);
                    }
                });
            } catch (Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return;
            }
            if (port != 0) {
                vertx.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort();
            metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
            actualServer.handlerManager.addHandler(handler, listenContext);
        }
        // just add it to the future so it gets notified once the bind is complete
        actualServer.bindFuture.addListener(res -> {
            if (listenHandler != null) {
                AsyncResult<Void> ares;
                if (res.succeeded()) {
                    ares = Future.succeededFuture();
                } else {
                    listening = false;
                    ares = Future.failedFuture(res.cause());
                }
                listenContext.runOnContext(v -> listenHandler.handle(ares));
            } else if (res.failed()) {
                log.error("Failed to listen", res.cause());
                listening = false;
            }
        });
    }
    return;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) ChannelGroup(io.netty.channel.group.ChannelGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2 Channel (io.netty.channel.Channel)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInitializer (io.netty.channel.ChannelInitializer)2 ChannelOption (io.netty.channel.ChannelOption)2 ChannelPipeline (io.netty.channel.ChannelPipeline)2 FixedRecvByteBufAllocator (io.netty.channel.FixedRecvByteBufAllocator)2 ChannelGroup (io.netty.channel.group.ChannelGroup)2 ChannelGroupFuture (io.netty.channel.group.ChannelGroupFuture)2 DefaultChannelGroup (io.netty.channel.group.DefaultChannelGroup)2 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)2 ByteBuf (io.netty.buffer.ByteBuf)1 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)1 Unpooled (io.netty.buffer.Unpooled)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 ChannelHandler (io.netty.channel.ChannelHandler)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1 EventLoop (io.netty.channel.EventLoop)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)1