Search in sources :

Example 21 with CommitConflictException

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

the class TXJUnitTest method testListener.

@Test
public void testListener() {
    assertTrue(this.txMgr.getListener() == null);
    TransactionListener oldListener = this.txMgr.setListener(new TransactionListener() {

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

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

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

        @Override
        public void close() {
            listenerClose = 1;
        }
    });
    assertTrue(oldListener == null);
    this.txMgr.begin();
    TransactionId myTxId = this.txMgr.getTransactionId();
    assertEquals(0, this.listenerAfterRollback);
    this.txMgr.rollback();
    assertEquals(1, this.listenerAfterRollback);
    assertEquals(0, this.te.getCreateEvents().size());
    assertEquals(0, this.te.getPutEvents().size());
    assertEquals(0, this.te.getInvalidateEvents().size());
    assertEquals(0, this.te.getDestroyEvents().size());
    assertEquals(0, this.te.getEvents().size());
    assertEquals(myTxId, this.te.getTransactionId());
    this.txMgr.begin();
    myTxId = this.txMgr.getTransactionId();
    try {
        assertEquals(0, this.listenerAfterCommit);
        this.txMgr.commit();
    } catch (CommitConflictException unexpected) {
        fail("did not expect " + unexpected);
    }
    assertEquals(1, this.listenerAfterCommit);
    assertEquals(0, this.te.getCreateEvents().size());
    assertEquals(0, this.te.getPutEvents().size());
    assertEquals(0, this.te.getInvalidateEvents().size());
    assertEquals(0, this.te.getDestroyEvents().size());
    assertEquals(0, this.te.getEvents().size());
    assertEquals(myTxId, this.te.getTransactionId());
    assertEquals(0, this.listenerClose);
    oldListener = this.txMgr.setListener(new TransactionListener() {

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

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

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

        @Override
        public void close() {
            listenerClose = 2;
        }
    });
    assertEquals(1, this.listenerClose);
    this.txMgr.begin();
    assertEquals(1, this.listenerAfterRollback);
    this.txMgr.rollback();
    assertEquals(2, this.listenerAfterRollback);
    this.txMgr.begin();
    this.txMgr.setListener(oldListener);
    assertEquals(2, this.listenerClose);
    this.txMgr.rollback();
    assertEquals(1, this.listenerAfterRollback);
    closeCache();
    assertEquals(1, this.listenerClose);
}
Also used : TransactionListener(org.apache.geode.cache.TransactionListener) TransactionEvent(org.apache.geode.cache.TransactionEvent) CommitConflictException(org.apache.geode.cache.CommitConflictException) TransactionId(org.apache.geode.cache.TransactionId) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 22 with CommitConflictException

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

the class TXMessage method process.

@Override
protected void process(final DistributionManager dm) {
    Throwable thr = null;
    boolean sendReply = true;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("processing {}", this);
        }
        InternalCache cache = GemFireCacheImpl.getInstance();
        if (checkCacheClosing(cache) || checkDSClosing(cache.getInternalDistributedSystem())) {
            thr = new CacheClosedException(LocalizedStrings.PartitionMessage_REMOTE_CACHE_IS_CLOSED_0.toLocalizedString(dm.getId()));
            return;
        }
        TXManagerImpl txMgr = cache.getTXMgr();
        TXStateProxy tx = null;
        try {
            assert this.txUniqId != TXManagerImpl.NOTX;
            TXId txId = new TXId(getMemberToMasqueradeAs(), this.txUniqId);
            tx = txMgr.masqueradeAs(this);
            sendReply = operateOnTx(txId, dm);
        } finally {
            txMgr.unmasquerade(tx);
        }
    } catch (CommitConflictException cce) {
        thr = cce;
    } catch (DistributedSystemDisconnectedException se) {
        sendReply = false;
        if (logger.isDebugEnabled()) {
            logger.debug("shutdown caught, abandoning message: " + se);
        }
    } catch (RegionDestroyedException rde) {
        thr = new ForceReattemptException(LocalizedStrings.PartitionMessage_REGION_IS_DESTROYED_IN_0.toLocalizedString(dm.getDistributionManagerId()), rde);
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // now, so don't let this thread continue.
        throw err;
    } catch (Throwable t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        if (sendReply) {
            thr = t;
        }
    } finally {
        ReplySender rs = getReplySender(dm);
        if (sendReply && (this.processorId != 0 || (rs != dm))) {
            ReplyException rex = null;
            if (thr != null) {
                rex = new ReplyException(thr);
            }
            sendReply(getSender(), this.processorId, dm, rex);
        }
    }
}
Also used : DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) CacheClosedException(org.apache.geode.cache.CacheClosedException) ReplyException(org.apache.geode.distributed.internal.ReplyException) CommitConflictException(org.apache.geode.cache.CommitConflictException) ReplySender(org.apache.geode.distributed.internal.ReplySender)

