Search in sources :

Example 21 with TXManagerImpl

use of org.apache.geode.internal.cache.TXManagerImpl in project geode by apache.

the class RollbackCommand method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, ClassNotFoundException, InterruptedException {
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    TXManagerImpl txMgr = (TXManagerImpl) serverConnection.getCache().getCacheTransactionManager();
    InternalDistributedMember client = (InternalDistributedMember) serverConnection.getProxyID().getDistributedMember();
    int uniqId = clientMessage.getTransactionId();
    TXId txId = new TXId(client, uniqId);
    if (txMgr.isHostedTxRecentlyCompleted(txId)) {
        if (logger.isDebugEnabled()) {
            logger.debug("TX: found a recently rolled back tx: {}", txId);
            sendRollbackReply(clientMessage, serverConnection);
            txMgr.removeHostedTXState(txId);
            return;
        }
    }
    final TXStateProxy txState = txMgr.getTXState();
    try {
        if (txState != null) {
            txId = txState.getTxId();
            txMgr.rollback();
            sendRollbackReply(clientMessage, serverConnection);
        } else {
            // could not find TxState in the host server.
            // Protect against a failover command received so late,
            // and it is removed from the failoverMap due to capacity.
            sendRollbackReply(clientMessage, serverConnection);
        }
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug("TX: removing tx state for {}", txId);
        }
        if (txId != null) {
            TXStateProxy proxy = txMgr.removeHostedTXState(txId);
            if (logger.isDebugEnabled()) {
                logger.debug("TX: removed tx state proxy {}", proxy);
            }
        }
    }
}
Also used : TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) TXId(org.apache.geode.internal.cache.TXId) IOException(java.io.IOException)

Example 22 with TXManagerImpl

use of org.apache.geode.internal.cache.TXManagerImpl in project geode by apache.

