Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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

License:Apache License

@Test
public void sendFrameShouldSucceed() throws Exception {
    createStream();//from w w  w . j a  v a2s.  com

    // Send a frame and verify that it was written.
    ChannelFuture future = enqueue(new SendGrpcFrameCommand(streamTransportState, content(), true));

    assertTrue(future.isSuccess());
    verifyWrite().writeData(eq(ctx()), eq(3), eq(content()), eq(0), eq(true), any(ChannelPromise.class));
    verify(mockKeepAliveManager, times(1)).onTransportActive(); // onStreamActive
    verifyNoMoreInteractions(mockKeepAliveManager);
}

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

License:Apache License

@Test
public void sendForUnknownStreamShouldFail() throws Exception {
    ChannelFuture future = enqueue(new SendGrpcFrameCommand(streamTransportState, content(), true));
    assertTrue(future.isDone());/*from ww w.  j  a  v  a 2  s .  co  m*/
    assertFalse(future.isSuccess());
}

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

License:Apache License

@Test
public void receivedGoAwayShouldCancelBufferedStream() throws Exception {
    // Force the stream to be buffered.
    receiveMaxConcurrentStreams(0);/*w ww . j a v  a2  s.co m*/
    ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));
    channelRead(goAwayFrame(0));
    assertTrue(future.isDone());
    assertFalse(future.isSuccess());
    Status status = Status.fromThrowable(future.cause());
    assertEquals(Status.Code.UNAVAILABLE, status.getCode());
    assertEquals("HTTP/2 error code: NO_ERROR\nReceived Goaway", status.getDescription());
}

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

License:Apache License

@Test
public void receivedGoAwayShouldFailUnknownBufferedStreams() throws Exception {
    receiveMaxConcurrentStreams(0);/*from   w ww.j  av  a 2  s  .com*/

    ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));

    // Read a GOAWAY that indicates our stream was never processed by the server.
    channelRead(goAwayFrame(0, 8 /* Cancel */, Unpooled.copiedBuffer("this is a test", UTF_8)));
    assertTrue(future.isDone());
    assertFalse(future.isSuccess());
    Status status = Status.fromThrowable(future.cause());
    assertEquals(Status.CANCELLED.getCode(), status.getCode());
    assertEquals("HTTP/2 error code: CANCEL\nReceived Goaway\nthis is a test", status.getDescription());
}

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

License:Apache License

@Test
public void receivedGoAwayShouldFailNewStreams() throws Exception {
    // Read a GOAWAY that indicates our stream was never processed by the server.
    channelRead(goAwayFrame(0, 8 /* Cancel */, Unpooled.copiedBuffer("this is a test", UTF_8)));

    // Now try to create a stream.
    ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));
    assertTrue(future.isDone());//  ww  w.java2s . co m
    assertFalse(future.isSuccess());
    Status status = Status.fromThrowable(future.cause());
    assertEquals(Status.CANCELLED.getCode(), status.getCode());
    assertEquals("HTTP/2 error code: CANCEL\nReceived Goaway\nthis is a test", status.getDescription());
}

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

License:Apache License

@Test
public void channelShutdownShouldCancelBufferedStreams() throws Exception {
    // Force a stream to get added to the pending queue.
    receiveMaxConcurrentStreams(0);/*ww w .j ava 2 s . com*/
    ChannelFuture future = enqueue(newCreateStreamCommand(grpcHeaders, streamTransportState));

    handler().channelInactive(ctx());
    assertTrue(future.isDone());
    assertFalse(future.isSuccess());
    verify(mockKeepAliveManager, times(1)).onTransportTermination(); // channelInactive
    verifyNoMoreInteractions(mockKeepAliveManager);
}

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

License:Apache License

