io.netty.handler.codec.http2.Http2FrameLogger Java Examples

The following examples show how to use io.netty.handler.codec.http2.Http2FrameLogger. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: H2ServerParentChannelInitializer.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public void init(final Channel channel) {
    final Http2FrameCodecBuilder multiplexCodecBuilder = forServer()
            // We do not want close to trigger graceful closure (go away), instead when user triggers a graceful
            // close, we do the appropriate go away handling.
            .decoupleCloseAndGoAway(true)
            // We don't want to rely upon Netty to manage the graceful close timeout, because we expect
            // the user to apply their own timeout at the call site.
            .gracefulShutdownTimeoutMillis(-1);

    final BiPredicate<CharSequence, CharSequence> headersSensitivityDetector =
            config.headersSensitivityDetector();
    multiplexCodecBuilder.headerSensitivityDetector(headersSensitivityDetector::test);

    final String frameLoggerName = config.frameLoggerName();
    if (frameLoggerName != null) {
        multiplexCodecBuilder.frameLogger(new Http2FrameLogger(TRACE, frameLoggerName));
    }

    // TODO(scott): more configuration. header validation, settings stream, etc...

    channel.pipeline().addLast(multiplexCodecBuilder.build(), new Http2MultiplexHandler(streamChannelInitializer));
}
 
Example #2
Source File: Http2FrontendHandler.java    From nitmproxy with MIT License 6 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("{} : handlerAdded", connectionInfo);

    Http2Connection connection = new DefaultHttp2Connection(true);
    ChannelHandler http2ConnHandler = new HttpToHttp2ConnectionHandlerBuilder()
            .frameListener(new DelegatingDecompressorFrameListener(
                    connection,
                    new InboundHttp2ToHttpAdapterBuilder(connection)
                            .maxContentLength(master.config().getMaxContentLength())
                            .propagateSettings(true)
                            .build()))
            .connection(connection)
            .frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
            .build();
    ctx.pipeline()
       .addBefore(ctx.name(), null, http2ConnHandler)
       .addBefore(ctx.name(), null, new Http2Handler());
}
 
Example #3
Source File: Http2BackendHandler.java    From nitmproxy with MIT License 6 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("{} : handlerAdded", connectionInfo);

    Http2Connection connection = new DefaultHttp2Connection(false);
    ChannelHandler http2ConnHandler = new HttpToHttp2ConnectionHandlerBuilder()
            .frameListener(new DelegatingDecompressorFrameListener(
                    connection,
                    new InboundHttp2ToHttpAdapterBuilder(connection)
                            .maxContentLength(master.config().getMaxContentLength())
                            .propagateSettings(true)
                            .build()))
            .frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
            .connection(connection)
            .build();
    ctx.pipeline()
       .addBefore(ctx.name(), null, http2ConnHandler)
       .addBefore(ctx.name(), null, new Http2Handler());
}
 
Example #4
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureHttp2Pipeline(ChannelPipeline p, HttpResponseDecoderSpec decoder, Http2Settings http2Settings,
		ConnectionObserver observer) {
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forClient()
			                      .validateHeaders(decoder.validateHeaders())
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.client.h2"));
	}

	p.addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(new H2Codec()))
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpTrafficHandler, new HttpTrafficHandler(observer));
}
 
Example #5
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureH2Pipeline(ChannelPipeline p,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	p.remove(NettyPipeline.ReactiveBridge);

	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}

	p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addLast(NettyPipeline.H2MultiplexHandler,
	          new Http2MultiplexHandler(new H2Codec(opsFactory, listener, forwarded, cookieEncoder, cookieDecoder)));
}
 
Example #6
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Http11OrH2CleartextCodec(
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		boolean debug,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		ChannelOperations.OnSetup opsFactory,
		boolean validate) {
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.forwarded = forwarded;
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forServer()
			                      .validateHeaders(validate)
			                      .initialSettings(http2Settings);

	if (debug) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(
				LogLevel.DEBUG,
				"reactor.netty.http.server.h2"));
	}
	this.http2FrameCodec = http2FrameCodecBuilder.build();
	this.listener = listener;
	this.opsFactory = opsFactory;
}
 
