Search in sources :

Example 66 with CancelException

use of org.apache.geode.CancelException in project geode by apache.

the class CacheClientProxy method destroyRQ.

private void destroyRQ() {
    if (this._messageDispatcher == null) {
        return;
    }
    try {
        // Using Destroy Region bcoz this method is modified in HARegion so as
        // not to distribute.
        // For normal Regions , even the localDestroyRegion actually propagates
        HARegionQueue rq = this._messageDispatcher._messageQueue;
        rq.destroy();
    // if (!rq.getRegion().isDestroyed()) {
    // rq.getRegion().destroyRegion();
    // }
    } catch (RegionDestroyedException rde) {
    // throw rde;
    } catch (CancelException e) {
    // throw e;
    } catch (Exception warning) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.CacheClientProxy_0_EXCEPTION_IN_CLOSING_THE_UNDERLYING_HAREGION_OF_THE_HAREGIONQUEUE, this), warning);
    }
}
Also used : RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CancelException(org.apache.geode.CancelException) HARegionQueue(org.apache.geode.internal.cache.ha.HARegionQueue) RegionExistsException(org.apache.geode.cache.RegionExistsException) CqException(org.apache.geode.cache.query.CqException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CancelException(org.apache.geode.CancelException) SocketException(java.net.SocketException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException)

Example 67 with CancelException

use of org.apache.geode.CancelException in project geode by apache.

the class TCPConduit method run.

/**
   * this is the server socket listener thread's run loop
   */
public void run() {
    ConnectionTable.threadWantsSharedResources();
    if (logger.isTraceEnabled(LogMarker.DM)) {
        logger.trace(LogMarker.DM, "Starting P2P Listener on  {}", id);
    }
    for (; ; ) {
        SystemFailure.checkFailure();
        if (stopper.isCancelInProgress()) {
            break;
        }
        if (stopped) {
            break;
        }
        if (Thread.currentThread().isInterrupted()) {
            break;
        }
        if (stopper.isCancelInProgress()) {
            // part of bug 37271
            break;
        }
        Socket othersock = null;
        try {
            if (this.useNIO) {
                SocketChannel otherChannel = channel.accept();
                othersock = otherChannel.socket();
            } else {
                try {
                    othersock = socket.accept();
                } catch (SSLException ex) {
                    // SW: This is the case when there is a problem in P2P
                    // SSL configuration, so need to exit otherwise goes into an
                    // infinite loop just filling the logs
                    logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_STOPPING_P2P_LISTENER_DUE_TO_SSL_CONFIGURATION_PROBLEM), ex);
                    break;
                }
                socketCreator.configureServerSSLSocket(othersock);
            }
            if (stopped) {
                try {
                    if (othersock != null) {
                        othersock.close();
                    }
                } catch (Exception e) {
                }
                continue;
            }
            acceptConnection(othersock);
        } catch (ClosedByInterruptException cbie) {
        // safe to ignore
        } catch (ClosedChannelException e) {
            // we're dead
            break;
        } catch (CancelException e) {
            break;
        } catch (Exception e) {
            if (!stopped) {
                if (e instanceof SocketException && "Socket closed".equalsIgnoreCase(e.getMessage())) {
                    // safe to ignore; see bug 31156
                    if (!socket.isClosed()) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_SERVERSOCKET_THREW_SOCKET_CLOSED_EXCEPTION_BUT_SAYS_IT_IS_NOT_CLOSED), e);
                        try {
                            socket.close();
                            createServerSocket();
                        } catch (IOException ioe) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.TCPConduit_UNABLE_TO_CLOSE_AND_RECREATE_SERVER_SOCKET), ioe);
                            // post 5.1.0x, this should force shutdown
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException ie) {
                                // Don't reset; we're just exiting the thread
                                logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_INTERRUPTED_AND_EXITING_WHILE_TRYING_TO_RECREATE_LISTENER_SOCKETS));
                                return;
                            }
                        }
                    }
                } else {
                    this.stats.incFailedAccept();
                    if (e instanceof IOException && "Too many open files".equals(e.getMessage())) {
                        getConTable().fileDescriptorsExhausted();
                    } else {
                        logger.warn(e.getMessage(), e);
                    }
                }
            }
        // connections.cleanupLowWater();
        }
        if (!stopped && socket.isClosed()) {
            // NOTE: do not check for distributed system closing here. Messaging
            // may need to occur during the closing of the DS or cache
            logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_SERVERSOCKET_CLOSED_REOPENING));
            try {
                createServerSocket();
            } catch (ConnectionException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        }
    }
    if (logger.isTraceEnabled(LogMarker.DM)) {
        logger.debug("Stopped P2P Listener on  {}", id);
    }
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) SocketException(java.net.SocketException) CancelException(org.apache.geode.CancelException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SSLException(javax.net.ssl.SSLException)

Example 68 with CancelException

use of org.apache.geode.CancelException in project geode by apache.

the class TCPConduit method getConnection.

/**
   * Return a connection to the given member. This method must continue to attempt to create a
   * connection to the given member as long as that member is in the membership view and the system
   * is not shutting down.
   * 
   * @param memberAddress the IDS associated with the remoteId
   * @param preserveOrder whether this is an ordered or unordered connection
   * @param retry false if this is the first attempt
   * @param startTime the time this operation started
   * @param ackTimeout the ack-wait-threshold * 1000 for the operation to be transmitted (or zero)
   * @param ackSATimeout the ack-severe-alert-threshold * 1000 for the operation to be transmitted
   *        (or zero)
   *
   * @return the connection
   */
public Connection getConnection(InternalDistributedMember memberAddress, final boolean preserveOrder, boolean retry, long startTime, long ackTimeout, long ackSATimeout) throws java.io.IOException, DistributedSystemDisconnectedException {
    // (processorType == DistributionManager.PARTITIONED_REGION_EXECUTOR);
    if (stopped) {
        throw new DistributedSystemDisconnectedException(LocalizedStrings.TCPConduit_THE_CONDUIT_IS_STOPPED.toLocalizedString());
    }
    Connection conn = null;
    InternalDistributedMember memberInTrouble = null;
    boolean breakLoop = false;
    for (; ; ) {
        stopper.checkCancelInProgress(null);
        boolean interrupted = Thread.interrupted();
        try {
            // rebuilt.
            if (retry || conn != null) {
                // not first time in loop
                if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress) || membershipManager.shutdownInProgress()) {
                    throw new IOException(LocalizedStrings.TCPConduit_TCPIP_CONNECTION_LOST_AND_MEMBER_IS_NOT_IN_VIEW.toLocalizedString());
                }
                // Pause just a tiny bit...
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    interrupted = true;
                    stopper.checkCancelInProgress(e);
                }
                // try again after sleep
                if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress)) {
                    // OK, the member left. Just register an error.
                    throw new IOException(LocalizedStrings.TCPConduit_TCPIP_CONNECTION_LOST_AND_MEMBER_IS_NOT_IN_VIEW.toLocalizedString());
                }
                // Print a warning (once)
                if (memberInTrouble == null) {
                    memberInTrouble = memberAddress;
                    logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_ATTEMPTING_TCPIP_RECONNECT_TO__0, memberInTrouble));
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Attempting TCP/IP reconnect to {}", memberInTrouble);
                    }
                }
                // Close the connection (it will get rebuilt later).
                this.stats.incReconnectAttempts();
                if (conn != null) {
                    try {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Closing old connection.  conn={} before retrying. memberInTrouble={}", conn, memberInTrouble);
                        }
                        conn.closeForReconnect("closing before retrying");
                    } catch (CancelException ex) {
                        throw ex;
                    } catch (Exception ex) {
                    }
                }
            }
            // not first time in loop
            Exception problem = null;
            try {
                // Get (or regenerate) the connection
                // bug36202: this could generate a ConnectionException, so it
                // must be caught and retried
                boolean retryForOldConnection;
                boolean debugRetry = false;
                do {
                    retryForOldConnection = false;
                    conn = getConTable().get(memberAddress, preserveOrder, startTime, ackTimeout, ackSATimeout);
                    if (conn == null) {
                        // conduit may be closed - otherwise an ioexception would be thrown
                        problem = new IOException(LocalizedStrings.TCPConduit_UNABLE_TO_RECONNECT_TO_SERVER_POSSIBLE_SHUTDOWN_0.toLocalizedString(memberAddress));
                    } else if (conn.isClosing() || !conn.getRemoteAddress().equals(memberAddress)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Got an old connection for {}: {}@{}", memberAddress, conn, conn.hashCode());
                        }
                        conn.closeOldConnection("closing old connection");
                        conn = null;
                        retryForOldConnection = true;
                        debugRetry = true;
                    }
                } while (retryForOldConnection);
                if (debugRetry && logger.isDebugEnabled()) {
                    logger.debug("Done removing old connections");
                }
            // we have a connection; fall through and return it
            } catch (ConnectionException e) {
                // Race condition between acquiring the connection and attempting
                // to use it: another thread closed it.
                problem = e;
                // [sumedh] No need to retry since Connection.createSender has already
                // done retries and now member is really unreachable for some reason
                // even though it may be in the view
                breakLoop = true;
            } catch (IOException e) {
                problem = e;
                // bug #43962 don't keep trying to connect to an alert listener
                if (AlertAppender.isThreadAlerting()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Giving up connecting to alert listener {}", memberAddress);
                    }
                    breakLoop = true;
                }
            }
            if (problem != null) {
                // Some problems are not recoverable; check and error out early.
                if (!membershipManager.memberExists(memberAddress) || membershipManager.isShunned(memberAddress)) {
                    // Bracket our original warning
                    if (memberInTrouble != null) {
                        // make this msg info to bracket warning
                        logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_ENDING_RECONNECT_ATTEMPT_BECAUSE_0_HAS_DISAPPEARED, memberInTrouble));
                    }
                    throw new IOException(LocalizedStrings.TCPConduit_PEER_HAS_DISAPPEARED_FROM_VIEW.toLocalizedString(memberAddress));
                }
                if (membershipManager.shutdownInProgress()) {
                    // Bracket our original warning
                    if (memberInTrouble != null) {
                        // make this msg info to bracket warning
                        logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_ENDING_RECONNECT_ATTEMPT_TO_0_BECAUSE_SHUTDOWN_HAS_STARTED, memberInTrouble));
                    }
                    stopper.checkCancelInProgress(null);
                    throw new DistributedSystemDisconnectedException(LocalizedStrings.TCPConduit_ABANDONED_BECAUSE_SHUTDOWN_IS_IN_PROGRESS.toLocalizedString());
                }
                // to have m defined for a nice message...
                if (memberInTrouble == null) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_ERROR_SENDING_MESSAGE_TO_0_WILL_REATTEMPT_1, new Object[] { memberAddress, problem }));
                    memberInTrouble = memberAddress;
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Error sending message to {}", memberAddress, problem);
                    }
                }
                if (breakLoop) {
                    if (!problem.getMessage().startsWith("Cannot form connection to alert listener")) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_THROWING_IOEXCEPTION_AFTER_FINDING_BREAKLOOP_TRUE), problem);
                    }
                    if (problem instanceof IOException) {
                        throw (IOException) problem;
                    } else {
                        IOException ioe = new IOException(LocalizedStrings.TCPConduit_PROBLEM_CONNECTING_TO_0.toLocalizedString(memberAddress));
                        ioe.initCause(problem);
                        throw ioe;
                    }
                }
                // Retry the operation (indefinitely)
                continue;
            }
            // Make sure our logging is bracketed if there was a problem
            if (memberInTrouble != null) {
                logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_SUCCESSFULLY_RECONNECTED_TO_MEMBER_0, memberInTrouble));
                if (logger.isTraceEnabled()) {
                    logger.trace("new connection is {} memberAddress={}", conn, memberAddress);
                }
            }
            return conn;
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }
// for(;;)
}
Also used : DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) IOException(java.io.IOException) CancelException(org.apache.geode.CancelException) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) SSLException(javax.net.ssl.SSLException)

