Search in sources :

Example 21 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project hbase by apache.

the class FanOutOneBlockAsyncDFSOutputHelper method connectToDataNodes.

private static List<Future<Channel>> connectToDataNodes(Configuration conf, DFSClient client, String clientName, LocatedBlock locatedBlock, long maxBytesRcvd, long latestGS, BlockConstructionStage stage, DataChecksum summer, EventLoop eventLoop) {
    Enum<?>[] storageTypes = locatedBlock.getStorageTypes();
    DatanodeInfo[] datanodeInfos = locatedBlock.getLocations();
    boolean connectToDnViaHostname = conf.getBoolean(DFS_CLIENT_USE_DN_HOSTNAME, DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
    int timeoutMs = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY, READ_TIMEOUT);
    ExtendedBlock blockCopy = new ExtendedBlock(locatedBlock.getBlock());
    blockCopy.setNumBytes(locatedBlock.getBlockSize());
    ClientOperationHeaderProto header = ClientOperationHeaderProto.newBuilder().setBaseHeader(BaseHeaderProto.newBuilder().setBlock(PB_HELPER.convert(blockCopy)).setToken(PB_HELPER.convert(locatedBlock.getBlockToken()))).setClientName(clientName).build();
    ChecksumProto checksumProto = DataTransferProtoUtil.toProto(summer);
    OpWriteBlockProto.Builder writeBlockProtoBuilder = OpWriteBlockProto.newBuilder().setHeader(header).setStage(OpWriteBlockProto.BlockConstructionStage.valueOf(stage.name())).setPipelineSize(1).setMinBytesRcvd(locatedBlock.getBlock().getNumBytes()).setMaxBytesRcvd(maxBytesRcvd).setLatestGenerationStamp(latestGS).setRequestedChecksum(checksumProto).setCachingStrategy(CachingStrategyProto.newBuilder().setDropBehind(true).build());
    List<Future<Channel>> futureList = new ArrayList<>(datanodeInfos.length);
    for (int i = 0; i < datanodeInfos.length; i++) {
        DatanodeInfo dnInfo = datanodeInfos[i];
        Enum<?> storageType = storageTypes[i];
        Promise<Channel> promise = eventLoop.newPromise();
        futureList.add(promise);
        String dnAddr = dnInfo.getXferAddr(connectToDnViaHostname);
        new Bootstrap().group(eventLoop).channel(NioSocketChannel.class).option(CONNECT_TIMEOUT_MILLIS, timeoutMs).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
            // we need to get the remote address of the channel so we can only move on after
            // channel connected. Leave an empty implementation here because netty does not allow
            // a null handler.
            }
        }).connect(NetUtils.createSocketAddr(dnAddr)).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    initialize(conf, future.channel(), dnInfo, storageType, writeBlockProtoBuilder, timeoutMs, client, locatedBlock.getBlockToken(), promise);
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
    }
    return futureList;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DatanodeInfo(org.apache.hadoop.hdfs.protocol.DatanodeInfo) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ExtendedBlock(org.apache.hadoop.hdfs.protocol.ExtendedBlock) ArrayList(java.util.ArrayList) ChecksumProto(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ChecksumProto) OpWriteBlockProto(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpWriteBlockProto) ChannelFutureListener(io.netty.channel.ChannelFutureListener) UnresolvedLinkException(org.apache.hadoop.fs.UnresolvedLinkException) LeaseExpiredException(org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException) InvalidBlockTokenException(org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) RemoteException(org.apache.hadoop.ipc.RemoteException) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Bootstrap(io.netty.bootstrap.Bootstrap) ClientOperationHeaderProto(org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ClientOperationHeaderProto)

Example 22 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project failsafe by jhalterman.

the class NettyExample method createBootstrap.

static Bootstrap createBootstrap(EventLoopGroup group) {
    return new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ctx.write(msg);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) {
                    ctx.flush();
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    // Close the connection when an exception is raised.
                    cause.printStackTrace();
                    ctx.close();
                }
            });
        }
    });
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 23 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project jersey by jersey.

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 24 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project flink by apache.

the class KvStateServerTest method testSimpleRequest.

/**
	 * Tests a simple successful query via a SocketChannel.
	 */