Example #7
Source File: H2ClientParentChannelInitializer.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public void init(final Channel channel) {
    final Http2FrameCodecBuilder multiplexCodecBuilder = forClient()
            // We do not want close to trigger graceful closure (go away), instead when user triggers a graceful
            // close, we do the appropriate go away handling.
            .decoupleCloseAndGoAway(true)
            // The max concurrent streams is made available via a publisher and may be consumed asynchronously
            // (e.g. when offloading is enabled), so we manually control the SETTINGS ACK frames.
            .autoAckSettingsFrame(false)
            // We don't want to rely upon Netty to manage the graceful close timeout, because we expect
            // the user to apply their own timeout at the call site.
            .gracefulShutdownTimeoutMillis(-1);

    // Notify server that this client does not support server push and request it to be disabled.
    multiplexCodecBuilder.initialSettings().pushEnabled(false).maxConcurrentStreams(0L);

    final BiPredicate<CharSequence, CharSequence> headersSensitivityDetector =
            config.headersSensitivityDetector();
    multiplexCodecBuilder.headerSensitivityDetector(headersSensitivityDetector::test);

    final String frameLoggerName = config.frameLoggerName();
    if (frameLoggerName != null) {
        multiplexCodecBuilder.frameLogger(new Http2FrameLogger(TRACE, frameLoggerName));
    }

    // TODO(scott): more configuration. header validation, settings stream, etc...

    channel.pipeline().addLast(multiplexCodecBuilder.build(),
            new Http2MultiplexHandler(H2PushStreamHandler.INSTANCE));
}
 
Example #8
Source File: Http2TestUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public static EmbeddedChannel newHttp2Channel(ChannelHandler channelHandler) {
    Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().initialSettings(
        Http2Settings.defaultSettings().initialWindowSize(INITIAL_WINDOW_SIZE))
                                                            .frameLogger(new Http2FrameLogger(LogLevel.DEBUG)).build();
    EmbeddedChannel channel = new EmbeddedChannel(http2FrameCodec,
                                                  new Http2MultiplexHandler(channelHandler));

    channel.attr(ChannelAttributeKey.HTTP2_CONNECTION).set(http2FrameCodec.connection());
    channel.attr(ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE).set(INITIAL_WINDOW_SIZE);
    channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2));
    return channel;
}
 
Example #9
Source File: Http2Util.java    From tutorials with MIT License 5 votes vote down vote up
public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) {
    final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class);
    final Http2Connection connection = new DefaultHttp2Connection(false);

    HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder()
        .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength)
        .propagateSettings(true)
        .build()))
        .frameLogger(logger)
        .connection(connection)
        .build();

    ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                p.addLast(settingsHandler, responseHandler);
                return;
            }
            ctx.close();
            throw new IllegalStateException("Protocol: " + protocol + " not supported");
        }
    };

    return clientAPNHandler;

}
 
Example #10
Source File: Http2ChannelPoolHandler.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public void channelCreated(Channel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT));
  pipeline.addLast(sslHandler);
  pipeline.addLast(Http2FrameCodecBuilder.forClient()
      .initialSettings(Http2Settings.defaultSettings()
          .maxFrameSize(http2ClientConfig.http2FrameMaxSize)
          .initialWindowSize(http2ClientConfig.http2InitialWindowSize))
      .frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "client"))
      .build());
  pipeline.addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter()));
}
 
Example #11
Source File: StorageServerNettyChannelInitializer.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  // To honor http2 window size, WriteBufferWaterMark.high() should be greater or equal to http2 window size.
  // Also see: https://github.com/netty/netty/issues/10193
  // https://stackoverflow.com/questions/25281124/netty-4-high-and-low-write-watermarks
  ch.config()
      .setSendBufferSize(http2ClientConfig.nettySendBufferSize)
      .setReceiveBufferSize(http2ClientConfig.nettyReceiveBufferSize)
      .setWriteBufferWaterMark(new WriteBufferWaterMark(http2ClientConfig.http2InitialWindowSize,
          2 * http2ClientConfig.http2InitialWindowSize));
  // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class
  // in the pipeline for every connection.
  // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
  ChannelPipeline pipeline = ch.pipeline();
  // connection stats handler to track connection related metrics
  pipeline.addLast("ConnectionStatsHandler", connectionStatsHandler);
  InetSocketAddress peerAddress = ch.remoteAddress();
  String peerHost = peerAddress.getHostName();
  int peerPort = peerAddress.getPort();
  SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER));
  pipeline.addLast("SslHandler", sslHandler);
  pipeline.addLast("SecurityChecker", serverSecurityHandler);
  pipeline.addLast("Http2FrameCodec", Http2FrameCodecBuilder.forServer()
      .initialSettings(Http2Settings.defaultSettings()
          .maxFrameSize(http2ClientConfig.http2FrameMaxSize)
          .initialWindowSize(http2ClientConfig.http2InitialWindowSize))
      .frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "server"))
      .build());
  pipeline.addLast("Http2MultiplexHandler", new Http2MultiplexHandler(http2ServerStreamHandler));
  pipeline.addLast("CloseOnExceptionHandler", closeOnExceptionHandler);
}
 
