Search in sources :

Example 26 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 27 with TXManagerImpl

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

the class IndexManager method createIndex.

// @todo need more specific list of exceptions
/**
   * Create an index that can be used when executing queries.
   * 
   * @param indexName the name of this index, used for statistics collection
   * @param indexType the type of index
   * @param origIndexedExpression the expression to index on, a function dependent on region entries
   *        individually.
   * @param origFromClause expression that evaluates to the collection(s) that will be queried over,
   *        must contain one and only one region path.
   * @return the newly created Index
   */
public Index createIndex(String indexName, IndexType indexType, String origIndexedExpression, String origFromClause, String imports, ExecutionContext externalContext, PartitionedIndex prIndex, boolean loadEntries) throws IndexNameConflictException, IndexExistsException, IndexInvalidException {
    if (QueryMonitor.isLowMemory()) {
        throw new IndexInvalidException(LocalizedStrings.IndexCreationMsg_CANCELED_DUE_TO_LOW_MEMORY.toLocalizedString());
    }
    boolean oldReadSerialized = DefaultQuery.getPdxReadSerialized();
    DefaultQuery.setPdxReadSerialized(this.region.getCache(), true);
    TXStateProxy tx = null;
    if (!((InternalCache) this.region.getCache()).isClient()) {
        tx = ((TXManagerImpl) this.region.getCache().getCacheTransactionManager()).internalSuspend();
    }
    try {
        // for now this is the only option
        String projectionAttributes = "*";
        if (getIndex(indexName) != null) {
            throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
        }
        IndexCreationHelper helper = null;
        boolean isCompactOrHash = false;
        // to recalculate the index key for the entry for comparisons during query.
        if (indexType == IndexType.HASH && isOverFlowRegion()) {
            indexType = IndexType.FUNCTIONAL;
        }
        if (indexType != IndexType.PRIMARY_KEY) {
            helper = new FunctionalIndexCreationHelper(origFromClause, origIndexedExpression, projectionAttributes, imports, (InternalCache) region.getCache(), externalContext, this);
            // Asif: For now support Map index as non compact .expand later
            // The limitation for compact range index also apply to hash index for now
            isCompactOrHash = shouldCreateCompactIndex((FunctionalIndexCreationHelper) helper);
        } else if (indexType == IndexType.PRIMARY_KEY) {
            helper = new PrimaryKeyIndexCreationHelper(origFromClause, origIndexedExpression, projectionAttributes, (InternalCache) region.getCache(), externalContext, this);
        } else {
            throw new AssertionError("Don't know how to set helper for " + indexType);
        }
        if (!isCompactOrHash && indexType != IndexType.PRIMARY_KEY) {
            if (indexType == IndexType.HASH) {
                if (!isIndexMaintenanceTypeSynchronous()) {
                    throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_HASH_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_ASYNC_MAINTENANCE.toLocalizedString());
                }
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_HASH_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_MULTIPLE_ITERATORS.toLocalizedString());
            }
            // Overflow is not supported with range index.
            if (isOverFlowRegion()) {
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_REGIONS_WHICH_OVERFLOW_TO_DISK_THE_REGION_INVOLVED_IS_0.toLocalizedString(region.getFullPath()));
            }
            // OffHeap is not supported with range index.
            if (isOffHeap()) {
                if (!isIndexMaintenanceTypeSynchronous()) {
                    throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_OFF_HEAP_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_ASYNC_MAINTENANCE_THE_REGION_IS_0.toLocalizedString(region.getFullPath()));
                }
                throw new UnsupportedOperationException(LocalizedStrings.DefaultQueryService_OFF_HEAP_INDEX_CREATION_IS_NOT_SUPPORTED_FOR_MULTIPLE_ITERATORS_THE_REGION_IS_0.toLocalizedString(region.getFullPath()));
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Started creating index with indexName: {} On region: {}", indexName, region.getFullPath());
        }
        if (IndexManager.testHook != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("IndexManager TestHook is set.");
            }
            if (((LocalRegion) this.region).isInitialized()) {
                testHook.hook(1);
            } else {
                testHook.hook(0);
            }
        }
        IndexTask indexTask = new IndexTask(indexName, indexType, origFromClause, origIndexedExpression, helper, isCompactOrHash, prIndex, loadEntries);
        FutureTask<Index> indexFutureTask = new FutureTask<Index>(indexTask);
        Object oldIndex = this.indexes.putIfAbsent(indexTask, indexFutureTask);
        Index index = null;
        boolean interrupted = false;
        try {
            if (oldIndex == null) {
                // Initialize index.
                indexFutureTask.run();
                // Set the index.
                index = (Index) indexFutureTask.get();
            } else {
                // Check if index creation is complete.
                if (!(oldIndex instanceof Index)) {
                    // Some other thread is creating the same index.
                    // Wait for index to be initialized from other thread.
                    ((Future) oldIndex).get();
                }
                // from this thread.
                if (getIndex(indexName) != null) {
                    throw new IndexNameConflictException(LocalizedStrings.IndexManager_INDEX_NAMED_0_ALREADY_EXISTS.toLocalizedString(indexName));
                } else {
                    throw new IndexExistsException(LocalizedStrings.IndexManager_SIMILAR_INDEX_EXISTS.toLocalizedString());
                }
            }
        } catch (InterruptedException ignored) {
            interrupted = true;
        } catch (ExecutionException ee) {
            Throwable c = ee.getCause();
            if (c instanceof IndexNameConflictException) {
                throw (IndexNameConflictException) c;
            } else if (c instanceof IndexExistsException) {
                throw (IndexExistsException) c;
            } else if (c instanceof IMQException) {
                throw new IndexInvalidException(c.getMessage());
            }
            throw new IndexInvalidException(ee);
        } finally {
            // the map.
            if (oldIndex == null && index == null) {
                Object ind = this.indexes.get(indexTask);
                if (ind != null && !(ind instanceof Index)) {
                    this.indexes.remove(indexTask);
                }
            }
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
        assert (index != null);
        if (logger.isDebugEnabled()) {
            logger.debug("Completed creating index with indexName: {} On region: {}", indexName, region.getFullPath());
        }
        return index;
    } finally {
        DefaultQuery.setPdxReadSerialized(this.region.getCache(), oldReadSerialized);
        if (tx != null) {
            ((TXManagerImpl) this.region.getCache().getCacheTransactionManager()).internalResume(tx);
        }
    }
}
Also used : IndexExistsException(org.apache.geode.cache.query.IndexExistsException) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) InternalCache(org.apache.geode.internal.cache.InternalCache) Index(org.apache.geode.cache.query.Index) LocalRegion(org.apache.geode.internal.cache.LocalRegion) FutureTask(java.util.concurrent.FutureTask) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) IndexNameConflictException(org.apache.geode.cache.query.IndexNameConflictException) Future(java.util.concurrent.Future) IndexInvalidException(org.apache.geode.cache.query.IndexInvalidException) ExecutionException(java.util.concurrent.ExecutionException)

