Search in sources :

Example 21 with TimeoutException

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

the class GlobalLockingDUnitTest method testLoadLockTimeout.

/**
   * get lock in one VM, try to invoke loader in other
   */
@Test
public void testLoadLockTimeout() {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    final String name = this.getUniqueName();
    final Object key = new Integer(5);
    // In first VM, get a lock on the entry
    vm0.invoke(new CacheSerializableRunnable("Get lock") {

        public void run2() throws CacheException {
            Region r = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
            Lock lock = r.getDistributedLock(key);
            lock.lock();
        }
    });
    // In second VM, do a get that tries to invoke a loader
    vm1.invoke(new CacheSerializableRunnable("Lock timeout local loader") {

        public void run2() throws CacheException {
            getOrCreateRootRegion().getCache().setLockTimeout(2);
            Region r = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
            r.getAttributesMutator().setCacheLoader(new CacheLoader() {

                public Object load(LoaderHelper helper) throws CacheLoaderException {
                    throw new CacheLoaderException("Made it into the loader!");
                }

                public void close() {
                }
            });
            try {
                r.get(key);
                fail("get() should have thrown TimeoutException");
            } catch (TimeoutException ex) {
            // pass
            }
        }
    });
}
Also used : CacheException(org.apache.geode.cache.CacheException) Host(org.apache.geode.test.dunit.Host) Lock(java.util.concurrent.locks.Lock) LoaderHelper(org.apache.geode.cache.LoaderHelper) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region) CacheLoader(org.apache.geode.cache.CacheLoader) TimeoutException(org.apache.geode.cache.TimeoutException) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) DLockTest(org.apache.geode.test.junit.categories.DLockTest)

Example 22 with TimeoutException

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

the class GlobalLockingDUnitTest method testLockGetPut.

/**
   * get the lock, region.get(), region.put(), release lock
   */
@Test
public void testLockGetPut() throws CacheException {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    final String name = this.getUniqueName() + "-GLOBAL";
    final Object key = new Integer(5);
    // First, create region & entry, and lock the entry, in Master VM
    Region r = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
    Lock lock = r.getDistributedLock(key);
    lock.lock();
    r.create(key, "value 1");
    assertEquals("value 1", r.get(key));
    // Now, make sure a locking operation times out in another VM
    vm0.invoke(new CacheSerializableRunnable("Unsuccessful locking operation") {

        public void run2() throws CacheException {
            try {
                getOrCreateRootRegion().getCache().setLockTimeout(2);
                Region r2 = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
                assertEquals("value 1", r2.get(key));
                r2.put(key, "wrong value");
                fail("put() should have thrown TimeoutException");
            } catch (TimeoutException ex) {
            // pass
            }
        }
    });
    // Now, in Master, do another locking operation, then release the lock
    r.put(key, "value 2");
    lock.unlock();
    // Finally, successfully perform a locking in other VM
    vm1.invoke(new CacheSerializableRunnable("Successful locking operation") {

        public void run2() throws CacheException {
            getOrCreateRootRegion().getCache().setLockTimeout(2);
            Region r2 = getOrCreateRootRegion().createSubregion(name, getGlobalAttrs());
            assertEquals("value 2", r2.get(key));
            r2.put(key, "value 3");
        }
    });
    assertEquals("value 3", r.get(key));
}
Also used : CacheException(org.apache.geode.cache.CacheException) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region) Host(org.apache.geode.test.dunit.Host) Lock(java.util.concurrent.locks.Lock) TimeoutException(org.apache.geode.cache.TimeoutException) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest) DLockTest(org.apache.geode.test.junit.categories.DLockTest)

Example 23 with TimeoutException

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

the class CqServiceImpl method stopCq.

/**
   * Called directly on server side.
   */
