Search in sources :

Example 46 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project zuul by Netflix.

the class ClientResponseWriter method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final Channel channel = ctx.channel();
    if (msg instanceof HttpResponseMessage) {
        final HttpResponseMessage resp = (HttpResponseMessage) msg;
        if (skipProcessing(resp)) {
            return;
        }
        if ((!isHandlingRequest) || (startedSendingResponseToClient)) {
            /* This can happen if we are already in the process of streaming response back to client OR NOT within active
                   request/response cycle and something like IDLE or Request Read timeout occurs. In that case we have no way
                   to recover other than closing the socket and cleaning up resources used by BOTH responses.
                 */
            resp.disposeBufferedBody();
            if (zuulResponse != null)
                zuulResponse.disposeBufferedBody();
            // This will trigger CompleteEvent if one is needed
            ctx.close();
            return;
        }
        startedSendingResponseToClient = true;
        zuulResponse = resp;
        if ("close".equalsIgnoreCase(zuulResponse.getHeaders().getFirst("Connection"))) {
            closeConnection = true;
        }
        channel.attr(ATTR_ZUUL_RESP).set(zuulResponse);
        if (channel.isActive()) {
            // Track if this is happening.
            if (!ClientRequestReceiver.isLastContentReceivedForChannel(channel)) {
                StatusCategory status = StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel));
                if (ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT.equals(status)) {
                // If the request timed-out while being read, then there won't have been any LastContent, but thats ok because the connection will have to be discarded anyway.
                } else {
                    responseBeforeReceivedLastContentCounter.increment();
                    LOG.warn("Writing response to client channel before have received the LastContent of request! " + zuulResponse.getInboundRequest().getInfoForLogging() + ", " + ChannelUtils.channelInfoForLogging(channel));
                }
            }
            // Write out and flush the response to the client channel.
            channel.write(buildHttpResponse(zuulResponse));
            writeBufferedBodyContent(zuulResponse, channel);
            channel.flush();
        } else {
            channel.close();
        }
    } else if (msg instanceof HttpContent) {
        final HttpContent chunk = (HttpContent) msg;
        if (channel.isActive()) {
            channel.writeAndFlush(chunk);
        } else {
            chunk.release();
            channel.close();
        }
    } else {
        // should never happen
        ReferenceCountUtil.release(msg);
        throw new ZuulException("Received invalid message from origin", true);
    }
}
Also used : HttpResponseMessage(com.netflix.zuul.message.http.HttpResponseMessage) StatusCategory(com.netflix.zuul.stats.status.StatusCategory) ZuulStatusCategory(com.netflix.zuul.stats.status.ZuulStatusCategory) Channel(io.netty.channel.Channel) ZuulException(com.netflix.zuul.exception.ZuulException) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 47 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project zuul by Netflix.

the class OriginResponseReceiver method writeInternal.

private void writeInternal(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (!ctx.channel().isActive()) {
        ReferenceCountUtil.release(msg);
        return;
    }
    if (msg instanceof HttpRequestMessage) {
        promise.addListener((future) -> {
            if (!future.isSuccess()) {
                Throwable cause = ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).get();
                if (cause != null) {
                    // Set the specific SSL handshake error if the handlers have already caught them
                    ctx.channel().attr(SSL_HANDSHAKE_UNSUCCESS_FROM_ORIGIN_THROWABLE).set(null);
                    fireWriteError("request headers", cause, ctx);
                    LOG.debug("SSLException is overridden by SSLHandshakeException caught in handler level. Original SSL exception message: ", future.cause());
                } else {
                    fireWriteError("request headers", future.cause(), ctx);
                }
            }
        });
        HttpRequestMessage zuulReq = (HttpRequestMessage) msg;
        preWriteHook(ctx, zuulReq);
        super.write(ctx, buildOriginHttpRequest(zuulReq), promise);
    } else if (msg instanceof HttpContent) {
        promise.addListener((future) -> {
            if (!future.isSuccess()) {
                fireWriteError("request content chunk", future.cause(), ctx);
            }
        });
        super.write(ctx, msg, promise);
    } else {
        // should never happen
        ReferenceCountUtil.release(msg);
        throw new ZuulException("Received invalid message from client", true);
    }
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpVersion(io.netty.handler.codec.http.HttpVersion) LoggerFactory(org.slf4j.LoggerFactory) READ_TIMEOUT(com.netflix.zuul.exception.OutboundErrorType.READ_TIMEOUT) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelPromise(io.netty.channel.ChannelPromise) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) HttpQueryParams(com.netflix.zuul.message.http.HttpQueryParams) TaskCloseable(io.perfmark.TaskCloseable) ProxyEndpoint(com.netflix.zuul.filters.endpoint.ProxyEndpoint) Header(com.netflix.zuul.message.Header) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) RESET_CONNECTION(com.netflix.zuul.exception.OutboundErrorType.RESET_CONNECTION) CompleteEvent(com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent) HttpContent(io.netty.handler.codec.http.HttpContent) OriginConnectException(com.netflix.zuul.netty.connectionpool.OriginConnectException) HttpRequest(io.netty.handler.codec.http.HttpRequest) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) Logger(org.slf4j.Logger) OutboundException(com.netflix.zuul.exception.OutboundException) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) HttpRequestMessage(com.netflix.zuul.message.http.HttpRequestMessage) PerfMark(io.perfmark.PerfMark) ZuulException(com.netflix.zuul.exception.ZuulException) PassportState(com.netflix.zuul.passport.PassportState) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) HttpResponse(io.netty.handler.codec.http.HttpResponse) CompleteReason(com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason) ChannelUtils(com.netflix.zuul.netty.ChannelUtils) SESSION_COMPLETE(com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason.SESSION_COMPLETE) HttpRequestMessage(com.netflix.zuul.message.http.HttpRequestMessage) ZuulException(com.netflix.zuul.exception.ZuulException) HttpContent(io.netty.handler.codec.http.HttpContent)

