Search in sources :

Example 16 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class SimpleChannelPoolTest method testUnhealthyChannelIsNotOffered.

/**
     * Tests that if channel was unhealthy it is not offered back to the pool.
     *
     * @throws Exception
     */
@Test
public void testUnhealthyChannelIsNotOffered() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
        }
    });
    // Start server
    Channel sc = sb.bind(addr).syncUninterruptibly().channel();
    ChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler);
    Channel channel1 = pool.acquire().syncUninterruptibly().getNow();
    pool.release(channel1).syncUninterruptibly();
    Channel channel2 = pool.acquire().syncUninterruptibly().getNow();
    //first check that when returned healthy then it actually offered back to the pool.
    assertSame(channel1, channel2);
    expectedException.expect(IllegalStateException.class);
    channel1.close().syncUninterruptibly();
    try {
        pool.release(channel1).syncUninterruptibly();
    } finally {
        sc.close().syncUninterruptibly();
        channel2.close().syncUninterruptibly();
        group.shutdownGracefully();
    }
}
Also used : LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExpectedException(org.junit.rules.ExpectedException) EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 17 with LocalAddress

use of io.netty.channel.local.LocalAddress in project grpc-java by grpc.

the class AbstractBenchmark method setup.

/**
   * Initialize the environment for the executor.
   */
public void setup(ExecutorType clientExecutor, ExecutorType serverExecutor, MessageSize requestSize, MessageSize responseSize, FlowWindowSize windowSize, ChannelType channelType, int maxConcurrentStreams, int channelCount) throws Exception {
    NettyServerBuilder serverBuilder;
    NettyChannelBuilder channelBuilder;
    if (channelType == ChannelType.LOCAL) {
        LocalAddress address = new LocalAddress("netty-e2e-benchmark");
        serverBuilder = NettyServerBuilder.forAddress(address);
        serverBuilder.channelType(LocalServerChannel.class);
        channelBuilder = NettyChannelBuilder.forAddress(address);
        channelBuilder.channelType(LocalChannel.class);
    } else {
        ServerSocket sock = new ServerSocket();
        // Pick a port using an ephemeral socket.
        sock.bind(new InetSocketAddress(BENCHMARK_ADDR, 0));
        SocketAddress address = sock.getLocalSocketAddress();
        sock.close();
        serverBuilder = NettyServerBuilder.forAddress(address);
        channelBuilder = NettyChannelBuilder.forAddress(address);
    }
    if (serverExecutor == ExecutorType.DIRECT) {
        serverBuilder.directExecutor();
    }
    if (clientExecutor == ExecutorType.DIRECT) {
        channelBuilder.directExecutor();
    }
    // Always use a different worker group from the client.
    ThreadFactory serverThreadFactory = new DefaultThreadFactory("STF pool", true);
    serverBuilder.workerEventLoopGroup(new NioEventLoopGroup(0, serverThreadFactory));
    // Always set connection and stream window size to same value
    serverBuilder.flowControlWindow(windowSize.bytes());
    channelBuilder.flowControlWindow(windowSize.bytes());
    channelBuilder.negotiationType(NegotiationType.PLAINTEXT);
    serverBuilder.maxConcurrentCallsPerConnection(maxConcurrentStreams);
    // Create buffers of the desired size for requests and responses.
    PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
    // Use a heap buffer for now, since MessageFramer doesn't know how to directly convert this
    // into a WritableBuffer
    // TODO(carl-mastrangelo): convert this into a regular buffer() call.  See
    // https://github.com/grpc/grpc-java/issues/2062#issuecomment-234646216
    request = alloc.heapBuffer(requestSize.bytes());
    request.writerIndex(request.capacity() - 1);
    response = alloc.heapBuffer(responseSize.bytes());
    response.writerIndex(response.capacity() - 1);
    // Simple method that sends and receives NettyByteBuf
    unaryMethod = MethodDescriptor.<ByteBuf, ByteBuf>newBuilder().setType(MethodType.UNARY).setFullMethodName("benchmark/unary").setRequestMarshaller(new ByteBufOutputMarshaller()).setResponseMarshaller(new ByteBufOutputMarshaller()).build();
    pingPongMethod = unaryMethod.toBuilder().setType(MethodType.BIDI_STREAMING).setFullMethodName("benchmark/pingPong").build();
    flowControlledStreaming = pingPongMethod.toBuilder().setFullMethodName("benchmark/flowControlledStreaming").build();
    // Server implementation of unary & streaming methods
    serverBuilder.addService(ServerServiceDefinition.builder(new ServiceDescriptor("benchmark", unaryMethod, pingPongMethod, flowControlledStreaming)).addMethod(unaryMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    // no-op
                    message.release();
                    call.sendMessage(response.slice());
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }
            };
        }
    }).addMethod(pingPongMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    message.release();
                    call.sendMessage(response.slice());
                    // Request next message
                    call.request(1);
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }
            };
        }
    }).addMethod(flowControlledStreaming, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    message.release();
                    while (call.isReady()) {
                        call.sendMessage(response.slice());
                    }
                    // Request next message
                    call.request(1);
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void onReady() {
                    while (call.isReady()) {
                        call.sendMessage(response.slice());
                    }
                }
            };
        }
    }).build());
    // Build and start the clients and servers
    server = serverBuilder.build();
    server.start();
    channels = new ManagedChannel[channelCount];
    ThreadFactory clientThreadFactory = new DefaultThreadFactory("CTF pool", true);
    for (int i = 0; i < channelCount; i++) {
        // Use a dedicated event-loop for each channel
        channels[i] = channelBuilder.eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory)).build();
    }
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ThreadFactory(java.util.concurrent.ThreadFactory) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) LocalAddress(io.netty.channel.local.LocalAddress) ServerCallHandler(io.grpc.ServerCallHandler) InetSocketAddress(java.net.InetSocketAddress) Metadata(io.grpc.Metadata) ServerSocket(java.net.ServerSocket) ByteBuf(io.netty.buffer.ByteBuf) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ByteBufOutputMarshaller(io.grpc.benchmarks.ByteBufOutputMarshaller) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerCall(io.grpc.ServerCall) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 18 with LocalAddress

