use of org.apache.geode.cache.EntryNotFoundException in project geode by apache.
the class Destroy65 method cmdExecute.
@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
Part regionNamePart;
Part keyPart;
Part callbackArgPart;
Part eventPart;
Part expectedOldValuePart;
Object operation = null;
Object expectedOldValue = null;
String regionName = null;
Object callbackArg = null, key = null;
StringBuffer errMessage = new StringBuffer();
CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
CacheServerStats stats = serverConnection.getCacheServerStats();
serverConnection.setAsTrue(REQUIRES_RESPONSE);
long now = DistributionStats.getStatTime();
stats.incReadDestroyRequestTime(now - start);
// Retrieve the data from the message parts
regionNamePart = clientMessage.getPart(0);
keyPart = clientMessage.getPart(1);
expectedOldValuePart = clientMessage.getPart(2);
try {
operation = clientMessage.getPart(3).getObject();
if (((operation instanceof Operation) && ((Operation) operation == Operation.REMOVE)) || ((operation instanceof Byte) && (Byte) operation == OpType.DESTROY)) {
expectedOldValue = expectedOldValuePart.getObject();
}
} catch (Exception e) {
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
eventPart = clientMessage.getPart(4);
if (clientMessage.getNumberOfParts() > 5) {
callbackArgPart = clientMessage.getPart(5);
try {
callbackArg = callbackArgPart.getObject();
} catch (Exception e) {
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
}
regionName = regionNamePart.getString();
try {
key = keyPart.getStringOrObject();
} catch (Exception e) {
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("{}: Received destroy65 request ({} bytes; op={}) from {} for region {} key {}{} txId {}", serverConnection.getName(), clientMessage.getPayloadLength(), operation, serverConnection.getSocketString(), regionName, key, (operation == Operation.REMOVE ? " value=" + expectedOldValue : ""), clientMessage.getTransactionId());
}
boolean entryNotFoundForRemove = false;
// Process the destroy request
if (key == null || regionName == null) {
if (key == null) {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_THE_INPUT_KEY_FOR_THE_DESTROY_REQUEST_IS_NULL, serverConnection.getName()));
errMessage.append(LocalizedStrings.Destroy__THE_INPUT_KEY_FOR_THE_DESTROY_REQUEST_IS_NULL.toLocalizedString());
}
if (regionName == null) {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_THE_INPUT_REGION_NAME_FOR_THE_DESTROY_REQUEST_IS_NULL, serverConnection.getName()));
errMessage.append(LocalizedStrings.Destroy__THE_INPUT_REGION_NAME_FOR_THE_DESTROY_REQUEST_IS_NULL.toLocalizedString());
}
writeErrorResponse(clientMessage, MessageType.DESTROY_DATA_ERROR, errMessage.toString(), serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
if (region == null) {
String reason = LocalizedStrings.Destroy__0_WAS_NOT_FOUND_DURING_DESTROY_REQUEST.toLocalizedString(regionName);
writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
// Destroy the entry
ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
EventIDHolder clientEvent = new EventIDHolder(eventId);
Breadcrumbs.setEventId(eventId);
// msg.isRetry might be set by v7.0 and later clients
if (clientMessage.isRetry()) {
// if (logger.isDebugEnabled()) {
// logger.debug("DEBUG: encountered isRetry in Destroy65");
// }
clientEvent.setPossibleDuplicate(true);
if (region.getAttributes().getConcurrencyChecksEnabled()) {
// recover the version tag from other servers
clientEvent.setRegion(region);
if (!recoverVersionTagForRetriedOperation(clientEvent)) {
// no-one has seen this event
clientEvent.setPossibleDuplicate(false);
}
}
}
try {
// for integrated security
this.securityService.authorizeRegionWrite(regionName, key.toString());
AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
if (authzRequest != null) {
if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
RegionDestroyOperationContext destroyContext = authzRequest.destroyRegionAuthorize((String) key, callbackArg);
callbackArg = destroyContext.getCallbackArg();
} else {
DestroyOperationContext destroyContext = authzRequest.destroyAuthorize(regionName, key, callbackArg);
callbackArg = destroyContext.getCallbackArg();
}
}
if (operation == null || operation == Operation.DESTROY) {
region.basicBridgeDestroy(key, callbackArg, serverConnection.getProxyID(), true, clientEvent);
} else {
// this throws exceptions if expectedOldValue checks fail
try {
if (expectedOldValue == null) {
expectedOldValue = Token.INVALID;
}
if (operation == Operation.REMOVE && clientMessage.isRetry() && clientEvent.getVersionTag() != null) {
// success status
if (logger.isDebugEnabled()) {
logger.debug("remove(k,v) operation was successful last time with version {}", clientEvent.getVersionTag());
}
// try the operation anyway to ensure that it's been distributed to all servers
try {
region.basicBridgeRemove(key, expectedOldValue, callbackArg, serverConnection.getProxyID(), true, clientEvent);
} catch (EntryNotFoundException e) {
// ignore, and don't set entryNotFoundForRemove because this was a successful
// operation - bug #51664
}
} else {
region.basicBridgeRemove(key, expectedOldValue, callbackArg, serverConnection.getProxyID(), true, clientEvent);
if (logger.isDebugEnabled()) {
logger.debug("region.remove succeeded");
}
}
} catch (EntryNotFoundException e) {
serverConnection.setModificationInfo(true, regionName, key);
if (logger.isDebugEnabled()) {
logger.debug("writing entryNotFound response");
}
entryNotFoundForRemove = true;
}
}
serverConnection.setModificationInfo(true, regionName, key);
} catch (EntryNotFoundException e) {
// Don't send an exception back to the client if this
// exception happens. Just log it and continue.
logger.info(LocalizedMessage.create(LocalizedStrings.Destroy_0_DURING_ENTRY_DESTROY_NO_ENTRY_WAS_FOUND_FOR_KEY_1, new Object[] { serverConnection.getName(), key }));
entryNotFoundForRemove = true;
} catch (RegionDestroyedException rde) {
writeException(clientMessage, rde, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
} catch (Exception e) {
// If an interrupted exception is thrown , rethrow it
checkForInterrupt(serverConnection, e);
// If an exception occurs during the destroy, preserve the connection
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
if (e instanceof GemFireSecurityException) {
// logged by the security logger
if (logger.isDebugEnabled()) {
logger.debug("{}: Unexpected Security exception", serverConnection.getName(), e);
}
} else {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), e);
}
return;
}
// Update the statistics and write the reply
now = DistributionStats.getStatTime();
stats.incProcessDestroyTime(now - start);
if (region instanceof PartitionedRegion) {
PartitionedRegion pr = (PartitionedRegion) region;
if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, entryNotFoundForRemove, pr.getNetworkHopType(), clientEvent.getVersionTag());
pr.clearNetworkHopData();
} else {
writeReply(clientMessage, serverConnection, entryNotFoundForRemove | clientEvent.getIsRedestroyedEntry(), clientEvent.getVersionTag());
}
} else {
writeReply(clientMessage, serverConnection, entryNotFoundForRemove | clientEvent.getIsRedestroyedEntry(), clientEvent.getVersionTag());
}
serverConnection.setAsTrue(RESPONDED);
if (logger.isDebugEnabled()) {
logger.debug("{}: Sent destroy response for region {} key {}", serverConnection.getName(), regionName, key);
}
stats.incWriteDestroyResponseTime(DistributionStats.getStatTime() - start);
}
use of org.apache.geode.cache.EntryNotFoundException in project geode by apache.
the class Destroy method cmdExecute.
@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long startparam) throws IOException, InterruptedException {
long start = startparam;
Part regionNamePart = null, keyPart = null, callbackArgPart = null;
String regionName = null;
Object callbackArg = null, key = null;
Part eventPart = null;
StringBuffer errMessage = new StringBuffer();
CacheServerStats stats = serverConnection.getCacheServerStats();
serverConnection.setAsTrue(REQUIRES_RESPONSE);
{
long oldStart = start;
start = DistributionStats.getStatTime();
stats.incReadDestroyRequestTime(start - oldStart);
}
// Retrieve the data from the message parts
regionNamePart = clientMessage.getPart(0);
keyPart = clientMessage.getPart(1);
eventPart = clientMessage.getPart(2);
// callbackArgPart = null; (redundant assignment)
if (clientMessage.getNumberOfParts() > 3) {
callbackArgPart = clientMessage.getPart(3);
try {
callbackArg = callbackArgPart.getObject();
} catch (Exception e) {
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
}
regionName = regionNamePart.getString();
try {
key = keyPart.getStringOrObject();
} catch (Exception e) {
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("{}: Received destroy request ({} bytes) from {} for region {} key {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key);
}
// Process the destroy request
if (key == null || regionName == null) {
if (key == null) {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_THE_INPUT_KEY_FOR_THE_DESTROY_REQUEST_IS_NULL, serverConnection.getName()));
errMessage.append(LocalizedStrings.Destroy__THE_INPUT_KEY_FOR_THE_DESTROY_REQUEST_IS_NULL.toLocalizedString());
}
if (regionName == null) {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_THE_INPUT_REGION_NAME_FOR_THE_DESTROY_REQUEST_IS_NULL, serverConnection.getName()));
errMessage.append(LocalizedStrings.Destroy__THE_INPUT_REGION_NAME_FOR_THE_DESTROY_REQUEST_IS_NULL.toLocalizedString());
}
writeErrorResponse(clientMessage, MessageType.DESTROY_DATA_ERROR, errMessage.toString(), serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
if (region == null) {
String reason = LocalizedStrings.Destroy__0_WAS_NOT_FOUND_DURING_DESTROY_REQUEST.toLocalizedString(regionName);
writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
// Destroy the entry
ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
try {
// for integrated security
this.securityService.authorizeRegionWrite(regionName, key.toString());
AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
if (authzRequest != null) {
if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
RegionDestroyOperationContext destroyContext = authzRequest.destroyRegionAuthorize((String) key, callbackArg);
callbackArg = destroyContext.getCallbackArg();
} else {
DestroyOperationContext destroyContext = authzRequest.destroyAuthorize(regionName, key, callbackArg);
callbackArg = destroyContext.getCallbackArg();
}
}
region.basicBridgeDestroy(key, callbackArg, serverConnection.getProxyID(), true, new EventIDHolder(eventId));
serverConnection.setModificationInfo(true, regionName, key);
} catch (EntryNotFoundException e) {
// Don't send an exception back to the client if this
// exception happens. Just log it and continue.
logger.info(LocalizedMessage.create(LocalizedStrings.Destroy_0_DURING_ENTRY_DESTROY_NO_ENTRY_WAS_FOUND_FOR_KEY_1, new Object[] { serverConnection.getName(), key }));
} catch (RegionDestroyedException rde) {
writeException(clientMessage, rde, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
} catch (Exception e) {
// If an interrupted exception is thrown , rethrow it
checkForInterrupt(serverConnection, e);
// If an exception occurs during the destroy, preserve the connection
writeException(clientMessage, e, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
if (e instanceof GemFireSecurityException) {
// logged by the security logger
if (logger.isDebugEnabled()) {
logger.debug("{}: Unexpected Security exception", serverConnection.getName(), e);
}
} else {
logger.warn(LocalizedMessage.create(LocalizedStrings.Destroy_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), e);
}
return;
}
// Update the statistics and write the reply
{
long oldStart = start;
start = DistributionStats.getStatTime();
stats.incProcessDestroyTime(start - oldStart);
}
if (region instanceof PartitionedRegion) {
PartitionedRegion pr = (PartitionedRegion) region;
if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, pr.getNetworkHopType());
pr.clearNetworkHopData();
} else {
writeReply(clientMessage, serverConnection);
}
} else {
writeReply(clientMessage, serverConnection);
}
serverConnection.setAsTrue(RESPONDED);
if (logger.isDebugEnabled()) {
logger.debug("{}: Sent destroy response for region {} key {}", serverConnection.getName(), regionName, key);
}
stats.incWriteDestroyResponseTime(DistributionStats.getStatTime() - start);
}
use of org.apache.geode.cache.EntryNotFoundException in project geode by apache.
the class PRQueryDUnitHelper method getCacheSerializableRunnableForPRRandomOps.
/**
* This function puts portfolio objects into the created Region (PR or RR). Also, other operation
* like, invalidate, destroy and create are performed in random manner based on
* {@link Random#nextInt(int)}.
*
* @param regionName
* @param to
* @param from
* @return cacheSerializable object
*/
public CacheSerializableRunnable getCacheSerializableRunnableForPRRandomOps(final String regionName, final int from, final int to) {
SerializableRunnable prPuts = new CacheSerializableRunnable("PRPuts") {
@Override
public void run2() throws CacheException {
Cache cache = getCache();
Region region = cache.getRegion(regionName);
for (int i = 0; i < 3; i++) {
for (int j = from; j < to; j++) {
int op = new Random().nextInt(4);
try {
switch(op) {
case 0:
// Put operation
region.put(new Integer(j), new Portfolio(j));
break;
case 1:
// invalidate
if (region.containsKey(new Integer(j))) {
region.invalidate(new Integer(j));
}
break;
case 2:
if (region.containsKey(new Integer(j))) {
region.destroy(new Integer(j));
}
break;
case 3:
if (!region.containsKey(new Integer(j))) {
region.create(new Integer(j), null);
}
break;
default:
break;
}
} catch (EntryExistsException e) {
// Do nothing let it go
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("EntryExistsException was thrown for key " + j);
} catch (EntryNotFoundException e) {
// Do nothing let it go
org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("EntryNotFoundException was thrown for key " + j);
}
}
}
}
};
return (CacheSerializableRunnable) prPuts;
}
use of org.apache.geode.cache.EntryNotFoundException in project geode by apache.
the class AbstractRegionMap method destroy.
public boolean destroy(EntryEventImpl event, boolean inTokenMode, boolean duringRI, boolean cacheWrite, boolean isEviction, Object expectedOldValue, boolean removeRecoveredEntry) throws CacheWriterException, EntryNotFoundException, TimeoutException {
final LocalRegion owner = _getOwner();
if (owner == null) {
Assert.assertTrue(false, // "fix" for bug 32440
"The owner for RegionMap " + this + " is null for event " + event);
}
boolean retry = true;
lockForCacheModification(owner, event);
try {
while (retry) {
retry = false;
boolean opCompleted = false;
boolean doPart3 = false;
// We need to acquire the region entry while holding the lock to avoid #45620.
// The outer try/finally ensures that the lock will be released without fail.
// I'm avoiding indenting just to preserve the ability
// to track diffs since the code is fairly complex.
RegionEntry re = getOrCreateRegionEntry(owner, event, Token.REMOVED_PHASE1, null, true, true);
RegionEntry tombstone = null;
boolean haveTombstone = false;
/*
* Execute the test hook runnable inline (not threaded) if it is not null.
*/
if (null != testHookRunnableFor48182) {
testHookRunnableFor48182.run();
}
try {
if (logger.isTraceEnabled(LogMarker.LRU_TOMBSTONE_COUNT) && !(owner instanceof HARegion)) {
logger.trace(LogMarker.LRU_TOMBSTONE_COUNT, "ARM.destroy() inTokenMode={}; duringRI={}; riLocalDestroy={}; withRepl={}; fromServer={}; concurrencyEnabled={}; isOriginRemote={}; isEviction={}; operation={}; re={}", inTokenMode, duringRI, event.isFromRILocalDestroy(), owner.dataPolicy.withReplication(), event.isFromServer(), owner.concurrencyChecksEnabled, event.isOriginRemote(), isEviction, event.getOperation(), re);
}
if (event.isFromRILocalDestroy()) {
// for RI local-destroy we don't want to keep tombstones.
// In order to simplify things we just set this recovery
// flag to true to force the entry to be removed
removeRecoveredEntry = true;
}
// for a tombstone here and, if found, pretend for a bit that the entry is null
if (re != null && re.isTombstone() && !removeRecoveredEntry) {
tombstone = re;
haveTombstone = true;
re = null;
}
IndexManager oqlIndexManager = owner.getIndexManager();
if (re == null) {
// we need to create an entry if in token mode or if we've received
// a destroy from a peer or WAN gateway and we need to retain version
// information for concurrency checks
boolean retainForConcurrency = (!haveTombstone && (owner.dataPolicy.withReplication() || event.isFromServer()) && owner.concurrencyChecksEnabled && (event.isOriginRemote() || /* destroy received from other must create tombstone */
event.isFromWANAndVersioned() || /* wan event must create a tombstone */
event.isBridgeEvent()));
/*
* event from client must create a tombstone so
* client has a version #
*/
if (inTokenMode || retainForConcurrency) {
// removeRecoveredEntry should be false in this case
RegionEntry newRe = getEntryFactory().createEntry(owner, event.getKey(), Token.REMOVED_PHASE1);
// happened in parallel as it also does index INIT.
if (oqlIndexManager != null) {
oqlIndexManager.waitForIndexInit();
}
try {
synchronized (newRe) {
RegionEntry oldRe = putEntryIfAbsent(event.getKey(), newRe);
while (!opCompleted && oldRe != null) {
synchronized (oldRe) {
if (oldRe.isRemovedPhase2()) {
owner.getCachePerfStats().incRetries();
_getMap().remove(event.getKey(), oldRe);
oldRe = putEntryIfAbsent(event.getKey(), newRe);
} else {
event.setRegionEntry(oldRe);
// is being added to transaction state.
if (isEviction) {
if (!confirmEvictionDestroy(oldRe)) {
opCompleted = false;
return opCompleted;
}
}
try {
// if concurrency checks are enabled, destroy will
// set the version tag
boolean destroyed = destroyEntry(oldRe, event, inTokenMode, cacheWrite, expectedOldValue, false, removeRecoveredEntry);
if (destroyed) {
if (retainForConcurrency) {
owner.basicDestroyBeforeRemoval(oldRe, event);
}
owner.basicDestroyPart2(oldRe, event, inTokenMode, false, /* conflict with clear */
duringRI, true);
lruEntryDestroy(oldRe);
doPart3 = true;
}
} catch (RegionClearedException rce) {
// Ignore. The exception will ensure that we do not update
// the LRU List
owner.basicDestroyPart2(oldRe, event, inTokenMode, true, /* conflict with clear */
duringRI, true);
doPart3 = true;
} catch (ConcurrentCacheModificationException ccme) {
VersionTag tag = event.getVersionTag();
if (tag != null && tag.isTimeStampUpdated()) {
// Notify gateways of new time-stamp.
owner.notifyTimestampsToGateways(event);
}
throw ccme;
}
re = oldRe;
opCompleted = true;
}
}
// synchronized oldRe
}
// while
if (!opCompleted) {
// happens if we didn't get completed with oldRe in the above while loop.
try {
re = newRe;
event.setRegionEntry(newRe);
try {
// set the version tag
if (isEviction) {
opCompleted = false;
return opCompleted;
}
opCompleted = destroyEntry(newRe, event, inTokenMode, cacheWrite, expectedOldValue, true, removeRecoveredEntry);
if (opCompleted) {
// This is a new entry that was created because we are in
// token mode or are accepting a destroy operation by adding
// a tombstone. There is no oldValue, so we don't need to
// call updateSizeOnRemove
// owner.recordEvent(event);
// native clients need to know if the
event.setIsRedestroyedEntry(true);
// entry didn't exist
if (retainForConcurrency) {
owner.basicDestroyBeforeRemoval(oldRe, event);
}
owner.basicDestroyPart2(newRe, event, inTokenMode, false, /* conflict with clear */
duringRI, true);
doPart3 = true;
}
} catch (RegionClearedException rce) {
// Ignore. The exception will ensure that we do not update
// the LRU List
opCompleted = true;
EntryLogger.logDestroy(event);
owner.basicDestroyPart2(newRe, event, inTokenMode, true, /* conflict with clear */
duringRI, true);
doPart3 = true;
} catch (ConcurrentCacheModificationException ccme) {
VersionTag tag = event.getVersionTag();
if (tag != null && tag.isTimeStampUpdated()) {
// Notify gateways of new time-stamp.
owner.notifyTimestampsToGateways(event);
}
throw ccme;
}
// Note no need for LRU work since the entry is destroyed
// and will be removed when gii completes
} finally {
if (!opCompleted && !haveTombstone) /* to fix bug 51583 do this for all operations */
{
removeEntry(event.getKey(), newRe, false);
}
if (!opCompleted && isEviction) {
removeEntry(event.getKey(), newRe, false);
}
}
}
// !opCompleted
}
// synchronized newRe
} finally {
if (oqlIndexManager != null) {
oqlIndexManager.countDownIndexUpdaters();
}
}
} else // inTokenMode or tombstone creation
{
if (!isEviction || owner.concurrencyChecksEnabled) {
// The following ensures that there is not a concurrent operation
// on the entry and leaves behind a tombstone if concurrencyChecksEnabled.
// It fixes bug #32467 by propagating the destroy to the server even though
// the entry isn't in the client
RegionEntry newRe = haveTombstone ? tombstone : getEntryFactory().createEntry(owner, event.getKey(), Token.REMOVED_PHASE1);
synchronized (newRe) {
if (haveTombstone && !tombstone.isTombstone()) {
// we have to check this again under synchronization since it may have changed
retry = true;
// retryEntry = tombstone; // leave this in place for debugging
continue;
}
re = (RegionEntry) _getMap().putIfAbsent(event.getKey(), newRe);
if (re != null && re != tombstone) {
// concurrent change - try again
retry = true;
// retryEntry = tombstone; // leave this in place for debugging
continue;
} else if (!isEviction) {
boolean throwex = false;
EntryNotFoundException ex = null;
try {
if (!cacheWrite) {
throwex = true;
} else {
try {
if (!removeRecoveredEntry) {
throwex = !owner.bridgeWriteBeforeDestroy(event, expectedOldValue);
}
} catch (EntryNotFoundException e) {
throwex = true;
ex = e;
}
}
if (throwex) {
if (!event.isOriginRemote() && !event.getOperation().isLocal() && (// if this is a replayed client
event.isFromBridgeAndVersioned() || // version
event.isFromWANAndVersioned())) {
// in peers
if (logger.isDebugEnabled()) {
logger.debug("ARM.destroy is allowing wan/client destroy of {} to continue", event.getKey());
}
throwex = false;
event.setIsRedestroyedEntry(true);
// distributing this destroy op.
if (re == null) {
re = newRe;
}
doPart3 = true;
}
}
if (throwex) {
if (ex == null) {
// Fix for 48182, check cache state and/or region state before sending
// entry not found.
// this is from the server and any exceptions will propogate to the client
owner.checkEntryNotFound(event.getKey());
} else {
throw ex;
}
}
} finally {
// either remove the entry or leave a tombstone
try {
if (!event.isOriginRemote() && event.getVersionTag() != null && owner.concurrencyChecksEnabled) {
// this shouldn't fail since we just created the entry.
// it will either generate a tag or apply a server's version tag
processVersionTag(newRe, event);
if (doPart3) {
owner.generateAndSetVersionTag(event, newRe);
}
try {
owner.recordEvent(event);
newRe.makeTombstone(owner, event.getVersionTag());
} catch (RegionClearedException e) {
// that's okay - when writing a tombstone into a disk, the
// region has been cleared (including this tombstone)
}
opCompleted = true;
// lruEntryCreate(newRe);
} else if (!haveTombstone) {
try {
assert newRe != tombstone;
newRe.setValue(owner, Token.REMOVED_PHASE2);
removeEntry(event.getKey(), newRe, false);
} catch (RegionClearedException e) {
// that's okay - we just need to remove the new entry
}
} else if (event.getVersionTag() != null) {
// haveTombstone - update the
// tombstone version info
processVersionTag(tombstone, event);
if (doPart3) {
owner.generateAndSetVersionTag(event, newRe);
}
// version tag
try {
tombstone.setValue(owner, Token.TOMBSTONE);
} catch (RegionClearedException e) {
// that's okay - when writing a tombstone into a disk, the
// region has been cleared (including this tombstone)
}
owner.recordEvent(event);
owner.rescheduleTombstone(tombstone, event.getVersionTag());
owner.basicDestroyPart2(tombstone, event, inTokenMode, true, /* conflict with clear */
duringRI, true);
opCompleted = true;
}
} catch (ConcurrentCacheModificationException ccme) {
VersionTag tag = event.getVersionTag();
if (tag != null && tag.isTimeStampUpdated()) {
// Notify gateways of new time-stamp.
owner.notifyTimestampsToGateways(event);
}
throw ccme;
}
}
}
}
// synchronized(newRe)
}
}
} else // no current entry
{
// current entry exists
if (oqlIndexManager != null) {
oqlIndexManager.waitForIndexInit();
}
try {
synchronized (re) {
// if the entry is a tombstone and the event is from a peer or a client
// then we allow the operation to be performed so that we can update the
// version stamp. Otherwise we would retain an old version stamp and may allow
// an operation that is older than the destroy() to be applied to the cache
// Bug 45170: If removeRecoveredEntry, we treat tombstone as regular entry to be
// deleted
boolean createTombstoneForConflictChecks = (owner.concurrencyChecksEnabled && (event.isOriginRemote() || event.getContext() != null || removeRecoveredEntry));
if (!re.isRemoved() || createTombstoneForConflictChecks) {
if (re.isRemovedPhase2()) {
_getMap().remove(event.getKey(), re);
owner.getCachePerfStats().incRetries();
retry = true;
continue;
}
if (!event.isOriginRemote() && event.getOperation().isExpiration()) {
// used by a tx.
if (re.isInUseByTransaction()) {
opCompleted = false;
return opCompleted;
}
}
event.setRegionEntry(re);
// See comment above about eviction checks
if (isEviction) {
assert expectedOldValue == null;
if (!confirmEvictionDestroy(re)) {
opCompleted = false;
return opCompleted;
}
}
boolean removed = false;
try {
opCompleted = destroyEntry(re, event, inTokenMode, cacheWrite, expectedOldValue, false, removeRecoveredEntry);
if (opCompleted) {
// It is very, very important for Partitioned Regions to keep
// the entry in the map until after distribution occurs so that other
// threads performing a create on this entry wait until the destroy
// distribution is finished.
// keeping backup copies consistent. Fix for bug 35906.
// -- mthomas 07/02/2007 <-- how about that date, kinda cool eh?
owner.basicDestroyBeforeRemoval(re, event);
// do this before basicDestroyPart2 to fix bug 31786
if (!inTokenMode) {
if (re.getVersionStamp() == null) {
re.removePhase2();
removeEntry(event.getKey(), re, true, event, owner);
removed = true;
}
}
if (inTokenMode && !duringRI) {
event.inhibitCacheListenerNotification(true);
}
doPart3 = true;
owner.basicDestroyPart2(re, event, inTokenMode, false, /* conflict with clear */
duringRI, true);
// if (!re.isTombstone() || isEviction) {
lruEntryDestroy(re);
// } else {
// lruEntryUpdate(re);
// lruUpdateCallback = true;
// }
} else {
if (!inTokenMode) {
EntryLogger.logDestroy(event);
owner.recordEvent(event);
if (re.getVersionStamp() == null) {
re.removePhase2();
removeEntry(event.getKey(), re, true, event, owner);
lruEntryDestroy(re);
} else {
if (re.isTombstone()) {
// again, so we need to reschedule the tombstone's expiration
if (event.isOriginRemote()) {
owner.rescheduleTombstone(re, re.getVersionStamp().asVersionTag());
}
}
}
lruEntryDestroy(re);
opCompleted = true;
}
}
} catch (RegionClearedException rce) {
// Ignore. The exception will ensure that we do not update
// the LRU List
opCompleted = true;
owner.recordEvent(event);
if (inTokenMode && !duringRI) {
event.inhibitCacheListenerNotification(true);
}
owner.basicDestroyPart2(re, event, inTokenMode, true, /* conflict with clear */
duringRI, true);
doPart3 = true;
} finally {
if (re.isRemoved() && !re.isTombstone()) {
if (!removed) {
removeEntry(event.getKey(), re, true, event, owner);
}
}
}
} else // !isRemoved
{
// already removed
if (re.isTombstone() && event.getVersionTag() != null) {
// if we're dealing with a tombstone and this is a remote event
// (e.g., from cache client update thread) we need to update
// the tombstone's version information
// TODO use destroyEntry() here
processVersionTag(re, event);
try {
re.makeTombstone(owner, event.getVersionTag());
} catch (RegionClearedException e) {
// that's okay - when writing a tombstone into a disk, the
// region has been cleared (including this tombstone)
}
}
if (expectedOldValue != null) {
// if re is removed then there is no old value, so return false
return false;
}
if (!inTokenMode && !isEviction) {
owner.checkEntryNotFound(event.getKey());
}
}
}
// synchronized re
} catch (ConcurrentCacheModificationException ccme) {
VersionTag tag = event.getVersionTag();
if (tag != null && tag.isTimeStampUpdated()) {
// Notify gateways of new time-stamp.
owner.notifyTimestampsToGateways(event);
}
throw ccme;
} finally {
if (oqlIndexManager != null) {
oqlIndexManager.countDownIndexUpdaters();
}
}
// No need to call lruUpdateCallback since the only lru action
// we may have taken was lruEntryDestroy. This fixes bug 31759.
}
// current entry exists
if (opCompleted) {
EntryLogger.logDestroy(event);
}
return opCompleted;
} finally {
try {
// do NOT distribute.
if (event.isConcurrencyConflict() && (event.getVersionTag() != null && event.getVersionTag().isGatewayTag())) {
doPart3 = false;
}
// distribution and listener notification
if (doPart3) {
owner.basicDestroyPart3(re, event, inTokenMode, duringRI, true, expectedOldValue);
}
} finally {
if (opCompleted) {
if (re != null) {
// we only want to cancel if concurrency-check is not enabled
// re(regionentry) will be null when concurrency-check is enable and removeTombstone
// method
// will call cancelExpiryTask on regionEntry
owner.cancelExpiryTask(re);
}
}
}
}
}
// retry loop
} finally {
// failsafe on the read lock...see comment above
releaseCacheModificationLock(owner, event);
}
return false;
}
use of org.apache.geode.cache.EntryNotFoundException in project geode by apache.
the class AbstractRegionEntry method destroy.
/**
* @throws EntryNotFoundException if expectedOldValue is not null and is not equal to current
* value
*/
@Override
@Released
public boolean destroy(LocalRegion region, EntryEventImpl event, boolean inTokenMode, boolean cacheWrite, @Unretained Object expectedOldValue, boolean forceDestroy, boolean removeRecoveredEntry) throws CacheWriterException, EntryNotFoundException, TimeoutException, RegionClearedException {
// A design decision was made to not retrieve the old value from the disk
// if the entry has been evicted to only have the CacheListener afterDestroy
// method ignore it. We don't want to pay the performance penalty. The
// getValueInVM method does not retrieve the value from disk if it has been
// evicted. Instead, it uses the NotAvailable token.
//
// If the region is a WAN queue region, the old value is actually used by the
// afterDestroy callback on a secondary. It is not needed on a primary.
// Since the destroy that sets WAN_QUEUE_TOKEN always originates on the primary
// we only pay attention to WAN_QUEUE_TOKEN if the event is originRemote.
//
// We also read old value from disk or buffer
// in the case where there is a non-null expectedOldValue
// see PartitionedRegion#remove(Object key, Object value)
ReferenceCountHelper.skipRefCountTracking();
@Retained @Released Object curValue = _getValueRetain(region, true);
ReferenceCountHelper.unskipRefCountTracking();
boolean proceed;
try {
if (curValue == null) {
curValue = Token.NOT_AVAILABLE;
}
if (curValue == Token.NOT_AVAILABLE) {
// the state of the transmitting cache's entry & should be used here
if (event.getCallbackArgument() != null && event.getCallbackArgument().equals(RegionQueue.WAN_QUEUE_TOKEN) && event.isOriginRemote()) {
// check originRemote for bug 40508
// curValue = getValue(region); can cause deadlock if GII is occurring
curValue = getValueOnDiskOrBuffer(region);
} else {
FilterProfile fp = region.getFilterProfile();
if (fp != null && (fp.getCqCount() > 0 || expectedOldValue != null)) {
// curValue = getValue(region); can cause deadlock will fault in the value
// and will confuse LRU.
curValue = getValueOnDiskOrBuffer(region);
}
}
}
if (expectedOldValue != null) {
if (!checkExpectedOldValue(expectedOldValue, curValue, region)) {
throw new EntryNotFoundException(LocalizedStrings.AbstractRegionEntry_THE_CURRENT_VALUE_WAS_NOT_EQUAL_TO_EXPECTED_VALUE.toLocalizedString());
}
}
if (inTokenMode && event.hasOldValue()) {
proceed = true;
} else {
proceed = event.setOldValue(curValue, curValue instanceof GatewaySenderEventImpl) || removeRecoveredEntry || forceDestroy || region.getConcurrencyChecksEnabled() || (event.getOperation() == Operation.REMOVE && (curValue == null || curValue == Token.LOCAL_INVALID || curValue == Token.INVALID));
}
} finally {
OffHeapHelper.releaseWithNoTracking(curValue);
}
if (proceed) {
// after the entry not found exception above.
if (!removeRecoveredEntry) {
region.generateAndSetVersionTag(event, this);
}
if (cacheWrite) {
region.cacheWriteBeforeDestroy(event, expectedOldValue);
if (event.getRegion().getServerProxy() != null) {
// server will return a version tag
// update version information (may throw ConcurrentCacheModificationException)
VersionStamp stamp = getVersionStamp();
if (stamp != null) {
stamp.processVersionTag(event);
}
}
}
region.recordEvent(event);
// RegionEntry (the old value) is invalid
if (!region.isProxy() && !isInvalid()) {
IndexManager indexManager = region.getIndexManager();
if (indexManager != null) {
try {
if (isValueNull()) {
@Released Object value = getValueOffHeapOrDiskWithoutFaultIn(region);
try {
Object preparedValue = prepareValueForCache(region, value, false);
_setValue(preparedValue);
releaseOffHeapRefIfRegionBeingClosedOrDestroyed(region, preparedValue);
} finally {
OffHeapHelper.release(value);
}
}
indexManager.updateIndexes(this, IndexManager.REMOVE_ENTRY, IndexProtocol.OTHER_OP);
} catch (QueryException e) {
throw new IndexMaintenanceException(e);
}
}
}
boolean removeEntry = false;
VersionTag v = event.getVersionTag();
if (region.concurrencyChecksEnabled && !removeRecoveredEntry && !event.isFromRILocalDestroy()) {
// Destroy will write a tombstone instead
if (v == null || !v.hasValidVersion()) {
// localDestroy and eviction and ops received with no version tag
// should create a tombstone using the existing version stamp, as should
// (bug #45245) responses from servers that do not have valid version information
VersionStamp stamp = this.getVersionStamp();
if (stamp != null) {
// proxy has no stamps
v = stamp.asVersionTag();
event.setVersionTag(v);
}
}
removeEntry = v == null || !v.hasValidVersion();
} else {
removeEntry = true;
}
if (removeEntry) {
boolean isThisTombstone = isTombstone();
if (inTokenMode && !event.getOperation().isEviction()) {
setValue(region, Token.DESTROYED);
} else {
removePhase1(region, false);
}
if (isThisTombstone) {
region.unscheduleTombstone(this);
}
} else {
makeTombstone(region, v);
}
return true;
} else {
return false;
}
}
Aggregations