Search in sources :

Example 66 with ByteBuf

use of io.netty.buffer.ByteBuf in project netty by netty.

the class LoggingHandlerTest method shouldLogByteBufDataRead.

@Test
public void shouldLogByteBufDataRead() throws Exception {
    ByteBuf msg = Unpooled.copiedBuffer("hello", CharsetUtil.UTF_8);
    EmbeddedChannel channel = new EmbeddedChannel(new LoggingHandler());
    channel.writeInbound(msg);
    verify(appender).doAppend(argThat(new RegexLogMatcher(".+RECEIVED: " + msg.readableBytes() + "B$")));
    ByteBuf handledMsg = channel.readInbound();
    assertThat(msg, is(sameInstance(handledMsg)));
    handledMsg.release();
    assertThat(channel.readInbound(), is(nullValue()));
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 67 with ByteBuf

use of io.netty.buffer.ByteBuf in project grpc-java by grpc.

the class AbstractBenchmark method startUnaryCalls.

/**
   * Start a continuously executing set of unary calls that will terminate when
   * {@code done.get()} is true. Each completed call will increment the counter by the specified
   * delta which benchmarks can use to measure QPS or bandwidth.
   */
protected void startUnaryCalls(int callsPerChannel, final AtomicLong counter, final AtomicBoolean done, final long counterDelta) {
    for (final ManagedChannel channel : channels) {
        for (int i = 0; i < callsPerChannel; i++) {
            StreamObserver<ByteBuf> observer = new StreamObserver<ByteBuf>() {

                @Override
                public void onNext(ByteBuf value) {
                    counter.addAndGet(counterDelta);
                }

                @Override
                public void onError(Throwable t) {
                    done.set(true);
                }

                @Override
                public void onCompleted() {
                    if (!done.get()) {
                        ByteBuf slice = request.slice();
                        ClientCalls.asyncUnaryCall(channel.newCall(unaryMethod, CALL_OPTIONS), slice, this);
                    }
                }
            };
            observer.onCompleted();
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ManagedChannel(io.grpc.ManagedChannel) ByteBuf(io.netty.buffer.ByteBuf)

Example 68 with ByteBuf

use of io.netty.buffer.ByteBuf in project grpc-java by grpc.

the class AbstractBenchmark method startFlowControlledStreamingCalls.

/**
   * Start a continuously executing set of duplex streaming ping-pong calls that will terminate when
   * {@code done.get()} is true. Each completed call will increment the counter by the specified
   * delta which benchmarks can use to measure messages per second or bandwidth.
   */
protected CountDownLatch startFlowControlledStreamingCalls(int callsPerChannel, final AtomicLong counter, final AtomicBoolean record, final AtomicBoolean done, final long counterDelta) {
    final CountDownLatch latch = new CountDownLatch(callsPerChannel * channels.length);
    for (final ManagedChannel channel : channels) {
        for (int i = 0; i < callsPerChannel; i++) {
            final ClientCall<ByteBuf, ByteBuf> streamingCall = channel.newCall(flowControlledStreaming, CALL_OPTIONS);
            final AtomicReference<StreamObserver<ByteBuf>> requestObserverRef = new AtomicReference<StreamObserver<ByteBuf>>();
            final AtomicBoolean ignoreMessages = new AtomicBoolean();
            StreamObserver<ByteBuf> requestObserver = ClientCalls.asyncBidiStreamingCall(streamingCall, new StreamObserver<ByteBuf>() {

                @Override
                public void onNext(ByteBuf value) {
                    StreamObserver<ByteBuf> obs = requestObserverRef.get();
                    if (done.get()) {
                        if (!ignoreMessages.getAndSet(true)) {
                            obs.onCompleted();
                        }
                        return;
                    }
                    if (record.get()) {
                        counter.addAndGet(counterDelta);
                    }
                // request is called automatically because the observer implicitly has auto
                // inbound flow control
                }

                @Override
                public void onError(Throwable t) {
                    logger.log(Level.WARNING, "call error", t);
                    latch.countDown();
                }

                @Override
                public void onCompleted() {
                    latch.countDown();
                }
            });
            requestObserverRef.set(requestObserver);
            // Add some outstanding requests to ensure the server is filling the connection
            streamingCall.request(5);
            requestObserver.onNext(request.slice());
        }
    }
    return latch;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedChannel(io.grpc.ManagedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf)

Example 69 with ByteBuf

use of io.netty.buffer.ByteBuf in project grpc-java by grpc.

the class NettyClientHandler method sendPingFrame.

/**
   * Sends a PING frame. If a ping operation is already outstanding, the callback in the message is
   * registered to be called when the existing operation completes, and no new frame is sent.
   */
private void sendPingFrame(ChannelHandlerContext ctx, SendPingCommand msg, ChannelPromise promise) {
    // Don't check lifecycleManager.getShutdownStatus() since we want to allow pings after shutdown
    // but before termination. After termination, messages will no longer arrive because the
    // pipeline clears all handlers on channel close.
    PingCallback callback = msg.callback();
    Executor executor = msg.executor();
    // any outstanding operation
    if (ping != null) {
        promise.setSuccess();
        ping.addCallback(callback, executor);
        return;
    }
    // Use a new promise to prevent calling the callback twice on write failure: here and in
    // NettyClientTransport.ping(). It may appear strange, but it will behave the same as if
    // ping != null above.
    promise.setSuccess();
    promise = ctx().newPromise();
    // set outstanding operation
    long data = USER_PING_PAYLOAD;
    ByteBuf buffer = ctx.alloc().buffer(8);
    buffer.writeLong(data);
    Stopwatch stopwatch = Stopwatch.createStarted(ticker);
    ping = new Http2Ping(data, stopwatch);
    ping.addCallback(callback, executor);
    // and then write the ping
    encoder().writePing(ctx, false, buffer, promise);
    ctx.flush();
    final Http2Ping finalPing = ping;
    promise.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                if (cause instanceof ClosedChannelException) {
                    cause = lifecycleManager.getShutdownThrowable();
                    if (cause == null) {
                        cause = Status.UNKNOWN.withDescription("Ping failed but for unknown reason.").withCause(future.cause()).asException();
                    }
                }
                finalPing.failed(cause);
                if (ping == finalPing) {
                    ping = null;
                }
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ClosedChannelException(java.nio.channels.ClosedChannelException) Executor(java.util.concurrent.Executor) Http2Ping(io.grpc.internal.Http2Ping) Stopwatch(com.google.common.base.Stopwatch) PingCallback(io.grpc.internal.ClientTransport.PingCallback) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2Exception(io.netty.handler.codec.http2.Http2Exception) StatusException(io.grpc.StatusException) ClosedChannelException(java.nio.channels.ClosedChannelException)

Example 70 with ByteBuf

use of io.netty.buffer.ByteBuf in project grpc-java by grpc.

the class NettyClientHandlerTest method oustandingUserPingShouldNotInteractWithDataPing.

@Test
public void oustandingUserPingShouldNotInteractWithDataPing() throws Exception {
    createStream();
    handler().setAutoTuneFlowControl(true);
    PingCallbackImpl callback = new PingCallbackImpl();
    sendPing(callback);
    ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
    verifyWrite().writePing(eq(ctx()), eq(false), captor.capture(), any(ChannelPromise.class));
    ByteBuf payload = captor.getValue();
    channelRead(grpcDataFrame(3, false, contentAsArray()));
    long pingData = handler().flowControlPing().payload();
    ByteBuf buffer = handler().ctx().alloc().buffer(8);
    buffer.writeLong(pingData);
    channelRead(pingFrame(true, buffer));
    assertEquals(1, handler().flowControlPing().getPingReturn());
    assertEquals(0, callback.invocationCount);
    channelRead(pingFrame(true, payload));
    assertEquals(1, handler().flowControlPing().getPingReturn());
    assertEquals(1, callback.invocationCount);
}
Also used : ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)1557 Test (org.junit.Test)668 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)162 IOException (java.io.IOException)99 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)89 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)81 Test (org.testng.annotations.Test)68 InetSocketAddress (java.net.InetSocketAddress)60 Channel (io.netty.channel.Channel)57 ChannelFuture (io.netty.channel.ChannelFuture)56 ArrayList (java.util.ArrayList)55 Map (java.util.Map)45 ChannelPromise (io.netty.channel.ChannelPromise)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)36 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)35 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 HashMap (java.util.HashMap)34 CountDownLatch (java.util.concurrent.CountDownLatch)34 RecyclableDuplicateByteBuf (io.netty.buffer.RecyclableDuplicateByteBuf)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32