use of io.netty.channel.local.LocalAddress in project grpc-java by grpc.

the class Http2NettyLocalChannelTest method createChannel.

@Override
protected ManagedChannel createChannel() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(new LocalAddress("in-process-1")).negotiationType(NegotiationType.PLAINTEXT).channelType(LocalChannel.class).flowControlWindow(65 * 1024).maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
    io.grpc.internal.TestingAccessor.setStatsContextFactory(builder, getClientStatsFactory());
    return builder.build();
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder)

Example 19 with LocalAddress

use of io.netty.channel.local.LocalAddress in project grpc-java by grpc.

the class ProtocolNegotiatorsTest method httpProxy_completes.

@Test(timeout = 5000)
public void httpProxy_completes() throws Exception {
    DefaultEventLoopGroup elg = new DefaultEventLoopGroup(1);
    // ProxyHandler is incompatible with EmbeddedChannel because when channelRegistered() is called
    // the channel is already active.
    LocalAddress proxy = new LocalAddress("httpProxy_completes");
    SocketAddress host = InetSocketAddress.createUnresolved("specialHost", 314);
    ChannelInboundHandler mockHandler = mock(ChannelInboundHandler.class);
    Channel serverChannel = new ServerBootstrap().group(elg).channel(LocalServerChannel.class).childHandler(mockHandler).bind(proxy).sync().channel();
    ProtocolNegotiator nego = ProtocolNegotiators.httpProxy(proxy, null, null, ProtocolNegotiators.plaintext());
    ChannelHandler handler = nego.newHandler(grpcHandler);
    Channel channel = new Bootstrap().group(elg).channel(LocalChannel.class).handler(handler).register().sync().channel();
    pipeline = channel.pipeline();
    // Wait for initialization to complete
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    // The grpcHandler must be in the pipeline, but we don't actually want it during our test
    // because it will consume all events since it is a mock. We only use it because it is required
    // to construct the Handler.
    pipeline.remove(grpcHandler);
    channel.connect(host).sync();
    serverChannel.close();
    ArgumentCaptor<ChannelHandlerContext> contextCaptor = ArgumentCaptor.forClass(ChannelHandlerContext.class);
    Mockito.verify(mockHandler).channelActive(contextCaptor.capture());
    ChannelHandlerContext serverContext = contextCaptor.getValue();
    final String golden = "isThisThingOn?";
    ChannelFuture negotiationFuture = channel.writeAndFlush(bb(golden, channel));
    // Wait for sending initial request to complete
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    ArgumentCaptor<Object> objectCaptor = ArgumentCaptor.forClass(Object.class);
    Mockito.verify(mockHandler).channelRead(any(ChannelHandlerContext.class), objectCaptor.capture());
    ByteBuf b = (ByteBuf) objectCaptor.getValue();
    String request = b.toString(UTF_8);
    b.release();
    assertTrue("No trailing newline: " + request, request.endsWith("\r\n\r\n"));
    assertTrue("No CONNECT: " + request, request.startsWith("CONNECT specialHost:314 "));
    assertTrue("No host header: " + request, request.contains("host: specialHost:314"));
    assertFalse(negotiationFuture.isDone());
    serverContext.writeAndFlush(bb("HTTP/1.1 200 OK\r\n\r\n", serverContext.channel())).sync();
    negotiationFuture.sync();
    channel.eventLoop().submit(NOOP_RUNNABLE).sync();
    objectCaptor.getAllValues().clear();
    Mockito.verify(mockHandler, times(2)).channelRead(any(ChannelHandlerContext.class), objectCaptor.capture());
    b = (ByteBuf) objectCaptor.getAllValues().get(1);
    // If we were using the real grpcHandler, this would have been the HTTP/2 preface
    String preface = b.toString(UTF_8);
    b.release();
    assertEquals(golden, preface);
    channel.close();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) Test(org.junit.Test)

