Example usage for io.netty.channel ChannelFuture syncUninterruptibly

List of usage examples for io.netty.channel ChannelFuture syncUninterruptibly

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture syncUninterruptibly.

Prototype

@Override
    ChannelFuture syncUninterruptibly();

Source Link

Usage

From source file:org.apache.geode.redis.GeodeRedisServer.java

License:Apache License

/**
 * Shutdown method for {@link GeodeRedisServer}. This closes the {@link Cache}, interrupts all
 * execution and forcefully closes all connections.
 *//*  w ww  . ja  v  a 2  s  .  c o  m*/
public synchronized void shutdown() {
    if (!shutdown) {
        if (logger.infoEnabled())
            logger.info("GeodeRedisServer shutting down");
        ChannelFuture closeFuture = this.serverChannel.closeFuture();
        Future<?> c = workerGroup.shutdownGracefully();
        Future<?> c2 = bossGroup.shutdownGracefully();
        this.serverChannel.close();
        c.syncUninterruptibly();
        c2.syncUninterruptibly();
        this.regionCache.close();
        if (mainThread != null)
            mainThread.interrupt();
        for (ScheduledFuture<?> f : this.expirationFutures.values())
            f.cancel(true);
        this.expirationFutures.clear();
        this.expirationExecutor.shutdownNow();
        closeFuture.syncUninterruptibly();
        shutdown = true;
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.DatanodeHttpServer.java

License:Apache License

public void start() {
    if (httpServer != null) {
        ChannelFuture f = httpServer.bind(DataNode.getInfoAddr(conf));
        f.syncUninterruptibly();
        httpAddress = (InetSocketAddress) f.channel().localAddress();
        LOG.info("Listening HTTP traffic on " + httpAddress);
    }//w  w w .j a va 2s.co m

    if (httpsServer != null) {
        InetSocketAddress secInfoSocAddr = NetUtils.createSocketAddr(
                conf.getTrimmed(DFS_DATANODE_HTTPS_ADDRESS_KEY, DFS_DATANODE_HTTPS_ADDRESS_DEFAULT));
        ChannelFuture f = httpsServer.bind(secInfoSocAddr);
        f.syncUninterruptibly();
        httpsAddress = (InetSocketAddress) f.channel().localAddress();
        LOG.info("Listening HTTPS traffic on " + httpsAddress);
    }
}

From source file:org.apache.reef.wake.remote.transport.netty.NettyMessagingTransport.java

License:Apache License

/**
 * Returns a link for the remote address if cached; otherwise opens, caches and returns
 * When it opens a link for the remote address, only one attempt for the address is made at a given time
 *
 * @param remoteAddr the remote socket address
 * @param encoder    the encoder/* w ww  . j  av  a  2  s.co m*/
 * @param listener   the link listener
 * @return a link associated with the address
 */
@Override
public <T> Link<T> open(final SocketAddress remoteAddr, final Encoder<? super T> encoder,
        final LinkListener<? super T> listener) throws IOException {

    Link<T> link = null;

    for (int i = 0; i < this.numberOfTries; ++i) {
        LinkReference linkRef = this.addrToLinkRefMap.get(remoteAddr);

        if (linkRef != null) {
            link = (Link<T>) linkRef.getLink();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "Link {0} for {1} found", new Object[] { link, remoteAddr });
            }
            if (link != null) {
                return link;
            }
        }

        LOG.log(Level.FINE, "No cached link for {0} thread {1}",
                new Object[] { remoteAddr, Thread.currentThread() });

        // no linkRef
        final LinkReference newLinkRef = new LinkReference();
        final LinkReference prior = this.addrToLinkRefMap.putIfAbsent(remoteAddr, newLinkRef);
        final AtomicInteger flag = prior != null ? prior.getConnectInProgress()
                : newLinkRef.getConnectInProgress();

        synchronized (flag) {
            if (!flag.compareAndSet(0, 1)) {
                while (flag.get() == 1) {
                    try {
                        flag.wait();
                    } catch (final InterruptedException ex) {
                        LOG.log(Level.WARNING, "Wait interrupted", ex);
                    }
                }
            }
        }

        linkRef = this.addrToLinkRefMap.get(remoteAddr);
        link = (Link<T>) linkRef.getLink();

        if (link != null) {
            return link;
        }

        ChannelFuture connectFuture = null;
        try {
            connectFuture = this.clientBootstrap.connect(remoteAddr);
            connectFuture.syncUninterruptibly();

            link = new NettyLink<>(connectFuture.channel(), encoder, listener);
            linkRef.setLink(link);

            synchronized (flag) {
                flag.compareAndSet(1, 2);
                flag.notifyAll();
            }
            break;
        } catch (final Exception e) {
            if (e.getClass().getSimpleName().compareTo("ConnectException") == 0) {
                LOG.log(Level.WARNING, "Connection refused. Retry {0} of {1}",
                        new Object[] { i + 1, this.numberOfTries });
                synchronized (flag) {
                    flag.compareAndSet(1, 0);
                    flag.notifyAll();
                }

                if (i < this.numberOfTries) {
                    try {
                        Thread.sleep(retryTimeout);
                    } catch (final InterruptedException interrupt) {
                        LOG.log(Level.WARNING, "Thread {0} interrupted while sleeping", Thread.currentThread());
                    }
                }
            } else {
                throw e;
            }
        }
    }
    return link;
}