the class Put65 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long p_start) throws IOException, InterruptedException {
    long start = p_start;
    Part regionNamePart = null, keyPart = null, valuePart = null, callbackArgPart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    Part eventPart = null;
    StringBuffer errMessage = new StringBuffer();
    boolean isDelta = false;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    // requiresResponse = true;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadPutRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    int idx = 0;
    regionNamePart = clientMessage.getPart(idx++);
    Operation operation;
    try {
        operation = (Operation) clientMessage.getPart(idx++).getObject();
        if (operation == null) {
            // native clients send a null since the op is java-serialized
            operation = Operation.UPDATE;
        }
    } catch (ClassNotFoundException e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    int flags = clientMessage.getPart(idx++).getInt();
    boolean requireOldValue = ((flags & 0x01) == 0x01);
    boolean haveExpectedOldValue = ((flags & 0x02) == 0x02);
    Object expectedOldValue = null;
    if (haveExpectedOldValue) {
        try {
            expectedOldValue = clientMessage.getPart(idx++).getObject();
        } catch (ClassNotFoundException e) {
            writeException(clientMessage, e, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    keyPart = clientMessage.getPart(idx++);
    try {
        isDelta = ((Boolean) clientMessage.getPart(idx).getObject()).booleanValue();
        idx += 1;
    } catch (Exception e) {
        writeException(clientMessage, MessageType.PUT_DELTA_ERROR, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        // CachePerfStats not available here.
        return;
    }
    valuePart = clientMessage.getPart(idx++);
    eventPart = clientMessage.getPart(idx++);
    if (clientMessage.getNumberOfParts() > idx) {
        callbackArgPart = clientMessage.getPart(idx++);
        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;
    }
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
        logger.debug("{}: Received {}put request ({} bytes) from {} for region {} key {} txId {} posdup: {}", serverConnection.getName(), (isDelta ? " delta " : " "), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key, clientMessage.getTransactionId(), clientMessage.isRetry());
    }
    // Process the put request
    if (key == null || regionName == null) {
        if (key == null) {
            String putMsg = " The input key for the put request is null";
            if (isDebugEnabled) {
                logger.debug("{}:{}", serverConnection.getName(), putMsg);
            }
            errMessage.append(putMsg);
        }
        if (regionName == null) {
            String putMsg = " The input region name for the put request is null";
            if (isDebugEnabled) {
                logger.debug("{}:{}", serverConnection.getName(), putMsg);
            }
            errMessage.append(putMsg);
        }
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = " was not found during put request";
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (valuePart.isNull() && operation != Operation.PUT_IF_ABSENT && region.containsKey(key)) {
        // Invalid to 'put' a null value in an existing key
        String putMsg = " Attempted to put a null value for existing key " + key;
        if (isDebugEnabled) {
            logger.debug("{}:{}", serverConnection.getName(), putMsg);
        }
        errMessage.append(putMsg);
        writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
    long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
    EventIDHolder clientEvent = new EventIDHolder(new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId));
    Breadcrumbs.setEventId(clientEvent.getEventId());
    // msg.isRetry might be set by v7.0 and later clients
    if (clientMessage.isRetry()) {
        // if (logger.isDebugEnabled()) {
        // logger.debug("DEBUG: encountered isRetry in Put65");
        // }
        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);
            }
        }
    }
    boolean result = false;
    boolean sendOldValue = false;
    boolean oldValueIsObject = true;
    Object oldValue = null;
    try {
        Object value = null;
        if (!isDelta) {
            value = valuePart.getSerializedForm();
        }
        boolean isObject = valuePart.isObject();
        boolean isMetaRegion = region.isUsedForMetaRegion();
        clientMessage.setMetaRegion(isMetaRegion);
        this.securityService.authorizeRegionWrite(regionName, key.toString());
        AuthorizeRequest authzRequest = null;
        if (!isMetaRegion) {
            authzRequest = serverConnection.getAuthzRequest();
        }
        if (authzRequest != null) {
            if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
                authzRequest.createRegionAuthorize((String) key);
            } else // Allow PUT operations on meta regions (bug #38961)
            {
                PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg);
                value = putContext.getValue();
                isObject = putContext.isObject();
                callbackArg = putContext.getCallbackArg();
            }
        }
        if (isDebugEnabled) {
            logger.debug("processing put65 with operation={}", operation);
        }
        // to be publicly accessible.
        if (operation == Operation.PUT_IF_ABSENT) {
            // try {
            if (clientMessage.isRetry() && clientEvent.getVersionTag() != null) {
                // version tag
                if (isDebugEnabled) {
                    logger.debug("putIfAbsent operation was successful last time with version {}", clientEvent.getVersionTag());
                }
                // invoke basicBridgePutIfAbsent anyway to ensure that the event is distributed to all
                // servers - bug #51664
                region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent);
                oldValue = null;
            } else {
                oldValue = region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent);
            }
            sendOldValue = true;
            oldValueIsObject = true;
            Version clientVersion = serverConnection.getClientVersion();
            if (oldValue instanceof CachedDeserializable) {
                oldValue = ((CachedDeserializable) oldValue).getSerializedValue();
            } else if (oldValue instanceof byte[]) {
                oldValueIsObject = false;
            } else if ((oldValue instanceof Token) && clientVersion.compareTo(Version.GFE_651) <= 0) {
                // older clients don't know that Token is now a DSFID class, so we
                // put the token in a serialized form they can consume
                HeapDataOutputStream str = new HeapDataOutputStream(Version.CURRENT);
                DataOutput dstr = new DataOutputStream(str);
                InternalDataSerializer.writeSerializableObject(oldValue, dstr);
                oldValue = str.toByteArray();
            }
            result = true;
        // } catch (Exception e) {
        // writeException(msg, e, false, servConn);
        // servConn.setAsTrue(RESPONDED);
        // return;
        // }
        } else if (operation == Operation.REPLACE) {
            // try {
            if (requireOldValue) {
                // <V> replace(<K>, <V>)
                if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) {
                    if (isDebugEnabled) {
                        logger.debug("replace(k,v) operation was successful last time with version {}", clientEvent.getVersionTag());
                    }
                }
                oldValue = region.basicBridgeReplace(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent);
                sendOldValue = !clientEvent.isConcurrencyConflict();
                oldValueIsObject = true;
                Version clientVersion = serverConnection.getClientVersion();
                if (oldValue instanceof CachedDeserializable) {
                    oldValue = ((CachedDeserializable) oldValue).getSerializedValue();
                } else if (oldValue instanceof byte[]) {
                    oldValueIsObject = false;
                } else if ((oldValue instanceof Token) && clientVersion.compareTo(Version.GFE_651) <= 0) {
                    // older clients don't know that Token is now a DSFID class, so we
                    // put the token in a serialized form they can consume
                    HeapDataOutputStream str = new HeapDataOutputStream(Version.CURRENT);
                    DataOutput dstr = new DataOutputStream(str);
                    InternalDataSerializer.writeSerializableObject(oldValue, dstr);
                    oldValue = str.toByteArray();
                }
                if (isDebugEnabled) {
                    logger.debug("returning {} from replace(K,V)", oldValue);
                }
                result = true;
            } else {
                // boolean replace(<K>, <V>, <V>) {
                boolean didPut;
                didPut = region.basicBridgeReplace(key, expectedOldValue, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent);
                if (clientMessage.isRetry() && clientEvent.getVersionTag() != null) {
                    if (isDebugEnabled) {
                        logger.debug("replace(k,v,v) operation was successful last time with version {}", clientEvent.getVersionTag());
                    }
                    didPut = true;
                }
                sendOldValue = true;
                oldValueIsObject = true;
                oldValue = didPut ? Boolean.TRUE : Boolean.FALSE;
                if (isDebugEnabled) {
                    logger.debug("returning {} from replace(K,V,V)", oldValue);
                }
                result = true;
            }
        // } catch (Exception e) {
        // writeException(msg, e, false, servConn);
        // servConn.setAsTrue(RESPONDED);
        // return;
        // }
        } else if (value == null && !isDelta) {
            // Create the null entry. Since the value is null, the value of the
            // isObject
            // the true after null doesn't matter and is not used.
            result = region.basicBridgeCreate(key, null, true, callbackArg, serverConnection.getProxyID(), true, clientEvent, false);
            if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) {
                result = true;
                if (isDebugEnabled) {
                    logger.debug("create(k,null) operation was successful last time with version {}", clientEvent.getVersionTag());
                }
            }
        } else {
            // Put the entry
            byte[] delta = null;
            if (isDelta) {
                delta = valuePart.getSerializedForm();
            }
            TXManagerImpl txMgr = (TXManagerImpl) serverConnection.getCache().getCacheTransactionManager();
            // bug 43068 - use create() if in a transaction and op is CREATE
            if (txMgr.getTXState() != null && operation.isCreate()) {
                result = region.basicBridgeCreate(key, (byte[]) value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent, true);
            } else {
                result = region.basicBridgePut(key, value, delta, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent);
            }
            if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) {
                if (isDebugEnabled) {
                    logger.debug("put(k,v) operation was successful last time with version {}", clientEvent.getVersionTag());
                }
                result = true;
            }
        }
        if (result) {
            serverConnection.setModificationInfo(true, regionName, key);
        } else {
            String message = serverConnection.getName() + ": Failed to put entry for region " + regionName + " key " + key + " value " + valuePart;
            if (isDebugEnabled) {
                logger.debug(message);
            }
            throw new Exception(message);
        }
    } catch (RegionDestroyedException rde) {
        writeException(clientMessage, rde, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (ResourceException re) {
        writeException(clientMessage, re, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    } catch (InvalidDeltaException ide) {
        logger.info(LocalizedMessage.create(LocalizedStrings.UpdateOperation_ERROR_APPLYING_DELTA_FOR_KEY_0_OF_REGION_1, new Object[] { key, regionName }));
        writeException(clientMessage, MessageType.PUT_DELTA_ERROR, ide, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        region.getCachePerfStats().incDeltaFullValuesRequested();
        return;
    } catch (Exception ce) {
        // If an interrupted exception is thrown , rethrow it
        checkForInterrupt(serverConnection, ce);
        // If an exception occurs during the put, preserve the connection
        writeException(clientMessage, ce, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        if (ce instanceof GemFireSecurityException) {
            // logged by the security logger
            if (isDebugEnabled) {
                logger.debug("{}: Unexpected Security exception", serverConnection.getName(), ce);
            }
        } else if (isDebugEnabled) {
            logger.debug("{}: Unexpected Exception", serverConnection.getName(), ce);
        }
        return;
    } finally {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessPutTime(start - oldStart);
    }
    // Increment statistics and write the reply
    if (region instanceof PartitionedRegion) {
        PartitionedRegion pr = (PartitionedRegion) region;
        if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
            writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, sendOldValue, oldValueIsObject, oldValue, pr.getNetworkHopType(), clientEvent.getVersionTag());
            pr.clearNetworkHopData();
        } else {
            writeReply(clientMessage, serverConnection, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag());
        }
    } else {
        writeReply(clientMessage, serverConnection, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag());
    }
    serverConnection.setAsTrue(RESPONDED);
    if (isDebugEnabled) {
        logger.debug("{}: Sent put response back to {} for region {} key {} value {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, key, valuePart);
    }
    stats.incWritePutResponseTime(DistributionStats.getStatTime() - start);
}
Also used : InvalidDeltaException(org.apache.geode.InvalidDeltaException) DataOutput(java.io.DataOutput) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) DataOutputStream(java.io.DataOutputStream) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) Token(org.apache.geode.internal.cache.Token) Operation(org.apache.geode.cache.Operation) LocalRegion(org.apache.geode.internal.cache.LocalRegion) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) Version(org.apache.geode.internal.Version) ResourceException(org.apache.geode.cache.ResourceException) CachedDeserializable(org.apache.geode.internal.cache.CachedDeserializable) EventIDHolder(org.apache.geode.internal.cache.EventIDHolder) ByteBuffer(java.nio.ByteBuffer) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InvalidDeltaException(org.apache.geode.InvalidDeltaException) IOException(java.io.IOException) ResourceException(org.apache.geode.cache.ResourceException) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) EventID(org.apache.geode.internal.cache.EventID) PutOperationContext(org.apache.geode.cache.operations.PutOperationContext)

