Example usage for io.netty.channel Channel isOpen

List of usage examples for io.netty.channel Channel isOpen

Introduction

In this page you can find the example usage for io.netty.channel Channel isOpen.

Prototype

boolean isOpen();

Source Link

Document

Returns true if the Channel is open and may get active later

Usage

From source file:alluxio.client.fs.NettyChannelCloseIntegrationTest.java

License:Apache License

@Test
public void closeAsync() throws Exception {
    for (int i = 0; i < 1000; i++) {
        Channel channel = FileSystemContext.get().acquireNettyChannel(mWorkerNetAddress);
        Assert.assertTrue(channel.isOpen());
        // Note: If you replace closeChannel with channel.close(), this test fails with high
        // probability.
        CommonUtils.closeChannel(channel);
        Assert.assertTrue(!channel.isOpen());
        FileSystemContext.get().releaseNettyChannel(mWorkerNetAddress, channel);
    }//ww  w . j  ava2  s  .  c o  m
}

From source file:alluxio.client.fs.NettyChannelCloseIntegrationTest.java

License:Apache License

@Test
public void closeSync() throws Exception {
    for (int i = 0; i < 1000; i++) {
        Channel channel = FileSystemContext.get().acquireNettyChannel(mWorkerNetAddress);
        Assert.assertTrue(channel.isOpen());
        // Note: If you replace closeChannel with channel.close(), this test fails with high
        // probability.
        CommonUtils.closeChannelSync(channel);
        Assert.assertTrue(!channel.isOpen());
        FileSystemContext.get().releaseNettyChannel(mWorkerNetAddress, channel);
    }/* w  w w  .  j a va  2 s.co m*/
}

From source file:alluxio.client.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context/* w w  w.ja v  a2  s  . c  o m*/
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request));
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        throw new IOException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponse(message.asResponse());
    }
    return message;
}

From source file:alluxio.client.NettyChannelCloseIntegrationTest.java

License:Apache License

@Test
public void closeAsync() throws Exception {
    for (int i = 0; i < 1000; i++) {
        Channel channel = FileSystemContext.INSTANCE.acquireNettyChannel(mWorkerNetAddress);
        Assert.assertTrue(channel.isOpen());
        // Note: If you replace closeChannel with channel.close(), this test fails with high
        // probability.
        CommonUtils.closeChannel(channel);
        Assert.assertTrue(!channel.isOpen());
        FileSystemContext.INSTANCE.releaseNettyChannel(mWorkerNetAddress, channel);
    }//from  w w w  .  java 2s. c o  m
}

From source file:alluxio.client.NettyChannelCloseIntegrationTest.java

License:Apache License

@Test
public void closeSync() throws Exception {
    for (int i = 0; i < 1000; i++) {
        Channel channel = FileSystemContext.INSTANCE.acquireNettyChannel(mWorkerNetAddress);
        Assert.assertTrue(channel.isOpen());
        // Note: If you replace closeChannel with channel.close(), this test fails with high
        // probability.
        CommonUtils.closeChannelSync(channel);
        Assert.assertTrue(!channel.isOpen());
        FileSystemContext.INSTANCE.releaseNettyChannel(mWorkerNetAddress, channel);
    }//from  ww  w .j ava2 s.  c om
}

From source file:alluxio.network.netty.NettyChannelPool.java

License:Apache License

/**
 * Checks whether a channel is healthy.//from   ww w .  ja v  a 2  s . co  m
 *
 * @param channel the channel to check
 * @return true if the channel is active (i.e. connected)
 */
@Override
protected boolean isHealthy(Channel channel) {
    if (POOL_DISABLED) {
        // If we always return false here, channels acquired by NettyChannelPool#acquire() will always
        // be newly created channels. With this feature turned on, >= 1.3.0 client will be backward
        // compatible with <= 1.2.0 server.
        return false;
    }
    return channel.isOpen() && channel.isActive();
}

From source file:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context/*w ww.j a  v a2s . c o m*/
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    final Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
            promise.tryFailure(future.cause());
        }
    });
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        CommonUtils.closeChannel(channel);
        throw new IOException(e);
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponseFrom(message.asResponse(), context.getChannel());
    }
    return message;
}

From source file:c5db.client.C5NettyConnectionManager.java

License:Apache License