Example 20 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class ReentrantChannelTest method testWriteFlushPingPong.

@Test
public void testWriteFlushPingPong() throws Exception {
    LocalAddress addr = new LocalAddress("testWriteFlushPingPong");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        int writeCount;

        int flushCount;

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (writeCount < 5) {
                writeCount++;
                ctx.channel().flush();
            }
            super.write(ctx, msg, promise);
        }

        @Override
        public void flush(ChannelHandlerContext ctx) throws Exception {
            if (flushCount < 5) {
                flushCount++;
                ctx.channel().write(createTestBuf(2000));
            }
            super.flush(ctx);
        }
    });
    clientChannel.writeAndFlush(createTestBuf(2000));
    clientChannel.close().sync();
    assertLog("WRITE\n" + "FLUSH\n" + "WRITE\n" + "FLUSH\n" + "WRITE\n" + "FLUSH\n" + "WRITE\n" + "FLUSH\n" + "WRITE\n" + "FLUSH\n" + "WRITE\n" + "FLUSH\n" + "CLOSE\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.Test)

Aggregations

LocalAddress (io.netty.channel.local.LocalAddress)34 Bootstrap (io.netty.bootstrap.Bootstrap)26 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)25 LocalChannel (io.netty.channel.local.LocalChannel)24 Test (org.junit.Test)24 LocalServerChannel (io.netty.channel.local.LocalServerChannel)23 Channel (io.netty.channel.Channel)22 EventLoopGroup (io.netty.channel.EventLoopGroup)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)16 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)15 LocalEventLoopGroup (io.netty.channel.local.LocalEventLoopGroup)14 ChannelFuture (io.netty.channel.ChannelFuture)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeoutException (java.util.concurrent.TimeoutException)6 ClosedChannelException (java.nio.channels.ClosedChannelException)4 ChannelPipeline (io.netty.channel.ChannelPipeline)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)3 InetSocketAddress (java.net.InetSocketAddress)3