Example 23 with TXManagerImpl

use of org.apache.geode.internal.cache.TXManagerImpl in project geode by apache.

the class TXJUnitTest method testRepeatableRead.

@Test
public void testRepeatableRead() throws CacheException {
    final TXManagerImpl txMgrImpl = (TXManagerImpl) this.txMgr;
    TXStateProxy tx;
    // try repeating a get and make sure it doesn't cause a conflict
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals("value1", this.region.get("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals("value1", this.region.get("key1"));
    txMgrImpl.commit();
    // try repeating a get and modify the entry and make sure it causes a conflict
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals("value1", this.region.get("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals("value1", this.region.get("key1"));
    this.region.put("key1", "value3");
    assertEquals("value3", this.region.get("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try repeating a getEntry and make sure it doesn't cause a conflict
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    this.region.getEntry("key1");
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals("value1", this.region.get("key1"));
    txMgrImpl.commit();
    // try repeating a getEntry and modify the entry and make sure it causes a conflict
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    this.region.getEntry("key1");
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    this.region.put("key1", "value3");
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try RR when entry fetched using entrySet
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    // bootstrap the tx, entrySet does not
    this.region.get("key1");
    this.region.entrySet(false).iterator().next();
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals("value1", this.region.get("key1"));
    txMgrImpl.commit();
    // try RRW->CONFLICT when entry fetched using entrySet
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    // bootstrap the tx, entrySet does not
    this.region.get("key1");
    this.region.entrySet(false).iterator().next();
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals("value1", this.region.get("key1"));
    this.region.put("key1", "value3");
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try containsKey
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals(true, this.region.containsKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsKey("key1"));
    txMgrImpl.commit();
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals(true, this.region.containsKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsKey("key1"));
    this.region.put("key1", "value3");
    assertEquals(true, this.region.containsKey("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try containsValueForKey
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals(true, this.region.containsValueForKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsValueForKey("key1"));
    txMgrImpl.commit();
    // non-tx
    this.region.put("key1", "value1");
    txMgrImpl.begin();
    assertEquals(true, this.region.containsValueForKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsValueForKey("key1"));
    this.region.put("key1", "value3");
    assertEquals(true, this.region.containsValueForKey("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // now try the same things but with no entry in committed state at
    // the time of the first read
    // try repeating a get and make sure it doesn't cause a conflict
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(null, this.region.get("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(null, this.region.get("key1"));
    txMgrImpl.commit();
    // try repeating a get and modify the entry and make sure it causes a conflict
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(null, this.region.get("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(null, this.region.get("key1"));
    this.region.put("key1", "value3");
    assertEquals("value3", this.region.get("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try repeating a getEntry and make sure it doesn't cause a conflict
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(null, this.region.getEntry("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(null, this.region.getEntry("key1"));
    txMgrImpl.commit();
    // try repeating a getEntry and modify the entry and make sure it causes a conflict
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(null, this.region.getEntry("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(null, this.region.getEntry("key1"));
    this.region.put("key1", "value3");
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try containsKey
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(false, this.region.containsKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(false, this.region.containsKey("key1"));
    txMgrImpl.commit();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(false, this.region.containsKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(false, this.region.containsKey("key1"));
    this.region.put("key1", "value3");
    assertEquals(true, this.region.containsKey("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try containsValueForKey
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(false, this.region.containsValueForKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(false, this.region.containsValueForKey("key1"));
    txMgrImpl.commit();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    assertEquals(false, this.region.containsValueForKey("key1"));
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.put("key1", "value2");
    txMgrImpl.internalResume(tx);
    assertEquals(false, this.region.containsValueForKey("key1"));
    this.region.put("key1", "value3");
    assertEquals(true, this.region.containsValueForKey("key1"));
    try {
        txMgrImpl.commit();
        fail("expected CommitConflictException");
    } catch (CommitConflictException ex) {
    }
    // try an invalidate of an already invalid entry
    // non-tx
    this.region.remove("key1");
    // non-tx
    this.region.create("key1", null);
    txMgrImpl.begin();
    this.region.get("key1");
    // should be a noop since it is already invalid
    this.region.localInvalidate("key1");
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    txMgrImpl.commit();
    assertEquals(false, this.region.containsKey("key1"));
    // make sure a noop invalidate is repeatable read
    // non-tx
    this.region.remove("key1");
    // non-tx
    this.region.create("key1", null);
    txMgrImpl.begin();
    // should be a noop since it is already invalid
    this.region.localInvalidate("key1");
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsKey("key1"));
    assertEquals(false, this.region.containsValueForKey("key1"));
    txMgrImpl.commit();
    assertEquals(false, this.region.containsKey("key1"));
    // make sure a destroy that throws entryNotFound is repeatable read
    // non-tx
    this.region.remove("key1");
    txMgrImpl.begin();
    try {
        this.region.localDestroy("key1");
        fail("expected EntryNotFoundException");
    } catch (EntryNotFoundException expected) {
    }
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.create("key1", "value1");
    txMgrImpl.internalResume(tx);
    assertEquals(false, this.region.containsKey("key1"));
    txMgrImpl.commit();
    assertEquals(true, this.region.containsKey("key1"));
    // non-tx
    this.region.remove("key1");
    // make sure a create that throws entryExists is repeatable read
    // non-tx
    this.region.create("key1", "non-tx-value1");
    txMgrImpl.begin();
    try {
        this.region.create("key1", "value1");
        fail("expected EntryExistsException");
    } catch (EntryExistsException expected) {
    }
    tx = txMgrImpl.internalSuspend();
    // non-tx
    this.region.remove("key1");
    txMgrImpl.internalResume(tx);
    assertEquals(true, this.region.containsKey("key1"));
    txMgrImpl.commit();
    assertEquals(false, this.region.containsKey("key1"));
}
Also used : CommitConflictException(org.apache.geode.cache.CommitConflictException) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) EntryExistsException(org.apache.geode.cache.EntryExistsException) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 24 with TXManagerImpl

use of org.apache.geode.internal.cache.TXManagerImpl in project geode by apache.

the class TXJUnitTest method testJTAEnlistment.

@Test
public void testJTAEnlistment() throws CacheException, javax.transaction.NotSupportedException, javax.transaction.RollbackException, javax.transaction.SystemException, javax.transaction.HeuristicMixedException, javax.transaction.HeuristicRollbackException {
    TransactionListener tl = new TransactionListener() {

        @Override
        public void afterCommit(TransactionEvent event) {
            ++listenerAfterCommit;
            te = event;
        }

        @Override
        public void afterFailedCommit(TransactionEvent event) {
            ++listenerAfterFailedCommit;
            te = event;
        }

        @Override
        public void afterRollback(TransactionEvent event) {
            ++listenerAfterRollback;
            te = event;
        }

        @Override
        public void close() {
            ++listenerClose;
        }
    };
    this.txMgr.addListener(tl);
    javax.transaction.UserTransaction userTx = null;
    try {
        userTx = (javax.transaction.UserTransaction) this.cache.getJNDIContext().lookup("java:/UserTransaction");
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable badDog) {
        fail("Expected to get a healthy UserTransaction!");
    }
    // Test enlistment for put
    // Test enlisted rollback
    // Test prevention of rollback/commit for enlisted transaction
    assertEquals(0, this.listenerAfterRollback);
    userTx.begin();
    this.region.put("enlistKey", "enlistVal");
    assertEquals("enlistVal", this.region.getEntry("enlistKey").getValue());
    assertNotNull(this.txMgr.getTransactionId());
    try {
        this.txMgr.rollback();
        fail("Should not allow a CacheTransactionManager.rollback call once the GF Tx is enlisted");
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable ok) {
    }
    try {
        this.txMgr.commit();
        fail("Should not allow a CacheTransactionManager.commit() call once the GF Tx is enlisted");
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable alsoOk) {
    }
    userTx.rollback();
    assertNull(this.txMgr.getTransactionId());
    assertTrue(!this.region.containsKey("enlistKey"));
    assertEquals(1, this.listenerAfterRollback);
    // Test enlistment for create
    // Test commit
    assertEquals(0, this.listenerAfterCommit);
    userTx.begin();
    this.region.create("enlistKey", "enlistVal");
    assertEquals("enlistVal", this.region.getEntry("enlistKey").getValue());
    assertNotNull(this.txMgr.getTransactionId());
    userTx.commit();
    assertNull(this.txMgr.getTransactionId());
    assertTrue(this.region.containsKey("enlistKey"));
    assertEquals("enlistVal", this.region.getEntry("enlistKey").getValue());
    assertEquals(1, this.listenerAfterCommit);
    // Test enlistment for get
    assertEquals(1, this.listenerAfterCommit);
    userTx.begin();
    assertEquals("enlistVal", this.region.get("enlistKey"));
    assertNotNull(this.txMgr.getTransactionId());
    userTx.commit();
    assertNull(this.txMgr.getTransactionId());
    assertEquals(2, this.listenerAfterCommit);
    // Test enlistment for invalidate
    assertEquals(2, this.listenerAfterCommit);
    userTx.begin();
    this.region.invalidate("enlistKey");
    assertTrue(this.region.containsKey("enlistKey"));
    assertTrue(!this.region.containsValueForKey("enlistKey"));
    assertNotNull(this.txMgr.getTransactionId());
    userTx.commit();
    assertNull(this.txMgr.getTransactionId());
    assertTrue(this.region.containsKey("enlistKey"));
    assertTrue(!this.region.containsValueForKey("enlistKey"));
    assertEquals(3, this.listenerAfterCommit);
    // Test enlistment for destroy
    assertEquals(3, this.listenerAfterCommit);
    userTx.begin();
    this.region.destroy("enlistKey");
    assertTrue(!this.region.containsKey("enlistKey"));
    assertNotNull(this.txMgr.getTransactionId());
    userTx.commit();
    assertNull(this.txMgr.getTransactionId());
    assertTrue(!this.region.containsKey("enlistKey"));
    assertEquals(4, this.listenerAfterCommit);
    // Test enlistment for load
    AttributesMutator<String, String> mutator = this.region.getAttributesMutator();
    mutator.setCacheLoader(new CacheLoader<String, String>() {

        int count = 0;

        @Override
        public String load(LoaderHelper helper) throws CacheLoaderException {
            return String.valueOf(count++);
        }

        @Override
        public void close() {
        }
    });
    assertEquals(4, this.listenerAfterCommit);
    userTx.begin();
    assertEquals("0", this.region.get("enlistKey"));
    assertNotNull(this.txMgr.getTransactionId());
    userTx.commit();
    assertNull(this.txMgr.getTransactionId());
    assertTrue(this.region.containsKey("enlistKey"));
    assertEquals("0", this.region.getEntry("enlistKey").getValue());
    assertEquals(5, this.listenerAfterCommit);
    mutator.setCacheLoader(null);
    // Test enlisted failed commit
    assertEquals(0, this.listenerAfterFailedCommit);
    userTx.begin();
    this.region.put("enlistKey", "enlistVal");
    assertEquals("enlistVal", this.region.get("enlistKey"));
    assertNotNull(this.txMgr.getTransactionId());
    {
        TXManagerImpl gfTxMgrImpl = (TXManagerImpl) this.txMgr;
        TXStateProxy gfTx = gfTxMgrImpl.internalSuspend();
        javax.transaction.TransactionManager jtaTxMgr = this.cache.getJTATransactionManager();
        javax.transaction.Transaction jtaTx = jtaTxMgr.suspend();
        this.region.put("enlistKey", "conflictVal");
        assertEquals("conflictVal", this.region.get("enlistKey"));
        try {
            jtaTxMgr.resume(jtaTx);
        } catch (Exception failure) {
            fail("JTA resume failed");
        }
        gfTxMgrImpl.internalResume(gfTx);
    }
    assertEquals("enlistVal", this.region.get("enlistKey"));
    try {
        userTx.commit();
        fail("Expected JTA commit exception!");
    } catch (javax.transaction.HeuristicRollbackException expected) {
    } catch (javax.transaction.RollbackException alsoExpected) {
    } catch (Exception yuk) {
        fail("Did not expect this exception from JTA commit: " + yuk);
    }
    assertNull(this.txMgr.getTransactionId());
    assertEquals("conflictVal", this.region.getEntry("enlistKey").getValue());
    assertEquals(1, this.listenerAfterFailedCommit);
    // Test rollbackOnly UserTransaction enlistment
    userTx.begin();
    assertNull(this.txMgr.getTransactionId());
    userTx.setRollbackOnly();
    assertEquals(javax.transaction.Status.STATUS_MARKED_ROLLBACK, userTx.getStatus());
    try {
        this.region.put("enlistKey", "enlistVal2");
        fail("Expected to get a FailedSynchronizationException!");
    } catch (FailedSynchronizationException okay) {
    }
    assertNull(this.txMgr.getTransactionId());
    try {
        assertEquals("conflictVal", this.region.getEntry("enlistKey").getValue());
        fail("Expected to get a FailedSynchronizationException!");
    } catch (FailedSynchronizationException okay) {
    }
    assertTrue(!this.region.containsKey("enlistKey2"));
    try {
        this.region.put("enlistKey2", "enlistVal3");
        fail("Expected to get a FailedSynchronizationException!");
    } catch (FailedSynchronizationException okay) {
    }
    assertNull(this.txMgr.getTransactionId());
    try {
        assertEquals("conflictVal", this.region.getEntry("enlistKey").getValue());
        fail("Expected to get a FailedSynchronizationException!");
    } catch (FailedSynchronizationException okay) {
    }
    assertTrue(!this.region.containsKey("enlistKey2"));
    userTx.rollback();
    assertEquals("conflictVal", this.region.getEntry("enlistKey").getValue());
    assertTrue(!this.region.containsKey("enlistKey2"));
    this.txMgr.removeListener(tl);
}
Also used : TransactionListener(org.apache.geode.cache.TransactionListener) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) TimeoutException(org.apache.geode.cache.TimeoutException) EntryExistsException(org.apache.geode.cache.EntryExistsException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) CacheWriterException(org.apache.geode.cache.CacheWriterException) TransactionException(org.apache.geode.cache.TransactionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) UnsupportedOperationInTransactionException(org.apache.geode.cache.UnsupportedOperationInTransactionException) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) NoSuchElementException(java.util.NoSuchElementException) CacheException(org.apache.geode.cache.CacheException) CommitConflictException(org.apache.geode.cache.CommitConflictException) QueryException(org.apache.geode.cache.query.QueryException) LoaderHelper(org.apache.geode.cache.LoaderHelper) TransactionEvent(org.apache.geode.cache.TransactionEvent) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) CacheTransactionManager(org.apache.geode.cache.CacheTransactionManager) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 25 with TXManagerImpl

use of org.apache.geode.internal.cache.TXManagerImpl in project geode by apache.

the class PeerTypeRegistration method resumeTX.

private void resumeTX(TXStateProxy state) {
    if (state != null) {
        TXManagerImpl txManager = state.getTxMgr();
        txManager.internalResume(state);
    }
}
Also used : TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl)

Aggregations

TXManagerImpl (org.apache.geode.internal.cache.TXManagerImpl)31 TXStateProxy (org.apache.geode.internal.cache.TXStateProxy)20 Test (org.junit.Test)13 LocalRegion (org.apache.geode.internal.cache.LocalRegion)10 CommitConflictException (org.apache.geode.cache.CommitConflictException)8 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)8 Region (org.apache.geode.cache.Region)7 CacheTransactionManager (org.apache.geode.cache.CacheTransactionManager)6 InternalCache (org.apache.geode.internal.cache.InternalCache)6 IOException (java.io.IOException)5 CacheException (org.apache.geode.cache.CacheException)5 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)5 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)5 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)5 EntryExistsException (org.apache.geode.cache.EntryExistsException)4 TransactionException (org.apache.geode.cache.TransactionException)4 TXId (org.apache.geode.internal.cache.TXId)4 AttributesFactory (org.apache.geode.cache.AttributesFactory)3 CacheWriterException (org.apache.geode.cache.CacheWriterException)3 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)3