Example 48 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project zuul by Netflix.

the class GZipResponseFilterTest method prepareResponseBody_NeedsGZipping_gzipDeflate.

@Test
public void prepareResponseBody_NeedsGZipping_gzipDeflate() throws Exception {
    originalRequestHeaders.set("Accept-Encoding", "gzip,deflate");
    byte[] originBody = "blah".getBytes();
    response.getHeaders().set("Content-Length", Integer.toString(originBody.length));
    // Force GZip for small response
    Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true);
    response.setHasBody(true);
    assertTrue(filter.shouldFilter(response));
    final HttpResponseMessage result = filter.apply(response);
    final HttpContent hc1 = filter.processContentChunk(response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain());
    final HttpContent hc2 = filter.processContentChunk(response, new DefaultLastHttpContent());
    final byte[] body = new byte[hc1.content().readableBytes() + hc2.content().readableBytes()];
    final int hc1Len = hc1.content().readableBytes();
    final int hc2Len = hc2.content().readableBytes();
    hc1.content().readBytes(body, 0, hc1Len);
    hc2.content().readBytes(body, hc1Len, hc2Len);
    String bodyStr;
    // Check body is a gzipped version of the origin body.
    try (ByteArrayInputStream bais = new ByteArrayInputStream(body);
        GZIPInputStream gzis = new GZIPInputStream(bais);
        ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        int b;
        while ((b = gzis.read()) != -1) {
            baos.write(b);
        }
        bodyStr = baos.toString("UTF-8");
    }
    assertEquals("blah", bodyStr);
    assertEquals("gzip", result.getHeaders().getFirst("Content-Encoding"));
    // Check Content-Length header has been removed
    assertEquals(0, result.getHeaders().getAll("Content-Length").size());
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HttpResponseMessage(com.netflix.zuul.message.http.HttpResponseMessage) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 49 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project zuul by Netflix.

the class ZuulMessageImpl method runBufferedBodyContentThroughFilter.

@Override
public void runBufferedBodyContentThroughFilter(ZuulFilter<?, ?> filter) {
    // original chunk passed in as is without any processing
    for (int i = 0; i < bodyChunks.size(); i++) {
        final HttpContent origChunk = bodyChunks.get(i);
        final HttpContent filteredChunk = filter.processContentChunk(this, origChunk);
        if ((filteredChunk != null) && (filteredChunk != origChunk)) {
            // filter actually did some processing, set the new chunk in and release the old chunk.
            bodyChunks.set(i, filteredChunk);
            final int refCnt = origChunk.refCnt();
            if (refCnt > 0) {
                origChunk.release(refCnt);
            }
        }
    }
}
Also used : HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 50 with HttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpContent in project vert.x by eclipse.

the class WebSocketHandshakeInboundHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse resp = (HttpResponse) msg;
        response = new DefaultFullHttpResponse(resp.protocolVersion(), resp.status());
        response.headers().add(resp.headers());
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        try {
            if (response != null) {
                response.content().writeBytes(content.content());
                if (msg instanceof LastHttpContent) {
                    response.trailingHeaders().add(((LastHttpContent) msg).trailingHeaders());
                    ChannelPipeline pipeline = chctx.pipeline();
                    pipeline.remove(WebSocketHandshakeInboundHandler.this);
                    ChannelHandler handler = pipeline.get(HttpContentDecompressor.class);
                    if (handler != null) {
                        // remove decompressor as its not needed anymore once connection was upgraded to WebSocket
                        ctx.pipeline().remove(handler);
                    }
                    Future<HeadersAdaptor> fut = handshakeComplete(response);
                    wsHandler.handle(fut);
                }
            }
        } finally {
            content.release();
        }
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HeadersAdaptor(io.vertx.core.http.impl.headers.HeadersAdaptor) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandler(io.netty.channel.ChannelHandler) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) ChannelPipeline(io.netty.channel.ChannelPipeline)

Aggregations

HttpContent (io.netty.handler.codec.http.HttpContent)158 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)122 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)62 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)59 Test (org.junit.Test)59 ByteBuf (io.netty.buffer.ByteBuf)40 HttpResponse (io.netty.handler.codec.http.HttpResponse)37 HttpRequest (io.netty.handler.codec.http.HttpRequest)35 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)34 ArrayList (java.util.ArrayList)30 HttpObject (io.netty.handler.codec.http.HttpObject)28 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)24 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)20 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)17 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 Channel (io.netty.channel.Channel)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)15 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 IOException (java.io.IOException)13