@Override
public void stopCq(String cqName, ClientProxyMembershipID clientId) throws CqException {
    String serverCqName = cqName;
    if (clientId != null) {
        serverCqName = this.constructServerCqName(cqName, clientId);
        removeFromCacheForServerToConstructedCQName(cqName, clientId);
    }
    ServerCQImpl cQuery = null;
    StringId errMsg = null;
    Exception ex = null;
    try {
        HashMap<String, CqQueryImpl> cqMap = cqQueryMap;
        if (!cqMap.containsKey(serverCqName)) {
            /*
         * gregp 052808: We should silently fail here instead of throwing error. This is to deal
         * with races in recovery
         */
            return;
        }
        cQuery = (ServerCQImpl) getCq(serverCqName);
    } catch (CacheLoaderException e1) {
        errMsg = LocalizedStrings.CqService_CQ_NOT_FOUND_IN_THE_CQ_META_REGION_CQNAME_0;
        ex = e1;
    } catch (TimeoutException e2) {
        errMsg = LocalizedStrings.CqService_TIMEOUT_WHILE_TRYING_TO_GET_CQ_FROM_META_REGION_CQNAME_0;
        ex = e2;
    } finally {
        if (ex != null) {
            String s = errMsg.toLocalizedString(cqName);
            if (logger.isDebugEnabled()) {
                logger.debug(s);
            }
            throw new CqException(s, ex);
        }
    }
    try {
        if (!cQuery.isStopped()) {
            cQuery.stop();
        }
    } catch (CqClosedException cce) {
        throw new CqException(cce.getMessage());
    } finally {
        // If this CQ is stopped, disable caching event keys for this CQ.
        // this.removeCQFromCaching(cQuery.getServerCqName());
        this.removeFromMatchingCqMap(cQuery);
    }
    // Send stop message to peers.
    cQuery.getCqBaseRegion().getFilterProfile().stopCq(cQuery);
}
Also used : StringId(org.apache.geode.i18n.StringId) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) CqException(org.apache.geode.cache.query.CqException) CqClosedException(org.apache.geode.cache.query.CqClosedException) TimeoutException(org.apache.geode.cache.TimeoutException) CqExistsException(org.apache.geode.cache.query.CqExistsException) CqException(org.apache.geode.cache.query.CqException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) InvalidDeltaException(org.apache.geode.InvalidDeltaException) RegionNotFoundException(org.apache.geode.cache.query.RegionNotFoundException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) CqClosedException(org.apache.geode.cache.query.CqClosedException) QueryException(org.apache.geode.cache.query.QueryException) TimeoutException(org.apache.geode.cache.TimeoutException)

Example 24 with TimeoutException

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

the class DirectChannel method handleAckTimeout.

/**
   * 
   * @param ackTimeout ack wait threshold
   * @param ackSATimeout severe alert threshold
   * @param c
   * @param processor
   * @throws ConnectionException
   */