From source file:org.fiware.kiara.transport.http.HttpHandler.java

License:Open Source License

@Override
public ListenableFuture<Void> send(TransportMessage message) {
    if (message == null) {
        throw new NullPointerException("message");
    }//w w w .ja  v  a 2 s. c  o m
    if (state != State.CONNECTED || channel == null) {
        throw new IllegalStateException("state=" + state.toString() + " channel=" + channel);
    }

    HttpMessage httpMsg;

    boolean keepAlive = true;

    if (message instanceof HttpRequestMessage) {
        HttpRequestMessage msg = (HttpRequestMessage) message;

        httpMsg = msg.finalizeRequest();

        if (logger.isDebugEnabled()) {
            logger.debug("SEND CONTENT: {}", HexDump.dumpHexString(msg.getPayload()));
        }
    } else if (message instanceof HttpResponseMessage) {
        HttpResponseMessage msg = (HttpResponseMessage) message;

        httpMsg = msg.finalizeResponse();

        keepAlive = HttpHeaders.isKeepAlive(httpMsg);

        if (logger.isDebugEnabled()) {
            logger.debug("SEND CONTENT: {}", HexDump.dumpHexString(msg.getPayload()));
        }
    } else {
        throw new IllegalArgumentException("msg is neither of type HttpRequestMessage nor HttpResponseMessage");
    }

    final HttpMessage httpMsgArg = httpMsg;
    final boolean keepAliveArg = keepAlive;

    ListenableFuture<Void> f = Global.executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            if (SYNC_REQUEST_RESPONSE) {
                semaphore.acquireUninterruptibly();
                canSend.set(false);
            }
            final ChannelFuture result = channel.writeAndFlush(httpMsgArg);
            if (!keepAliveArg) {
                // If keep-alive is off, close the connection once the content is fully written.
                channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
            result.syncUninterruptibly();
            return null;
        }
    });
    return f;
}

From source file:org.opendaylight.sxp.core.SxpNode.java

License:Open Source License

/**
 * Administratively shutdown.//from w  w  w  .  j a  v  a 2 s .  com
 */
public synchronized SxpNode shutdown() {
    // Wait until server channel ends its own initialization.
    channelInitializationWait("Error while shut down");
    setTimer(TimerType.RetryOpenTimer, 0);
    shutdownConnections();
    for (ThreadsWorker.WorkerType type : ThreadsWorker.WorkerType.values()) {
        getWorker().cancelTasksInSequence(false, type);
    }
    if (serverChannel != null) {
        ChannelFuture channelFuture = serverChannel.close();
        if (channelFuture != null)
            channelFuture.syncUninterruptibly();
        serverChannel = null;
    }
    LOG.info(this + " Server stopped");
    serverChannelInit.set(false);
    return this;
}

