Search in sources :

Example 1 with StorageException

use of org.apache.ignite.internal.pagemem.wal.StorageException in project ignite by apache.

the class IgniteTxLocalAdapter method userCommit.

/** {@inheritDoc} */
@SuppressWarnings({ "CatchGenericClass" })
@Override
public void userCommit() throws IgniteCheckedException {
    TransactionState state = state();
    if (state != COMMITTING) {
        if (remainingTime() == -1)
            throw new IgniteTxTimeoutCheckedException("Transaction timed out: " + this);
        setRollbackOnly();
        throw new IgniteCheckedException("Invalid transaction state for commit [state=" + state + ", tx=" + this + ']');
    }
    checkValid();
    Collection<IgniteTxEntry> commitEntries = near() ? allEntries() : writeEntries();
    boolean empty = F.isEmpty(commitEntries);
    // locks on backup nodes.
    if (!empty || colocated())
        cctx.tm().addCommittedTx(this);
    if (!empty) {
        batchStoreCommit(writeEntries());
        WALPointer ptr = null;
        cctx.database().checkpointReadLock();
        try {
            cctx.tm().txContext(this);
            AffinityTopologyVersion topVer = topologyVersion();
            /*
                 * Commit to cache. Note that for 'near' transaction we loop through all the entries.
                 */
            for (IgniteTxEntry txEntry : commitEntries) {
                GridCacheContext cacheCtx = txEntry.context();
                GridDrType drType = cacheCtx.isDrEnabled() ? DR_PRIMARY : DR_NONE;
                UUID nodeId = txEntry.nodeId() == null ? this.nodeId : txEntry.nodeId();
                try {
                    while (true) {
                        try {
                            GridCacheEntryEx cached = txEntry.cached();
                            // transaction manager to make sure locks are held.
                            if (!evictNearEntry(txEntry, false)) {
                                if (cacheCtx.isNear() && cacheCtx.dr().receiveEnabled()) {
                                    cached.markObsolete(xidVer);
                                    break;
                                }
                                if (cached.detached())
                                    break;
                                GridCacheEntryEx nearCached = null;
                                boolean metrics = true;
                                if (updateNearCache(cacheCtx, txEntry.key(), topVer))
                                    nearCached = cacheCtx.dht().near().peekEx(txEntry.key());
                                else if (cacheCtx.isNear() && txEntry.locallyMapped())
                                    metrics = false;
                                boolean evt = !isNearLocallyMapped(txEntry, false);
                                if (!F.isEmpty(txEntry.entryProcessors()) || !F.isEmpty(txEntry.filters()))
                                    txEntry.cached().unswap(false);
                                IgniteBiTuple<GridCacheOperation, CacheObject> res = applyTransformClosures(txEntry, true, null);
                                GridCacheVersion dhtVer = null;
                                // backup remote transaction completes.
                                if (cacheCtx.isNear()) {
                                    if (txEntry.op() == CREATE || txEntry.op() == UPDATE || txEntry.op() == DELETE || txEntry.op() == TRANSFORM)
                                        dhtVer = txEntry.dhtVersion();
                                    if ((txEntry.op() == CREATE || txEntry.op() == UPDATE) && txEntry.conflictExpireTime() == CU.EXPIRE_TIME_CALCULATE) {
                                        ExpiryPolicy expiry = cacheCtx.expiryForTxEntry(txEntry);
                                        if (expiry != null) {
                                            txEntry.cached().unswap(false);
                                            Duration duration = cached.hasValue() ? expiry.getExpiryForUpdate() : expiry.getExpiryForCreation();
                                            txEntry.ttl(CU.toTtl(duration));
                                        }
                                    }
                                }
                                GridCacheOperation op = res.get1();
                                CacheObject val = res.get2();
                                // Deal with conflicts.
                                GridCacheVersion explicitVer = txEntry.conflictVersion() != null ? txEntry.conflictVersion() : writeVersion();
                                if ((op == CREATE || op == UPDATE) && txEntry.conflictExpireTime() == CU.EXPIRE_TIME_CALCULATE) {
                                    ExpiryPolicy expiry = cacheCtx.expiryForTxEntry(txEntry);
                                    if (expiry != null) {
                                        Duration duration = cached.hasValue() ? expiry.getExpiryForUpdate() : expiry.getExpiryForCreation();
                                        long ttl = CU.toTtl(duration);
                                        txEntry.ttl(ttl);
                                        if (ttl == CU.TTL_ZERO)
                                            op = DELETE;
                                    }
                                }
                                boolean conflictNeedResolve = cacheCtx.conflictNeedResolve();
                                GridCacheVersionConflictContext<?, ?> conflictCtx = null;
                                if (conflictNeedResolve) {
                                    IgniteBiTuple<GridCacheOperation, GridCacheVersionConflictContext> conflictRes = conflictResolve(op, txEntry, val, explicitVer, cached);
                                    assert conflictRes != null;
                                    conflictCtx = conflictRes.get2();
                                    if (conflictCtx.isUseOld())
                                        op = NOOP;
                                    else if (conflictCtx.isUseNew()) {
                                        txEntry.ttl(conflictCtx.ttl());
                                        txEntry.conflictExpireTime(conflictCtx.expireTime());
                                    } else {
                                        assert conflictCtx.isMerge();
                                        op = conflictRes.get1();
                                        val = txEntry.context().toCacheObject(conflictCtx.mergeValue());
                                        explicitVer = writeVersion();
                                        txEntry.ttl(conflictCtx.ttl());
                                        txEntry.conflictExpireTime(conflictCtx.expireTime());
                                    }
                                } else
                                    // Nullify explicit version so that innerSet/innerRemove will work as usual.
                                    explicitVer = null;
                                if (sndTransformedVals || conflictNeedResolve) {
                                    assert sndTransformedVals && cacheCtx.isReplicated() || conflictNeedResolve;
                                    txEntry.value(val, true, false);
                                    txEntry.op(op);
                                    txEntry.entryProcessors(null);
                                    txEntry.conflictVersion(explicitVer);
                                }
                                if (dhtVer == null)
                                    dhtVer = explicitVer != null ? explicitVer : writeVersion();
                                if (cctx.wal() != null && !writeEntries().isEmpty() && op != NOOP && op != RELOAD && op != READ)
                                    ptr = cctx.wal().log(new DataRecord(new DataEntry(cacheCtx.cacheId(), txEntry.key(), val, op, nearXidVersion(), writeVersion(), 0, txEntry.key().partition(), txEntry.updateCounter())));
                                if (op == CREATE || op == UPDATE) {
                                    GridCacheUpdateTxResult updRes = cached.innerSet(this, eventNodeId(), txEntry.nodeId(), val, false, false, txEntry.ttl(), evt, metrics, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, null, cached.detached() ? DR_NONE : drType, txEntry.conflictExpireTime(), cached.isNear() ? null : explicitVer, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, null);
                                    if (updRes.success())
                                        txEntry.updateCounter(updRes.updatePartitionCounter());
                                    if (nearCached != null && updRes.success()) {
                                        nearCached.innerSet(null, eventNodeId(), nodeId, val, false, false, txEntry.ttl(), false, metrics, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, CU.empty0(), DR_NONE, txEntry.conflictExpireTime(), null, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, null);
                                    }
                                } else if (op == DELETE) {
                                    GridCacheUpdateTxResult updRes = cached.innerRemove(this, eventNodeId(), txEntry.nodeId(), false, evt, metrics, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, null, cached.detached() ? DR_NONE : drType, cached.isNear() ? null : explicitVer, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, null);
                                    if (updRes.success())
                                        txEntry.updateCounter(updRes.updatePartitionCounter());
                                    if (nearCached != null && updRes.success()) {
                                        nearCached.innerRemove(null, eventNodeId(), nodeId, false, false, metrics, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, CU.empty0(), DR_NONE, null, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, null);
                                    }
                                } else if (op == RELOAD) {
                                    cached.innerReload();
                                    if (nearCached != null)
                                        nearCached.innerReload();
                                } else if (op == READ) {
                                    ExpiryPolicy expiry = cacheCtx.expiryForTxEntry(txEntry);
                                    if (expiry != null) {
                                        Duration duration = expiry.getExpiryForAccess();
                                        if (duration != null)
                                            cached.updateTtl(null, CU.toTtl(duration));
                                    }
                                    if (log.isDebugEnabled())
                                        log.debug("Ignoring READ entry when committing: " + txEntry);
                                } else {
                                    assert ownsLock(txEntry.cached()) : "Transaction does not own lock for group lock entry during  commit [tx=" + this + ", txEntry=" + txEntry + ']';
                                    if (conflictCtx == null || !conflictCtx.isUseOld()) {
                                        if (txEntry.ttl() != CU.TTL_NOT_CHANGED)
                                            cached.updateTtl(null, txEntry.ttl());
                                    }
                                    if (log.isDebugEnabled())
                                        log.debug("Ignoring NOOP entry when committing: " + txEntry);
                                }
                            }
                            // if an entry is obsolete).
                            if (txEntry.op() != READ)
                                checkCommitLocks(cached);
                            // Break out of while loop.
                            break;
                        }// If entry cached within transaction got removed.
                         catch (GridCacheEntryRemovedException ignored) {
                            if (log.isDebugEnabled())
                                log.debug("Got removed entry during transaction commit (will retry): " + txEntry);
                            txEntry.cached(entryEx(cacheCtx, txEntry.txKey(), topologyVersion()));
                        }
                    }
                } catch (Throwable ex) {
                    // We are about to initiate transaction rollback when tx has started to committing.
                    // Need to remove version from committed list.
                    cctx.tm().removeCommittedTx(this);
                    if (X.hasCause(ex, GridCacheIndexUpdateException.class) && cacheCtx.cache().isMongoDataCache()) {
                        if (log.isDebugEnabled())
                            log.debug("Failed to update mongo document index (transaction entry will " + "be ignored): " + txEntry);
                        // Set operation to NOOP.
                        txEntry.op(NOOP);
                        errorWhenCommitting();
                        throw ex;
                    } else {
                        IgniteCheckedException err = new IgniteTxHeuristicCheckedException("Failed to locally write to cache " + "(all transaction entries will be invalidated, however there was a window when " + "entries for this transaction were visible to others): " + this, ex);
                        U.error(log, "Heuristic transaction failure.", err);
                        COMMIT_ERR_UPD.compareAndSet(this, null, err);
                        state(UNKNOWN);
                        try {
                            // Courtesy to minimize damage.
                            uncommit();
                        } catch (Throwable ex1) {
                            U.error(log, "Failed to uncommit transaction: " + this, ex1);
                            if (ex1 instanceof Error)
                                throw ex1;
                        }
                        if (ex instanceof Error)
                            throw ex;
                        throw err;
                    }
                }
            }
            if (ptr != null)
                cctx.wal().fsync(ptr);
        } catch (StorageException e) {
            throw new IgniteCheckedException("Failed to log transaction record " + "(transaction will be rolled back): " + this, e);
        } finally {
            cctx.database().checkpointReadUnlock();
            cctx.tm().resetContext();
        }
    }
    // Do not unlock transaction entries if one-phase commit.
    if (!onePhaseCommit()) {
        if (DONE_FLAG_UPD.compareAndSet(this, 0, 1)) {
            // Unlock all locks.
            cctx.tm().commitTx(this);
            boolean needsCompletedVersions = needsCompletedVersions();
            assert !needsCompletedVersions || completedBase != null;
            assert !needsCompletedVersions || committedVers != null;
            assert !needsCompletedVersions || rolledbackVers != null;
        }
    }
}
Also used : TransactionState(org.apache.ignite.transactions.TransactionState) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) DataEntry(org.apache.ignite.internal.pagemem.wal.record.DataEntry) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteCacheExpiryPolicy(org.apache.ignite.internal.processors.cache.IgniteCacheExpiryPolicy) ExpiryPolicy(javax.cache.expiry.ExpiryPolicy) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) DataRecord(org.apache.ignite.internal.pagemem.wal.record.DataRecord) UUID(java.util.UUID) WALPointer(org.apache.ignite.internal.pagemem.wal.WALPointer) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) Duration(javax.cache.expiry.Duration) GridCacheVersionConflictContext(org.apache.ignite.internal.processors.cache.version.GridCacheVersionConflictContext) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) GridDrType(org.apache.ignite.internal.processors.dr.GridDrType) GridCacheUpdateTxResult(org.apache.ignite.internal.processors.cache.GridCacheUpdateTxResult) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) GridCacheOperation(org.apache.ignite.internal.processors.cache.GridCacheOperation) StorageException(org.apache.ignite.internal.pagemem.wal.StorageException)

