Search in sources :

Example 21 with CacheClosedException

use of org.apache.geode.cache.CacheClosedException in project geode by apache.

the class RemoteOperationMessage method process.

/**
   * Upon receipt of the message, both process the message and send an acknowledgement, not
   * necessarily in that order. Note: Any hang in this message may cause a distributed deadlock for
   * those threads waiting for an acknowledgement.
   * 
   * @throws PartitionedRegionException if the region does not exist (typically, if it has been
   *         destroyed)
   */
@Override
public void process(final DistributionManager dm) {
    Throwable thr = null;
    boolean sendReply = true;
    LocalRegion r = null;
    long startTime = 0;
    try {
        if (checkCacheClosing(dm) || checkDSClosing(dm)) {
            thr = new CacheClosedException(LocalizedStrings.PartitionMessage_REMOTE_CACHE_IS_CLOSED_0.toLocalizedString(dm.getId()));
            return;
        }
        InternalCache cache = getCache(dm);
        r = getRegionByPath(cache);
        if (r == null && failIfRegionMissing()) {
            // if the distributed system is disconnecting, don't send a reply saying
            // the partitioned region can't be found (bug 36585)
            thr = new RegionDestroyedException(LocalizedStrings.RemoteOperationMessage_0_COULD_NOT_FIND_REGION_1.toLocalizedString(dm.getDistributionManagerId(), regionPath), regionPath);
            // reply sent in finally block below
            return;
        }
        thr = UNHANDLED_EXCEPTION;
        // [bruce] r might be null here, so we have to go to the cache instance to get the txmgr
        TXManagerImpl txMgr = getTXManager(cache);
        TXStateProxy tx = txMgr.masqueradeAs(this);
        if (tx == null) {
            sendReply = operateOnRegion(dm, r, startTime);
        } else {
            try {
                if (txMgr.isClosed()) {
                    // NO DISTRIBUTED MESSAGING CAN BE DONE HERE!
                    sendReply = false;
                } else if (tx.isInProgress()) {
                    sendReply = operateOnRegion(dm, r, startTime);
                    tx.updateProxyServer(this.getSender());
                }
            } finally {
                txMgr.unmasquerade(tx);
            }
        }
        thr = null;
    } catch (RemoteOperationException fre) {
        thr = fre;
    } catch (DistributedSystemDisconnectedException se) {
        // bug 37026: this is too noisy...
        // throw new CacheClosedException("remote system shutting down");
        // thr = se; cache is closed, no point trying to send a reply
        thr = null;
        sendReply = false;
        if (logger.isDebugEnabled()) {
            logger.debug("shutdown caught, abandoning message: {}", se.getMessage(), se);
        }
    } catch (RegionDestroyedException rde) {
        // [bruce] RDE does not always mean that the sender's region is also
        // destroyed, so we must send back an exception. If the sender's
        // region is also destroyed, who cares if we send it an exception
        // if (pr != null && pr.isClosed) {
        thr = new ForceReattemptException(LocalizedStrings.PartitionMessage_REGION_IS_DESTROYED_IN_0.toLocalizedString(dm.getDistributionManagerId()), rde);
    // }
    } 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();
        // log the exception at fine level if there is no reply to the message
        thr = null;
        if (sendReply) {
            if (!checkDSClosing(dm)) {
                thr = t;
            } else {
                // don't pass arbitrary runtime exceptions and errors back if this
                // cache/vm is closing
                thr = new ForceReattemptException(LocalizedStrings.PartitionMessage_DISTRIBUTED_SYSTEM_IS_DISCONNECTING.toLocalizedString());
            }
        }
        if (logger.isTraceEnabled(LogMarker.DM) && (t instanceof RuntimeException)) {
            logger.trace(LogMarker.DM, "Exception caught while processing message", t);
        }
    } finally {
        if (sendReply) {
            ReplyException rex = null;
            if (thr != null) {
                // don't transmit the exception if this message was to a listener
                // and this listener is shutting down
                rex = new ReplyException(thr);
            }
            // Send the reply if the operateOnPartitionedRegion returned true
            sendReply(getSender(), this.processorId, dm, rex, r, startTime);
        }
    }
}
Also used : DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CacheClosedException(org.apache.geode.cache.CacheClosedException) ReplyException(org.apache.geode.distributed.internal.ReplyException)