Example #12
Source File: NettyServerHandler.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
static NettyServerHandler newHandler(
    ServerTransportListener transportListener,
    ChannelPromise channelUnused,
    List<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);
  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);
}
 
Example #13
Source File: Http2HandlerBuilder.java    From xrpc with Apache License 2.0 4 votes vote down vote up
public Http2HandlerBuilder() {
  if (FRAME_LOGGER.isDebugEnabled()) {
    frameLogger(new Http2FrameLogger(LogLevel.DEBUG, FRAME_LOGGER_NAME));
  }
}
 
Example #14
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
static void configureHttp11OrH2CleartextPipeline(
		ChannelPipeline p,
		boolean acceptGzip,
		HttpResponseDecoderSpec decoder,
		Http2Settings http2Settings,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		ConnectionObserver observer,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	HttpClientCodec httpClientCodec =
			new HttpClientCodec(
					decoder.maxInitialLineLength(),
					decoder.maxHeaderSize(),
					decoder.maxChunkSize(),
					decoder.failOnMissingResponse,
					decoder.validateHeaders(),
					decoder.initialBufferSize(),
					decoder.parseHttpAfterConnectRequest);

	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forClient()
					.validateHeaders(decoder.validateHeaders())
					.initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.client.h2"));
	}

	Http2FrameCodec http2FrameCodec = http2FrameCodecBuilder.build();

	Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(http2FrameCodec, new H2CleartextCodec(http2FrameCodec, opsFactory));

	HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(httpClientCodec, upgradeCodec, decoder.h2cMaxContentLength());

	p.addBefore(NettyPipeline.ReactiveBridge, null, httpClientCodec)
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.H2CUpgradeHandler, upgradeHandler)
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpTrafficHandler, new HttpTrafficHandler(observer));

	if (acceptGzip) {
		p.addAfter(NettyPipeline.HttpCodec, NettyPipeline.HttpDecompressor, new HttpContentDecompressor());
	}

	if (metricsRecorder != null) {
		ChannelMetricsRecorder channelMetricsRecorder = metricsRecorder.get();
		if (channelMetricsRecorder instanceof HttpClientMetricsRecorder) {
			p.addBefore(NettyPipeline.ReactiveBridge,
					NettyPipeline.HttpMetricsHandler,
					new HttpClientMetricsHandler((HttpClientMetricsRecorder) channelMetricsRecorder, uriTagValue));
		}
	}

}
 
Example #15
Source File: NettyServerHandler.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
static NettyServerHandler newHandler(
    ServerTransportListener transportListener,
    ChannelPromise channelUnused,
    List<? extends ServerStreamTracer.Factory> streamTracerFactories,
    TransportTracer transportTracer,
    int maxStreams,
    boolean autoFlowControl,
    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: %s",
      maxHeaderListSize);
  Http2FrameLogger frameLogger = new Http2FrameLogger(LogLevel.DEBUG, NettyServerHandler.class);
  Http2HeadersDecoder headersDecoder = new GrpcHttp2ServerHeadersDecoder(maxHeaderListSize);
  Http2FrameReader frameReader = new Http2InboundFrameLogger(
      new DefaultHttp2FrameReader(headersDecoder), frameLogger);
  Http2FrameWriter frameWriter =
      new Http2OutboundFrameLogger(new DefaultHttp2FrameWriter(), frameLogger);
  return newHandler(
      channelUnused,
      frameReader,
      frameWriter,
      transportListener,
      streamTracerFactories,
      transportTracer,
      maxStreams,
      autoFlowControl,
      flowControlWindow,
      maxHeaderListSize,
      maxMessageSize,
      keepAliveTimeInNanos,
      keepAliveTimeoutInNanos,
      maxConnectionIdleInNanos,
      maxConnectionAgeInNanos,
      maxConnectionAgeGraceInNanos,
      permitKeepAliveWithoutCalls,
      permitKeepAliveTimeInNanos);
}