Example usage for io.netty.handler.logging LogLevel DEBUG

List of usage examples for io.netty.handler.logging LogLevel DEBUG

Introduction

In this page you can find the example usage for io.netty.handler.logging LogLevel DEBUG.

Prototype

LogLevel DEBUG

To view the source code for io.netty.handler.logging LogLevel DEBUG.

Click Source Link

Usage

From source file:de.dfki.kiara.tcp.TcpServerInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();/*from w  w w  . j  a  v  a  2 s . c om*/
    // Enable TCPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast("logger", new LoggingHandler(LogLevel.DEBUG));

    p.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, 4, 0, 4, true));
    p.addLast(new ByteBufferDecoder());

    p.addLast(new LengthFieldPrepender(4, 0, false) {
        @Override
        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
            ByteBuf outWithLittleEndian = out.order(ByteOrder.LITTLE_ENDIAN);
            super.encode(ctx, msg, outWithLittleEndian);
        }
    });
    p.addLast(new ByteBufferEncoder());
    p.addLast(new TcpHandler(transport, connectionListener));
}

From source file:gribbit.http.server.GribbitHttpServer.java

License:Open Source License

/**
 * Start the HTTP server./*from ww  w .  j a  v  a  2  s .  c  om*/
 * 
 * @throws IllegalArgumentException
 *             if port is already in use, or the server cannot be started for some other reason.
 */
public GribbitHttpServer start() {
    if (channel != null) {
        throw new IllegalArgumentException(serverName + " has already been started");
    }

    if (port == null) {
        port = useTLS ? 8443 : 8080;
    }

    // Initialize logger
    Log.info("Starting " + serverName + " on port " + port);

    if (!portAvailable(port)) {
        throw new IllegalArgumentException("Port " + port + " is not available -- is server already running?");
    }

    // TODO: allow the number of threads to be configurable?
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventLoopGroup requestDecoderGroup = new NioEventLoopGroup();
    try {
        final SslContext sslCtx = useTLS ? configureTLS() : null;

        ServerBootstrap b = new ServerBootstrap();
        // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#14.0
        //b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        //b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup) //
                .channel(NioServerSocketChannel.class) //
                .handler(new LoggingHandler(LogLevel.DEBUG)) //
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    // Create an HTTP decoder/encoder and request handler for each connection,
                    // so that the request can be handled in a stateful way
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        HttpRequestDecoder httpRequestDecoder = new HttpRequestDecoder(httpRequestHandlers,
                                webSocketHandlers, errorHandlers);
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc()),
                                    new Http2OrHttpHandler(requestDecoderGroup, httpRequestDecoder)); // TODO: correct for HTTP2?
                        } else {
                            // TODO: unify this with HTTP 1.1 treatment in http2OrHttpHandler

                            p.addLast(new HttpServerCodec());
                            p.addLast(new HttpContentDecompressor());
                            p.addLast(new HttpObjectAggregator(65536));
                            p.addLast(new ChunkedWriteHandler());
                            // The name is needed in the last handler, because it is used to dynamically add in
                            // HttpContentCompressor if the content in the response needs to be compressed.
                            p.addLast(HttpRequestDecoder.NAME_IN_PIPELINE, httpRequestDecoder);

                            //                                // p.addLast(new HttpContentDecompressor());
                            //                                p.addLast(new HttpServerCodec());
                            //                                // TODO: We're currently doing manual aggregation of chunked requests
                            //                                // (without limiting len) 
                            //                                p.addLast(new HttpObjectAggregator(65536));
                            //                                p.addLast(new ChunkedWriteHandler());
                            //                                // p.addLast(new WebSocketServerCompressionHandler());
                            //                                p.addLast(/*requestDecoderGroup, */ httpRequestDecoder);
                        }
                    }
                });

        //    // TODO: test these options suggested in http://goo.gl/AHvjmq
        //    // See also http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#11.0
        //    b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
        //    b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 64 * 1024);
        //    b.childOption(ChannelOption.SO_SNDBUF, 1048576);
        //    b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        //    // bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

        // TODO: Apache closes KeepAlive connections after a few seconds, see
        //       http://en.wikipedia.org/wiki/HTTP_persistent_connection
        // TODO: implement a stale connection tracker
        // final StaleConnectionTrackingHandler staleConnectionTrackingHandler = 
        //          new StaleConnectionTrackingHandler(STALE_CONNECTION_TIMEOUT, executor);
        //            ScheduledExecutorService staleCheckExecutor = 
        //               Executors.newSingleThreadScheduledExecutor(
        //                 new NamingThreadFactory(Gribbit.class.getSimpleName()
        //                    + "-stale-connection-check"));
        //            staleCheckExecutor.scheduleWithFixedDelay(new Runnable() {
        //                @Override
        //                public void run() {
        //                    staleConnectionTrackingHandler.closeStaleConnections();
        //                }
        //            }, STALE_CONNECTION_TIMEOUT / 2, STALE_CONNECTION_TIMEOUT / 2,
        //                TimeUnit.MILLISECONDS);
        //            executorServices.add(staleCheckExecutor);
        // connectionTrackingHandler = new ConnectionTrackingHandler();

        String domainAndPort = domain + ((!useTLS && port == 80) || (useTLS && port == 443) ? "" : ":" + port);
        uri = new URI((useTLS ? "https" : "http") + "://" + domainAndPort);
        wsUri = new URI((useTLS ? "wss" : "ws") + "://" + domainAndPort);

        // Set up channel
        channel = b.bind(port).sync().channel();

        Log.info(serverName + " started at " + uri + "/");

        // Wait (possibly indefinitely) for channel to close via call to this.shutdown()
        channel.closeFuture().sync();
        channel = null;

        Log.info(serverName + " successfully shut down");

    } catch (Exception e) {
        throw new RuntimeException("Could not start server", e);

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        requestDecoderGroup.shutdownGracefully();
    }
    return this;
}