Example 23 with CommitConflictException

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

the class TXJUnitTest method testSimpleOps.

@Test
public void testSimpleOps() throws CacheException {
    final CachePerfStats stats = this.cache.getCachePerfStats();
    // See if things are ok when no transaction
    checkNoTxState();
    this.txMgr.begin();
    // now that a transaction exists make sure things behave as expected
    assertTrue(this.txMgr.getTransactionId() != null);
    assertTrue(this.txMgr.exists());
    try {
        this.txMgr.begin();
        fail("expected IllegalStateException");
    } catch (IllegalStateException expected) {
    }
    try {
        this.txMgr.commit();
    } catch (CommitConflictException unexpected) {
        fail("did not expect " + unexpected);
    }
    checkNoTxState();
    this.txMgr.begin();
    this.txMgr.rollback();
    checkNoTxState();
    this.region.put("uaKey", "val");
    {
        Region.Entry cmtre = this.region.getEntry("uaKey");
        cmtre.setUserAttribute("uaValue1");
        assertEquals("uaValue1", cmtre.getUserAttribute());
        int txRollbackChanges = stats.getTxRollbackChanges();
        int txCommitChanges = stats.getTxCommitChanges();
        int txFailureChanges = stats.getTxFailureChanges();
        this.txMgr.begin();
        Region.Entry txre = this.region.getEntry("uaKey");
        assertEquals(this.region, txre.getRegion());
        if (isPR()) {
            this.region.put("1", "one");
            try {
                txre.setUserAttribute("uaValue2");
            } catch (UnsupportedOperationException e) {
            // expected
            }
            try {
                txre.getUserAttribute();
            } catch (UnsupportedOperationException e) {
            // expected
            }
        } else {
            assertEquals("uaValue1", txre.getUserAttribute());
            txre.setUserAttribute("uaValue2");
            assertEquals("uaValue2", txre.getUserAttribute());
        }
        this.txMgr.rollback();
        try {
            txre.getValue();
            fail("expected IllegalStateException");
        } catch (IllegalStateException ok) {
        }
        try {
            txre.isDestroyed();
            fail("expected IllegalStateException");
        } catch (IllegalStateException ok) {
        }
        try {
            txre.getUserAttribute();
            fail("expected IllegalStateException");
        } catch (IllegalStateException ok) {
        }
        try {
            txre.setUserAttribute("foo");
            fail("expected IllegalStateException");
        } catch (IllegalStateException ok) {
        }
        assertEquals(txRollbackChanges + 1, stats.getTxRollbackChanges());
        assertEquals(txCommitChanges, stats.getTxCommitChanges());
        assertEquals(txFailureChanges, stats.getTxFailureChanges());
        assertEquals("uaValue1", cmtre.getUserAttribute());
    }
    {
        int txRollbackChanges = stats.getTxRollbackChanges();
        int txCommitChanges = stats.getTxCommitChanges();
        int txFailureChanges = stats.getTxFailureChanges();
        this.region.create("key1", "value1");
        this.txMgr.begin();
        this.region.invalidate("key1");
        this.txMgr.rollback();
        assertEquals(this.region.get("key1"), "value1");
        assertEquals(txRollbackChanges + 1, stats.getTxRollbackChanges());
        assertEquals(txCommitChanges, stats.getTxCommitChanges());
        assertEquals(txFailureChanges, stats.getTxFailureChanges());
        txRollbackChanges = stats.getTxRollbackChanges();
        this.txMgr.begin();
        this.region.destroy("key1");
        this.txMgr.rollback();
        assertEquals(this.region.get("key1"), "value1");
        assertEquals(txRollbackChanges + 1, stats.getTxRollbackChanges());
        assertEquals(txCommitChanges, stats.getTxCommitChanges());
        assertEquals(txFailureChanges, stats.getTxFailureChanges());
        txRollbackChanges = stats.getTxRollbackChanges();
        this.txMgr.begin();
        this.region.put("key1", "value2");
        this.txMgr.rollback();
        assertEquals(this.region.get("key1"), "value1");
        assertEquals(txRollbackChanges + 1, stats.getTxRollbackChanges());
        assertEquals(txCommitChanges, stats.getTxCommitChanges());
        assertEquals(txFailureChanges, stats.getTxFailureChanges());
    }
}
Also used : CommitConflictException(org.apache.geode.cache.CommitConflictException) CachePerfStats(org.apache.geode.internal.cache.CachePerfStats) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 24 with CommitConflictException

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

