Search in sources :

Example 91 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project crate by crate.

the class Messages method sendShortMsg.

/**
     * Send a message that just contains the msgType and the msg length
     */
private static void sendShortMsg(Channel channel, char msgType, final String traceLogMsg) {
    ChannelBuffer buffer = ChannelBuffers.buffer(5);
    buffer.writeByte(msgType);
    buffer.writeInt(4);
    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                LOGGER.trace(traceLogMsg);
            }
        });
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 92 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project jstorm by alibaba.

the class NettyClient method closeChannel.

/**
     * Avoid channel double close
     *
     * @param channel
     */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return;
        }
        closingChannel.add(channel);
    }
    LOG.debug(channel.toString() + " begin to closed");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener)

Example 93 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project canal by alibaba.

the class ClientAuthenticationHandler method messageReceived.

public void messageReceived(final ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    final Packet packet = Packet.parseFrom(buffer.readBytes(buffer.readableBytes()).array());
    switch(packet.getVersion()) {
        case SUPPORTED_VERSION:
        default:
            final ClientAuth clientAuth = ClientAuth.parseFrom(packet.getBody());
            // 如果存在订阅信息
            if (StringUtils.isNotEmpty(clientAuth.getDestination()) && StringUtils.isNotEmpty(clientAuth.getClientId())) {
                ClientIdentity clientIdentity = new ClientIdentity(clientAuth.getDestination(), Short.valueOf(clientAuth.getClientId()), clientAuth.getFilter());
                try {
                    MDC.put("destination", clientIdentity.getDestination());
                    embeddedServer.subscribe(clientIdentity);
                    // 设置状态数据
                    ctx.setAttachment(clientIdentity);
                    // 尝试启动,如果已经启动,忽略
                    if (!embeddedServer.isStart(clientIdentity.getDestination())) {
                        ServerRunningMonitor runningMonitor = ServerRunningMonitors.getRunningMonitor(clientIdentity.getDestination());
                        if (!runningMonitor.isStart()) {
                            runningMonitor.start();
                        }
                    }
                } finally {
                    MDC.remove("destination");
                }
            }
            NettyUtils.ack(ctx.getChannel(), new ChannelFutureListener() {

                public void operationComplete(ChannelFuture future) throws Exception {
                    logger.info("remove unused channel handlers after authentication is done successfully.");
                    ctx.getPipeline().remove(HandshakeInitializationHandler.class.getName());
                    ctx.getPipeline().remove(ClientAuthenticationHandler.class.getName());
                    int readTimeout = defaultSubscriptorDisconnectIdleTimeout;
                    int writeTimeout = defaultSubscriptorDisconnectIdleTimeout;
                    if (clientAuth.getNetReadTimeout() > 0) {
                        readTimeout = clientAuth.getNetReadTimeout();
                    }
                    if (clientAuth.getNetWriteTimeout() > 0) {
                        writeTimeout = clientAuth.getNetWriteTimeout();
                    }
                    IdleStateHandler idleStateHandler = new IdleStateHandler(NettyUtils.hashedWheelTimer, readTimeout, writeTimeout, 0);
                    ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateHandler.class.getName(), idleStateHandler);
                    IdleStateAwareChannelHandler idleStateAwareChannelHandler = new IdleStateAwareChannelHandler() {

                        public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
                            logger.warn("channel:{} idle timeout exceeds, close channel to save server resources...", ctx.getChannel());
                            ctx.getChannel().close();
                        }
                    };
                    ctx.getPipeline().addBefore(SessionHandler.class.getName(), IdleStateAwareChannelHandler.class.getName(), idleStateAwareChannelHandler);
                }
            });
            break;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) IdleStateEvent(org.jboss.netty.handler.timeout.IdleStateEvent) Packet(com.alibaba.otter.canal.protocol.CanalPacket.Packet) ClientIdentity(com.alibaba.otter.canal.protocol.ClientIdentity) IdleStateHandler(org.jboss.netty.handler.timeout.IdleStateHandler) ChannelHandlerContext(org.jboss.netty.channel.ChannelHandlerContext) ServerRunningMonitor(com.alibaba.otter.canal.common.zookeeper.running.ServerRunningMonitor) ClientAuth(com.alibaba.otter.canal.protocol.CanalPacket.ClientAuth) IdleStateAwareChannelHandler(org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 94 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project neo4j by neo4j.

the class Client method start.

@Override
public void start() {
    bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(newCachedThreadPool(daemon(getClass().getSimpleName() + "-boss@" + destination)), newCachedThreadPool(daemon(getClass().getSimpleName() + "-worker@" + destination))));
    bootstrap.setPipelineFactory(this);
    channelPool = new ResourcePool<ChannelContext>(maxUnusedChannels, new ResourcePool.CheckStrategy.TimeoutCheckStrategy(DEFAULT_CHECK_INTERVAL, Clocks.systemClock()), new LoggingResourcePoolMonitor(msgLog)) {

        @Override
        protected ChannelContext create() {
            msgLog.info(threadInfo() + "Trying to open a new channel from " + origin + " to " + destination, true);
            // We must specify the origin address in case the server has multiple IPs per interface
            ChannelFuture channelFuture = bootstrap.connect(destination, origin);
            channelFuture.awaitUninterruptibly(5, TimeUnit.SECONDS);
            if (channelFuture.isSuccess()) {
                msgLog.info(threadInfo() + "Opened a new channel from " + channelFuture.getChannel().getLocalAddress() + " to " + channelFuture.getChannel().getRemoteAddress());
                return new ChannelContext(channelFuture.getChannel(), ChannelBuffers.dynamicBuffer(), ByteBuffer.allocate(1024 * 1024));
            }
            Throwable cause = channelFuture.getCause();
            String msg = Client.this.getClass().getSimpleName() + " could not connect from " + origin + " to " + destination;
            msgLog.debug(msg, true);
            throw traceComException(new ComException(msg, cause), "Client.start");
        }

        @Override
        protected boolean isAlive(ChannelContext context) {
            return context.channel().isConnected();
        }

        @Override
        protected void dispose(ChannelContext context) {
            Channel channel = context.channel();
            if (channel.isConnected()) {
                msgLog.info(threadInfo() + "Closing: " + context + ". " + "Channel pool size is now " + currentSize());
                channel.close();
            }
        }

        private String threadInfo() {
            return "Thread[" + Thread.currentThread().getId() + ", " + Thread.currentThread().getName() + "] ";
        }
    };
    /*
         * This is here to couple the channel releasing to Response.close() itself and not
         * to TransactionStream.close() as it is implemented here. The reason is that a Response
         * that is returned without a TransactionStream will still hold the channel and should
         * release it eventually. Also, logically, closing the channel is not dependent on the
         * TransactionStream.
         */
    resourcePoolReleaser = () -> {
        if (channelPool != null) {
            channelPool.release();
        }
    };
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ReadableClosablePositionAwareChannel(org.neo4j.kernel.impl.transaction.log.ReadableClosablePositionAwareChannel) Channel(org.jboss.netty.channel.Channel) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap)