Example 2 with StorageException

use of org.apache.ignite.internal.pagemem.wal.StorageException in project ignite by apache.

the class GridDhtAtomicCache method processDhtAtomicUpdateRequest.

/**
     * @param nodeId Sender node ID.
     * @param req Dht atomic update request.
     */
private void processDhtAtomicUpdateRequest(UUID nodeId, GridDhtAtomicAbstractUpdateRequest req) {
    assert Thread.currentThread().getName().startsWith("sys-stripe-") : Thread.currentThread().getName();
    if (msgLog.isDebugEnabled()) {
        msgLog.debug("Received DHT atomic update request [futId=" + req.futureId() + ", writeVer=" + req.writeVersion() + ", node=" + nodeId + ']');
    }
    assert req.partition() >= 0 : req;
    GridCacheVersion ver = req.writeVersion();
    GridDhtAtomicNearResponse nearRes = null;
    if (req.nearNodeId() != null) {
        nearRes = new GridDhtAtomicNearResponse(ctx.cacheId(), req.partition(), req.nearFutureId(), nodeId, req.flags());
    }
    boolean replicate = ctx.isDrEnabled();
    boolean intercept = req.forceTransformBackups() && ctx.config().getInterceptor() != null;
    String taskName = ctx.kernalContext().task().resolveTaskName(req.taskNameHash());
    ctx.shared().database().checkpointReadLock();
    try {
        for (int i = 0; i < req.size(); i++) {
            KeyCacheObject key = req.key(i);
            try {
                while (true) {
                    GridDhtCacheEntry entry = null;
                    try {
                        entry = entryExx(key);
                        CacheObject val = req.value(i);
                        CacheObject prevVal = req.previousValue(i);
                        EntryProcessor<Object, Object, Object> entryProcessor = req.entryProcessor(i);
                        Long updateIdx = req.updateCounter(i);
                        GridCacheOperation op = entryProcessor != null ? TRANSFORM : (val != null) ? UPDATE : DELETE;
                        long ttl = req.ttl(i);
                        long expireTime = req.conflictExpireTime(i);
                        GridCacheUpdateAtomicResult updRes = entry.innerUpdate(ver, nodeId, nodeId, op, op == TRANSFORM ? entryProcessor : val, op == TRANSFORM ? req.invokeArguments() : null, /*write-through*/
                        (ctx.store().isLocal() && !ctx.shared().localStorePrimaryOnly()) && writeThrough() && !req.skipStore(), /*read-through*/
                        false, /*retval*/
                        false, req.keepBinary(), /*expiry policy*/
                        null, /*event*/
                        true, /*metrics*/
                        true, /*primary*/
                        false, /*check version*/
                        !req.forceTransformBackups(), req.topologyVersion(), CU.empty0(), replicate ? DR_BACKUP : DR_NONE, ttl, expireTime, req.conflictVersion(i), false, intercept, req.subjectId(), taskName, prevVal, updateIdx, null);
                        if (updRes.removeVersion() != null)
                            ctx.onDeferredDelete(entry, updRes.removeVersion());
                        entry.onUnlock();
                        // While.
                        break;
                    } catch (GridCacheEntryRemovedException ignored) {
                        if (log.isDebugEnabled())
                            log.debug("Got removed entry while updating backup value (will retry): " + key);
                        entry = null;
                    } finally {
                        if (entry != null)
                            ctx.evicts().touch(entry, req.topologyVersion());
                    }
                }
            } catch (NodeStoppingException e) {
                U.error(log, "Failed to update key on backup (local node is stopping):" + key, e);
                return;
            } catch (GridDhtInvalidPartitionException ignored) {
            // Ignore.
            } catch (IgniteCheckedException e) {
                IgniteCheckedException err = new IgniteCheckedException("Failed to update key on backup node: " + key, e);
                if (nearRes != null)
                    nearRes.addFailedKey(key, err);
                U.error(log, "Failed to update key on backup node: " + key, e);
            }
        }
    } finally {
        ctx.shared().database().checkpointReadUnlock();
    }
    GridDhtAtomicUpdateResponse dhtRes = null;
    if (isNearEnabled(cacheCfg)) {
        List<KeyCacheObject> nearEvicted = ((GridNearAtomicCache<K, V>) near()).processDhtAtomicUpdateRequest(nodeId, req, nearRes);
        if (nearEvicted != null) {
            dhtRes = new GridDhtAtomicUpdateResponse(ctx.cacheId(), req.partition(), req.futureId(), ctx.deploymentEnabled());
            dhtRes.nearEvicted(nearEvicted);
        }
    }
    try {
        // TODO fire events only after successful fsync
        if (ctx.shared().wal() != null)
            ctx.shared().wal().fsync(null);
    } catch (StorageException e) {
        if (dhtRes != null)
            dhtRes.onError(new IgniteCheckedException(e));
        if (nearRes != null)
            nearRes.onClassError(e);
    } catch (IgniteCheckedException e) {
        if (dhtRes != null)
            dhtRes.onError(e);
        if (nearRes != null)
            nearRes.onClassError(e);
    }
    if (nearRes != null)
        sendDhtNearResponse(req, nearRes);
    if (dhtRes == null && req.replyWithoutDelay()) {
        dhtRes = new GridDhtAtomicUpdateResponse(ctx.cacheId(), req.partition(), req.futureId(), ctx.deploymentEnabled());
    }
    if (dhtRes != null)
        sendDhtPrimaryResponse(nodeId, req, dhtRes);
    else
        sendDeferredUpdateResponse(req.partition(), nodeId, req.futureId());
}
Also used : GridDhtInvalidPartitionException(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) GridNearAtomicCache(org.apache.ignite.internal.processors.cache.distributed.near.GridNearAtomicCache) GridDhtCacheEntry(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheEntry) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) GridCacheOperation(org.apache.ignite.internal.processors.cache.GridCacheOperation) GridCacheUpdateAtomicResult(org.apache.ignite.internal.processors.cache.GridCacheUpdateAtomicResult) StorageException(org.apache.ignite.internal.pagemem.wal.StorageException) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 3 with StorageException