@Test
public void testSimpleRequest() throws Exception {
    KvStateServer server = null;
    Bootstrap bootstrap = null;
    try {
        KvStateRegistry registry = new KvStateRegistry();
        KvStateRequestStats stats = new AtomicKvStateRequestStats();
        server = new KvStateServer(InetAddress.getLocalHost(), 0, 1, 1, registry, stats);
        server.start();
        KvStateServerAddress serverAddress = server.getAddress();
        int numKeyGroups = 1;
        AbstractStateBackend abstractBackend = new MemoryStateBackend();
        DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0);
        dummyEnv.setKvStateRegistry(registry);
        AbstractKeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, new JobID(), "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), registry.createTaskRegistry(new JobID(), new JobVertexID()));
        final KvStateServerHandlerTest.TestRegistryListener registryListener = new KvStateServerHandlerTest.TestRegistryListener();
        registry.registerListener(registryListener);
        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE);
        desc.setQueryable("vanilla");
        ValueState<Integer> state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc);
        // Update KvState
        int expectedValue = 712828289;
        int key = 99812822;
        backend.setCurrentKey(key);
        state.update(expectedValue);
        // Request
        byte[] serializedKeyAndNamespace = KvStateRequestSerializer.serializeKeyAndNamespace(key, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE);
        // Connect to the server
        final BlockingQueue<ByteBuf> responses = new LinkedBlockingQueue<>();
        bootstrap = createBootstrap(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4), new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                responses.add((ByteBuf) msg);
            }
        });
        Channel channel = bootstrap.connect(serverAddress.getHost(), serverAddress.getPort()).sync().channel();
        long requestId = Integer.MAX_VALUE + 182828L;
        assertTrue(registryListener.registrationName.equals("vanilla"));
        ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), requestId, registryListener.kvStateId, serializedKeyAndNamespace);
        channel.writeAndFlush(request);
        ByteBuf buf = responses.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertEquals(KvStateRequestType.REQUEST_RESULT, KvStateRequestSerializer.deserializeHeader(buf));
        KvStateRequestResult response = KvStateRequestSerializer.deserializeKvStateRequestResult(buf);
        assertEquals(requestId, response.getRequestId());
        int actualValue = KvStateRequestSerializer.deserializeValue(response.getSerializedResult(), IntSerializer.INSTANCE);
        assertEquals(expectedValue, actualValue);
    } finally {
        if (server != null) {
            server.shutDown();
        }
        if (bootstrap != null) {
            EventLoopGroup group = bootstrap.group();
            if (group != null) {
                group.shutdownGracefully();
            }
        }
    }
}
Also used : KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) KvStateRequestResult(org.apache.flink.runtime.query.netty.message.KvStateRequestResult) MemoryStateBackend(org.apache.flink.runtime.state.memory.MemoryStateBackend) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) KvStateServerAddress(org.apache.flink.runtime.query.KvStateServerAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ByteBuf(io.netty.buffer.ByteBuf) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) AbstractStateBackend(org.apache.flink.runtime.state.AbstractStateBackend) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) DummyEnvironment(org.apache.flink.runtime.operators.testutils.DummyEnvironment) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) JobID(org.apache.flink.api.common.JobID) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 25 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project netty by netty.

the class HttpToHttp2ConnectionHandlerTest method bootstrapEnv.

private void bootstrapEnv(int requestCountDown, int serverSettingsAckCount, int trailersCount) throws Exception {
    final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(serverSettingsAckCount);
    trailersLatch = trailersCount == 0 ? null : new CountDownLatch(trailersCount);
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new DefaultEventLoopGroup());
    sb.channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            serverConnectedChannel = ch;
            ChannelPipeline p = ch.pipeline();
            serverFrameCountDown = new FrameCountDown(serverListener, serverSettingsAckLatch, requestLatch, null, trailersLatch);
            p.addLast(new HttpToHttp2ConnectionHandlerBuilder().server(true).frameListener(serverFrameCountDown).build());
            serverChannelLatch.countDown();
        }
    });
    cb.group(new DefaultEventLoopGroup());
    cb.channel(LocalChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            HttpToHttp2ConnectionHandler handler = new HttpToHttp2ConnectionHandlerBuilder().server(false).frameListener(clientListener).gracefulShutdownTimeoutMillis(0).build();
            p.addLast(handler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof Http2ConnectionPrefaceWrittenEvent) {
                        prefaceWrittenLatch.countDown();
                        ctx.pipeline().remove(this);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new LocalAddress("HttpToHttp2ConnectionHandlerTest")).sync().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    assertTrue(prefaceWrittenLatch.await(5, SECONDS));
    assertTrue(serverChannelLatch.await(WAIT_TIME_SECONDS, SECONDS));
}
Also used : FrameCountDown(io.netty.handler.codec.http2.Http2TestUtil.FrameCountDown) ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)171 Channel (io.netty.channel.Channel)84 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)73 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)73 ChannelFuture (io.netty.channel.ChannelFuture)65 EventLoopGroup (io.netty.channel.EventLoopGroup)64 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)39 SocketChannel (io.netty.channel.socket.SocketChannel)35 ChannelPipeline (io.netty.channel.ChannelPipeline)33 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18