private void handleAckTimeout(long ackTimeout, long ackSATimeout, Connection c, DirectReplyProcessor processor) throws ConnectionException {
    DM dm = getDM();
    Set activeMembers = dm.getDistributionManagerIds();
    // Increment the stat
    dm.getStats().incReplyTimeouts();
    // an alert that will show up in the console
    {
        final StringId msg = LocalizedStrings.DirectChannel_0_SECONDS_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLY_FROM_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3;
        final Object[] msgArgs = new Object[] { Long.valueOf(ackTimeout / 1000), c.getRemoteAddress(), dm.getId(), activeMembers };
        logger.warn(LocalizedMessage.create(msg, msgArgs));
        msgArgs[3] = "(omitted)";
        Breadcrumbs.setProblem(msg, msgArgs);
        if (ReplyProcessor21.THROW_EXCEPTION_ON_TIMEOUT) {
            // init the cause to be a TimeoutException so catchers can determine cause
            TimeoutException cause = new TimeoutException(LocalizedStrings.TIMED_OUT_WAITING_FOR_ACKS.toLocalizedString());
            throw new InternalGemFireException(msg.toLocalizedString(msgArgs), cause);
        }
    }
    if (activeMembers.contains(c.getRemoteAddress())) {
        // wait for ack-severe-alert-threshold period first, then wait forever
        if (ackSATimeout > 0) {
            try {
                c.readAck((int) ackSATimeout, ackSATimeout, processor);
                return;
            } catch (SocketTimeoutException e) {
                Object[] args = new Object[] { Long.valueOf((ackSATimeout + ackTimeout) / 1000), c.getRemoteAddress(), dm.getId(), activeMembers };
                logger.fatal(LocalizedMessage.create(LocalizedStrings.DirectChannel_0_SECONDS_HAVE_ELAPSED_WHILE_WAITING_FOR_REPLY_FROM_1_ON_2_WHOSE_CURRENT_MEMBERSHIP_LIST_IS_3, args));
            }
        }
        try {
            c.readAck(0, 0, processor);
        } catch (SocketTimeoutException ex) {
            // this can never happen when called with timeout of 0
            logger.error(LocalizedMessage.create(LocalizedStrings.DirectChannel_UNEXPECTED_TIMEOUT_WHILE_WAITING_FOR_ACK_FROM__0, c.getRemoteAddress()), ex);
        }
    } else {
        logger.warn(LocalizedMessage.create(LocalizedStrings.DirectChannel_VIEW_NO_LONGER_HAS_0_AS_AN_ACTIVE_MEMBER_SO_WE_WILL_NO_LONGER_WAIT_FOR_IT, c.getRemoteAddress()));
        processor.memberDeparted(c.getRemoteAddress(), true);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) StringId(org.apache.geode.i18n.StringId) TimeoutException(org.apache.geode.cache.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 25 with TimeoutException

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

the class PartitionedRegion method destroyInBucket.

/**
   * @param expectedOldValue only succeed if current value is equal to expectedOldValue
   * @throws EntryNotFoundException if entry not found or if expectedOldValue not null and current
   *         value was not equal to expectedOldValue
   */
public void destroyInBucket(final EntryEventImpl event, Object expectedOldValue) throws EntryNotFoundException, CacheWriterException {
    // Get the bucket id for the key
    final Integer bucketId = event.getKeyInfo().getBucketId();
    assert bucketId != KeyInfo.UNKNOWN_BUCKET;
    // check in bucket2Node region
    final InternalDistributedMember targetNode = getOrCreateNodeForBucketWrite(bucketId, null);
    if (logger.isDebugEnabled()) {
        logger.debug("destroyInBucket: key={} ({}) in node {} to bucketId={} retry={} ms", event.getKey(), event.getKey().hashCode(), targetNode, bucketStringForLogs(bucketId), retryTimeout);
    }
    // retry the put remotely until it finds the right node managing the bucket
    RetryTimeKeeper retryTime = null;
    InternalDistributedMember currentTarget = targetNode;
    long timeOut = 0;
    int count = 0;
    for (; ; ) {
        switch(count) {
            case 0:
                // First time, keep going
                break;
            case 1:
                // First failure
                this.cache.getCancelCriterion().checkCancelInProgress(null);
                timeOut = System.currentTimeMillis() + this.retryTimeout;
                break;
            default:
                this.cache.getCancelCriterion().checkCancelInProgress(null);
                // test for timeout
                long timeLeft = timeOut - System.currentTimeMillis();
                if (timeLeft < 0) {
                    PRHARedundancyProvider.timedOut(this, null, null, "destroy an entry", this.retryTimeout);
                // NOTREACHED
                }
                // Didn't time out. Sleep a bit and then continue
                boolean interrupted = Thread.interrupted();
                try {
                    Thread.sleep(PartitionedRegionHelper.DEFAULT_WAIT_PER_RETRY_ITERATION);
                } catch (InterruptedException ignore) {
                    interrupted = true;
                } finally {
                    if (interrupted) {
                        Thread.currentThread().interrupt();
                    }
                }
                break;
        }
        count++;
        if (currentTarget == null) {
            // pick target
            checkReadiness();
            if (retryTime == null) {
                retryTime = new RetryTimeKeeper(this.retryTimeout);
            }
            if (retryTime.overMaximum()) {
                // }
                if (getRegionAdvisor().getBucket(bucketId).getBucketAdvisor().basicGetPrimaryMember() == null) {
                    throw new EntryNotFoundException(LocalizedStrings.PartitionedRegion_ENTRY_NOT_FOUND_FOR_KEY_0.toLocalizedString(event.getKey()));
                }
                TimeoutException e = new TimeoutException(LocalizedStrings.PartitionedRegion_TIME_OUT_LOOKING_FOR_TARGET_NODE_FOR_DESTROY_WAITED_0_MS.toLocalizedString(retryTime.getRetryTime()));
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                }
                checkReadiness();
                throw e;
            }
            currentTarget = getOrCreateNodeForBucketWrite(bucketId, retryTime);
            // No storage found for bucket, early out preventing hot loop, bug 36819
            if (currentTarget == null) {
                checkEntryNotFound(event.getKey());
            }
            continue;
        }
        // pick target
        final boolean isLocal = (this.localMaxMemory > 0) && currentTarget.equals(getMyId());
        try {
            DistributedRemoveAllOperation savedOp = event.setRemoveAllOperation(null);
            if (savedOp != null) {
                savedOp.addEntry(event, bucketId);
                return;
            }
            if (isLocal) {
                // doCacheWriteBeforeDestroy(event);
                event.setInvokePRCallbacks(true);
                this.dataStore.destroyLocally(bucketId, event, expectedOldValue);
            } else {
                if (event.isBridgeEvent()) {
                    setNetworkHopType(bucketId, currentTarget);
                }
                destroyRemotely(currentTarget, bucketId, event, expectedOldValue);
            }
            return;
        // NOTREACHED (success)
        } catch (ConcurrentCacheModificationException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("destroyInBucket: caught concurrent cache modification exception", e);
            }
            event.isConcurrencyConflict(true);
            if (logger.isTraceEnabled()) {
                logger.trace("ConcurrentCacheModificationException received for destroyInBucket for bucketId: {}{}{} for event: {} No reattempt is done, returning from here", getPRId(), BUCKET_ID_SEPARATOR, bucketId, event);
            }
            return;
        } catch (ForceReattemptException e) {
            e.checkKey(event.getKey());
            // We don't know if the destroy took place or not at this point.
            // Assume that if the next destroy throws EntryDestroyedException, the
            // previous destroy attempt was a success
            checkReadiness();
            InternalDistributedMember lastNode = currentTarget;
            if (retryTime == null) {
                retryTime = new RetryTimeKeeper(this.retryTimeout);
            }
            currentTarget = getOrCreateNodeForBucketWrite(bucketId, retryTime);
            event.setPossibleDuplicate(true);
            if (lastNode.equals(currentTarget)) {
                if (retryTime.overMaximum()) {
                    PRHARedundancyProvider.timedOut(this, null, null, "destroy an entry", retryTime.getRetryTime());
                }
                retryTime.waitToRetryNode();
            }
        } catch (PrimaryBucketException notPrimary) {
            if (logger.isDebugEnabled()) {
                logger.debug("destroyInBucket: {} on Node {} not primary", notPrimary.getLocalizedMessage(), currentTarget);
            }
            getRegionAdvisor().notPrimary(bucketId, currentTarget);
            if (retryTime == null) {
                retryTime = new RetryTimeKeeper(this.retryTimeout);
            }
            currentTarget = getOrCreateNodeForBucketWrite(bucketId, retryTime);
        }
        // If we get here, the attempt failed.
        if (count == 1) {
            this.prStats.incDestroyOpsRetried();
        }
        this.prStats.incDestroyRetries();
        if (logger.isDebugEnabled()) {
            logger.debug("destroyInBucket: Attempting to resend destroy to node {} after {} failed attempts", currentTarget, count);
        }
    }
// for
}
Also used : ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) TimeoutException(org.apache.geode.cache.TimeoutException)

Aggregations

TimeoutException (org.apache.geode.cache.TimeoutException)48 Test (org.junit.Test)24 CacheException (org.apache.geode.cache.CacheException)22 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)21 Host (org.apache.geode.test.dunit.Host)20 VM (org.apache.geode.test.dunit.VM)20 Region (org.apache.geode.cache.Region)18 AttributesFactory (org.apache.geode.cache.AttributesFactory)17 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)14 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)13 CacheWriterException (org.apache.geode.cache.CacheWriterException)10 LoaderHelper (org.apache.geode.cache.LoaderHelper)10 Lock (java.util.concurrent.locks.Lock)8 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)6 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)6 DLockTest (org.apache.geode.test.junit.categories.DLockTest)6 IOException (java.io.IOException)5 InternalGemFireError (org.apache.geode.InternalGemFireError)5 CacheWriter (org.apache.geode.cache.CacheWriter)5 StringId (org.apache.geode.i18n.StringId)5