From source file:org.redisson.client.RedisClient.java

License:Apache License

public RedisConnection connect() {
    try {//from  w  w  w  .  j  a  v  a 2s . co  m
        ChannelFuture future = bootstrap.connect();
        future.syncUninterruptibly();
        return new RedisConnection(this, future.channel());
    } catch (Exception e) {
        throw new RedisConnectionException("Unable to connect to: " + addr, e);
    }
}

From source file:org.redisson.client.RedisClient.java

License:Apache License

public RedisPubSubConnection connectPubSub() {
    try {/*from   ww w.  j  a va  2s  . co m*/
        ChannelFuture future = bootstrap.connect();
        future.syncUninterruptibly();
        return new RedisPubSubConnection(this, future.channel());
    } catch (Exception e) {
        throw new RedisConnectionException("Unable to connect to: " + addr, e);
    }
}

From source file:org.teiid.transport.SocketListener.java

License:Apache License

public SocketListener(final InetSocketAddress address, final int inputBufferSize, final int outputBufferSize,
        int maxWorkers, final SSLConfiguration config, final ClientServiceRegistryImpl csr,
        final StorageManager storageManager) {

    if (config != null) {
        this.isClientEncryptionEnabled = config.isClientEncryptionEnabled();
    }//  w w w. j a  va 2 s  . com
    this.csr = csr;

    NamedThreadFactory nettyPool = new NamedThreadFactory("NIO"); //$NON-NLS-1$
    if (LogManager.isMessageToBeRecorded(LogConstants.CTX_TRANSPORT, MessageLevel.DETAIL)) {
        LogManager.logDetail(LogConstants.CTX_TRANSPORT,
                "server = " + address.getAddress() + "binding to port:" + address.getPort()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (maxWorkers == 0) {
        maxWorkers = Math.max(4, PropertiesUtils.getIntProperty(System.getProperties(),
                "io.netty.eventLoopThreads", 2 * Runtime.getRuntime().availableProcessors())); //$NON-NLS-1$
    }
    EventLoopGroup workers = new NioEventLoopGroup(maxWorkers, nettyPool);

    bootstrap = new ServerBootstrap();
    bootstrap.group(workers).channel(NioServerSocketChannel.class);
    this.channelHandler = createChannelHandler();
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            configureChannelPipeline(pipeline, config, storageManager);
        }
    });
    if (inputBufferSize != 0) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, new Integer(inputBufferSize));
    }
    if (outputBufferSize != 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, new Integer(outputBufferSize));
    }
    bootstrap.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
    ChannelFuture future = bootstrap.bind(address);
    future.syncUninterruptibly();
    this.serverChannel = future.channel();
}

From source file:org.waarp.openr66.proxy.configuration.Configuration.java

License:Open Source License