Example 28 with TXManagerImpl

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

the class ClientHealthMonitor method expireTXStates.

/**
   * expire the transaction states for the given client. This uses the transactionTimeToLive setting
   * that is inherited from the TXManagerImpl. If that setting is non-positive we expire the states
   * immediately
   * 
   * @param proxyID
   */
private void expireTXStates(ClientProxyMembershipID proxyID) {
    final TXManagerImpl txMgr = (TXManagerImpl) this._cache.getCacheTransactionManager();
    final Set<TXId> txids = txMgr.getTransactionsForClient((InternalDistributedMember) proxyID.getDistributedMember());
    if (this._cache.isClosed()) {
        return;
    }
    long timeout = txMgr.getTransactionTimeToLive() * 1000;
    if (!txids.isEmpty()) {
        if (logger.isDebugEnabled()) {
            logger.debug("expiring {} transaction contexts for {} timeout={}", txids.size(), proxyID, timeout / 1000);
        }
        if (timeout <= 0) {
            txMgr.removeTransactions(txids, true);
        } else {
            if (scheduledToBeRemovedTx != null)
                scheduledToBeRemovedTx.addAll(txids);
            SystemTimerTask task = new SystemTimerTask() {

                @Override
                public void run2() {
                    txMgr.removeTransactions(txids, true);
                    if (scheduledToBeRemovedTx != null)
                        scheduledToBeRemovedTx.removeAll(txids);
                }
            };
            this._cache.getCCPTimer().schedule(task, timeout);
        }
    }
}
Also used : TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) TXId(org.apache.geode.internal.cache.TXId) SystemTimerTask(org.apache.geode.internal.SystemTimer.SystemTimerTask)

Example 29 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)

Example 30 with TXManagerImpl

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

the class PeerTypeRegistration method suspendTX.

private TXStateProxy suspendTX() {
    InternalCache cache = (InternalCache) getIdToType().getRegionService();
    TXManagerImpl txManager = (TXManagerImpl) cache.getCacheTransactionManager();
    return txManager.internalSuspend();
}
Also used : TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) InternalCache(org.apache.geode.internal.cache.InternalCache)

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