use of org.apache.ignite.internal.pagemem.wal.StorageException in project ignite by apache.

the class GridDistributedTxRemoteAdapter method commitIfLocked.

/**
     * @throws IgniteCheckedException If commit failed.
     */
@SuppressWarnings({ "CatchGenericClass" })
private void commitIfLocked() throws IgniteCheckedException {
    if (state() == COMMITTING) {
        for (IgniteTxEntry txEntry : writeEntries()) {
            assert txEntry != null : "Missing transaction entry for tx: " + this;
            while (true) {
                GridCacheEntryEx entry = txEntry.cached();
                assert entry != null : "Missing cached entry for transaction entry: " + txEntry;
                try {
                    GridCacheVersion ver = txEntry.explicitVersion() != null ? txEntry.explicitVersion() : xidVer;
                    // If locks haven't been acquired yet, keep waiting.
                    if (!entry.lockedBy(ver)) {
                        if (log.isDebugEnabled())
                            log.debug("Transaction does not own lock for entry (will wait) [entry=" + entry + ", tx=" + this + ']');
                        return;
                    }
                    // While.
                    break;
                } catch (GridCacheEntryRemovedException ignore) {
                    if (log.isDebugEnabled())
                        log.debug("Got removed entry while committing (will retry): " + txEntry);
                    txEntry.cached(txEntry.context().cache().entryEx(txEntry.key(), topologyVersion()));
                }
            }
        }
        // Only one thread gets to commit.
        if (COMMIT_ALLOWED_UPD.compareAndSet(this, 0, 1)) {
            IgniteCheckedException err = null;
            Map<IgniteTxKey, IgniteTxEntry> writeMap = txState.writeMap();
            GridCacheReturnCompletableWrapper wrapper = null;
            if (!F.isEmpty(writeMap)) {
                GridCacheReturn ret = null;
                if (!near() && !local() && onePhaseCommit()) {
                    if (needReturnValue()) {
                        ret = new GridCacheReturn(null, cctx.localNodeId().equals(otherNodeId()), true, null, true);
                        // Originating node.
                        UUID origNodeId = otherNodeId();
                        cctx.tm().addCommittedTxReturn(this, wrapper = new GridCacheReturnCompletableWrapper(!cctx.localNodeId().equals(origNodeId) ? origNodeId : null));
                    } else
                        cctx.tm().addCommittedTx(this, this.nearXidVersion(), null);
                }
                // Register this transaction as completed prior to write-phase to
                // ensure proper lock ordering for removed entries.
                cctx.tm().addCommittedTx(this);
                AffinityTopologyVersion topVer = topologyVersion();
                WALPointer ptr = null;
                cctx.database().checkpointReadLock();
                try {
                    Collection<IgniteTxEntry> entries = near() ? allEntries() : writeEntries();
                    List<DataEntry> dataEntries = null;
                    batchStoreCommit(writeMap().values());
                    try {
                        // Node that for near transactions we grab all entries.
                        for (IgniteTxEntry txEntry : entries) {
                            GridCacheContext cacheCtx = txEntry.context();
                            boolean replicate = cacheCtx.isDrEnabled();
                            try {
                                while (true) {
                                    try {
                                        GridCacheEntryEx cached = txEntry.cached();
                                        if (cached == null)
                                            txEntry.cached(cached = cacheCtx.cache().entryEx(txEntry.key(), topologyVersion()));
                                        if (near() && cacheCtx.dr().receiveEnabled()) {
                                            cached.markObsolete(xidVer);
                                            break;
                                        }
                                        GridNearCacheEntry nearCached = null;
                                        if (updateNearCache(cacheCtx, txEntry.key(), topVer))
                                            nearCached = cacheCtx.dht().near().peekExx(txEntry.key());
                                        if (!F.isEmpty(txEntry.entryProcessors()))
                                            txEntry.cached().unswap(false);
                                        IgniteBiTuple<GridCacheOperation, CacheObject> res = applyTransformClosures(txEntry, false, ret);
                                        GridCacheOperation op = res.get1();
                                        CacheObject val = res.get2();
                                        GridCacheVersion explicitVer = txEntry.conflictVersion();
                                        if (explicitVer == null)
                                            explicitVer = writeVersion();
                                        if (txEntry.ttl() == CU.TTL_ZERO)
                                            op = DELETE;
                                        boolean conflictNeedResolve = cacheCtx.conflictNeedResolve();
                                        GridCacheVersionConflictContext conflictCtx = null;
                                        if (conflictNeedResolve) {
                                            IgniteBiTuple<GridCacheOperation, GridCacheVersionConflictContext> drRes = conflictResolve(op, txEntry, val, explicitVer, cached);
                                            assert drRes != null;
                                            conflictCtx = drRes.get2();
                                            if (conflictCtx.isUseOld())
                                                op = NOOP;
                                            else if (conflictCtx.isUseNew()) {
                                                txEntry.ttl(conflictCtx.ttl());
                                                txEntry.conflictExpireTime(conflictCtx.expireTime());
                                            } else if (conflictCtx.isMerge()) {
                                                op = drRes.get1();
                                                val = txEntry.context().toCacheObject(conflictCtx.mergeValue());
                                                explicitVer = writeVersion();
                                                txEntry.ttl(conflictCtx.ttl());
                                                txEntry.conflictExpireTime(conflictCtx.expireTime());
                                            }
                                        } else
                                            // Nullify explicit version so that innerSet/innerRemove will work as usual.
                                            explicitVer = null;
                                        GridCacheVersion dhtVer = cached.isNear() ? writeVersion() : null;
                                        if (!near() && cctx.wal() != null && op != NOOP && op != RELOAD && op != READ) {
                                            if (dataEntries == null)
                                                dataEntries = new ArrayList<>(entries.size());
                                            dataEntries.add(new DataEntry(cacheCtx.cacheId(), txEntry.key(), val, op, nearXidVersion(), writeVersion(), 0, txEntry.key().partition(), txEntry.updateCounter()));
                                        }
                                        if (op == CREATE || op == UPDATE) {
                                            // Invalidate only for near nodes (backups cannot be invalidated).
                                            if (isSystemInvalidate() || (isInvalidate() && cacheCtx.isNear()))
                                                cached.innerRemove(this, eventNodeId(), nodeId, false, true, true, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, null, replicate ? DR_BACKUP : DR_NONE, near() ? null : explicitVer, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, txEntry.updateCounter());
                                            else {
                                                cached.innerSet(this, eventNodeId(), nodeId, val, false, false, txEntry.ttl(), true, true, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, null, replicate ? DR_BACKUP : DR_NONE, txEntry.conflictExpireTime(), near() ? null : explicitVer, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, txEntry.updateCounter());
                                                // Keep near entry up to date.
                                                if (nearCached != null) {
                                                    CacheObject val0 = cached.valueBytes();
                                                    nearCached.updateOrEvict(xidVer, val0, cached.expireTime(), cached.ttl(), nodeId, topVer);
                                                }
                                            }
                                        } else if (op == DELETE) {
                                            cached.innerRemove(this, eventNodeId(), nodeId, false, true, true, txEntry.keepBinary(), txEntry.hasOldValue(), txEntry.oldValue(), topVer, null, replicate ? DR_BACKUP : DR_NONE, near() ? null : explicitVer, CU.subjectId(this, cctx), resolveTaskName(), dhtVer, txEntry.updateCounter());
                                            // Keep near entry up to date.
                                            if (nearCached != null)
                                                nearCached.updateOrEvict(xidVer, null, 0, 0, nodeId, topVer);
                                        } else if (op == RELOAD) {
                                            CacheObject reloaded = cached.innerReload();
                                            if (nearCached != null) {
                                                nearCached.innerReload();
                                                nearCached.updateOrEvict(cached.version(), reloaded, cached.expireTime(), cached.ttl(), nodeId, topVer);
                                            }
                                        } else if (op == READ) {
                                            assert near();
                                            if (log.isDebugEnabled())
                                                log.debug("Ignoring READ entry when committing: " + txEntry);
                                        } else // No-op.
                                        {
                                            if (conflictCtx == null || !conflictCtx.isUseOld()) {
                                                if (txEntry.ttl() != CU.TTL_NOT_CHANGED)
                                                    cached.updateTtl(null, txEntry.ttl());
                                                if (nearCached != null) {
                                                    CacheObject val0 = cached.valueBytes();
                                                    nearCached.updateOrEvict(xidVer, val0, cached.expireTime(), cached.ttl(), nodeId, topVer);
                                                }
                                            }
                                        }
                                        // that if we replaced removed entries.
                                        assert txEntry.op() == READ || onePhaseCommit() || // and we simply allow the commit to proceed.
                                        !cached.hasLockCandidateUnsafe(xidVer) || cached.lockedByUnsafe(xidVer) : "Transaction does not own lock for commit [entry=" + cached + ", tx=" + this + ']';
                                        // Break out of while loop.
                                        break;
                                    } catch (GridCacheEntryRemovedException ignored) {
                                        if (log.isDebugEnabled())
                                            log.debug("Attempting to commit a removed entry (will retry): " + txEntry);
                                        // Renew cached entry.
                                        txEntry.cached(cacheCtx.cache().entryEx(txEntry.key(), topologyVersion()));
                                    }
                                }
                            } catch (Throwable ex) {
                                // In case of error, we still make the best effort to commit,
                                // as there is no way to rollback at this point.
                                err = new IgniteTxHeuristicCheckedException("Commit produced a runtime exception " + "(all transaction entries will be invalidated): " + CU.txString(this), ex);
                                U.error(log, "Commit failed.", err);
                                uncommit();
                                state(UNKNOWN);
                                if (ex instanceof Error)
                                    throw (Error) ex;
                            }
                        }
                        if (!near() && cctx.wal() != null)
                            cctx.wal().log(new DataRecord(dataEntries));
                        if (ptr != null)
                            cctx.wal().fsync(ptr);
                    } catch (StorageException e) {
                        throw new IgniteCheckedException("Failed to log transaction record " + "(transaction will be rolled back): " + this, e);
                    } finally {
                        cctx.database().checkpointReadUnlock();
                    }
                } finally {
                    if (wrapper != null)
                        wrapper.initialize(ret);
                }
            }
            if (err != null) {
                state(UNKNOWN);
                throw err;
            }
            cctx.tm().commitTx(this);
            state(COMMITTED);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteTxHeuristicCheckedException(org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException) DataEntry(org.apache.ignite.internal.pagemem.wal.record.DataEntry) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheEntryRemovedException(org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) DataRecord(org.apache.ignite.internal.pagemem.wal.record.DataRecord) UUID(java.util.UUID) WALPointer(org.apache.ignite.internal.pagemem.wal.WALPointer) IgniteTxEntry(org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) GridCacheReturn(org.apache.ignite.internal.processors.cache.GridCacheReturn) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridCacheVersionConflictContext(org.apache.ignite.internal.processors.cache.version.GridCacheVersionConflictContext) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) GridNearCacheEntry(org.apache.ignite.internal.processors.cache.distributed.near.GridNearCacheEntry) IgniteTxKey(org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey) GridCacheOperation(org.apache.ignite.internal.processors.cache.GridCacheOperation) GridCacheReturnCompletableWrapper(org.apache.ignite.internal.processors.cache.GridCacheReturnCompletableWrapper) StorageException(org.apache.ignite.internal.pagemem.wal.StorageException)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3 StorageException (org.apache.ignite.internal.pagemem.wal.StorageException)3 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)3 GridCacheEntryRemovedException (org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException)3 GridCacheOperation (org.apache.ignite.internal.processors.cache.GridCacheOperation)3 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)3 GridCacheVersion (org.apache.ignite.internal.processors.cache.version.GridCacheVersion)3 UUID (java.util.UUID)2 WALPointer (org.apache.ignite.internal.pagemem.wal.WALPointer)2 DataEntry (org.apache.ignite.internal.pagemem.wal.record.DataEntry)2 DataRecord (org.apache.ignite.internal.pagemem.wal.record.DataRecord)2 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)2 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)2 GridCacheEntryEx (org.apache.ignite.internal.processors.cache.GridCacheEntryEx)2 GridCacheVersionConflictContext (org.apache.ignite.internal.processors.cache.version.GridCacheVersionConflictContext)2 IgniteTxHeuristicCheckedException (org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException)2 ArrayList (java.util.ArrayList)1 Duration (javax.cache.expiry.Duration)1 ExpiryPolicy (javax.cache.expiry.ExpiryPolicy)1 NodeStoppingException (org.apache.ignite.internal.NodeStoppingException)1