Search in sources :

Example 11 with CacheObject

use of org.apache.ignite.internal.processors.cache.CacheObject in project ignite by apache.

the class GridDhtTxPrepareFuture method versionCheckError.

/**
     * @param entry Entry.
     * @return Optimistic version check error.
     */
private IgniteTxOptimisticCheckedException versionCheckError(IgniteTxEntry entry) {
    StringBuilder msg = new StringBuilder("Failed to prepare transaction, read/write conflict [");
    GridCacheContext cctx = entry.context();
    try {
        Object key = cctx.unwrapBinaryIfNeeded(entry.key(), entry.keepBinary(), false);
        assert key != null : entry.key();
        if (S.INCLUDE_SENSITIVE)
            msg.append("key=").append(key.toString()).append(", keyCls=").append(key.getClass().getName());
    } catch (Exception e) {
        msg.append("key=<failed to get key: ").append(e.toString()).append(">");
    }
    try {
        GridCacheEntryEx entryEx = entry.cached();
        CacheObject cacheVal = entryEx != null ? entryEx.rawGet() : null;
        Object val = cacheVal != null ? cctx.unwrapBinaryIfNeeded(cacheVal, entry.keepBinary(), false) : null;
        if (val != null) {
            if (S.INCLUDE_SENSITIVE)
                msg.append(", val=").append(val.toString()).append(", valCls=").append(val.getClass().getName());
        } else
            msg.append(", val=null");
    } catch (Exception e) {
        msg.append(", val=<failed to get value: ").append(e.toString()).append(">");
    }
    msg.append(", cache=").append(cctx.name()).append(", thread=").append(Thread.currentThread()).append("]");
    return new IgniteTxOptimisticCheckedException(msg.toString());
}
Also used : GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) IgniteInterruptedException(org.apache.ignite.IgniteInterruptedException) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) IgniteFutureCancelledException(org.apache.ignite.lang.IgniteFutureCancelledException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) IgniteTxOptimisticCheckedException(org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException) IgniteTxOptimisticCheckedException(org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException)

Example 12 with CacheObject

use of org.apache.ignite.internal.processors.cache.CacheObject in project ignite by apache.

the class GridDhtAtomicCache method getAllAsync0.

/**
     * Entry point to all public API get methods.
     *
     * @param keys Keys.
     * @param forcePrimary Force primary flag.
     * @param subjId Subject ID.
     * @param taskName Task name.
     * @param deserializeBinary Deserialize binary flag.
     * @param expiryPlc Expiry policy.
     * @param skipVals Skip values flag.
     * @param skipStore Skip store flag.
     * @param needVer Need version.
     * @return Get future.
     */