@Override
public Channel getOrCreateChannel(String host, int port)
        throws InterruptedException, ExecutionException, TimeoutException {
    final String hash = getHostPortHash(host, port);
    if (!regionChannelMap.containsKey(hash)) {
        final Channel channel = connect(host, port);
        regionChannelMap.put(hash, channel);
        Log.warn("Channel" + channel);
        return channel;
    }//ww w  .  j  a v a  2  s  .  c  om

    Channel channel = regionChannelMap.get(hash);

    // Clear stale channels
    if (!(channel.isOpen() && channel.isActive() && isHandShakeConnected(channel))) {
        closeChannel(host, port);
        channel.disconnect();
        channel = getOrCreateChannel(host, port);
    }

    return channel;
}

From source file:c5db.replication.ReplicatorService.java

License:Apache License

@FiberOnly
private void handleWireRequestMessage(final Channel channel, final ReplicationWireMessage msg) {
    RpcWireRequest wireRequest = new RpcWireRequest(msg);
    String quorumId = wireRequest.quorumId;

    ReplicatorInstance replInst = replicatorInstances.get(quorumId);
    if (replInst == null) {
        LOG.trace("Instance not found {} for message id {} from {} (normal during region bootstrap)", quorumId,
                msg.getMessageId(), msg.getSenderId());
        // TODO send RPC failure to the sender?
        return;//www . j  a  va2  s .c om
    }

    AsyncRequest.withOneReply(fiber, replInst.getIncomingChannel(), wireRequest, reply -> {
        if (!channel.isOpen()) {
            // TODO cant signal comms failure, so just drop on the floor. Is there a better thing to do?
            return;
        }

        ReplicationWireMessage b = reply.getWireMessage(msg.getMessageId(), nodeId, msg.getSenderId(), true);

        channel.writeAndFlush(b).addListener(future -> {
            if (!future.isSuccess()) {
                LOG.warn("node {} error sending reply {} to node {} in response to request {}: {}", nodeId,
                        reply, wireRequest.from, wireRequest, future.cause());
            }
        });
    });
}

From source file:c5db.replication.ReplicatorService.java

License:Apache License

@FiberOnly
private void handleOutgoingMessage(final Request<RpcRequest, RpcWireReply> message) {
    final RpcRequest request = message.getRequest();
    final long to = request.to;

    if (to == nodeId) {
        handleLoopBackMessage(message);/*  ww  w  . j a v a  2 s . c om*/
        return;
    }

    // check to see if we have a connection:
    Channel channel = connections.get(to);
    if (channel != null && channel.isOpen()) {
        sendMessageAsync(message, channel);
        return;
    } else if (channel != null) {
        // stale?
        LOG.debug("Removing stale !isOpen channel from connections.get() for peer {}", to);
        connections.remove(to);
    }

    NodeInfoRequest nodeInfoRequest = new NodeInfoRequest(to, ModuleType.Replication);
    LOG.debug("node {} sending node info request {} ", nodeId, nodeInfoRequest);
    AsyncRequest.withOneReply(fiber, discoveryModule.getNodeInfo(), nodeInfoRequest,
            new Callback<NodeInfoReply>() {
                @SuppressWarnings("RedundantCast")
                @FiberOnly
                @Override
                public void onMessage(NodeInfoReply nodeInfoReply) {
                    if (!nodeInfoReply.found) {
                        LOG.debug("Can't find the info for the peer {}", to);
                        // TODO signal TCP/transport layer failure in a better way
                        //message.reply(null);
                        return;
                    }

                    LOG.debug("node {} got node info for node {} reply {} ", nodeId, to, nodeInfoReply);
                    // what if existing outgoing connection attempt?
                    Channel channel = connections.get(to);
                    if (channel != null && channel.isOpen()) {
                        sendMessageAsync(message, channel);
                        return;
                    } else if (channel != null) {
                        LOG.debug("Removing stale2 !isOpen channel from connections.get() for peer {}", to);
                        connections.remove(to);
                    }

                    // ok so we connect now:
                    ChannelFuture channelFuture = outgoingBootstrap.connect(nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);
                    LOG.trace("Connecting to peer {} at address {} port {}", to, nodeInfoReply.addresses.get(0),
                            nodeInfoReply.port);

                    // the channel might not be open, so defer the write.
                    connections.put(to, channelFuture.channel());
                    channelFuture.channel().closeFuture()
                            .addListener((ChannelFutureListener) future -> fiber.execute(() -> {
                                // remove only THIS channel. It might have been removed prior so.
                                connections.remove(to, future.channel());
                            }));

                    // funny hack, if the channel future is already open, we execute immediately!
                    channelFuture.addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) {
                            sendMessageAsync(message, future.channel());
                        }
                    });
                }
            },
            // If the NodeInfoRequest times out:
            ReplicatorConstants.REPLICATOR_NODE_INFO_REQUEST_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS,
            () -> LOG.warn("node info request timeout {} ", nodeInfoRequest));
}