From source file:io.aos.netty5.socksproxy.SocksServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline p = socketChannel.pipeline();
    p.addFirst(new LoggingHandler(LogLevel.DEBUG));
    p.addLast(new SocksPortUnificationServerHandler());
}

From source file:io.apigee.trireme.container.netty.NettyHttpServer.java

License:Open Source License

private ChannelInitializer<SocketChannel> makePipeline(final TLSParams tls) {
    return new ChannelInitializer<SocketChannel>() {
        @Override//from  ww w.j  av a2 s .  co  m
        public void initChannel(SocketChannel c) throws Exception {

            c.pipeline().addLast(new IdleStateHandler(IDLE_CONNECTION_SECONDS, IDLE_CONNECTION_SECONDS,
                    IDLE_CONNECTION_SECONDS));
            if (tls != null) {
                isTls = true;
                SSLEngine engine = makeSSLEngine(tls);
                c.pipeline().addLast(new SslHandler(engine));
            }
            if (log.isTraceEnabled()) {
                c.pipeline().addLast("loggingReq", new LoggingHandler(LogLevel.DEBUG));
            }
            c.pipeline().addLast(new HttpRequestDecoder()).addLast(new HttpHandler())
                    .addLast(new HttpResponseEncoder());
            if (log.isTraceEnabled()) {
                c.pipeline().addLast("loggingResp", new LoggingHandler(LogLevel.DEBUG));
            }
        }
    };
}

From source file:io.apigee.trireme.container.netty.NettyHttpServer.java

License:Open Source License

private void makeUpgradePipeline(SocketChannel c, UpgradedHandler handler) {
    // Remove the last handlers until we have remove the requestDecoder
    ChannelHandler lastHandler = null;/*from   w  ww.ja v  a 2s .c o m*/
    do {
        lastHandler = c.pipeline().removeLast();
    } while (!(lastHandler instanceof HttpRequestDecoder));

    // Now tack the new handler on the end instead
    c.pipeline().addLast(handler);
    if (log.isTraceEnabled()) {
        c.pipeline().addLast("loggingResp", new LoggingHandler(LogLevel.DEBUG));
    }
}

From source file:io.atomix.catalyst.transport.netty.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *///from  ww  w  .j  a  v a 2  s.  c o  m
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context, transport.properties());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(false)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog())
            .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay())
            .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress())
            .childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:io.atomix.catalyst.transport.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *//*from  ww  w. ja va2 s  . c  om*/
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context);

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class
                    : NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:io.awacs.server.MessageReportServer.java

License:Apache License

@Override
public void start() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*w  ww.j a va2s  . co m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    //??
                    ch.pipeline().addLast(new BinaryMessageDecoder());
                    ch.pipeline().addLast(new BinaryMessageEncoder());
                    //
                    ch.pipeline().addLast(new MessageReportRouter(MessageReportServer.this));
                }
            }).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        bootstrap.bind(host, port).sync();
    } catch (InterruptedException e) {
        stop();
    }
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