Example 95 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project neo4j by neo4j.

the class NetworkSender method send.

private synchronized void send(final Message message) {
    monitor.queuedMessage(message);
    final URI to = URI.create(message.getHeader(Message.TO));
    ExecutorService senderExecutor = senderExecutors.get(to);
    if (senderExecutor == null) {
        senderExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("Cluster Sender " + to.toASCIIString(), monitor));
        senderExecutors.put(to, senderExecutor);
    }
    senderExecutor.submit(new Runnable() {

        @Override
        public void run() {
            Channel channel = getChannel(to);
            try {
                if (channel == null) {
                    channel = openChannel(to);
                    openedChannel(to, channel);
                    // Instance could be connected to, remove any marker of it being failed
                    failedInstances.remove(to);
                }
            } catch (Exception e) {
                // Only print out failure message on first fail
                if (!failedInstances.contains(to)) {
                    msgLog.warn(e.getMessage());
                    failedInstances.add(to);
                }
                return;
            }
            try {
                // Set FROM header
                message.setHeader(Message.FROM, me.toASCIIString());
                msgLog.debug("Sending to " + to + ": " + message);
                ChannelFuture future = channel.write(message);
                future.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        monitor.sentMessage(message);
                        if (!future.isSuccess()) {
                            msgLog.debug("Unable to write " + message + " to " + future.getChannel(), future.getCause());
                            closedChannel(future.getChannel());
                            // Try again
                            send(message);
                        }
                    }
                });
            } catch (Exception e) {
                if (Exceptions.contains(e, ClosedChannelException.class)) {
                    msgLog.warn("Could not send message, because the connection has been closed.");
                } else {
                    msgLog.warn("Could not send message", e);
                }
                channel.close();
            }
        }
    });
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NamedThreadFactory(org.neo4j.helpers.NamedThreadFactory) ThreadRenamingRunnable(org.jboss.netty.util.ThreadRenamingRunnable) Channel(org.jboss.netty.channel.Channel) ExecutorService(java.util.concurrent.ExecutorService) URI(java.net.URI) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) URISyntaxException(java.net.URISyntaxException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)122 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)36 Channel (org.jboss.netty.channel.Channel)33 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)29 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)26 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)25 InetSocketAddress (java.net.InetSocketAddress)22 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)22 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)19 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 Test (org.junit.Test)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)8 Test (org.testng.annotations.Test)8 ConnectException (java.net.ConnectException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6