private IgniteInternalFuture<Map<K, V>> getAllAsync0(@Nullable Collection<KeyCacheObject> keys, boolean forcePrimary, UUID subjId, String taskName, boolean deserializeBinary, boolean recovery, @Nullable ExpiryPolicy expiryPlc, boolean skipVals, boolean skipStore, boolean canRemap, boolean needVer) {
    AffinityTopologyVersion topVer = canRemap ? ctx.affinity().affinityTopologyVersion() : ctx.shared().exchange().readyAffinityVersion();
    final IgniteCacheExpiryPolicy expiry = skipVals ? null : expiryPolicy(expiryPlc);
    final boolean evt = !skipVals;
    // Optimisation: try to resolve value locally and escape 'get future' creation.
    if (!forcePrimary && ctx.affinityNode()) {
        try {
            Map<K, V> locVals = U.newHashMap(keys.size());
            boolean success = true;
            boolean readNoEntry = ctx.readNoEntry(expiry, false);
            // Optimistically expect that all keys are available locally (avoid creation of get future).
            for (KeyCacheObject key : keys) {
                if (readNoEntry) {
                    CacheDataRow row = ctx.offheap().read(key);
                    if (row != null) {
                        long expireTime = row.expireTime();
                        if (expireTime == 0 || expireTime > U.currentTimeMillis()) {
                            ctx.addResult(locVals, key, row.value(), skipVals, false, deserializeBinary, true, null, row.version(), 0, 0, needVer);
                            if (evt) {
                                ctx.events().readEvent(key, null, row.value(), subjId, taskName, !deserializeBinary);
                            }
                        } else
                            success = false;
                    } else
                        success = false;
                } else {
                    GridCacheEntryEx entry = null;
                    while (true) {
                        try {
                            entry = entryEx(key);
                            // If our DHT cache do has value, then we peek it.
                            if (entry != null) {
                                boolean isNew = entry.isNewLocked();
                                EntryGetResult getRes = null;
                                CacheObject v = null;
                                GridCacheVersion ver = null;
                                if (needVer) {
                                    getRes = entry.innerGetVersioned(null, null, /*update-metrics*/
                                    false, /*event*/
                                    evt, subjId, null, taskName, expiry, true, null);
                                    if (getRes != null) {
                                        v = getRes.value();
                                        ver = getRes.version();
                                    }
                                } else {
                                    v = entry.innerGet(null, null, /*read-through*/
                                    false, /*update-metrics*/
                                    false, /*event*/
                                    evt, subjId, null, taskName, expiry, !deserializeBinary);
                                }
                                // Entry was not in memory or in swap, so we remove it from cache.
                                if (v == null) {
                                    if (isNew && entry.markObsoleteIfEmpty(context().versions().next()))
                                        removeEntry(entry);
                                    success = false;
                                } else {
                                    ctx.addResult(locVals, key, v, skipVals, false, deserializeBinary, true, getRes, ver, 0, 0, needVer);
                                }
                            } else
                                success = false;
                            // While.
                            break;
                        } catch (GridCacheEntryRemovedException ignored) {
                        // No-op, retry.
                        } catch (GridDhtInvalidPartitionException ignored) {
                            success = false;
                            // While.
                            break;
                        } finally {
                            if (entry != null)
                                ctx.evicts().touch(entry, topVer);
                        }
                    }
                }
                if (!success)
                    break;
                else if (!skipVals && ctx.config().isStatisticsEnabled())
                    metrics0().onRead(true);
            }
            if (success) {
                sendTtlUpdateRequest(expiry);
                return new GridFinishedFuture<>(locVals);
            }
        } catch (IgniteCheckedException e) {
            return new GridFinishedFuture<>(e);
        }
    }
    if (expiry != null)
        expiry.reset();
    // Either reload or not all values are available locally.
    GridPartitionedGetFuture<K, V> fut = new GridPartitionedGetFuture<>(ctx, keys, topVer, !skipStore, forcePrimary, subjId, taskName, deserializeBinary, recovery, expiry, skipVals, canRemap, needVer, false);
    fut.init();
    return fut;
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.database.CacheDataRow) GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException) GridPartitionedGetFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedGetFuture) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryGetResult(org.apache.ignite.internal.processors.cache.EntryGetResult) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) IgniteCacheExpiryPolicy(org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 13 with CacheObject

use of org.apache.ignite.internal.processors.cache.CacheObject in project ignite by apache.

the class GridPartitionedGetFuture method localGet.

/**
     * @param key Key.
     * @param part Partition.
     * @param locVals Local values.
     * @return {@code True} if there is no need to further search value.
     */
private boolean localGet(KeyCacheObject key, int part, Map<K, V> locVals) {
    assert cctx.affinityNode() : this;
    GridDhtCacheAdapter<K, V> cache = cache();
    boolean readNoEntry = cctx.readNoEntry(expiryPlc, false);
    boolean evt = !skipVals;
    while (true) {
        try {
            boolean skipEntry = readNoEntry;
            EntryGetResult getRes = null;
            CacheObject v = null;
            GridCacheVersion ver = null;
            if (readNoEntry) {
                CacheDataRow row = cctx.offheap().read(key);
                if (row != null) {
                    long expireTime = row.expireTime();
                    if (expireTime == 0 || expireTime > U.currentTimeMillis()) {
                        v = row.value();
                        if (needVer)
                            ver = row.version();
                        if (evt) {
                            cctx.events().readEvent(key, null, row.value(), subjId, taskName, !deserializeBinary);
                        }
                    } else
                        skipEntry = false;
                }
            }
            if (!skipEntry) {
                GridCacheEntryEx entry = cache.entryEx(key);
                // If our DHT cache do has value, then we peek it.
                if (entry != null) {
                    boolean isNew = entry.isNewLocked();
                    if (needVer) {
                        getRes = entry.innerGetVersioned(null, null, /*update-metrics*/
                        false, /*event*/
                        evt, subjId, null, taskName, expiryPlc, !deserializeBinary, null);
                        if (getRes != null) {
                            v = getRes.value();
                            ver = getRes.version();
                        }
                    } else {
                        v = entry.innerGet(null, null, /*read-through*/
                        false, /*update-metrics*/
                        false, /*event*/
                        evt, subjId, null, taskName, expiryPlc, !deserializeBinary);
                    }
                    cache.context().evicts().touch(entry, topVer);
                    // Entry was not in memory or in swap, so we remove it from cache.
                    if (v == null) {
                        if (isNew && entry.markObsoleteIfEmpty(ver))
                            cache.removeEntry(entry);
                    }
                }
            }
            if (v != null) {
                cctx.addResult(locVals, key, v, skipVals, keepCacheObjects, deserializeBinary, true, getRes, ver, 0, 0, needVer);
                return true;
            }
            boolean topStable = cctx.isReplicated() || topVer.equals(cctx.topology().topologyVersion());
            // Entry not found, do not continue search if topology did not change and there is no store.
            if (!cctx.readThroughConfigured() && (topStable || partitionOwned(part))) {
                if (!skipVals && cctx.config().isStatisticsEnabled())
                    cache.metrics0().onRead(false);
                return true;
            }
            return false;
        } catch (GridCacheEntryRemovedException ignored) {
        // No-op, will retry.
        } catch (GridDhtInvalidPartitionException ignored) {
            return false;
        } catch (IgniteCheckedException e) {
            onDone(e);
            return true;
        }
    }
}
Also used : CacheDataRow(org.apache.ignite.internal.processors.cache.database.CacheDataRow) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryGetResult(org.apache.ignite.internal.processors.cache.EntryGetResult) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 14 with CacheObject

use of org.apache.ignite.internal.processors.cache.CacheObject in project ignite by apache.

the class GridDhtColocatedLockFuture method map0.

/**
     * @param keys Keys to map.
     * @param remap Remap flag.
     * @param topLocked Topology locked flag.
     * @throws IgniteCheckedException If mapping failed.
     */
private synchronized void map0(Collection<KeyCacheObject> keys, boolean remap, boolean topLocked) throws IgniteCheckedException {
    AffinityTopologyVersion topVer = this.topVer;
    assert topVer != null;
    assert topVer.topologyVersion() > 0;
    if (CU.affinityNodes(cctx, topVer).isEmpty()) {
        onDone(new ClusterTopologyServerNotFoundException("Failed to map keys for cache " + "(all partition nodes left the grid): " + cctx.name()));
        return;
    }
    boolean clientNode = cctx.kernalContext().clientNode();
    assert !remap || (clientNode && (tx == null || !tx.hasRemoteLocks()));
    // First assume this node is primary for all keys passed in.
    if (!clientNode && mapAsPrimary(keys, topVer))
        return;
    mappings = new ArrayDeque<>();
    // Assign keys to primary nodes.
    GridNearLockMapping map = null;
    for (KeyCacheObject key : keys) {
        GridNearLockMapping updated = map(key, map, topVer);
        // If new mapping was created, add to collection.
        if (updated != map) {
            mappings.add(updated);
            if (tx != null && updated.node().isLocal())
                tx.colocatedLocallyMapped(true);
        }
        map = updated;
    }
    if (isDone()) {
        if (log.isDebugEnabled())
            log.debug("Abandoning (re)map because future is done: " + this);
        return;
    }
    if (log.isDebugEnabled())
        log.debug("Starting (re)map for mappings [mappings=" + mappings + ", fut=" + this + ']');
    boolean hasRmtNodes = false;
    boolean first = true;
    // Create mini futures.
    for (Iterator<GridNearLockMapping> iter = mappings.iterator(); iter.hasNext(); ) {
        GridNearLockMapping mapping = iter.next();
        ClusterNode node = mapping.node();
        Collection<KeyCacheObject> mappedKeys = mapping.mappedKeys();
        boolean loc = node.equals(cctx.localNode());
        assert !mappedKeys.isEmpty();
        GridNearLockRequest req = null;
        Collection<KeyCacheObject> distributedKeys = new ArrayList<>(mappedKeys.size());
        for (KeyCacheObject key : mappedKeys) {
            IgniteTxKey txKey = cctx.txKey(key);
            GridDistributedCacheEntry entry = null;
            if (tx != null) {
                IgniteTxEntry txEntry = tx.entry(txKey);
                if (txEntry != null) {
                    entry = (GridDistributedCacheEntry) txEntry.cached();
                    if (entry != null && loc == entry.detached()) {
                        entry = cctx.colocated().entryExx(key, topVer, true);
                        txEntry.cached(entry);
                    }
                }
            }
            boolean explicit;
            while (true) {
                try {
                    if (entry == null)
                        entry = cctx.colocated().entryExx(key, topVer, true);
                    if (!cctx.isAll(entry, filter)) {
                        if (log.isDebugEnabled())
                            log.debug("Entry being locked did not pass filter (will not lock): " + entry);
                        onComplete(false, false);
                        return;
                    }
                    assert loc ^ entry.detached() : "Invalid entry [loc=" + loc + ", entry=" + entry + ']';
                    GridCacheMvccCandidate cand = addEntry(entry);
                    // Will either return value from dht cache or null if this is a miss.
                    IgniteBiTuple<GridCacheVersion, CacheObject> val = entry.detached() ? null : ((GridDhtCacheEntry) entry).versionedValue(topVer);
                    GridCacheVersion dhtVer = null;
                    if (val != null) {
                        dhtVer = val.get1();
                        valMap.put(key, val);
                    }
                    if (cand != null && !cand.reentry()) {
                        if (req == null) {
                            boolean clientFirst = false;
                            if (first) {
                                clientFirst = clientNode && !topLocked && (tx == null || !tx.hasRemoteLocks());
                                first = false;
                            }
                            assert !implicitTx() && !implicitSingleTx() : tx;
                            req = new GridNearLockRequest(cctx.cacheId(), topVer, cctx.nodeId(), threadId, futId, lockVer, inTx(), read, retval, isolation(), isInvalidate(), timeout, mappedKeys.size(), inTx() ? tx.size() : mappedKeys.size(), inTx() && tx.syncMode() == FULL_SYNC, inTx() ? tx.subjectId() : null, inTx() ? tx.taskNameHash() : 0, read ? createTtl : -1L, read ? accessTtl : -1L, skipStore, keepBinary, clientFirst, cctx.deploymentEnabled());
                            mapping.request(req);
                        }
                        distributedKeys.add(key);
                        if (tx != null)
                            tx.addKeyMapping(txKey, mapping.node());
                        req.addKeyBytes(key, retval, // Include DHT version to match remote DHT entry.
                        dhtVer, cctx);
                    }
                    explicit = inTx() && cand == null;
                    if (explicit)
                        tx.addKeyMapping(txKey, mapping.node());
                    break;
                } catch (GridCacheEntryRemovedException ignored) {
                    if (log.isDebugEnabled())
                        log.debug("Got removed entry in lockAsync(..) method (will retry): " + entry);
                    entry = null;
                }
            }
            // Mark mapping explicit lock flag.
            if (explicit) {
                boolean marked = tx != null && tx.markExplicit(node.id());
                assert tx == null || marked;
            }
        }
        if (!distributedKeys.isEmpty()) {
            mapping.distributedKeys(distributedKeys);
            hasRmtNodes |= !mapping.node().isLocal();
        } else {
            assert mapping.request() == null;
            iter.remove();
        }
    }
    if (hasRmtNodes) {
        trackable = true;
        if (!remap && !cctx.mvcc().addFuture(this))
            throw new IllegalStateException("Duplicate future ID: " + this);
    } else
        trackable = false;
    proceedMapping();
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteTxEntry(org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry) GridDistributedCacheEntry(org.apache.ignite.internal.processors.cache.distributed.GridDistributedCacheEntry) GridNearLockMapping(org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockMapping) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridNearLockRequest(org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockRequest) ArrayList(java.util.ArrayList) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) IgniteTxKey(org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridCacheMvccCandidate(org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate)

Example 15 with CacheObject

use of org.apache.ignite.internal.processors.cache.CacheObject in project ignite by apache.

the class GridNearAtomicCache method processNearAtomicUpdateResponse.

/**
     * @param req Update request.
     * @param res Update response.
     */
public void processNearAtomicUpdateResponse(GridNearAtomicAbstractUpdateRequest req, GridNearAtomicUpdateResponse res) {
    if (F.size(res.failedKeys()) == req.size())
        return;
    /*
         * Choose value to be stored in near cache: first check key is not in failed and not in skipped list,
         * then check if value was generated on primary node, if not then use value sent in request.
         */
    Collection<KeyCacheObject> failed = res.failedKeys();
    List<Integer> nearValsIdxs = res.nearValuesIndexes();
    List<Integer> skipped = res.skippedIndexes();
    GridCacheVersion ver = res.nearVersion();
    assert ver != null : "Failed to find version [req=" + req + ", res=" + res + ']';
    int nearValIdx = 0;
    String taskName = ctx.kernalContext().task().resolveTaskName(req.taskNameHash());
    for (int i = 0; i < req.size(); i++) {
        if (F.contains(skipped, i))
            continue;
        KeyCacheObject key = req.key(i);
        if (F.contains(failed, key))
            continue;
        if (ctx.affinity().partitionBelongs(ctx.localNode(), ctx.affinity().partition(key), req.topologyVersion())) {
            // Reader became backup.
            GridCacheEntryEx entry = peekEx(key);
            if (entry != null && entry.markObsolete(ver))
                removeEntry(entry);
            continue;
        }
        CacheObject val = null;
        if (F.contains(nearValsIdxs, i)) {
            val = res.nearValue(nearValIdx);
            nearValIdx++;
        } else {
            assert req.operation() != TRANSFORM;
            if (req.operation() != DELETE)
                val = req.value(i);
        }
        long ttl = res.nearTtl(i);
        long expireTime = res.nearExpireTime(i);
        if (ttl != CU.TTL_NOT_CHANGED && expireTime == CU.EXPIRE_TIME_CALCULATE)
            expireTime = CU.toExpireTime(ttl);
        try {
            processNearAtomicUpdateResponse(ver, key, val, ttl, expireTime, req.keepBinary(), req.nodeId(), req.subjectId(), taskName);
        } catch (IgniteCheckedException e) {
            res.addFailedKey(key, new IgniteCheckedException("Failed to update key in near cache: " + key, e));
        }
    }
}
Also used : GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Aggregations

CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)82 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)74 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)42 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)41 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)34 GridCacheEntryEx (org.apache.ignite.internal.processors.cache.GridCacheEntryEx)24 CacheLockCandidates (org.apache.ignite.internal.processors.cache.CacheLockCandidates)17 GridCacheMvcc (org.apache.ignite.internal.processors.cache.GridCacheMvcc)17 EntryGetResult (org.apache.ignite.internal.processors.cache.EntryGetResult)14 ArrayList (java.util.ArrayList)13 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)12 IgniteTxEntry (org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry)12 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)11 GridCacheMvccCandidate (org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate)11 GridCacheOperation (org.apache.ignite.internal.processors.cache.GridCacheOperation)10 Nullable (org.jetbrains.annotations.Nullable)10 IgniteException (org.apache.ignite.IgniteException)9 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)9 IgniteTxKey (org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey)9 LinkedHashMap (java.util.LinkedHashMap)8