@Override
public void r66Startup() {
    logger.debug("Start R66: " + getHOST_SSLID());
    // add into configuration
    this.getConstraintLimitHandler().setServer(true);
    // Global Server
    serverChannelGroup = new DefaultChannelGroup("OpenR66", subTaskGroup.next());
    if (isUseNOSSL()) {
        serverBootstrap = new ServerBootstrap();
        WaarpNettyUtil.setServerBootstrap(serverBootstrap, bossGroup, workerGroup, (int) getTIMEOUTCON());
        networkServerInitializer = new NetworkServerInitializer(true);
        serverBootstrap.childHandler(networkServerInitializer);
        // FIXME take into account multiple address
        List<ChannelFuture> futures = new ArrayList<ChannelFuture>();
        for (ProxyEntry entry : ProxyEntry.proxyEntries.values()) {
            if (!entry.isLocalSsl()) {
                logger.debug("Future Activation: " + entry.getLocalSocketAddress());
                futures.add(serverBootstrap.bind(entry.getLocalSocketAddress()));
            }//  ww  w .  ja  va2 s.c  o  m
        }
        for (ChannelFuture future : futures) {
            future.syncUninterruptibly();
            if (future.isSuccess()) {
                bindNoSSL = future.channel();
                serverChannelGroup.add(bindNoSSL);
                logger.debug("Activation: " + bindNoSSL.localAddress());
            } else {
                logger.warn(Messages.getString("Configuration.NOSSLDeactivated") + " for " //$NON-NLS-2$
                        + bindNoSSL.localAddress());
            }
        }
    } else {
        networkServerInitializer = null;
        logger.warn(Messages.getString("Configuration.NOSSLDeactivated")); //$NON-NLS-1$
    }

    if (isUseSSL() && getHOST_SSLID() != null) {
        serverSslBootstrap = new ServerBootstrap();
        WaarpNettyUtil.setServerBootstrap(serverSslBootstrap, bossGroup, workerGroup, (int) getTIMEOUTCON());
        networkSslServerInitializer = new NetworkSslServerInitializer(false);
        serverSslBootstrap.childHandler(networkSslServerInitializer);
        // FIXME take into account multiple address
        List<ChannelFuture> futures = new ArrayList<ChannelFuture>();
        for (ProxyEntry entry : ProxyEntry.proxyEntries.values()) {
            if (entry.isLocalSsl()) {
                logger.debug("Future SslActivation: " + entry.getLocalSocketAddress());
                futures.add(serverSslBootstrap.bind(entry.getLocalSocketAddress()));
            }
        }
        for (ChannelFuture future : futures) {
            future.syncUninterruptibly();
            if (future.isSuccess()) {
                bindSSL = future.channel();
                serverChannelGroup.add(bindSSL);
                logger.debug("SslActivation: " + bindSSL.localAddress());
            } else {
                logger.warn(Messages.getString("Configuration.SSLMODEDeactivated") + " for " //$NON-NLS-2$
                        + bindSSL.localAddress());
            }
        }
    } else {
        networkSslServerInitializer = null;
        logger.warn(Messages.getString("Configuration.SSLMODEDeactivated")); //$NON-NLS-1$
    }

    // Factory for TrafficShapingHandler
    globalTrafficShapingHandler = new GlobalTrafficHandler(subTaskGroup, getServerGlobalWriteLimit(),
            getServerGlobalReadLimit(), getServerChannelWriteLimit(), getServerChannelReadLimit(),
            getDelayLimit());
    this.getConstraintLimitHandler().setHandler(globalTrafficShapingHandler);
    ProxyBridge.initialize();
    setThriftService(null);
}

From source file:se.sics.kompics.network.netty.ChannelManager.java

License:Open Source License

void clearConnections() {
    // clear these early to try avoid sending messages on them while closing
    tcpActiveChannels.clear();/*from w  w  w.j  a  va 2  s  . c om*/
    udtActiveChannels.clear();

    List<ChannelFuture> futures = new LinkedList<ChannelFuture>();

    synchronized (this) {
        component.extLog.info("Closing all connections...");
        for (ChannelFuture f : udtIncompleteChannels.values()) {
            try {
                f.cancel(false);
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }
        for (ChannelFuture f : tcpIncompleteChannels.values()) {
            try {
                f.cancel(false);
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        for (SocketChannel c : tcpChannelsByRemote.values()) {
            try {
                futures.add(c.close());
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        tcpActiveChannels.clear(); // clear them again just to be sure
        tcpChannels.clear();
        tcpChannelsByRemote.clear();

        for (UdtChannel c : udtChannelsByRemote.values()) {
            try {
                futures.add(c.close());
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        udtActiveChannels.clear();
        udtChannels.clear();
        udtChannelsByRemote.clear();

        udtBoundPorts.clear();

        udtIncompleteChannels.clear();
        tcpIncompleteChannels.clear();
    }
    for (ChannelFuture cf : futures) {
        try {
            cf.syncUninterruptibly();
        } catch (Exception ex) {
            component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
        }
    }
}