Search in sources :

Example 11 with GridClosureException

use of org.apache.ignite.internal.util.lang.GridClosureException in project ignite by apache.

the class GridCacheMapEntry method innerUpdate.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public GridCacheUpdateAtomicResult innerUpdate(final GridCacheVersion newVer, final UUID evtNodeId, final UUID affNodeId, final GridCacheOperation op, @Nullable final Object writeObj, @Nullable final Object[] invokeArgs, final boolean writeThrough, final boolean readThrough, final boolean retval, final boolean keepBinary, @Nullable final IgniteCacheExpiryPolicy expiryPlc, final boolean evt, final boolean metrics, final boolean primary, final boolean verCheck, final AffinityTopologyVersion topVer, @Nullable final CacheEntryPredicate[] filter, final GridDrType drType, final long explicitTtl, final long explicitExpireTime, @Nullable final GridCacheVersion conflictVer, final boolean conflictResolve, final boolean intercept, @Nullable final UUID subjId, final String taskName, @Nullable final CacheObject prevVal, @Nullable final Long updateCntr, @Nullable final GridDhtAtomicAbstractUpdateFuture fut) throws IgniteCheckedException, GridCacheEntryRemovedException, GridClosureException {
    assert cctx.atomic() && !detached();
    AtomicCacheUpdateClosure c;
    if (!primary && !isNear())
        ensureFreeSpace();
    lockEntry();
    try {
        checkObsolete();
        boolean internal = isInternal() || !context().userCache();
        Map<UUID, CacheContinuousQueryListener> lsnrs = cctx.continuousQueries().updateListeners(internal, false);
        boolean needVal = lsnrs != null || intercept || retval || op == GridCacheOperation.TRANSFORM || !F.isEmptyOrNulls(filter);
        // Possibly read value from store.
        boolean readFromStore = readThrough && needVal && (cctx.readThrough() && (op == GridCacheOperation.TRANSFORM || cctx.loadPreviousValue()));
        c = new AtomicCacheUpdateClosure(this, topVer, newVer, op, writeObj, invokeArgs, readFromStore, writeThrough, keepBinary, expiryPlc, primary, verCheck, filter, explicitTtl, explicitExpireTime, conflictVer, conflictResolve, intercept, updateCntr);
        key.valueBytes(cctx.cacheObjectContext());
        if (isNear()) {
            CacheDataRow dataRow = val != null ? new CacheDataRowAdapter(key, val, ver, expireTimeExtras()) : null;
            c.call(dataRow);
        } else
            cctx.offheap().invoke(cctx, key, localPartition(), c);
        GridCacheUpdateAtomicResult updateRes = c.updateRes;
        assert updateRes != null : c;
        CacheObject oldVal = c.oldRow != null ? c.oldRow.value() : null;
        CacheObject updateVal = null;
        GridCacheVersion updateVer = c.newVer;
        // Apply metrics.
        if (metrics && updateRes.outcome().updateReadMetrics() && cctx.statisticsEnabled() && needVal) {
            // PutIfAbsent methods must not update hit/miss statistics.
            if (op != GridCacheOperation.UPDATE || F.isEmpty(filter) || !cctx.putIfAbsentFilter(filter))
                cctx.cache().metrics0().onRead(oldVal != null);
        }
        switch(updateRes.outcome()) {
            case VERSION_CHECK_FAILED:
                {
                    if (!cctx.isNear()) {
                        CacheObject evtVal;
                        if (op == GridCacheOperation.TRANSFORM) {
                            EntryProcessor<Object, Object, ?> entryProcessor = (EntryProcessor<Object, Object, ?>) writeObj;
                            CacheInvokeEntry<Object, Object> entry = new CacheInvokeEntry<>(key, prevVal, version(), keepBinary, this);
                            try {
                                entryProcessor.process(entry, invokeArgs);
                                evtVal = entry.modified() ? cctx.toCacheObject(cctx.unwrapTemporary(entry.getValue())) : prevVal;
                            } catch (Exception ignore) {
                                evtVal = prevVal;
                            }
                        } else
                            evtVal = (CacheObject) writeObj;
                        long updateCntr0 = nextPartitionCounter(topVer, primary, updateCntr);
                        if (updateCntr != null)
                            updateCntr0 = updateCntr;
                        onUpdateFinished(updateCntr0);
                        cctx.continuousQueries().onEntryUpdated(key, evtVal, prevVal, isInternal() || !context().userCache(), partition(), primary, false, updateCntr0, null, topVer);
                    }
                    return updateRes;
                }
            case CONFLICT_USE_OLD:
            case FILTER_FAILED:
            case INVOKE_NO_OP:
            case INTERCEPTOR_CANCEL:
                return updateRes;
        }
        assert updateRes.outcome() == UpdateOutcome.SUCCESS || updateRes.outcome() == UpdateOutcome.REMOVE_NO_VAL;
        CacheObject evtOld = null;
        if (evt && op == TRANSFORM && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) {
            assert writeObj instanceof EntryProcessor : writeObj;
            evtOld = cctx.unwrapTemporary(oldVal);
            Object transformClo = EntryProcessorResourceInjectorProxy.unwrap(writeObj);
            cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_READ, evtOld, evtOld != null, evtOld, evtOld != null, subjId, transformClo.getClass().getName(), taskName, keepBinary);
        }
        if (c.op == GridCacheOperation.UPDATE) {
            updateVal = val;
            assert updateVal != null : c;
            drReplicate(drType, updateVal, updateVer, topVer);
            recordNodeId(affNodeId, topVer);
            if (evt && cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT)) {
                if (evtOld == null)
                    evtOld = cctx.unwrapTemporary(oldVal);
                cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_PUT, updateVal, true, evtOld, evtOld != null, subjId, null, taskName, keepBinary);
            }
        } else {
            assert c.op == GridCacheOperation.DELETE : c.op;
            clearReaders();
            drReplicate(drType, null, newVer, topVer);
            recordNodeId(affNodeId, topVer);
            if (evt && cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED)) {
                if (evtOld == null)
                    evtOld = cctx.unwrapTemporary(oldVal);
                cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_REMOVED, null, false, evtOld, evtOld != null, subjId, null, taskName, keepBinary);
            }
        }
        if (updateRes.success())
            updateMetrics(c.op, metrics);
        // Continuous query filter should be perform under lock.
        if (lsnrs != null) {
            CacheObject evtVal = cctx.unwrapTemporary(updateVal);
            CacheObject evtOldVal = cctx.unwrapTemporary(oldVal);
            cctx.continuousQueries().onEntryUpdated(lsnrs, key, evtVal, evtOldVal, internal, partition(), primary, false, c.updateRes.updateCounter(), fut, topVer);
        }
        cctx.dataStructures().onEntryUpdated(key, c.op == GridCacheOperation.DELETE, keepBinary);
        if (intercept) {
            if (c.op == GridCacheOperation.UPDATE) {
                cctx.config().getInterceptor().onAfterPut(new CacheLazyEntry(cctx, key, null, updateVal, null, keepBinary, c.updateRes.updateCounter()));
            } else {
                assert c.op == GridCacheOperation.DELETE : c.op;
                cctx.config().getInterceptor().onAfterRemove(new CacheLazyEntry(cctx, key, null, oldVal, null, keepBinary, c.updateRes.updateCounter()));
            }
        }
    } finally {
        unlockEntry();
    }
    onUpdateFinished(c.updateRes.updateCounter());
    return c.updateRes;
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) StorageException(org.apache.ignite.internal.pagemem.wal.StorageException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) CacheContinuousQueryListener(org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryListener) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) EntryProcessor(javax.cache.processor.EntryProcessor) CacheDataRowAdapter(org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter) UUID(java.util.UUID)