@Test
public void exhaustedStreamsShouldFail() throws Exception {
    streamId = Integer.MAX_VALUE;
    setUp();//from w  ww  .j  a  v  a2 s .  co  m

    assertNull(lifecycleManager.getShutdownStatus());
    // Create the MAX_INT stream.
    ChannelFuture future = createStream();
    assertTrue(future.isSuccess());

    TransportStateImpl newStreamTransportState = new TransportStateImpl(handler(), channel().eventLoop(),
            DEFAULT_MAX_MESSAGE_SIZE, transportTracer);

    // This should fail - out of stream IDs.
    future = enqueue(newCreateStreamCommand(grpcHeaders, newStreamTransportState));
    assertTrue(future.isDone());
    assertFalse(future.isSuccess());
    Status status = lifecycleManager.getShutdownStatus();
    assertNotNull(status);
    assertTrue("status does not reference 'exhausted': " + status,
            status.getDescription().contains("exhausted"));
}

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

License:Apache License

@Override
public void ping(final PingCallback callback, final Executor executor) {
    if (channel == null) {
        executor.execute(new Runnable() {
            @Override//from   w ww  . j  a va2  s  .c  o  m
            public void run() {
                callback.onFailure(statusExplainingWhyTheChannelIsNull.asException());
            }
        });
        return;
    }
    // The promise and listener always succeed in NettyClientHandler. So this listener handles the
    // error case, when the channel is closed and the NettyClientHandler no longer in the pipeline.
    ChannelFutureListener failureListener = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                Status s = statusFromFailedFuture(future);
                Http2Ping.notifyFailed(callback, executor, s.asException());
            }
        }
    };
    // Write the command requesting the ping
    handler.getWriteQueue().enqueue(new SendPingCommand(callback, executor), true).addListener(failureListener);
}

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

License:Apache License

@SuppressWarnings("unchecked")
@Override//from  ww  w .  jav a  2 s . c  o  m
public Runnable start(Listener transportListener) {
    lifecycleManager = new ClientTransportLifecycleManager(
            Preconditions.checkNotNull(transportListener, "listener"));
    EventLoop eventLoop = group.next();
    if (keepAliveTimeNanos != KEEPALIVE_TIME_NANOS_DISABLED) {
        keepAliveManager = new KeepAliveManager(new ClientKeepAlivePinger(this), eventLoop, keepAliveTimeNanos,
                keepAliveTimeoutNanos, keepAliveWithoutCalls);
    }

    handler = NettyClientHandler.newHandler(lifecycleManager, keepAliveManager, flowControlWindow,
            maxHeaderListSize, GrpcUtil.STOPWATCH_SUPPLIER, tooManyPingsRunnable, transportTracer,
            eagAttributes, authorityString);
    NettyHandlerSettings.setAutoWindow(handler);

    ChannelHandler negotiationHandler = negotiator.newHandler(handler);

    Bootstrap b = new Bootstrap();
    b.attr(LOGGER_KEY, channelLogger);
    b.group(eventLoop);
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_KEEPALIVE, true);
    // For non-epoll based channel, the option will be ignored.
    if (keepAliveTimeNanos != KEEPALIVE_TIME_NANOS_DISABLED) {
        ChannelOption<Integer> tcpUserTimeout = Utils.maybeGetTcpUserTimeoutOption();
        if (tcpUserTimeout != null) {
            b.option(tcpUserTimeout, (int) TimeUnit.NANOSECONDS.toMillis(keepAliveTimeoutNanos));
        }
    }
    for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
        // Every entry in the map is obtained from
        // NettyChannelBuilder#withOption(ChannelOption<T> option, T value)
        // so it is safe to pass the key-value pair to b.option().
        b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
    }

    ChannelHandler bufferingHandler = new WriteBufferingAndExceptionHandler(negotiationHandler);

    /**
     * We don't use a ChannelInitializer in the client bootstrap because its "initChannel" method
     * is executed in the event loop and we need this handler to be in the pipeline immediately so
     * that it may begin buffering writes.
     */
    b.handler(bufferingHandler);
    ChannelFuture regFuture = b.register();
    if (regFuture.isDone() && !regFuture.isSuccess()) {
        channel = null;
        // Initialization has failed badly. All new streams should be made to fail.
        Throwable t = regFuture.cause();
        if (t == null) {
            t = new IllegalStateException("Channel is null, but future doesn't have a cause");
        }
        statusExplainingWhyTheChannelIsNull = Utils.statusFromThrowable(t);
        // Use a Runnable since lifecycleManager calls transportListener
        return new Runnable() {
            @Override
            public void run() {
                // NOTICE: we not are calling lifecycleManager from the event loop. But there isn't really
                // an event loop in this case, so nothing should be accessing the lifecycleManager. We
                // could use GlobalEventExecutor (which is what regFuture would use for notifying
                // listeners in this case), but avoiding on-demand thread creation in an error case seems
                // a good idea and is probably clearer threading.
                lifecycleManager.notifyTerminated(statusExplainingWhyTheChannelIsNull);
            }
        };
    }
    channel = regFuture.channel();
    // Start the write queue as soon as the channel is constructed
    handler.startWriteQueue(channel);
    // This write will have no effect, yet it will only complete once the negotiationHandler
    // flushes any pending writes. We need it to be staged *before* the `connect` so that
    // the channel can't have been closed yet, removing all handlers. This write will sit in the
    // AbstractBufferingHandler's buffer, and will either be flushed on a successful connection,
    // or failed if the connection fails.
    channel.writeAndFlush(NettyClientHandler.NOOP_MESSAGE).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // Need to notify of this failure, because NettyClientHandler may not have been added to
                // the pipeline before the error occurred.
                lifecycleManager.notifyTerminated(Utils.statusFromThrowable(future.cause()));
            }
        }
    });
    // Start the connection operation to the server.
    SocketAddress localAddress = localSocketPicker.createSocketAddress(remoteAddress, eagAttributes);
    if (localAddress != null) {
        channel.connect(remoteAddress, localAddress);
    } else {
        channel.connect(remoteAddress);
    }

    if (keepAliveManager != null) {
        keepAliveManager.onTransportStarted();
    }

    return null;
}

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