the class ExecExecutor method executeCommand.

@Override
public void executeCommand(Command command, ExecutionHandlerContext context) {
    CacheTransactionManager txm = context.getCacheTransactionManager();
    if (!context.hasTransaction()) {
        command.setResponse(Coder.getNilResponse(context.getByteBufAllocator()));
        return;
    }
    TransactionId transactionId = context.getTransactionID();
    txm.resume(transactionId);
    boolean hasError = hasError(context.getTransactionQueue());
    if (hasError)
        txm.rollback();
    else {
        try {
            txm.commit();
        } catch (CommitConflictException e) {
            command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), RedisConstants.ERROR_COMMIT_CONFLICT));
            context.clearTransaction();
            return;
        }
    }
    ByteBuf response = constructResponseExec(context);
    command.setResponse(response);
    context.clearTransaction();
}
Also used : CommitConflictException(org.apache.geode.cache.CommitConflictException) ByteBuf(io.netty.buffer.ByteBuf) CacheTransactionManager(org.apache.geode.cache.CacheTransactionManager) TransactionId(org.apache.geode.cache.TransactionId)

Example 25 with CommitConflictException

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

the class CopyOnReadIndexDUnitTest method helpTestTransactionsOnReplicatedRegion.

public void helpTestTransactionsOnReplicatedRegion(final String queryString, final int numPortfolios, final int numExpectedResults, final boolean hasIndex) throws Exception {
    resetInstanceCount(vm0);
    resetInstanceCount(vm1);
    resetInstanceCount(vm2);
    createReplicatedRegion(vm0, "portfolios");
    createReplicatedRegion(vm1, "portfolios");
    createReplicatedRegion(vm2, "portfolios");
    // counts
    if (hasIndex) {
        vm0.invoke(new SerializableCallable() {

            public Object call() throws Exception {
                QueryTestUtils utils = new QueryTestUtils();
                utils.createHashIndex("idIndex", "p.ID", "/portfolios p");
                return null;
            }
        });
        // let's not create index on vm1 to check different scenarios
        vm2.invoke(new SerializableCallable() {

            public Object call() throws Exception {
                QueryTestUtils utils = new QueryTestUtils();
                utils.createHashIndex("idIndex", "p.ID", "/portfolios p");
                return null;
            }
        });
    }
    vm0.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            Region region = getCache().getRegion("/portfolios");
            for (int i = 0; i < numPortfolios; i++) {
                Portfolio p = new Portfolio(i);
                p.status = "testStatus";
                p.positions = new HashMap();
                p.positions.put("" + i, new Position("" + i, 20));
                region.put("key " + i, p);
            }
            // We should have the same number of portfolio objects that we created for the put
            Wait.waitForCriterion(verifyPortfolioCount(numPortfolios), 5000, 200, true);
            return null;
        }
    });
    vm1.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            // At this point, we should only have serialized values in this vm
            Region region = getCache().getRegion("/portfolios");
            Wait.waitForCriterion(verifyPortfolioCount(0), 0, 200, true);
            return null;
        }
    });
    vm2.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            // There is an index for vm2, so we should have deserialized values at this point,
            Region region = getCache().getRegion("/portfolios");
            if (hasIndex) {
                Wait.waitForCriterion(verifyPortfolioCount(numPortfolios), 0, 200, true);
            } else {
                Wait.waitForCriterion(verifyPortfolioCount(0), 0, 200, true);
            }
            return null;
        }
    });
    // start transaction
    // execute query
    // modify results
    // check instance count
    vm0.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            Region region = getCache().getRegion("/portfolios");
            CacheTransactionManager txManager = region.getCache().getCacheTransactionManager();
            try {
                txManager.begin();
                QueryService qs = getCache().getQueryService();
                Query query = qs.newQuery(queryString);
                SelectResults results = (SelectResults) query.execute();
                assertEquals(numExpectedResults, results.size());
                for (Object o : results) {
                    if (o instanceof Portfolio) {
                        Portfolio p = (Portfolio) o;
                        p.status = "discardStatus";
                    } else {
                        Struct struct = (Struct) o;
                        Portfolio p = (Portfolio) struct.getFieldValues()[0];
                        p.status = "discardStatus";
                    }
                }
                txManager.commit();
            } catch (CommitConflictException conflict) {
                Assert.fail("commit conflict exception", conflict);
            }
            // We have created puts from our previous callable
            // Now we have copied the results from the query
            Wait.waitForCriterion(verifyPortfolioCount(numExpectedResults + numPortfolios), 0, 200, true);
            return null;
        }
    });
    // Check objects in cache on vm1
    vm1.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            Region region = getCache().getRegion("/portfolios");
            QueryService qs = getCache().getQueryService();
            Query query = qs.newQuery(queryString);
            SelectResults results = (SelectResults) query.execute();
            assertEquals(numExpectedResults, results.size());
            for (Object o : results) {
                if (o instanceof Portfolio) {
                    Portfolio p = (Portfolio) o;
                    assertEquals("status should not have been changed", "testStatus", p.status);
                    p.status = "discardStatus";
                } else {
                    Struct struct = (Struct) o;
                    Portfolio p = (Portfolio) struct.getFieldValues()[0];
                    assertEquals("status should not have been changed", "testStatus", p.status);
                    p.status = "discardStatus";
                }
            }
            // first it must deserialize the portfolios in the replicated region
            // then we do a copy on read of these deserialized objects for the final result set
            Wait.waitForCriterion(verifyPortfolioCount(numExpectedResults + numPortfolios), 0, 200, true);
            results = (SelectResults) query.execute();
            assertEquals(numExpectedResults, results.size());
            for (Object o : results) {
                if (o instanceof Portfolio) {
                    Portfolio p = (Portfolio) o;
                    assertEquals("status should not have been changed", "testStatus", p.status);
                } else {
                    Struct struct = (Struct) o;
                    Portfolio p = (Portfolio) struct.getFieldValues()[0];
                    assertEquals("status should not have been changed", "testStatus", p.status);
                }
            }
            // we never created index on vm1
            // so in this case, we always have to deserialize the value from the region
            Wait.waitForCriterion(verifyPortfolioCount(numPortfolios * 2 + numExpectedResults * 2), 0, 200, true);
            return null;
        }
    });
    // Check objects in cache on vm2
    vm2.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            Region region = getCache().getRegion("/portfolios");
            QueryService qs = getCache().getQueryService();
            Query query = qs.newQuery(queryString);
            SelectResults results = (SelectResults) query.execute();
            assertEquals(numExpectedResults, results.size());
            for (Object o : results) {
                if (o instanceof Portfolio) {
                    Portfolio p = (Portfolio) o;
                    assertEquals("status should not have been changed", "testStatus", p.status);
                    p.status = "discardStatus";
                } else {
                    Struct struct = (Struct) o;
                    Portfolio p = (Portfolio) struct.getFieldValues()[0];
                    assertEquals("status should not have been changed", "testStatus", p.status);
                    p.status = "discardStatus";
                }
            }
            // with or without index, the values had to have been deserialized at one point
            Wait.waitForCriterion(verifyPortfolioCount(numPortfolios + numExpectedResults), 0, 200, true);
            results = (SelectResults) query.execute();
            assertEquals(numExpectedResults, results.size());
            for (Object o : results) {
                if (o instanceof Portfolio) {
                    Portfolio p = (Portfolio) o;
                    assertEquals("status should not have been changed", "testStatus", p.status);
                } else {
                    Struct struct = (Struct) o;
                    Portfolio p = (Portfolio) struct.getFieldValues()[0];
                    assertEquals("status should not have been changed", "testStatus", p.status);
                }
            }
            if (hasIndex) {
                // we have an index, so the values are already deserialized
                // total is now our original deserialization amount : numPortfolios
                // two query results copied.
                Wait.waitForCriterion(verifyPortfolioCount(numPortfolios + numExpectedResults * 2), 0, 200, true);
            } else {
                // we never created index on vm1
                // so in this case, we always have to deserialize the value from the region
                Wait.waitForCriterion(verifyPortfolioCount(numPortfolios * 2 + numExpectedResults * 2), 0, 200, true);
            }
            return null;
        }
    });
    // Check objects in cache on vm0
    vm0.invoke(new SerializableCallable() {

        public Object call() throws Exception {
            Region region = getCache().getRegion("/portfolios");
            QueryService qs = getCache().getQueryService();
            Query query = qs.newQuery(queryString);
            SelectResults results = (SelectResults) query.execute();
            assertEquals(numExpectedResults, results.size());
            for (Object o : results) {
                if (o instanceof Portfolio) {
                    Portfolio p = (Portfolio) o;
                    assertEquals("status should not have been changed", "testStatus", p.status);
                } else {
                    Struct struct = (Struct) o;
                    Portfolio p = (Portfolio) struct.getFieldValues()[0];
                    assertEquals("status should not have been changed", "testStatus", p.status);
                }
            }
            // with or without index, the values we put in the region were already deserialized values
            Wait.waitForCriterion(verifyPortfolioCount(numExpectedResults * 2 + numPortfolios), 0, 200, true);
            return null;
        }
    });
    destroyRegion("portfolio", vm0);
}
Also used : Query(org.apache.geode.cache.query.Query) HashMap(java.util.HashMap) Position(org.apache.geode.cache.query.data.Position) Portfolio(org.apache.geode.cache.query.data.Portfolio) CacheException(org.apache.geode.cache.CacheException) CommitConflictException(org.apache.geode.cache.CommitConflictException) CacheTransactionManager(org.apache.geode.cache.CacheTransactionManager) Struct(org.apache.geode.cache.query.Struct) CommitConflictException(org.apache.geode.cache.CommitConflictException) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) QueryTestUtils(org.apache.geode.cache.query.QueryTestUtils) SerializableCallable(org.apache.geode.test.dunit.SerializableCallable) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion)

Aggregations

CommitConflictException (org.apache.geode.cache.CommitConflictException)28 Test (org.junit.Test)17 TransactionWriterException (org.apache.geode.cache.TransactionWriterException)12 Region (org.apache.geode.cache.Region)11 UnsupportedOperationInTransactionException (org.apache.geode.cache.UnsupportedOperationInTransactionException)10 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)10 CacheTransactionManager (org.apache.geode.cache.CacheTransactionManager)8 TransactionDataRebalancedException (org.apache.geode.cache.TransactionDataRebalancedException)8 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)7 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)7 TransactionException (org.apache.geode.cache.TransactionException)7 Host (org.apache.geode.test.dunit.Host)7 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)7 VM (org.apache.geode.test.dunit.VM)7 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)7 NamingException (javax.naming.NamingException)6 RollbackException (javax.transaction.RollbackException)6 CacheWriterException (org.apache.geode.cache.CacheWriterException)6 TransactionDataNotColocatedException (org.apache.geode.cache.TransactionDataNotColocatedException)6 TransactionWriter (org.apache.geode.cache.TransactionWriter)6