Example 12 with GridClosureException

use of org.apache.ignite.internal.util.lang.GridClosureException in project ignite by apache.

the class GridDhtGetFuture method getAsync.

/**
 * @param keys Keys to get.
 * @return Future for local get.
 */
@SuppressWarnings({ "unchecked", "IfMayBeConditional" })
private IgniteInternalFuture<Collection<GridCacheEntryInfo>> getAsync(final Map<KeyCacheObject, Boolean> keys) {
    if (F.isEmpty(keys))
        return new GridFinishedFuture<Collection<GridCacheEntryInfo>>(Collections.<GridCacheEntryInfo>emptyList());
    String taskName0 = cctx.kernalContext().job().currentTaskName();
    if (taskName0 == null)
        taskName0 = cctx.kernalContext().task().resolveTaskName(taskNameHash);
    final String taskName = taskName0;
    GridCompoundFuture<Boolean, Boolean> txFut = null;
    ReaderArguments readerArgs = null;
    if (addReaders && !skipVals && !cctx.localNodeId().equals(reader)) {
        for (Map.Entry<KeyCacheObject, Boolean> k : keys.entrySet()) {
            if (!k.getValue())
                continue;
            while (true) {
                GridDhtCacheEntry e = cache().entryExx(k.getKey(), topVer);
                try {
                    if (e.obsolete())
                        continue;
                    boolean addReader = !e.deleted();
                    if (addReader) {
                        e.unswap(false);
                        // we have to add reader again later.
                        if (readerArgs == null)
                            readerArgs = new ReaderArguments(reader, msgId, topVer);
                    }
                    // Register reader. If there are active transactions for this entry,
                    // then will wait for their completion before proceeding.
                    // TODO: IGNITE-3498:
                    // TODO: What if any transaction we wait for actually removes this entry?
                    // TODO: In this case seems like we will be stuck with untracked near entry.
                    // TODO: To fix, check that reader is contained in the list of readers once
                    // TODO: again after the returned future completes - if not, try again.
                    IgniteInternalFuture<Boolean> f = addReader ? e.addReader(reader, msgId, topVer) : null;
                    if (f != null) {
                        if (txFut == null)
                            txFut = new GridCompoundFuture<>(CU.boolReducer());
                        txFut.add(f);
                    }
                    break;
                } catch (IgniteCheckedException err) {
                    return new GridFinishedFuture<>(err);
                } catch (GridCacheEntryRemovedException ignore) {
                    if (log.isDebugEnabled())
                        log.debug("Got removed entry when getting a DHT value: " + e);
                } finally {
                    cctx.evicts().touch(e, topVer);
                }
            }
        }
        if (txFut != null)
            txFut.markInitialized();
    }
    IgniteInternalFuture<Map<KeyCacheObject, EntryGetResult>> fut;
    if (txFut == null || txFut.isDone()) {
        fut = cache().getDhtAllAsync(keys.keySet(), readerArgs, readThrough, subjId, taskName, expiryPlc, skipVals, recovery);
    } else {
        final ReaderArguments args = readerArgs;
        // If we are here, then there were active transactions for some entries
        // when we were adding the reader. In that case we must wait for those
        // transactions to complete.
        fut = new GridEmbeddedFuture<>(txFut, new C2<Boolean, Exception, IgniteInternalFuture<Map<KeyCacheObject, EntryGetResult>>>() {

            @Override
            public IgniteInternalFuture<Map<KeyCacheObject, EntryGetResult>> apply(Boolean b, Exception e) {
                if (e != null)
                    throw new GridClosureException(e);
                return cache().getDhtAllAsync(keys.keySet(), args, readThrough, subjId, taskName, expiryPlc, skipVals, recovery);
            }
        });
    }
    if (fut.isDone()) {
        if (fut.error() != null)
            onDone(fut.error());
        else
            return new GridFinishedFuture<>(toEntryInfos(fut.result()));
    }
    return new GridEmbeddedFuture<>(new C2<Map<KeyCacheObject, EntryGetResult>, Exception, Collection<GridCacheEntryInfo>>() {

        @Override
        public Collection<GridCacheEntryInfo> apply(Map<KeyCacheObject, EntryGetResult> map, Exception e) {
            if (e != null) {
                onDone(e);
                return Collections.emptyList();
            } else
                return toEntryInfos(map);
        }
    }, fut);
}
Also used : GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) C2(org.apache.ignite.internal.util.typedef.C2) GridEmbeddedFuture(org.apache.ignite.internal.util.future.GridEmbeddedFuture) ReaderArguments(org.apache.ignite.internal.processors.cache.ReaderArguments) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryGetResult(org.apache.ignite.internal.processors.cache.EntryGetResult) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridCacheEntryInfo(org.apache.ignite.internal.processors.cache.GridCacheEntryInfo) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) Collection(java.util.Collection) Map(java.util.Map)