License:Apache License

@Override
public void start(ServerListener serverListener) throws IOException {
    listener = checkNotNull(serverListener, "serverListener");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);/* w w w  . j  ava 2  s.co m*/
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);

    if (channelOptions != null) {
        for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
            @SuppressWarnings("unchecked")
            ChannelOption<Object> key = (ChannelOption<Object>) entry.getKey();
            b.childOption(key, entry.getValue());
        }
    }

    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) {

            ChannelPromise channelDone = ch.newPromise();

            long maxConnectionAgeInNanos = NettyServer.this.maxConnectionAgeInNanos;
            if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
                // apply a random jitter of +/-10% to max connection age
                maxConnectionAgeInNanos = (long) ((.9D + Math.random() * .2D) * maxConnectionAgeInNanos);
            }

            NettyServerTransport transport = new NettyServerTransport(ch, channelDone, protocolNegotiator,
                    streamTracerFactories, transportTracerFactory.create(), maxStreamsPerConnection,
                    flowControlWindow, maxMessageSize, maxHeaderListSize, keepAliveTimeInNanos,
                    keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos,
                    maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos);
            ServerTransportListener transportListener;
            // This is to order callbacks on the listener, not to guard access to channel.
            synchronized (NettyServer.this) {
                if (channel != null && !channel.isOpen()) {
                    // Server already shutdown.
                    ch.close();
                    return;
                }
                // `channel` shutdown can race with `ch` initialization, so this is only safe to increment
                // inside the lock.
                eventLoopReferenceCounter.retain();
                transportListener = listener.transportCreated(transport);
            }

            /**
             * Releases the event loop if the channel is "done", possibly due to the channel closing.
             */
            final class LoopReleaser implements ChannelFutureListener {
                private boolean done;

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!done) {
                        done = true;
                        eventLoopReferenceCounter.release();
                    }
                }
            }

            transport.start(transportListener);
            ChannelFutureListener loopReleaser = new LoopReleaser();
            channelDone.addListener(loopReleaser);
            ch.closeFuture().addListener(loopReleaser);
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(address);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new IOException("Failed to bind", future.cause());
    }
    channel = future.channel();
    Future<?> channelzFuture = channel.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            InternalInstrumented<SocketStats> listenSocket = new ListenSocket(channel);
            listenSocketStats.set(listenSocket);
            channelz.addListenSocket(listenSocket);
        }
    });
    try {
        channelzFuture.await();
    } catch (InterruptedException ex) {
        throw new RuntimeException("Interrupted while registering listen socket to channelz", ex);
    }
}