Example 22 with CacheClosedException

use of org.apache.geode.cache.CacheClosedException in project geode by apache.

the class TXCommitMessage method fromData.

/*
   * /** Do not send shadowKey to clients or when there are member(s) older than 7.0.1.
   *
   * private boolean shouldSend701Message() { if (this.clientVersion == null &&
   * this.getDM().getMembersWithOlderVersion("7.0.1").isEmpty()) { return true; } return false; }
   * 
   * public boolean shouldReadShadowKey() { return this.shouldReadShadowKey; }
   * 
   * public void setShouldReadShadowKey(boolean shouldReadShadowKey) { this.shouldReadShadowKey =
   * shouldReadShadowKey; }
   * 
   * public boolean shouldWriteShadowKey() { return this.shouldWriteShadowKey; }
   */
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    int pId = in.readInt();
    if (isAckRequired()) {
        this.processorId = pId;
        ReplyProcessor21.setMessageRPId(this.processorId);
    } else {
        this.processorId = -1;
    }
    this.txIdent = TXId.createFromData(in);
    if (in.readBoolean()) {
        this.lockId = TXLockIdImpl.createFromData(in);
    }
    int totalMaxSize = in.readInt();
    this.farsideBaseMembershipId = DataSerializer.readByteArray(in);
    this.farsideBaseThreadId = in.readLong();
    this.farsideBaseSequenceId = in.readLong();
    this.needsLargeModCount = in.readBoolean();
    int regionsSize = in.readInt();
    this.regions = new ArrayList(regionsSize);
    this.farSideEntryOps = new ArrayList(totalMaxSize);
    for (int i = 0; i < regionsSize; i++) {
        RegionCommit rc = new RegionCommit(this);
        try {
            rc.fromData(in);
        } catch (CacheClosedException cce) {
            addProcessingException(cce);
            // return to avoid serialization error being sent in reply
            return;
        }
        this.regions.add(rc);
    }
    this.bridgeContext = ClientProxyMembershipID.readCanonicalized(in);
    this.farSiders = DataSerializer.readHashSet(in);
}
Also used : ArrayList(java.util.ArrayList) CacheClosedException(org.apache.geode.cache.CacheClosedException)

Example 23 with CacheClosedException

use of org.apache.geode.cache.CacheClosedException in project geode by apache.

the class FindRestEnabledServersFunction method execute.

public void execute(FunctionContext context) {
    try {
        InternalCache cache = (InternalCache) CacheFactory.getAnyInstance();
        DistributionConfig config = InternalDistributedSystem.getAnyInstance().getConfig();
        String bindAddress = RestAgent.getBindAddressForHttpService(config);
        final String protocolType = config.getHttpServiceSSLEnabled() ? "https" : "http";
        if (cache.isRESTServiceRunning()) {
            context.getResultSender().lastResult(protocolType + "://" + bindAddress + ":" + config.getHttpServicePort());
        } else {
            context.getResultSender().lastResult("");
        }
    } catch (CacheClosedException ex) {
        context.getResultSender().lastResult("");
    }
}
Also used : DistributionConfig(org.apache.geode.distributed.internal.DistributionConfig) InternalCache(org.apache.geode.internal.cache.InternalCache) CacheClosedException(org.apache.geode.cache.CacheClosedException)

Example 24 with CacheClosedException

use of org.apache.geode.cache.CacheClosedException 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 25 with CacheClosedException

use of org.apache.geode.cache.CacheClosedException in project geode by apache.

the class GemFireCacheImpl method shutDownOnePRGracefully.