Example 13 with GridClosureException

use of org.apache.ignite.internal.util.lang.GridClosureException in project ignite by apache.

the class IgfsMetaManager method reserveSpace.

/**
 * Reserve space for file.
 *
 * @param fileId File ID.
 * @param space Space.
 * @param affRange Affinity range.
 * @return New file info.
 */
public IgfsEntryInfo reserveSpace(IgniteUuid fileId, long space, IgfsFileAffinityRange affRange) throws IgniteCheckedException {
    validTxState(false);
    if (busyLock.enterBusy()) {
        try {
            if (log.isDebugEnabled())
                log.debug("Reserve file space: " + fileId);
            try (GridNearTxLocal tx = startTx()) {
                // Lock file ID for this transaction.
                IgfsEntryInfo oldInfo = info(fileId);
                if (oldInfo == null)
                    throw fsException("File has been deleted concurrently: " + fileId);
                IgfsEntryInfo newInfo = invokeAndGet(fileId, new IgfsMetaFileReserveSpaceProcessor(space, affRange));
                tx.commit();
                return newInfo;
            } catch (GridClosureException e) {
                throw U.cast(e);
            }
        } finally {
            busyLock.leaveBusy();
        }
    } else
        throw new IllegalStateException("Failed to reserve file space because Grid is stopping:" + fileId);
}
Also used : GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) IgfsMetaFileReserveSpaceProcessor(org.apache.ignite.internal.processors.igfs.meta.IgfsMetaFileReserveSpaceProcessor) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal)