Example 69 with CancelException

use of org.apache.geode.CancelException in project geode by apache.

the class Connection method runOioReader.

private void runOioReader() {
    InputStream input = null;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Socket is of type: {}", getSocket().getClass());
        }
        input = new BufferedInputStream(getSocket().getInputStream(), INITIAL_CAPACITY);
    } catch (IOException io) {
        if (stopped || owner.getConduit().getCancelCriterion().isCancelInProgress()) {
            // bug 37520: exit run loop (and thread)
            return;
        }
        logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNABLE_TO_GET_INPUT_STREAM), io);
        stopped = true;
    }
    if (!stopped) {
        Assert.assertTrue(owner != null, LocalizedStrings.Connection_OWNER_SHOULD_NOT_BE_NULL.toLocalizedString());
        if (logger.isDebugEnabled()) {
            logger.debug("Starting {}", p2pReaderName());
        }
    }
    byte[] lenbytes = new byte[MSG_HEADER_BYTES];
    final ByteArrayDataInput dis = new ByteArrayDataInput();
    while (!stopped) {
        try {
            if (SystemFailure.getFailure() != null) {
                // Allocate no objects here!
                Socket s = this.socket;
                if (s != null) {
                    try {
                        s.close();
                    } catch (IOException e) {
                    // don't care
                    }
                }
                // throws
                SystemFailure.checkFailure();
            }
            if (this.owner.getConduit().getCancelCriterion().isCancelInProgress()) {
                break;
            }
            int len = 0;
            if (readFully(input, lenbytes, lenbytes.length) < 0) {
                stopped = true;
                continue;
            }
            // long recvNanos = DistributionStats.getStatTime();
            len = ((lenbytes[MSG_HEADER_SIZE_OFFSET] & 0xff) * 0x1000000) + ((lenbytes[MSG_HEADER_SIZE_OFFSET + 1] & 0xff) * 0x10000) + ((lenbytes[MSG_HEADER_SIZE_OFFSET + 2] & 0xff) * 0x100) + (lenbytes[MSG_HEADER_SIZE_OFFSET + 3] & 0xff);
            /* byte msgHdrVersion = */
            calcHdrVersion(len);
            len = calcMsgByteSize(len);
            int msgType = lenbytes[MSG_HEADER_TYPE_OFFSET];
            short msgId = (short) (((lenbytes[MSG_HEADER_ID_OFFSET] & 0xff) << 8) + (lenbytes[MSG_HEADER_ID_OFFSET + 1] & 0xff));
            boolean myDirectAck = (msgType & DIRECT_ACK_BIT) != 0;
            if (myDirectAck) {
                // clear the bit
                msgType &= ~DIRECT_ACK_BIT;
            }
            // Following validation fixes bug 31145
            if (!validMsgType(msgType)) {
                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNKNOWN_P2P_MESSAGE_TYPE_0, Integer.valueOf(msgType)));
                this.readerShuttingDown = true;
                requestClose(LocalizedStrings.Connection_UNKNOWN_P2P_MESSAGE_TYPE_0.toLocalizedString(Integer.valueOf(msgType)));
                break;
            }
            if (logger.isTraceEnabled())
                logger.trace("{} reading {} bytes", conduitIdStr, len);
            byte[] bytes = new byte[len];
            if (readFully(input, bytes, len) < 0) {
                stopped = true;
                continue;
            }
            boolean interrupted = Thread.interrupted();
            try {
                if (this.handshakeRead) {
                    if (msgType == NORMAL_MSG_TYPE) {
                        // DMStats stats = this.owner.getConduit().stats;
                        // long start = DistributionStats.getStatTime();
                        this.owner.getConduit().stats.incMessagesBeingReceived(true, len);
                        dis.initialize(bytes, this.remoteVersion);
                        DistributionMessage msg = null;
                        try {
                            ReplyProcessor21.initMessageRPId();
                            long startSer = this.owner.getConduit().stats.startMsgDeserialization();
                            msg = (DistributionMessage) InternalDataSerializer.readDSFID(dis);
                            this.owner.getConduit().stats.endMsgDeserialization(startSer);
                            if (dis.available() != 0) {
                                logger.warn(LocalizedMessage.create(LocalizedStrings.Connection_MESSAGE_DESERIALIZATION_OF_0_DID_NOT_READ_1_BYTES, new Object[] { msg, Integer.valueOf(dis.available()) }));
                            }
                            // stats.incBatchCopyTime(start);
                            try {
                                // start = DistributionStats.getStatTime();
                                if (!dispatchMessage(msg, len, myDirectAck)) {
                                    continue;
                                }
                            // stats.incBatchSendTime(start);
                            } catch (MemberShunnedException e) {
                                continue;
                            } catch (Exception de) {
                                // bug
                                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(de);
                                // 37101
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DISPATCHING_MESSAGE), de);
                            }
                        } catch (VirtualMachineError err) {
                            SystemFailure.initiateFailure(err);
                            // now, so don't let this thread continue.
                            throw err;
                        } catch (Throwable e) {
                            // Whenever you catch Error or Throwable, you must also
                            // catch VirtualMachineError (see above). However, there is
                            // _still_ a possibility that you are dealing with a cascading
                            // error condition, so you also need to check to see if the JVM
                            // is still usable:
                            SystemFailure.checkFailure();
                            // In particular I want OutOfMem to be caught here
                            if (!myDirectAck) {
                                String reason = LocalizedStrings.Connection_ERROR_DESERIALIZING_MESSAGE.toLocalizedString();
                                sendFailureReply(ReplyProcessor21.getMessageRPId(), reason, e, myDirectAck);
                            }
                            if (e instanceof CancelException) {
                                if (!(e instanceof CacheClosedException)) {
                                    // CacheClosedException; see bug 43543
                                    throw (CancelException) e;
                                }
                            }
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DESERIALIZING_MESSAGE), e);
                        // requestClose();
                        // return;
                        } finally {
                            ReplyProcessor21.clearMessageRPId();
                        }
                    } else if (msgType == CHUNKED_MSG_TYPE) {
                        MsgDestreamer md = obtainMsgDestreamer(msgId, remoteVersion);
                        this.owner.getConduit().stats.incMessagesBeingReceived(md.size() == 0, len);
                        try {
                            md.addChunk(bytes);
                        } catch (IOException ex) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_FAILED_HANDLING_CHUNK_MESSAGE), ex);
                        }
                    } else /* (messageType == END_CHUNKED_MSG_TYPE) */
                    {
                        MsgDestreamer md = obtainMsgDestreamer(msgId, remoteVersion);
                        this.owner.getConduit().stats.incMessagesBeingReceived(md.size() == 0, len);
                        try {
                            md.addChunk(bytes);
                        } catch (IOException ex) {
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_FAILED_HANDLING_END_CHUNK_MESSAGE), ex);
                        }
                        DistributionMessage msg = null;
                        int msgLength = 0;
                        String failureMsg = null;
                        Throwable failureEx = null;
                        int rpId = 0;
                        try {
                            msg = md.getMessage();
                        } catch (ClassNotFoundException ex) {
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.warn(LocalizedMessage.create(LocalizedStrings.Connection_CLASSNOTFOUND_DESERIALIZING_MESSAGE_0, ex));
                        } catch (IOException ex) {
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureMsg = LocalizedStrings.Connection_IOEXCEPTION_DESERIALIZING_MESSAGE.toLocalizedString();
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_IOEXCEPTION_DESERIALIZING_MESSAGE), failureEx);
                        } catch (InterruptedException ex) {
                            Thread.currentThread().interrupt();
                            // caught by outer try
                            throw ex;
                        } catch (VirtualMachineError err) {
                            SystemFailure.initiateFailure(err);
                            // now, so don't let this thread continue.
                            throw err;
                        } catch (Throwable ex) {
                            // Whenever you catch Error or Throwable, you must also
                            // catch VirtualMachineError (see above). However, there is
                            // _still_ a possibility that you are dealing with a cascading
                            // error condition, so you also need to check to see if the JVM
                            // is still usable:
                            SystemFailure.checkFailure();
                            this.owner.getConduit().stats.decMessagesBeingReceived(md.size());
                            failureMsg = LocalizedStrings.Connection_UNEXPECTED_FAILURE_DESERIALIZING_MESSAGE.toLocalizedString();
                            failureEx = ex;
                            rpId = md.getRPid();
                            logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNEXPECTED_FAILURE_DESERIALIZING_MESSAGE), failureEx);
                        } finally {
                            msgLength = md.size();
                            releaseMsgDestreamer(msgId, md);
                        }
                        if (msg != null) {
                            try {
                                if (!dispatchMessage(msg, msgLength, myDirectAck)) {
                                    continue;
                                }
                            } catch (MemberShunnedException e) {
                                continue;
                            } catch (Exception de) {
                                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(de);
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_ERROR_DISPATCHING_MESSAGE), de);
                            } catch (ThreadDeath td) {
                                throw td;
                            } catch (VirtualMachineError err) {
                                SystemFailure.initiateFailure(err);
                                // now, so don't let this thread continue.
                                throw err;
                            } catch (Throwable t) {
                                // Whenever you catch Error or Throwable, you must also
                                // catch VirtualMachineError (see above). However, there is
                                // _still_ a possibility that you are dealing with a cascading
                                // error condition, so you also need to check to see if the JVM
                                // is still usable:
                                SystemFailure.checkFailure();
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_THROWABLE_DISPATCHING_MESSAGE), t);
                            }
                        } else if (failureEx != null) {
                            sendFailureReply(rpId, failureMsg, failureEx, myDirectAck);
                        }
                    }
                } else {
                    dis.initialize(bytes, null);
                    if (!this.isReceiver) {
                        this.replyCode = dis.readUnsignedByte();
                        if (this.replyCode != REPLY_CODE_OK && this.replyCode != REPLY_CODE_OK_WITH_ASYNC_INFO) {
                            Integer replyCodeInteger = Integer.valueOf(this.replyCode);
                            String err = LocalizedStrings.Connection_UNKNOWN_HANDSHAKE_REPLY_CODE_0.toLocalizedString(replyCodeInteger);
                            if (this.replyCode == 0) {
                                // bug 37113
                                if (logger.isDebugEnabled()) {
                                    logger.debug("{} (peer probably departed ungracefully)", err);
                                }
                            } else {
                                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_UNKNOWN_HANDSHAKE_REPLY_CODE_0, replyCodeInteger));
                            }
                            this.readerShuttingDown = true;
                            requestClose(err);
                            break;
                        }
                        if (this.replyCode == REPLY_CODE_OK_WITH_ASYNC_INFO) {
                            this.asyncDistributionTimeout = dis.readInt();
                            this.asyncQueueTimeout = dis.readInt();
                            this.asyncMaxQueueSize = (long) dis.readInt() * (1024 * 1024);
                            if (this.asyncDistributionTimeout != 0) {
                                logger.info(LocalizedMessage.create(LocalizedStrings.Connection_0_ASYNC_CONFIGURATION_RECEIVED_1, new Object[] { p2pReaderName(), " asyncDistributionTimeout=" + this.asyncDistributionTimeout + " asyncQueueTimeout=" + this.asyncQueueTimeout + " asyncMaxQueueSize=" + (this.asyncMaxQueueSize / (1024 * 1024)) }));
                            }
                            // read the product version ordinal for on-the-fly serialization
                            // transformations (for rolling upgrades)
                            this.remoteVersion = Version.readVersion(dis, true);
                        }
                        notifyHandshakeWaiter(true);
                    } else {
                        byte b = dis.readByte();
                        if (b != 0) {
                            throw new IllegalStateException(LocalizedStrings.Connection_DETECTED_OLD_VERSION_PRE_5_0_1_OF_GEMFIRE_OR_NONGEMFIRE_DURING_HANDSHAKE_DUE_TO_INITIAL_BYTE_BEING_0.toLocalizedString(new Byte(b)));
                        }
                        byte handShakeByte = dis.readByte();
                        if (handShakeByte != HANDSHAKE_VERSION) {
                            throw new IllegalStateException(LocalizedStrings.Connection_DETECTED_WRONG_VERSION_OF_GEMFIRE_PRODUCT_DURING_HANDSHAKE_EXPECTED_0_BUT_FOUND_1.toLocalizedString(new Object[] { new Byte(HANDSHAKE_VERSION), new Byte(handShakeByte) }));
                        }
                        InternalDistributedMember remote = DSFIDFactory.readInternalDistributedMember(dis);
                        setRemoteAddr(remote);
                        Thread.currentThread().setName(LocalizedStrings.Connection_P2P_MESSAGE_READER_FOR_0.toLocalizedString(this.remoteAddr, this.socket.getPort()));
                        this.sharedResource = dis.readBoolean();
                        this.preserveOrder = dis.readBoolean();
                        this.uniqueId = dis.readLong();
                        // read the product version ordinal for on-the-fly serialization
                        // transformations (for rolling upgrades)
                        this.remoteVersion = Version.readVersion(dis, true);
                        int dominoNumber = 0;
                        if (this.remoteVersion == null || (this.remoteVersion.compareTo(Version.GFE_80) >= 0)) {
                            dominoNumber = dis.readInt();
                            if (this.sharedResource) {
                                dominoNumber = 0;
                            }
                            dominoCount.set(dominoNumber);
                            // this.senderName = dis.readUTF();
                            setThreadName(dominoNumber);
                        }
                        if (!this.sharedResource) {
                            if (tipDomino()) {
                                logger.info(LocalizedMessage.create(LocalizedStrings.Connection_THREAD_OWNED_RECEIVER_FORCING_ITSELF_TO_SEND_ON_THREAD_OWNED_SOCKETS));
                            // bug #49565 - if domino count is >= 2 use shared resources.
                            // Also see DistributedCacheOperation#supportsDirectAck
                            } else {
                                // if (dominoNumber < 2){
                                ConnectionTable.threadWantsOwnResources();
                                if (logger.isDebugEnabled()) {
                                    logger.debug("thread-owned receiver with domino count of {} will prefer sending on thread-owned sockets", dominoNumber);
                                }
                            // } else {
                            // ConnectionTable.threadWantsSharedResources();
                            // logger.fine("thread-owned receiver with domino count of " + dominoNumber + "
                            // will prefer shared sockets");
                            }
                            this.conduit.stats.incThreadOwnedReceivers(1L, dominoNumber);
                        }
                        if (logger.isDebugEnabled()) {
                            logger.debug("{} remoteAddr is {} {}", p2pReaderName(), this.remoteAddr, (this.remoteVersion != null ? " (" + this.remoteVersion + ')' : ""));
                        }
                        String authInit = System.getProperty(DistributionConfigImpl.SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTH_INIT);
                        boolean isSecure = authInit != null && authInit.length() != 0;
                        if (isSecure) {
                            // ARB: wait till member authentication has been confirmed?
                            if (owner.getConduit().waitForMembershipCheck(this.remoteAddr)) {
                                // fix for bug 33224
                                sendOKHandshakeReply();
                                notifyHandshakeWaiter(true);
                            } else {
                                // ARB: throw exception??
                                notifyHandshakeWaiter(false);
                                logger.warn(LocalizedMessage.create(LocalizedStrings.Connection_0_TIMED_OUT_DURING_A_MEMBERSHIP_CHECK, p2pReaderName()));
                            }
                        } else {
                            // fix for bug 33224
                            sendOKHandshakeReply();
                            notifyHandshakeWaiter(true);
                        }
                    }
                    if (!this.isReceiver && (this.handshakeRead || this.handshakeCancelled)) {
                        if (logger.isDebugEnabled()) {
                            if (this.handshakeRead) {
                                logger.debug("{} handshake has been read {}", p2pReaderName(), this);
                            } else {
                                logger.debug("{} handshake has been cancelled {}", p2pReaderName(), this);
                            }
                        }
                        // Once we have read the handshake the reader can go away
                        break;
                    }
                    continue;
                }
            } catch (InterruptedException e) {
                interrupted = true;
                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(e);
                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_0_STRAY_INTERRUPT_READING_MESSAGE, p2pReaderName()), e);
                continue;
            } catch (Exception ioe) {
                // bug 37101
                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(ioe);
                if (!stopped) {
                    logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_0_ERROR_READING_MESSAGE, p2pReaderName()), ioe);
                }
                continue;
            } finally {
                if (interrupted) {
                    Thread.currentThread().interrupt();
                }
            }
        } catch (CancelException e) {
            if (logger.isDebugEnabled()) {
                String ccMsg = p2pReaderName() + " Cancelled: " + this;
                if (e.getMessage() != null) {
                    ccMsg += ": " + e.getMessage();
                }
                logger.debug(ccMsg);
            }
            this.readerShuttingDown = true;
            try {
                requestClose(LocalizedStrings.Connection_CACHECLOSED_IN_CHANNEL_READ_0.toLocalizedString(e));
            } catch (Exception ex) {
            }
            this.stopped = true;
        } catch (IOException io) {
            // needed
            boolean closed = isSocketClosed() || "Socket closed".equalsIgnoreCase(io.getMessage());
            // 1.4.2_08
            if (!closed) {
                if (logger.isDebugEnabled() && !isIgnorableIOException(io)) {
                    logger.debug("{} io exception for {}", p2pReaderName(), this, io);
                }
            }
            this.readerShuttingDown = true;
            try {
                requestClose(LocalizedStrings.Connection_IOEXCEPTION_RECEIVED_0.toLocalizedString(io));
            } catch (Exception ex) {
            }
            if (closed) {
                stopped = true;
            } else {
                // sleep a bit to avoid a hot error loop
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    if (this.owner.getConduit().getCancelCriterion().isCancelInProgress()) {
                        return;
                    }
                    break;
                }
            }
        }// IOException
         catch (Exception e) {
            if (this.owner.getConduit().getCancelCriterion().isCancelInProgress()) {
                // bug 37101
                return;
            }
            if (!stopped && !(e instanceof InterruptedException)) {
                logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_0_EXCEPTION_RECEIVED, p2pReaderName()), e);
            }
            if (isSocketClosed()) {
                stopped = true;
            } else {
                this.readerShuttingDown = true;
                try {
                    requestClose(LocalizedStrings.Connection_0_EXCEPTION_RECEIVED.toLocalizedString(e));
                } catch (Exception ex) {
                }
                // sleep a bit to avoid a hot error loop
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) DistributionMessage(org.apache.geode.distributed.internal.DistributionMessage) BufferedInputStream(java.io.BufferedInputStream) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CacheClosedException(org.apache.geode.cache.CacheClosedException) ByteArrayDataInput(org.apache.geode.internal.ByteArrayDataInput) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) CancelledKeyException(java.nio.channels.CancelledKeyException) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ReplyException(org.apache.geode.distributed.internal.ReplyException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CancelException(org.apache.geode.CancelException) Socket(java.net.Socket)

Example 70 with CancelException

use of org.apache.geode.CancelException in project geode by apache.

the class Connection method runNioReader.

private void runNioReader() {
    // take a snapshot of uniqueId to detect reconnect attempts; see bug 37592
    SocketChannel channel = null;
    try {
        channel = getSocket().getChannel();
        channel.configureBlocking(true);
    } catch (ClosedChannelException e) {
        // is done.
        try {
            requestClose(LocalizedStrings.Connection_RUNNIOREADER_CAUGHT_CLOSED_CHANNEL.toLocalizedString());
        } catch (Exception ignore) {
        }
        // exit loop and thread
        return;
    } catch (IOException ex) {
        if (stopped || owner.getConduit().getCancelCriterion().isCancelInProgress()) {
            try {
                requestClose(LocalizedStrings.Connection_RUNNIOREADER_CAUGHT_SHUTDOWN.toLocalizedString());
            } catch (Exception ignore) {
            }
            // bug37520: exit loop (and thread)
            return;
        }
        logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_FAILED_SETTING_CHANNEL_TO_BLOCKING_MODE_0, ex));
        this.readerShuttingDown = true;
        try {
            requestClose(LocalizedStrings.Connection_FAILED_SETTING_CHANNEL_TO_BLOCKING_MODE_0.toLocalizedString(ex));
        } catch (Exception ignore) {
        }
        return;
    }
    if (!stopped) {
        // Assert.assertTrue(owner != null, "How did owner become null");
        if (logger.isDebugEnabled()) {
            logger.debug("Starting {}", p2pReaderName());
        }
    }
    // we should not change the state of the connection if we are a handshake reader thread
    // as there is a race between this thread and the application thread doing direct ack
    // fix for #40869
    boolean isHandShakeReader = false;
    try {
        for (; ; ) {
            if (stopped) {
                break;
            }
            if (SystemFailure.getFailure() != null) {
                // Allocate no objects here!
                Socket s = this.socket;
                if (s != null) {
                    try {
                        s.close();
                    } catch (IOException e) {
                    // don't care
                    }
                }
                // throws
                SystemFailure.checkFailure();
            }
            if (this.owner.getConduit().getCancelCriterion().isCancelInProgress()) {
                break;
            }
            try {
                ByteBuffer buff = getNIOBuffer();
                synchronized (stateLock) {
                    connectionState = STATE_READING;
                }
                int amt = channel.read(buff);
                synchronized (stateLock) {
                    connectionState = STATE_IDLE;
                }
                if (amt == 0) {
                    continue;
                }
                if (amt < 0) {
                    this.readerShuttingDown = true;
                    try {
                        requestClose("SocketChannel.read returned EOF");
                        requestClose(LocalizedStrings.Connection_SOCKETCHANNEL_READ_RETURNED_EOF.toLocalizedString());
                    } catch (Exception e) {
                    // ignore - shutting down
                    }
                    return;
                }
                processNIOBuffer();
                if (!this.isReceiver && (this.handshakeRead || this.handshakeCancelled)) {
                    if (logger.isDebugEnabled()) {
                        if (this.handshakeRead) {
                            logger.debug("{} handshake has been read {}", p2pReaderName(), this);
                        } else {
                            logger.debug("{} handshake has been cancelled {}", p2pReaderName(), this);
                        }
                    }
                    isHandShakeReader = true;
                    // Once we have read the handshake the reader can go away
                    break;
                }
            } catch (CancelException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("{} Terminated <{}> due to cancellation", p2pReaderName(), this, e);
                }
                this.readerShuttingDown = true;
                try {
                    requestClose(LocalizedStrings.Connection_CACHECLOSED_IN_CHANNEL_READ_0.toLocalizedString(e));
                } catch (Exception ex) {
                }
                return;
            } catch (ClosedChannelException e) {
                this.readerShuttingDown = true;
                try {
                    requestClose(LocalizedStrings.Connection_CLOSEDCHANNELEXCEPTION_IN_CHANNEL_READ_0.toLocalizedString(e));
                } catch (Exception ex) {
                }
                return;
            } catch (IOException e) {
                if (// needed for
                !isSocketClosed() && !"Socket closed".equalsIgnoreCase(e.getMessage())) // Solaris jdk
                // 1.4.2_08
                {
                    if (logger.isDebugEnabled() && !isIgnorableIOException(e)) {
                        logger.debug("{} io exception for {}", p2pReaderName(), this, e);
                    }
                    if (e.getMessage().contains("interrupted by a call to WSACancelBlockingCall")) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("{} received unexpected WSACancelBlockingCall exception, which may result in a hang", p2pReaderName());
                        }
                    }
                }
                this.readerShuttingDown = true;
                try {
                    requestClose(LocalizedStrings.Connection_IOEXCEPTION_IN_CHANNEL_READ_0.toLocalizedString(e));
                } catch (Exception ex) {
                }
                return;
            } catch (Exception e) {
                // bug 37101
                this.owner.getConduit().getCancelCriterion().checkCancelInProgress(null);
                if (!stopped && !isSocketClosed()) {
                    logger.fatal(LocalizedMessage.create(LocalizedStrings.Connection_0_EXCEPTION_IN_CHANNEL_READ, p2pReaderName()), e);
                }
                this.readerShuttingDown = true;
                try {
                    requestClose(LocalizedStrings.Connection_0_EXCEPTION_IN_CHANNEL_READ.toLocalizedString(e));
                } catch (Exception ex) {
                }
                return;
            }
        }
    // for
    } finally {
        if (!isHandShakeReader) {
            synchronized (stateLock) {
                connectionState = STATE_IDLE;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("{} runNioReader terminated id={} from {}", p2pReaderName(), conduitIdStr, remoteAddr);
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CancelException(org.apache.geode.CancelException) ByteBuffer(java.nio.ByteBuffer) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) CancelException(org.apache.geode.CancelException) CancelledKeyException(java.nio.channels.CancelledKeyException) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ReplyException(org.apache.geode.distributed.internal.ReplyException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) Socket(java.net.Socket)

Aggregations

CancelException (org.apache.geode.CancelException)135 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)46 IOException (java.io.IOException)40 ReplyException (org.apache.geode.distributed.internal.ReplyException)30 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)25 CacheClosedException (org.apache.geode.cache.CacheClosedException)23 Region (org.apache.geode.cache.Region)22 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)21 LocalRegion (org.apache.geode.internal.cache.LocalRegion)18 Set (java.util.Set)16 Cache (org.apache.geode.cache.Cache)16 CacheException (org.apache.geode.cache.CacheException)16 HashSet (java.util.HashSet)15 Iterator (java.util.Iterator)15 QueryException (org.apache.geode.cache.query.QueryException)15 ArrayList (java.util.ArrayList)13 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)13 QueryInvocationTargetException (org.apache.geode.cache.query.QueryInvocationTargetException)13 DistributedSystemDisconnectedException (org.apache.geode.distributed.DistributedSystemDisconnectedException)13 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)13