Search in sources :

Example 6 with CancelledKeyException

use of java.nio.channels.CancelledKeyException in project hazelcast by hazelcast.

the class NonBlockingIOThread method rebuildSelector.

// this method is always invoked in this thread
// after we have blocked for selector.select in #runSelectLoopWithSelectorFix
private void rebuildSelector() {
    selectorRebuildCount.inc();
    Selector newSelector = newSelector(logger);
    Selector oldSelector = this.selector;
    // reset each handler's selectionKey, cancel the old keys
    for (SelectionKey key : oldSelector.keys()) {
        AbstractHandler handler = (AbstractHandler) key.attachment();
        SelectableChannel channel = key.channel();
        try {
            int ops = key.interestOps();
            SelectionKey newSelectionKey = channel.register(newSelector, ops, handler);
            handler.setSelectionKey(newSelectionKey);
        } catch (ClosedChannelException e) {
            logger.info("Channel was closed while trying to register with new selector.");
        } catch (CancelledKeyException e) {
            // a CancelledKeyException may be thrown in key.interestOps
            // in this case, since the key is already cancelled, just do nothing
            EmptyStatement.ignore(e);
        }
        key.cancel();
    }
    // close the old selector and substitute with new one
    closeSelector();
    this.selector = newSelector;
    logger.warning("Recreated Selector because of possible java/network stack bug.");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ClosedChannelException(java.nio.channels.ClosedChannelException) SelectableChannel(java.nio.channels.SelectableChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) Selector(java.nio.channels.Selector)

Example 7 with CancelledKeyException

use of java.nio.channels.CancelledKeyException in project voltdb by VoltDB.

the class NIOServerCnxn method doIO.

void doIO(SelectionKey k) throws InterruptedException {
    try {
        if (sock == null) {
            LOG.warn("trying to do i/o on a null socket for session:0x" + Long.toHexString(sessionId));
            return;
        }
        if (k.isReadable()) {
            int rc = sock.read(incomingBuffer);
            if (rc < 0) {
                throw new EndOfStreamException("Unable to read additional data from client sessionid 0x" + Long.toHexString(sessionId) + ", likely client has closed socket");
            }
            if (incomingBuffer.remaining() == 0) {
                boolean isPayload;
                if (incomingBuffer == lenBuffer) {
                    // start of next request
                    incomingBuffer.flip();
                    isPayload = readLength(k);
                    incomingBuffer.clear();
                } else {
                    // continuation
                    isPayload = true;
                }
                if (isPayload) {
                    // not the case for 4letterword
                    readPayload();
                } else {
                    // need not do anything else
                    return;
                }
            }
        }
        if (k.isWritable()) {
            // outgoingBuffers.size());
            if (outgoingBuffers.size() > 0) {
                // ZooLog.logTraceMessage(LOG,
                // ZooLog.CLIENT_DATA_PACKET_TRACE_MASK,
                // "sk " + k + " is valid: " +
                // k.isValid());
                /*
                     * This is going to reset the buffer position to 0 and the
                     * limit to the size of the buffer, so that we can fill it
                     * with data from the non-direct buffers that we need to
                     * send.
                     */
                ByteBuffer directBuffer = factory.directBuffer;
                directBuffer.clear();
                for (ByteBuffer b : outgoingBuffers) {
                    if (directBuffer.remaining() < b.remaining()) {
                        /*
                             * When we call put later, if the directBuffer is to
                             * small to hold everything, nothing will be copied,
                             * so we've got to slice the buffer if it's too big.
                             */
                        b = (ByteBuffer) b.slice().limit(directBuffer.remaining());
                    }
                    /*
                         * put() is going to modify the positions of both
                         * buffers, put we don't want to change the position of
                         * the source buffers (we'll do that after the send, if
                         * needed), so we save and reset the position after the
                         * copy
                         */
                    int p = b.position();
                    directBuffer.put(b);
                    b.position(p);
                    if (directBuffer.remaining() == 0) {
                        break;
                    }
                }
                /*
                     * Do the flip: limit becomes position, position gets set to
                     * 0. This sets us up for the write.
                     */
                directBuffer.flip();
                int sent = sock.write(directBuffer);
                ByteBuffer bb;
                // Remove the buffers that we have sent
                while (outgoingBuffers.size() > 0) {
                    bb = outgoingBuffers.peek();
                    if (bb == closeConn) {
                        throw new CloseRequestException("close requested");
                    }
                    int left = bb.remaining() - sent;
                    if (left > 0) {
                        /*
                             * We only partially sent this buffer, so we update
                             * the position and exit the loop.
                             */
                        bb.position(bb.position() + sent);
                        break;
                    }
                    packetSent();
                    /* We've sent the whole buffer, so drop the buffer */
                    sent -= bb.remaining();
                    outgoingBuffers.remove();
                }
            // ZooLog.logTraceMessage(LOG,
            // ZooLog.CLIENT_DATA_PACKET_TRACE_MASK, "after send,
            // outgoingBuffers.size() = " + outgoingBuffers.size());
            }
            synchronized (this.factory) {
                if (outgoingBuffers.size() == 0) {
                    if (!initialized && (sk.interestOps() & SelectionKey.OP_READ) == 0) {
                        throw new CloseRequestException("responded to info probe");
                    }
                    sk.interestOps(sk.interestOps() & (~SelectionKey.OP_WRITE));
                } else {
                    sk.interestOps(sk.interestOps() | SelectionKey.OP_WRITE);
                }
            }
        }
    } catch (CancelledKeyException e) {
        LOG.warn("Exception causing close of session 0x" + Long.toHexString(sessionId) + " due to " + e);
        if (LOG.isDebugEnabled()) {
            LOG.debug("CancelledKeyException stack trace", e);
        }
        close();
    } catch (CloseRequestException e) {
        // expecting close to log session closure
        close();
    } catch (EndOfStreamException e) {
        // tell user why
        LOG.warn(e);
        // expecting close to log session closure
        close();
    } catch (IOException e) {
        LOG.warn("Exception causing close of session 0x" + Long.toHexString(sessionId) + " due to " + e);
        if (LOG.isDebugEnabled()) {
            LOG.debug("IOException stack trace", e);
        }
        close();
    }
}
Also used : CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 8 with CancelledKeyException

use of java.nio.channels.CancelledKeyException in project CloudStack-archive by CloudStack-extras.

the class NioConnection method processTodos.

protected void processTodos() {
    List<ChangeRequest> todos;
    if (_todos.size() == 0) {
        // Nothing to do.
        return;
    }
    synchronized (this) {
        todos = _todos;
        _todos = new ArrayList<ChangeRequest>();
    }
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Todos Processing: " + todos.size());
    }
    SelectionKey key;
    for (ChangeRequest todo : todos) {
        switch(todo.type) {
            case ChangeRequest.CHANGEOPS:
                try {
                    key = (SelectionKey) todo.key;
                    if (key != null && key.isValid()) {
                        if (todo.att != null) {
                            key.attach(todo.att);
                            Link link = (Link) todo.att;
                            link.setKey(key);
                        }
                        key.interestOps(todo.ops);
                    }
                } catch (CancelledKeyException e) {
                    s_logger.debug("key has been cancelled");
                }
                break;
            case ChangeRequest.REGISTER:
                try {
                    key = ((SocketChannel) (todo.key)).register(_selector, todo.ops, todo.att);
                    if (todo.att != null) {
                        Link link = (Link) todo.att;
                        link.setKey(key);
                    }
                } catch (ClosedChannelException e) {
                    s_logger.warn("Couldn't register socket: " + todo.key);
                    try {
                        ((SocketChannel) (todo.key)).close();
                    } catch (IOException ignore) {
                    } finally {
                        Link link = (Link) todo.att;
                        link.terminated();
                    }
                }
                break;
            case ChangeRequest.CLOSE:
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Trying to close " + todo.key);
                }
                key = (SelectionKey) todo.key;
                closeConnection(key);
                if (key != null) {
                    Link link = (Link) key.attachment();
                    if (link != null) {
                        link.terminated();
                    }
                }
                break;
            default:
                s_logger.warn("Shouldn't be here");
                throw new RuntimeException("Shouldn't be here");
        }
    }
    s_logger.trace("Todos Done processing");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ClosedChannelException(java.nio.channels.ClosedChannelException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException)

