Search in sources :

Example 31 with TXStateProxy

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

the class ExecuteFunction66 method executeFunctionaLocally.

private void executeFunctionaLocally(final Function fn, final FunctionContext cx, final ServerToClientFunctionResultSender65 sender, DM dm, final FunctionStats stats) throws IOException {
    long startExecution = stats.startTime();
    stats.startFunctionExecution(fn.hasResult());
    if (fn.hasResult()) {
        fn.execute(cx);
        if (!((ServerToClientFunctionResultSender65) sender).isLastResultReceived() && fn.hasResult()) {
            throw new FunctionException(LocalizedStrings.ExecuteFunction_THE_FUNCTION_0_DID_NOT_SENT_LAST_RESULT.toString(fn.getId()));
        }
    } else {
        /*
       * if dm is null it mean cache is also null. Transactional function without cache cannot be
       * executed.
       */
        final TXStateProxy txState = TXManagerImpl.getCurrentTXState();
        Runnable functionExecution = new Runnable() {

            public void run() {
                InternalCache cache = null;
                try {
                    if (txState != null) {
                        cache = GemFireCacheImpl.getExisting("executing function");
                        cache.getTxManager().masqueradeAs(txState);
                        if (cache.getLoggerI18n().warningEnabled() && !ASYNC_TX_WARNING_ISSUED) {
                            ASYNC_TX_WARNING_ISSUED = true;
                            cache.getLoggerI18n().warning(LocalizedStrings.ExecuteFunction66_TRANSACTIONAL_FUNCTION_WITHOUT_RESULT);
                        }
                    }
                    fn.execute(cx);
                } catch (InternalFunctionInvocationTargetException internalfunctionException) {
                    // Fix for #44709: User should not be aware of
                    // InternalFunctionInvocationTargetException. No instance of
                    // InternalFunctionInvocationTargetException is giving useful
                    // information to user to take any corrective action hence logging
                    // this at fine level logging
                    // 1> Incase of HA FucntionInvocationTargetException thrown. Since
                    // it is HA, function will be reexecuted on right node
                    // 2> in case of HA member departed
                    stats.endFunctionExecutionWithException(fn.hasResult());
                    if (logger.isDebugEnabled()) {
                        logger.debug(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, new Object[] { fn }), internalfunctionException);
                    }
                } catch (FunctionException functionException) {
                    stats.endFunctionExecutionWithException(fn.hasResult());
                    logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, fn), functionException);
                } catch (Exception exception) {
                    stats.endFunctionExecutionWithException(fn.hasResult());
                    logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, fn), exception);
                } finally {
                    if (txState != null && cache != null) {
                        cache.getTxManager().unmasquerade(txState);
                    }
                }
            }
        };
        if (dm == null) {
            /**
         * Executing the function in its own thread pool as FunctionExecution Thread pool of
         * DisributionManager is not yet available.
         */
            execService.execute(functionExecution);
        } else {
            final DistributionManager newDM = (DistributionManager) dm;
            newDM.getFunctionExcecutor().execute(functionExecution);
        }
    }
    stats.endFunctionExecution(startExecution, fn.hasResult());
}
Also used : TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) ServerToClientFunctionResultSender65(org.apache.geode.internal.cache.execute.ServerToClientFunctionResultSender65) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException) FunctionException(org.apache.geode.cache.execute.FunctionException) InternalCache(org.apache.geode.internal.cache.InternalCache) DistributionManager(org.apache.geode.distributed.internal.DistributionManager) FunctionException(org.apache.geode.cache.execute.FunctionException) LowMemoryException(org.apache.geode.cache.LowMemoryException) IOException(java.io.IOException) InternalFunctionInvocationTargetException(org.apache.geode.internal.cache.execute.InternalFunctionInvocationTargetException)

Example 32 with TXStateProxy

use of org.apache.geode.internal.cache.TXStateProxy 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 33 with TXStateProxy

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

the class PeerTypeRegistration method addRemoteType.

public void addRemoteType(int typeId, PdxType type) {
    verifyConfiguration();
    TXStateProxy currentState = suspendTX();
    Region<Object, Object> r = getIdToType();
    try {
        if (!r.containsKey(typeId)) {
            // This type could actually be for this distributed system,
            // so we need to make sure the type is published while holding
            // the distributed lock.
            lock();
            try {
                r.put(typeId, type);
            } finally {
                unlock();
            }
        }
    } finally {
        resumeTX(currentState);
    }
}
Also used : TXStateProxy(org.apache.geode.internal.cache.TXStateProxy)

Example 34 with TXStateProxy

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

the class PeerTypeRegistration method addRemoteEnum.

public void addRemoteEnum(int id, EnumInfo enumInfo) {
    verifyConfiguration();
    TXStateProxy currentState = suspendTX();
    EnumId enumId = new EnumId(id);
    Region<Object, Object> r = getIdToType();
    try {
        if (!r.containsKey(enumId)) {
            // This enum could actually be for this distributed system,
            // so we need to make sure the enum is published while holding
            // the distributed lock.
            lock();
            try {
                r.put(enumId, enumInfo);
            } finally {
                unlock();
            }
        }
    } finally {
        resumeTX(currentState);
    }
}
Also used : TXStateProxy(org.apache.geode.internal.cache.TXStateProxy)

Example 35 with TXStateProxy

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

the class PeerTypeRegistration method getType.

public PdxType getType(int typeId) {
    verifyConfiguration();
    TXStateProxy currentState = suspendTX();
    try {
        return (PdxType) getIdToType().get(typeId);
    } finally {
        resumeTX(currentState);
    }
}
Also used : TXStateProxy(org.apache.geode.internal.cache.TXStateProxy)

Aggregations

TXStateProxy (org.apache.geode.internal.cache.TXStateProxy)37 TXManagerImpl (org.apache.geode.internal.cache.TXManagerImpl)20 Test (org.junit.Test)9 CommitConflictException (org.apache.geode.cache.CommitConflictException)8 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)8 IOException (java.io.IOException)6 TransactionException (org.apache.geode.cache.TransactionException)6 InternalCache (org.apache.geode.internal.cache.InternalCache)6 LocalRegion (org.apache.geode.internal.cache.LocalRegion)6 InternalGemFireError (org.apache.geode.InternalGemFireError)5 CacheLoaderException (org.apache.geode.cache.CacheLoaderException)5 EntryExistsException (org.apache.geode.cache.EntryExistsException)5 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)5 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)5 CacheWriterException (org.apache.geode.cache.CacheWriterException)4 EntryNotFoundException (org.apache.geode.cache.EntryNotFoundException)4 Region (org.apache.geode.cache.Region)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ResourceException (javax.resource.ResourceException)3