Search in sources :

Example 26 with ClosedSelectorException

use of java.nio.channels.ClosedSelectorException in project voldemort by voldemort.

the class NioSelectorManager method processEvents.

@Override
protected void processEvents() {
    try {
        // update stats
        stats.updateSelectStats(selectCount, selectTimeMs, processingTimeMs);
        SocketChannel socketChannel = null;
        while ((socketChannel = socketChannelQueue.poll()) != null) {
            if (isClosed.get()) {
                if (logger.isInfoEnabled())
                    logger.debug("Closed, exiting for " + endpoint);
                break;
            }
            try {
                if (logger.isDebugEnabled())
                    logger.debug("Registering connection from " + socketChannel.socket().getPort());
                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.socket().setReuseAddress(true);
                socketChannel.socket().setKeepAlive(socketKeepAlive);
                socketChannel.socket().setSendBufferSize(socketBufferSize);
                if (socketChannel.socket().getReceiveBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket receive buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getReceiveBufferSize() + " bytes.");
                if (socketChannel.socket().getSendBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket send buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getSendBufferSize() + " bytes.");
                socketChannel.configureBlocking(false);
                AsyncRequestHandler attachment = new AsyncRequestHandler(selector, socketChannel, requestHandlerFactory, socketBufferSize, stats);
                if (!isClosed.get()) {
                    socketChannel.register(selector, SelectionKey.OP_READ, attachment);
                    stats.addConnection();
                }
            } catch (ClosedSelectorException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Selector is closed, exiting");
                close();
                break;
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(e.getMessage(), e);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 27 with ClosedSelectorException

use of java.nio.channels.ClosedSelectorException in project voldemort by voldemort.

the class AbstractSelectorManager method run.

public void run() {
    threadName = Thread.currentThread().getName();
    try {
        while (true) {
            if (isClosed.get()) {
                logger.debug("SelectorManager is closed, exiting");
                break;
            }
            lastHeartBeatTimeMs = System.currentTimeMillis();
            processEvents();
            try {
                selectTimeMs = System.currentTimeMillis();
                int selected = selector.select(SELECTOR_POLL_MS);
                selectTimeMs = System.currentTimeMillis() - selectTimeMs;
                selectCount = selected;
                if (isClosed.get()) {
                    logger.debug("SelectorManager is closed, exiting");
                    break;
                }
                if (selected > 0) {
                    processingTimeMs = System.currentTimeMillis();
                    Iterator<SelectionKey> i = selector.selectedKeys().iterator();
                    while (i.hasNext()) {
                        SelectionKey selectionKey = i.next();
                        i.remove();
                        if (selectionKey.isValid() && (selectionKey.isConnectable() || selectionKey.isReadable() || selectionKey.isWritable())) {
                            Runnable worker = (Runnable) selectionKey.attachment();
                            worker.run();
                        }
                    }
                    processingTimeMs = System.currentTimeMillis() - processingTimeMs;
                }
            } catch (ClosedSelectorException e) {
                logger.debug("SelectorManager is closed, exiting");
                break;
            } catch (Throwable t) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(t.getMessage(), t);
            }
        }
    } catch (Throwable t) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(t.getMessage(), t);
    } finally {
        try {
            close();
        } catch (Exception e) {
            if (logger.isEnabledFor(Level.ERROR))
                logger.error(e.getMessage(), e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) VoldemortException(voldemort.VoldemortException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 28 with ClosedSelectorException

use of java.nio.channels.ClosedSelectorException in project zm-mailbox by Zimbra.

the class Server method run.

@Override
public void run() {
    while (!shutdown) {
        SelectionKey key = null;
        try {
            selector.select();
            for (Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); iter.hasNext(); ) {
                key = iter.next();
                iter.remove();
                if (key.isValid()) {
                    if (key.isAcceptable()) {
                        SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
                        if (channel != null) {
                            log.debug("server:accepting port %d", channel.socket().getPort());
                            // non blocking socket
                            channel.configureBlocking(false);
                            // socket close to be synchronous
                            channel.socket().setSoLinger(true, 0);
                            // Nagling disabled on high performance server
                            channel.socket().setTcpNoDelay(true);
                            SelectionKey newKey = channel.register(selector, SelectionKey.OP_READ);
                            ByteBuffer buf = ByteBuffer.allocate(Packet.maxMessageSize);
                            buf.clear();
                            newKey.attach(buf);
                        }
                    } else if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        log.debug("buffer remaining %d", buffer.remaining());
                        int bytesRead = channel.read(buffer);
                        log.debug("server:reading %d bytes from %d", bytesRead, channel.socket().getPort());
                        if (bytesRead == -1) {
                            log.debug("server:EOF 0");
                            throw IOChannelException.ChannelClosed(channel.toString());
                        } else {
                            int pos = buffer.position();
                            while (pos >= 20) {
                                int magic = buffer.getInt(0);
                                long headerLen = buffer.getLong(4);
                                long bodyLen = buffer.getLong(12);
                                if (magic != Packet.magic) {
                                    log.debug("server: magic mismatch %d, ignoring the data", magic);
                                    buffer.clear();
                                    break;
                                }
                                long packetLen = headerLen + bodyLen + 20;
                                log.debug("server:pos=%d packetLen=%d", pos, packetLen);
                                if (pos >= packetLen) {
                                    buffer.position((int) packetLen);
                                    ByteBuffer newBuffer = buffer.slice();
                                    newBuffer.position((int) (pos - packetLen));
                                    // attach the new buffer
                                    key.attach(newBuffer);
                                    // process current packet
                                    buffer.flip();
                                    buffer.position((int) packetLen);
                                    checkBuffer(buffer);
                                    buffer = newBuffer;
                                    pos = buffer.position();
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (buffer.limit() == buffer.position()) {
                                // increase the buffer size
                                ByteBuffer buf = ByteBuffer.allocate(Math.max(2 * buffer.limit(), Packet.maxMessageSize));
                                key.attach(buf);
                                if (buffer.position() > 0) {
                                    byte[] data = new byte[buffer.position()];
                                    buffer.flip();
                                    buffer.get(data);
                                    buf.put(data);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOChannelException e) {
            log.warn("exception while retrieving the message", e);
            switch(e.getCode()) {
                case ChannelClosed:
                    try {
                        key.channel().close();
                    } catch (IOException ignore) {
                    }
                    key.cancel();
                    break;
            }
            ByteBuffer buffer = (ByteBuffer) key.attachment();
            if (buffer != null) {
                buffer.clear();
            }
        } catch (ClosedSelectorException ignore) {
        // ignore since we are shutting down
        } catch (Throwable e) {
            log.warn("exception while retrieving the message", e);
            if (e instanceof OutOfMemoryError) {
                break;
            }
        }
    }
    log.info("server:shutting down");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 29 with ClosedSelectorException

use of java.nio.channels.ClosedSelectorException in project cloudstack by apache.

the class NioConnection method call.

@Override
public Boolean call() throws NioConnectionException {
    while (_isRunning) {
        try {
            _selector.select(50);
            // Someone is ready for I/O, get the ready keys
            final Set<SelectionKey> readyKeys = _selector.selectedKeys();
            final Iterator<SelectionKey> i = readyKeys.iterator();
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Keys Processing: " + readyKeys.size());
            }
            // Walk through the ready keys collection.
            while (i.hasNext()) {
                final SelectionKey sk = i.next();
                i.remove();
                if (!sk.isValid()) {
                    if (s_logger.isTraceEnabled()) {
                        s_logger.trace("Selection Key is invalid: " + sk.toString());
                    }
                    final Link link = (Link) sk.attachment();
                    if (link != null) {
                        link.terminated();
                    } else {
                        closeConnection(sk);
                    }
                } else if (sk.isReadable()) {
                    read(sk);
                } else if (sk.isWritable()) {
                    write(sk);
                } else if (sk.isAcceptable()) {
                    accept(sk);
                } else if (sk.isConnectable()) {
                    connect(sk);
                }
            }
            s_logger.trace("Keys Done Processing.");
            processTodos();
        } catch (final ClosedSelectorException e) {
        /*
                 * Exception occurred when calling java.nio.channels.Selector.selectedKeys() method. It means the connection has not yet been established. Let's continue trying
                 * We do not log it here otherwise we will fill the disk with messages.
                 */
        } catch (final IOException e) {
            s_logger.error("Agent will die due to this IOException!", e);
            throw new NioConnectionException(e.getMessage(), e);
        }
    }
    _isStartup = false;
    return true;
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) NioConnectionException(com.cloud.utils.exception.NioConnectionException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 30 with ClosedSelectorException

use of java.nio.channels.ClosedSelectorException in project tomcat by apache.

the class NioReceiver method closeSelector.

private void closeSelector() throws IOException {
    Selector selector = this.selector.getAndSet(null);
    if (selector == null) {
        return;
    }
    try {
        // look at each key in the selected set
        for (SelectionKey key : selector.keys()) {
            key.channel().close();
            key.attach(null);
            key.cancel();
        }
    } catch (IOException ignore) {
        if (log.isWarnEnabled()) {
            log.warn(sm.getString("nioReceiver.cleanup.fail"), ignore);
        }
    } catch (ClosedSelectorException ignore) {
    // Ignore
    }
    try {
        selector.selectNow();
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
    // Ignore everything else
    }
    selector.close();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) Selector(java.nio.channels.Selector) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Aggregations

ClosedSelectorException (java.nio.channels.ClosedSelectorException)30 SelectionKey (java.nio.channels.SelectionKey)20 IOException (java.io.IOException)16 ServerSocketChannel (java.nio.channels.ServerSocketChannel)8 SocketChannel (java.nio.channels.SocketChannel)8 CancelledKeyException (java.nio.channels.CancelledKeyException)6 ClosedChannelException (java.nio.channels.ClosedChannelException)5 Selector (java.nio.channels.Selector)4 NioConnectionException (com.cloud.utils.exception.NioConnectionException)2 Iterator (java.util.Iterator)2 EOFException (java.io.EOFException)1 InterruptedIOException (java.io.InterruptedIOException)1 ServerSocket (java.net.ServerSocket)1 Socket (java.net.Socket)1 ByteBuffer (java.nio.ByteBuffer)1 ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)1 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)1 SelectableChannel (java.nio.channels.SelectableChannel)1 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)1 HashMap (java.util.HashMap)1