Example 14 with GridClosureException

use of org.apache.ignite.internal.util.lang.GridClosureException in project ignite by apache.

the class GridQueryProcessor method executeQuery.

/**
 * @param qryType Query type.
 * @param qry Query description.
 * @param cctx Cache context.
 * @param clo Closure.
 * @param complete Complete.
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public <R> R executeQuery(GridCacheQueryType qryType, String qry, @Nullable GridCacheContext<?, ?> cctx, IgniteOutClosureX<R> clo, boolean complete) throws IgniteCheckedException {
    final long startTime = U.currentTimeMillis();
    Throwable err = null;
    R res = null;
    try {
        res = clo.apply();
        if (res instanceof CacheQueryFuture) {
            CacheQueryFuture fut = (CacheQueryFuture) res;
            err = fut.error();
        }
        return res;
    } catch (GridClosureException e) {
        err = e.unwrap();
        throw (IgniteCheckedException) err;
    } catch (CacheException | IgniteException e) {
        err = e;
        throw e;
    } catch (Exception e) {
        err = e;
        throw new IgniteCheckedException(e);
    } finally {
        boolean failed = err != null;
        long duration = U.currentTimeMillis() - startTime;
        if (complete || failed) {
            if (cctx != null)
                cctx.queries().collectMetrics(qryType, qry, startTime, duration, failed);
            if (log.isTraceEnabled())
                log.trace("Query execution [startTime=" + startTime + ", duration=" + duration + ", fail=" + failed + ", res=" + res + ']');
        }
    }
}
Also used : GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheException(javax.cache.CacheException) IgniteException(org.apache.ignite.IgniteException) CacheQueryFuture(org.apache.ignite.internal.processors.cache.query.CacheQueryFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SQLException(java.sql.SQLException) SchemaOperationException(org.apache.ignite.internal.processors.query.schema.SchemaOperationException) IgniteException(org.apache.ignite.IgniteException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) CacheException(javax.cache.CacheException) GridClosureException(org.apache.ignite.internal.util.lang.GridClosureException)

Aggregations

GridClosureException (org.apache.ignite.internal.util.lang.GridClosureException)14 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)11 NodeStoppingException (org.apache.ignite.internal.NodeStoppingException)8 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)8 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)8 CacheException (javax.cache.CacheException)7 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)7 IgniteTxRollbackCheckedException (org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException)7 Map (java.util.Map)6 IgniteTxOptimisticCheckedException (org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException)6 IgniteTxTimeoutCheckedException (org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException)6 GridFinishedFuture (org.apache.ignite.internal.util.future.GridFinishedFuture)6 HashMap (java.util.HashMap)5 LinkedHashMap (java.util.LinkedHashMap)5 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)5 GridTimeoutObject (org.apache.ignite.internal.processors.timeout.GridTimeoutObject)5 GridEmbeddedFuture (org.apache.ignite.internal.util.future.GridEmbeddedFuture)5 CacheOperationContext (org.apache.ignite.internal.processors.cache.CacheOperationContext)4 IgniteCacheExpiryPolicy (org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy)4 GridNearTxLocal (org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal)4