Example 9 with CancelledKeyException

use of java.nio.channels.CancelledKeyException in project jeromq by zeromq.

the class Poller method run.

@Override
public void run() {
    int returnsImmediately = 0;
    while (!stopping) {
        //  Execute any due timers.
        long timeout = executeTimers();
        while (retired.compareAndSet(true, false)) {
            Iterator<Map.Entry<SelectableChannel, PollSet>> it = fdTable.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<SelectableChannel, PollSet> entry = it.next();
                SelectableChannel ch = entry.getKey();
                PollSet pollset = entry.getValue();
                if (pollset.key == null) {
                    try {
                        pollset.key = ch.register(selector, pollset.ops, pollset.handler);
                    } catch (ClosedChannelException e) {
                    }
                }
                if (pollset.cancelled || !ch.isOpen()) {
                    if (pollset.key != null) {
                        pollset.key.cancel();
                    }
                    it.remove();
                }
            }
        }
        //  Wait for events.
        int rc;
        long start = System.currentTimeMillis();
        try {
            rc = selector.select(timeout);
        } catch (IOException e) {
            throw new ZError.IOException(e);
        }
        if (rc == 0) {
            //  Guess JDK epoll bug
            if (timeout == 0 || System.currentTimeMillis() - start < timeout / 2) {
                returnsImmediately++;
            } else {
                returnsImmediately = 0;
            }
            if (returnsImmediately > 10) {
                rebuildSelector();
                returnsImmediately = 0;
            }
            continue;
        }
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            IPollEvents evt = (IPollEvents) key.attachment();
            it.remove();
            try {
                if (key.isReadable()) {
                    evt.inEvent();
                } else if (key.isAcceptable()) {
                    evt.acceptEvent();
                } else if (key.isConnectable()) {
                    evt.connectEvent();
                }
                if (key.isWritable()) {
                    evt.outEvent();
                }
            } catch (CancelledKeyException e) {
            // channel might have been closed
            }
        }
    }
    stopped = true;
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) SelectableChannel(java.nio.channels.SelectableChannel) Map(java.util.Map) HashMap(java.util.HashMap)

