Search in sources :

Example 41 with Channel

use of io.netty.channel.Channel in project alluxio by Alluxio.

the class NettyUnderFileSystemFileWriter method write.

@Override
public void write(InetSocketAddress address, long ufsFileId, long fileOffset, byte[] source, int offset, int length) throws IOException {
    Channel channel = null;
    ClientHandler clientHandler = null;
    Metrics.NETTY_UFS_WRITE_OPS.inc();
    try {
        channel = mContext.acquireNettyChannel(address);
        if (!(channel.pipeline().last() instanceof ClientHandler)) {
            channel.pipeline().addLast(new ClientHandler());
        }
        clientHandler = (ClientHandler) channel.pipeline().last();
        SingleResponseListener listener = new SingleResponseListener();
        clientHandler.addListener(listener);
        ChannelFuture channelFuture = channel.writeAndFlush(new RPCFileWriteRequest(ufsFileId, fileOffset, length, new DataByteArrayChannel(source, offset, length))).sync();
        if (channelFuture.isDone() && !channelFuture.isSuccess()) {
            LOG.error("Failed to read ufs file from %s for ufsFilId %d with error %s.", address.toString(), ufsFileId, channelFuture.cause());
            throw new IOException(channelFuture.cause());
        }
        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        switch(response.getType()) {
            case RPC_FILE_WRITE_RESPONSE:
                RPCFileWriteResponse resp = (RPCFileWriteResponse) response;
                RPCResponse.Status status = resp.getStatus();
                LOG.debug("status: {} from remote machine {} received", status, address);
                if (status != RPCResponse.Status.SUCCESS) {
                    throw new IOException(ExceptionMessage.UNDER_FILE_WRITE_ERROR.getMessage(ufsFileId, address, status.getMessage()));
                }
                break;
            case RPC_ERROR_RESPONSE:
                RPCErrorResponse error = (RPCErrorResponse) response;
                throw new IOException(error.getStatus().getMessage());
            default:
                throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(), RPCMessage.Type.RPC_FILE_WRITE_RESPONSE));
        }
    } catch (Exception e) {
        Metrics.NETTY_UFS_WRITE_FAILURES.inc();
        try {
            if (channel != null) {
                channel.close().sync();
            }
        } catch (InterruptedException ee) {
            Throwables.propagate(ee);
        }
        throw new IOException(e);
    } finally {
        if (clientHandler != null) {
            clientHandler.removeListeners();
        }
        if (channel != null) {
            mContext.releaseNettyChannel(address, channel);
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) DataByteArrayChannel(alluxio.network.protocol.databuffer.DataByteArrayChannel) RPCFileWriteRequest(alluxio.network.protocol.RPCFileWriteRequest) RPCResponse(alluxio.network.protocol.RPCResponse) IOException(java.io.IOException) IOException(java.io.IOException) DataByteArrayChannel(alluxio.network.protocol.databuffer.DataByteArrayChannel) RPCErrorResponse(alluxio.network.protocol.RPCErrorResponse) RPCFileWriteResponse(alluxio.network.protocol.RPCFileWriteResponse)

Example 42 with Channel

use of io.netty.channel.Channel in project jersey by jersey.

the class NettyHttpContainerProvider method createServer.

/**
     * Create and start Netty server.
     *
     * @param baseUri       base uri.
     * @param configuration Jersey configuration.
     * @param sslContext    Netty SSL context (can be null).
     * @param block         when {@code true}, this method will block until the server is stopped. When {@code false}, the
     *                      execution will
     *                      end immediately after the server is started.
     * @return Netty channel instance.
     * @throws ProcessingException when there is an issue with creating new container.
     */
public static Channel createServer(final URI baseUri, final ResourceConfig configuration, SslContext sslContext, final boolean block) throws ProcessingException {
    // Configure the server.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new JerseyServerInitializer(baseUri, sslContext, container));
        int port = getPort(baseUri);
        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
        if (block) {
            ch.closeFuture().sync();
            return ch;
        } else {
            return ch;
        }
    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ProcessingException(javax.ws.rs.ProcessingException) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Future(io.netty.util.concurrent.Future) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ProcessingException(javax.ws.rs.ProcessingException)

Example 43 with Channel

use of io.netty.channel.Channel in project intellij-community by JetBrains.

the class SubServer method bind.

public boolean bind(int port) {
    if (port == server.getPort() || port == -1) {
        return true;
    }
    if (channelRegistrar == null) {
        Disposer.register(server, this);
        channelRegistrar = new ChannelRegistrar();
    }
    ServerBootstrap bootstrap = serverBootstrap(server.getEventLoopGroup());
    Map<String, Object> xmlRpcHandlers = user.createXmlRpcHandlers();
    if (xmlRpcHandlers == null) {
        BuiltInServer.configureChildHandler(bootstrap, channelRegistrar, null);
    } else {
        final XmlRpcDelegatingHttpRequestHandler handler = new XmlRpcDelegatingHttpRequestHandler(xmlRpcHandlers);
        bootstrap.childHandler(new ChannelInitializer() {

            @Override
            protected void initChannel(Channel channel) throws Exception {
                channel.pipeline().addLast(channelRegistrar);
                NettyUtil.addHttpServerCodec(channel.pipeline());
                channel.pipeline().addLast(handler);
            }
        });
    }
    try {
        bootstrap.localAddress(user.isAvailableExternally() ? new InetSocketAddress(port) : NetKt.loopbackSocketAddress(port));
        channelRegistrar.setServerChannel(bootstrap.bind().syncUninterruptibly().channel(), false);
        return true;
    } catch (Exception e) {
        try {
            NettyUtil.log(e, Logger.getInstance(BuiltInServer.class));
        } finally {
            user.cannotBind(e, port);
        }
        return false;
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 44 with Channel

use of io.netty.channel.Channel in project spring-framework by spring-projects.

the class RxNettyHttpHandlerAdapter method handle.

@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> nativeRequest, HttpServerResponse<ByteBuf> nativeResponse) {
    Channel channel = nativeResponse.unsafeNettyChannel();
    NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(channel.alloc());
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    RxNettyServerHttpRequest request = new RxNettyServerHttpRequest(nativeRequest, bufferFactory, remoteAddress);
    RxNettyServerHttpResponse response = new RxNettyServerHttpResponse(nativeResponse, bufferFactory);
    Publisher<Void> result = this.httpHandler.handle(request, response).otherwise(ex -> {
        logger.error("Could not complete request", ex);
        nativeResponse.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        return Mono.empty();
    }).doOnSuccess(aVoid -> logger.debug("Successfully completed request"));
    return RxReactiveStreams.toObservable(result);
}
Also used : HttpServerResponse(io.reactivex.netty.protocol.http.server.HttpServerResponse) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory) Publisher(org.reactivestreams.Publisher) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) Observable(rx.Observable) Channel(io.netty.channel.Channel) RxReactiveStreams(rx.RxReactiveStreams) ByteBuf(io.netty.buffer.ByteBuf) HttpServerRequest(io.reactivex.netty.protocol.http.server.HttpServerRequest) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) RequestHandler(io.reactivex.netty.protocol.http.server.RequestHandler) Assert(org.springframework.util.Assert) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NettyDataBufferFactory(org.springframework.core.io.buffer.NettyDataBufferFactory)

Example 45 with Channel

use of io.netty.channel.Channel in project netty by netty.

the class Http2StreamChannelBootstrap method connect.

/**
     * Used by the {@link Http2MultiplexCodec} to instantiate incoming/remotely-created streams.
     */
ChannelFuture connect(int streamId) {
    validateState();
    ParentChannelAndMultiplexCodec channelAndCodec0 = channelAndCodec;
    Channel parentChannel = channelAndCodec0.parentChannel;
    Http2MultiplexCodec multiplexCodec = channelAndCodec0.multiplexCodec;
    EventLoopGroup group0 = group;
    group0 = group0 == null ? parentChannel.eventLoop() : group0;
    return multiplexCodec.createStreamChannel(parentChannel, group0, handler, options, attributes, streamId);
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) Channel(io.netty.channel.Channel)

Aggregations

Channel (io.netty.channel.Channel)886 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)226 ChannelFuture (io.netty.channel.ChannelFuture)204 Test (org.junit.Test)203 Bootstrap (io.netty.bootstrap.Bootstrap)199 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)191 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)177 InetSocketAddress (java.net.InetSocketAddress)165 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)132 IOException (java.io.IOException)126 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)106 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)96 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)89