private void shutDownOnePRGracefully(PartitionedRegion partitionedRegion) {
    boolean acquiredLock = false;
    try {
        partitionedRegion.acquireDestroyLock();
        acquiredLock = true;
        synchronized (partitionedRegion.getRedundancyProvider()) {
            if (partitionedRegion.isDataStore() && partitionedRegion.getDataStore() != null && partitionedRegion.getDataPolicy() == DataPolicy.PERSISTENT_PARTITION) {
                int numBuckets = partitionedRegion.getTotalNumberOfBuckets();
                Map<InternalDistributedMember, PersistentMemberID>[] bucketMaps = new Map[numBuckets];
                PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore();
                // lock all the primary buckets
                Set<Entry<Integer, BucketRegion>> bucketEntries = dataStore.getAllLocalBuckets();
                for (Entry e : bucketEntries) {
                    BucketRegion bucket = (BucketRegion) e.getValue();
                    if (bucket == null || bucket.isDestroyed) {
                        // bucket region could be destroyed in race condition
                        continue;
                    }
                    bucket.getBucketAdvisor().tryLockIfPrimary();
                    // get map <InternalDistributedMember, persistentID> for this bucket's
                    // remote members
                    bucketMaps[bucket.getId()] = bucket.getBucketAdvisor().adviseInitializedPersistentMembers();
                    if (logger.isDebugEnabled()) {
                        logger.debug("shutDownAll: PR {}: initialized persistent members for {}:{}", partitionedRegion.getName(), bucket.getId(), bucketMaps[bucket.getId()]);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("shutDownAll: All buckets for PR {} are locked.", partitionedRegion.getName());
                }
                // send lock profile update to other members
                partitionedRegion.setShutDownAllStatus(PartitionedRegion.PRIMARY_BUCKETS_LOCKED);
                new UpdateAttributesProcessor(partitionedRegion).distribute(false);
                partitionedRegion.getRegionAdvisor().waitForProfileStatus(PartitionedRegion.PRIMARY_BUCKETS_LOCKED);
                if (logger.isDebugEnabled()) {
                    logger.debug("shutDownAll: PR {}: all bucketLock profiles received.", partitionedRegion.getName());
                }
                // if async write, do flush
                if (!partitionedRegion.getAttributes().isDiskSynchronous()) {
                    // several PRs might share the same diskStore, we will only flush once
                    // even flush is called several times.
                    partitionedRegion.getDiskStore().forceFlush();
                    // send flush profile update to other members
                    partitionedRegion.setShutDownAllStatus(PartitionedRegion.DISK_STORE_FLUSHED);
                    new UpdateAttributesProcessor(partitionedRegion).distribute(false);
                    partitionedRegion.getRegionAdvisor().waitForProfileStatus(PartitionedRegion.DISK_STORE_FLUSHED);
                    if (logger.isDebugEnabled()) {
                        logger.debug("shutDownAll: PR {}: all flush profiles received.", partitionedRegion.getName());
                    }
                }
                // async write
                // persist other members to OFFLINE_EQUAL for each bucket region
                // iterate through all the bucketMaps and exclude the items whose
                // idm is no longer online
                Set<InternalDistributedMember> membersToPersistOfflineEqual = partitionedRegion.getRegionAdvisor().adviseDataStore();
                for (Entry e : bucketEntries) {
                    BucketRegion bucket = (BucketRegion) e.getValue();
                    if (bucket == null || bucket.isDestroyed) {
                        // bucket region could be destroyed in race condition
                        continue;
                    }
                    Map<InternalDistributedMember, PersistentMemberID> persistMap = getSubMapForLiveMembers(membersToPersistOfflineEqual, bucketMaps[bucket.getId()]);
                    if (persistMap != null) {
                        bucket.getPersistenceAdvisor().persistMembersOfflineAndEqual(persistMap);
                        if (logger.isDebugEnabled()) {
                            logger.debug("shutDownAll: PR {}: persisting bucket {}:{}", partitionedRegion.getName(), bucket.getId(), persistMap);
                        }
                    }
                }
                // send persisted profile update to other members, let all members to persist
                // before close the region
                partitionedRegion.setShutDownAllStatus(PartitionedRegion.OFFLINE_EQUAL_PERSISTED);
                new UpdateAttributesProcessor(partitionedRegion).distribute(false);
                partitionedRegion.getRegionAdvisor().waitForProfileStatus(PartitionedRegion.OFFLINE_EQUAL_PERSISTED);
                if (logger.isDebugEnabled()) {
                    logger.debug("shutDownAll: PR {}: all offline_equal profiles received.", partitionedRegion.getName());
                }
            }
            // dataStore
            // after done all steps for buckets, close partitionedRegion
            // close accessor directly
            RegionEventImpl event = new RegionEventImpl(partitionedRegion, Operation.REGION_CLOSE, null, false, getMyId(), true);
            try {
                // not to acquire lock
                partitionedRegion.basicDestroyRegion(event, false, false, true);
            } catch (CacheWriterException e) {
                // not possible with local operation, CacheWriter not called
                throw new Error(LocalizedStrings.LocalRegion_CACHEWRITEREXCEPTION_SHOULD_NOT_BE_THROWN_IN_LOCALDESTROYREGION.toLocalizedString(), e);
            } catch (TimeoutException e) {
                // not possible with local operation, no distributed locks possible
                throw new Error(LocalizedStrings.LocalRegion_TIMEOUTEXCEPTION_SHOULD_NOT_BE_THROWN_IN_LOCALDESTROYREGION.toLocalizedString(), e);
            }
        }
    // synchronized
    } catch (CacheClosedException cce) {
        logger.debug("Encounter CacheClosedException when shutDownAll is closing PR: {}:{}", partitionedRegion.getFullPath(), cce.getMessage());
    } catch (CancelException ce) {
        logger.debug("Encounter CancelException when shutDownAll is closing PR: {}:{}", partitionedRegion.getFullPath(), ce.getMessage());
    } catch (RegionDestroyedException rde) {
        logger.debug("Encounter CacheDestroyedException when shutDownAll is closing PR: {}:{}", partitionedRegion.getFullPath(), rde.getMessage());
    } finally {
        if (acquiredLock) {
            partitionedRegion.releaseDestroyLock();
        }
    }
}
Also used : RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) InternalGemFireError(org.apache.geode.InternalGemFireError) CacheClosedException(org.apache.geode.cache.CacheClosedException) SimpleExtensionPoint(org.apache.geode.internal.cache.extension.SimpleExtensionPoint) ExtensionPoint(org.apache.geode.internal.cache.extension.ExtensionPoint) PersistentMemberID(org.apache.geode.internal.cache.persistence.PersistentMemberID) Entry(java.util.Map.Entry) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CancelException(org.apache.geode.CancelException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) CacheWriterException(org.apache.geode.cache.CacheWriterException) TimeoutException(org.apache.geode.cache.TimeoutException)

Aggregations

CacheClosedException (org.apache.geode.cache.CacheClosedException)95 Cache (org.apache.geode.cache.Cache)26 Test (org.junit.Test)21 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)20 FunctionException (org.apache.geode.cache.execute.FunctionException)20 FunctionInvocationTargetException (org.apache.geode.cache.execute.FunctionInvocationTargetException)20 CancelException (org.apache.geode.CancelException)18 Region (org.apache.geode.cache.Region)18 Host (org.apache.geode.test.dunit.Host)17 VM (org.apache.geode.test.dunit.VM)17 InternalCache (org.apache.geode.internal.cache.InternalCache)16 IgnoredException (org.apache.geode.test.dunit.IgnoredException)16 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)16 DistributedMember (org.apache.geode.distributed.DistributedMember)14 ReplyException (org.apache.geode.distributed.internal.ReplyException)14 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)12 Execution (org.apache.geode.cache.execute.Execution)11 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)11 HashMap (java.util.HashMap)10