Example 10 with CancelledKeyException

use of java.nio.channels.CancelledKeyException in project geode by apache.

the class AcceptorImpl method runSelectorLoop.

public void runSelectorLoop() {
    // int zeroEventsCount = 0;
    try {
        logger.info(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_SELECTOR_ENABLED));
        while (this.selector.isOpen() && !Thread.currentThread().isInterrupted()) {
            {
                SystemFailure.checkFailure();
                // this.cache.getDistributedSystem().getCancelCriterion().checkCancelInProgress(null);
                if (this.cache.isClosed()) {
                    // TODO should just ask cache's CancelCriterion
                    break;
                }
                if (this.cache.getCancelCriterion().isCancelInProgress()) {
                    break;
                }
                ServerConnection sc;
                registeredKeys = checkRegisteredKeys(registeredKeys);
                if (registeredKeys == 0) {
                    // do blocking wait on queue until we get some guys registered
                    // with the selector
                    sc = (ServerConnection) this.selectorQueue.take();
                } else {
                    // we already have some guys registered so just do a poll on queue
                    sc = (ServerConnection) this.selectorQueue.poll();
                }
                while (sc != null) {
                    try {
                        sc.registerWithSelector2(this.selector);
                        registeredKeys++;
                        this.selectorRegistrations.add(sc);
                    } catch (ClosedChannelException cce) {
                        // for bug bug 38474
                        finishCon(sc);
                    } catch (IOException ex) {
                        finishCon(sc);
                        logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_IGNORING, ex));
                    } catch (RuntimeException ex) {
                        finishCon(sc);
                        logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_IGNORING, ex));
                    }
                    sc = (ServerConnection) this.selectorQueue.poll();
                }
            }
            if (registeredKeys == 0) {
                continue;
            }
            int events = this.selector.select();
            // select() could have returned due to wakeup() during close of cache
            if (this.cache.getCancelCriterion().isCancelInProgress()) {
                break;
            }
            if (events == 0) {
                // zeroEventsCount++;
                // if (zeroEventsCount > 0) {
                // zeroEventsCount = 0;
                checkForStuckKeys();
            // try {
            // this.selector.close(); // this selector is sick!
            // } catch (IOException ignore) {
            // }
            // this.selector = Selector.open();
            // {
            // Iterator it = selectorRegistrations.iterator();
            // while (it.hasNext()) {
            // ServerConnection sc = (ServerConnection)it.next();
            // sc.registerWithSelector2(this.selector);
            // }
            // }
            // }
            // ArrayList al = new ArrayList();
            // Iterator keysIt = this.selector.keys().iterator();
            // while (keysIt.hasNext()) {
            // SelectionKey sk = (SelectionKey)keysIt.next();
            // al.add(sk.attachment());
            // sk.cancel();
            // }
            // events = this.selector.selectNow();
            // Iterator alIt = al.iterator();
            // while (alIt.hasNext()) {
            // ServerConnection sc = (ServerConnection)alIt.next();
            // sc.registerWithSelector2(this.selector);
            // }
            // events = this.selector.select();
            // } else {
            // zeroEventsCount = 0;
            }
            while (events > 0) {
                int cancelCount = 0;
                Set sk = this.selector.selectedKeys();
                if (sk == null) {
                    // something really bad has happened I'm not even sure this is possible
                    // but lhughes so an NPE during close one time so perhaps it can happen
                    // during selector close.
                    events = 0;
                    break;
                }
                Iterator keysIterator = sk.iterator();
                while (keysIterator.hasNext()) {
                    SelectionKey key = (SelectionKey) keysIterator.next();
                    // Remove the key from the selector's selectedKeys
                    keysIterator.remove();
                    final ServerConnection sc = (ServerConnection) key.attachment();
                    try {
                        if (key.isValid() && key.isReadable()) {
                            // this is the only event we currently register for
                            try {
                                key.cancel();
                                this.selectorRegistrations.remove(sc);
                                registeredKeys--;
                                cancelCount++;
                                sc.makeBlocking();
                                // we need to say we are processing a message
                                // so that that client health monitor will not
                                // kill us while we wait for a thread in the thread pool.
                                // This is also be used to determine how long we are
                                // in the thread pool queue and to cancel operations that
                                // have waited too long in the queue.
                                sc.setProcessingMessage();
                            } catch (ClosedChannelException ignore) {
                                finishCon(sc);
                                continue;
                            } catch (IOException ex) {
                                finishCon(sc);
                                if (isRunning()) {
                                    logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_UNEXPECTED, ex));
                                }
                                continue;
                            }
                            try {
                                AcceptorImpl.this.stats.incThreadQueueSize();
                                AcceptorImpl.this.pool.execute(sc);
                            } catch (RejectedExecutionException rejected) {
                                finishCon(sc);
                                AcceptorImpl.this.stats.decThreadQueueSize();
                                if (!isRunning()) {
                                    break;
                                }
                                logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_UNEXPECTED, rejected));
                            }
                        // } else if (key.isValid() && key.isConnectable()) {
                        // logger.info("DEBUG isConnectable and isValid key=" + key);
                        // finishCon(sc);
                        } else {
                            finishCon(sc);
                            if (key.isValid()) {
                                logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_IGNORING_EVENT_ON_SELECTOR_KEY__0, key));
                            // } else {
                            // logger.info("DEBUG !isValid key=" + key);
                            }
                        }
                    } catch (CancelledKeyException ex) {
                        // fix for bug 37739
                        finishCon(sc);
                    }
                }
                if (cancelCount > 0 && this.selector.isOpen()) {
                    // we need to do a select to cause the cancel to be unregisters.
                    events = this.selector.selectNow();
                } else {
                    events = 0;
                }
            }
        }
    } catch (InterruptedException ex) {
        // allow this thread to die
        Thread.currentThread().interrupt();
    } catch (ClosedSelectorException ex) {
    // allow this thread to exit
    } catch (IOException ex) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.AcceptorImpl_UNEXPECTED, ex));
    } finally {
        try {
            drainSelectorQueue();
        } finally {
            // note that if this method was called by close then the
            // following call is a noop since the first thing it does
            // is call isRunning.
            // make sure this is called to fix bug 37749
            close();
        }
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) Set(java.util.Set) HashSet(java.util.HashSet) CancelledKeyException(java.nio.channels.CancelledKeyException) Iterator(java.util.Iterator) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Aggregations

CancelledKeyException (java.nio.channels.CancelledKeyException)22 SelectionKey (java.nio.channels.SelectionKey)14 IOException (java.io.IOException)12 ClosedChannelException (java.nio.channels.ClosedChannelException)11 ClosedSelectorException (java.nio.channels.ClosedSelectorException)3 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)3 IllegalSelectorException (java.nio.channels.IllegalSelectorException)3 Selector (java.nio.channels.Selector)3 ByteBuffer (java.nio.ByteBuffer)2 SelectableChannel (java.nio.channels.SelectableChannel)2 ServerSocketChannel (java.nio.channels.ServerSocketChannel)2 SocketChannel (java.nio.channels.SocketChannel)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 Set (java.util.Set)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 ObjectReader (org.apache.catalina.tribes.io.ObjectReader)2 WebSocketImpl (org.java_websocket.WebSocketImpl)2 ListenCallback (com.koushikdutta.async.callback.ListenCallback)1 EventLoop (io.netty.channel.EventLoop)1