@VisibleForTesting
static NettyClientHandler newHandler(final Http2Connection connection, Http2FrameReader frameReader,
        Http2FrameWriter frameWriter, ClientTransportLifecycleManager lifecycleManager,
        KeepAliveManager keepAliveManager, int flowControlWindow, int maxHeaderListSize,
        Supplier<Stopwatch> stopwatchFactory, Runnable tooManyPingsRunnable, TransportTracer transportTracer,
        Attributes eagAttributes, String authority) {
    Preconditions.checkNotNull(connection, "connection");
    Preconditions.checkNotNull(frameReader, "frameReader");
    Preconditions.checkNotNull(lifecycleManager, "lifecycleManager");
    Preconditions.checkArgument(flowControlWindow > 0, "flowControlWindow must be positive");
    Preconditions.checkArgument(maxHeaderListSize > 0, "maxHeaderListSize must be positive");
    Preconditions.checkNotNull(stopwatchFactory, "stopwatchFactory");
    Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
    Preconditions.checkNotNull(eagAttributes, "eagAttributes");
    Preconditions.checkNotNull(authority, "authority");

    Http2FrameLogger frameLogger = new Http2FrameLogger(LogLevel.DEBUG, NettyClientHandler.class);
    frameReader = new Http2InboundFrameLogger(frameReader, frameLogger);
    frameWriter = new Http2OutboundFrameLogger(frameWriter, frameLogger);

    StreamBufferingEncoder encoder = new StreamBufferingEncoder(
            new DefaultHttp2ConnectionEncoder(connection, frameWriter));

    // Create the local flow controller configured to auto-refill the connection window.
    connection.local()//from w w w.ja  v  a2s .c  om
            .flowController(new DefaultHttp2LocalFlowController(connection, DEFAULT_WINDOW_UPDATE_RATIO, true));

    Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder, frameReader);

    transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() {
        final Http2FlowController local = connection.local().flowController();
        final Http2FlowController remote = connection.remote().flowController();

        @Override
        public TransportTracer.FlowControlWindows read() {
            return new TransportTracer.FlowControlWindows(local.windowSize(connection.connectionStream()),
                    remote.windowSize(connection.connectionStream()));
        }
    });

    Http2Settings settings = new Http2Settings();
    settings.pushEnabled(false);
    settings.initialWindowSize(flowControlWindow);
    settings.maxConcurrentStreams(0);
    settings.maxHeaderListSize(maxHeaderListSize);

    return new NettyClientHandler(decoder, encoder, settings, lifecycleManager, keepAliveManager,
            stopwatchFactory, tooManyPingsRunnable, transportTracer, eagAttributes, authority);
}

From source file:io.grpc.netty.NettyServerHandler.java

License:Apache License

static NettyServerHandler newHandler(ServerTransportListener transportListener, ChannelPromise channelUnused,
        List<? extends ServerStreamTracer.Factory> streamTracerFactories, TransportTracer transportTracer,
        int maxStreams, int flowControlWindow, int maxHeaderListSize, int maxMessageSize,
        long keepAliveTimeInNanos, long keepAliveTimeoutInNanos, long maxConnectionIdleInNanos,
        long maxConnectionAgeInNanos, long maxConnectionAgeGraceInNanos, boolean permitKeepAliveWithoutCalls,
        long permitKeepAliveTimeInNanos) {
    Preconditions.checkArgument(maxHeaderListSize > 0, "maxHeaderListSize must be positive");
    Http2FrameLogger frameLogger = new Http2FrameLogger(LogLevel.DEBUG, NettyServerHandler.class);
    Http2HeadersDecoder headersDecoder = new GrpcHttp2ServerHeadersDecoder(maxHeaderListSize);
    Http2FrameReader frameReader = new Http2InboundFrameLogger(new DefaultHttp2FrameReader(headersDecoder),
            frameLogger);/*from   w  w  w  .  j  av  a2  s.c  o m*/
    Http2FrameWriter frameWriter = new Http2OutboundFrameLogger(new DefaultHttp2FrameWriter(), frameLogger);
    return newHandler(channelUnused, frameReader, frameWriter, transportListener, streamTracerFactories,
            transportTracer, maxStreams, flowControlWindow, maxHeaderListSize, maxMessageSize,
            keepAliveTimeInNanos, keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos,
            maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos);
}