Search in sources :

Example 26 with GridNearTxLocal

use of org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal in project ignite by apache.

the class HibernateReadWriteAccessStrategy method rollbackCurrentTx.

/**
     * Roll backs current transaction.
     */
private void rollbackCurrentTx() {
    try {
        TxContext ctx = txCtx.get();
        if (ctx != null) {
            txCtx.remove();
            GridNearTxLocal tx = cache.tx();
            if (tx != null)
                tx.proxy().rollback();
        }
    } catch (IgniteException e) {
        log.error("Failed to rollback cache transaction.", e);
    }
}
Also used : IgniteException(org.apache.ignite.IgniteException) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal)

Example 27 with GridNearTxLocal

use of org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal in project ignite by apache.

the class CacheJtaManager method checkJta.

/** {@inheritDoc} */
@Override
public void checkJta() throws IgniteCheckedException {
    if (jtaTm == null) {
        try {
            CacheTmLookup tmLookup = tmLookupRef.get();
            if (tmLookup == null)
                return;
            jtaTm = tmLookup.getTm();
        } catch (Exception e) {
            throw new IgniteCheckedException("Failed to get transaction manager: " + e, e);
        }
    }
    if (jtaTm != null) {
        CacheJtaResource rsrc = this.rsrc.get();
        if (rsrc == null || rsrc.isFinished()) {
            try {
                Transaction jtaTx = jtaTm.getTransaction();
                if (jtaTx != null) {
                    GridNearTxLocal tx = cctx.tm().userTx();
                    if (tx == null) {
                        TransactionConfiguration tCfg = cctx.kernalContext().config().getTransactionConfiguration();
                        tx = cctx.tm().newTx(/*implicit*/
                        false, /*implicit single*/
                        false, null, tCfg.getDefaultTxConcurrency(), tCfg.getDefaultTxIsolation(), tCfg.getDefaultTxTimeout(), /*store enabled*/
                        true, /*tx size*/
                        0);
                    }
                    rsrc = new CacheJtaResource(tx, cctx.kernalContext());
                    if (useJtaSync)
                        jtaTx.registerSynchronization(rsrc);
                    else if (!jtaTx.enlistResource(rsrc))
                        throw new IgniteCheckedException("Failed to enlist XA resource to JTA user transaction.");
                    this.rsrc.set(rsrc);
                }
            } catch (SystemException e) {
                throw new IgniteCheckedException("Failed to obtain JTA transaction.", e);
            } catch (RollbackException e) {
                throw new IgniteCheckedException("Failed to enlist XAResource to JTA transaction.", e);
            }
        }
    }
}
Also used : TransactionConfiguration(org.apache.ignite.configuration.TransactionConfiguration) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) RollbackException(javax.transaction.RollbackException) CacheTmLookup(org.apache.ignite.cache.jta.CacheTmLookup) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException)

Example 28 with GridNearTxLocal

use of org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal in project ignite by apache.

the class IgniteTxPessimisticOriginatingNodeFailureAbstractSelfTest method checkPrimaryNodeCrash.

/**
     * Checks tx data consistency in case when primary node crashes.
     *
     * @param commmit Whether to commit or rollback a transaction.
     * @throws Exception If failed.
     */
private void checkPrimaryNodeCrash(final boolean commmit) throws Exception {
    Set<Integer> keys = new HashSet<>();
    for (int i = 0; i < 20; i++) keys.add(i);
    final Collection<IgniteKernal> grids = new ArrayList<>();
    ClusterNode primaryNode = grid(1).localNode();
    for (int i = 0; i < gridCount(); i++) {
        if (i != 1)
            grids.add((IgniteKernal) grid(i));
    }
    failingNodeId = primaryNode.id();
    final Map<Integer, String> map = new HashMap<>();
    final String initVal = "initialValue";
    for (Integer key : keys) {
        grid(originatingNode()).cache(DEFAULT_CACHE_NAME).put(key, initVal);
        map.put(key, String.valueOf(key));
    }
    Map<Integer, Collection<ClusterNode>> nodeMap = new HashMap<>();
    IgniteCache<Integer, String> cache = grid(0).cache(DEFAULT_CACHE_NAME);
    info("Failing node ID: " + grid(1).localNode().id());
    for (Integer key : keys) {
        Collection<ClusterNode> nodes = new ArrayList<>();
        nodes.addAll(affinity(cache).mapKeyToPrimaryAndBackups(key));
        nodes.remove(primaryNode);
        nodeMap.put(key, nodes);
    }
    info("Starting tx [values=" + map + ", topVer=" + grid(1).context().discovery().topologyVersion() + ']');
    assertNotNull(cache);
    try (Transaction tx = grid(0).transactions().txStart()) {
        cache.getAll(keys);
        // Should not send any messages.
        cache.putAll(map);
        TransactionProxyImpl txProxy = (TransactionProxyImpl) tx;
        GridNearTxLocal txEx = txProxy.tx();
        assertTrue(txEx.pessimistic());
        if (commmit) {
            txEx.prepare();
            // Fail the node in the middle of transaction.
            info(">>> Stopping primary node " + primaryNode);
            G.stop(Ignition.ignite(primaryNode.id()).name(), true);
            info(">>> Stopped originating node, finishing transaction: " + primaryNode.id());
            tx.commit();
        } else {
            // Fail the node in the middle of transaction.
            info(">>> Stopping primary node " + primaryNode);
            G.stop(G.ignite(primaryNode.id()).name(), true);
            info(">>> Stopped originating node, finishing transaction: " + primaryNode.id());
            tx.rollback();
        }
    }
    boolean txFinished = GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            for (IgniteKernal g : grids) {
                GridCacheAdapter<?, ?> cache = g.internalCache(DEFAULT_CACHE_NAME);
                IgniteTxManager txMgr = cache.isNear() ? ((GridNearCacheAdapter) cache).dht().context().tm() : cache.context().tm();
                int txNum = txMgr.idMapSize();
                if (txNum != 0)
                    return false;
            }
            return true;
        }
    }, 10000);
    assertTrue(txFinished);
    info("Transactions finished.");
    for (Map.Entry<Integer, Collection<ClusterNode>> e : nodeMap.entrySet()) {
        final Integer key = e.getKey();
        final String val = map.get(key);
        assertFalse(e.getValue().isEmpty());
        for (ClusterNode node : e.getValue()) {
            final UUID checkNodeId = node.id();
            compute(G.ignite(checkNodeId).cluster().forNode(node)).call(new IgniteCallable<Void>() {

                /** */
                @IgniteInstanceResource
                private Ignite ignite;

                @Override
                public Void call() throws Exception {
                    IgniteCache<Integer, String> cache = ignite.cache(DEFAULT_CACHE_NAME);
                    assertNotNull(cache);
                    assertEquals("Failed to check entry value on node: " + checkNodeId, !commmit ? initVal : val, cache.localPeek(key));
                    return null;
                }
            });
        }
    }
    for (Map.Entry<Integer, String> e : map.entrySet()) {
        for (Ignite g : G.allGrids()) assertEquals(!commmit ? initVal : e.getValue(), g.cache(DEFAULT_CACHE_NAME).get(e.getKey()));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) GridCacheAdapter(org.apache.ignite.internal.processors.cache.GridCacheAdapter) GridNearCacheAdapter(org.apache.ignite.internal.processors.cache.distributed.near.GridNearCacheAdapter) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID) HashSet(java.util.HashSet) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteKernal(org.apache.ignite.internal.IgniteKernal) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) IgniteTxManager(org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteFutureTimeoutException(org.apache.ignite.lang.IgniteFutureTimeoutException) IgniteException(org.apache.ignite.IgniteException) Transaction(org.apache.ignite.transactions.Transaction) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl)

Example 29 with GridNearTxLocal

use of org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal in project ignite by apache.

the class IgniteTxManager method txLocksInfo.

/**
     * @param txKeys Tx keys.
     * @return Transactions locks and nodes.
     */
private TxLocksResponse txLocksInfo(Collection<IgniteTxKey> txKeys) {
    TxLocksResponse res = new TxLocksResponse();
    Collection<IgniteInternalTx> txs = activeTransactions();
    for (IgniteInternalTx tx : txs) {
        boolean nearTxLoc = tx instanceof GridNearTxLocal;
        if (!(nearTxLoc || tx instanceof GridDhtTxLocal) || !hasKeys(tx, txKeys))
            continue;
        IgniteTxState state = tx.txState();
        assert state instanceof IgniteTxStateImpl || state instanceof IgniteTxImplicitSingleStateImpl;
        Collection<IgniteTxEntry> txEntries = state instanceof IgniteTxStateImpl ? ((IgniteTxStateImpl) state).allEntriesCopy() : state.allEntries();
        Set<IgniteTxKey> requestedKeys = null;
        // in order to reduce amount of requests to remote nodes.
        if (nearTxLoc) {
            if (tx.pessimistic()) {
                GridDhtColocatedLockFuture fut = (GridDhtColocatedLockFuture) mvccFuture(tx, GridDhtColocatedLockFuture.class);
                if (fut != null)
                    requestedKeys = fut.requestedKeys();
                GridNearLockFuture nearFut = (GridNearLockFuture) mvccFuture(tx, GridNearLockFuture.class);
                if (nearFut != null) {
                    Set<IgniteTxKey> nearRequestedKeys = nearFut.requestedKeys();
                    if (nearRequestedKeys != null) {
                        if (requestedKeys == null)
                            requestedKeys = nearRequestedKeys;
                        else
                            requestedKeys = nearRequestedKeys;
                    }
                }
            } else {
                GridNearOptimisticTxPrepareFuture fut = (GridNearOptimisticTxPrepareFuture) mvccFuture(tx, GridNearOptimisticTxPrepareFuture.class);
                if (fut != null)
                    requestedKeys = fut.requestedKeys();
            }
        }
        for (IgniteTxEntry txEntry : txEntries) {
            IgniteTxKey txKey = txEntry.txKey();
            if (res.txLocks(txKey) == null) {
                GridCacheMapEntry e = (GridCacheMapEntry) txEntry.cached();
                List<GridCacheMvccCandidate> locs = e.mvccAllLocal();
                if (locs != null) {
                    boolean owner = false;
                    for (GridCacheMvccCandidate loc : locs) {
                        if (!owner && loc.owner() && loc.tx())
                            owner = true;
                        if (// Skip all candidates in case when no tx that owns lock.
                        !owner)
                            break;
                        if (loc.tx()) {
                            UUID nearNodeId = loc.otherNodeId();
                            GridCacheVersion txId = loc.otherVersion();
                            TxLock txLock = new TxLock(txId == null ? loc.version() : txId, nearNodeId == null ? loc.nodeId() : nearNodeId, loc.threadId(), loc.owner() ? TxLock.OWNERSHIP_OWNER : TxLock.OWNERSHIP_CANDIDATE);
                            res.addTxLock(txKey, txLock);
                        }
                    }
                } else // Special case for optimal sequence of nodes processing.
                if (nearTxLoc && requestedKeys != null && requestedKeys.contains(txKey.key())) {
                    TxLock txLock = new TxLock(tx.nearXidVersion(), tx.nodeId(), tx.threadId(), TxLock.OWNERSHIP_REQUESTED);
                    res.addTxLock(txKey, txLock);
                } else
                    res.addKey(txKey);
            }
        }
    }
    return res;
}
Also used : GridDhtTxLocal(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxLocal) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) GridNearLockFuture(org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockFuture) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) GridDhtColocatedLockFuture(org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture) GridNearOptimisticTxPrepareFuture(org.apache.ignite.internal.processors.cache.distributed.near.GridNearOptimisticTxPrepareFuture) GridCacheMapEntry(org.apache.ignite.internal.processors.cache.GridCacheMapEntry) UUID(java.util.UUID) GridCacheMvccCandidate(org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate)

Example 30 with GridNearTxLocal

use of org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal in project ignite by apache.

the class IgniteTxManager method newTx.

/**
     * @param implicit {@code True} if transaction is implicit.
     * @param implicitSingle Implicit-with-single-key flag.
     * @param concurrency Concurrency.
     * @param isolation Isolation.
     * @param timeout transaction timeout.
     * @param txSize Expected transaction size.
     * @return New transaction.
     */
public GridNearTxLocal newTx(boolean implicit, boolean implicitSingle, @Nullable GridCacheContext sysCacheCtx, TransactionConcurrency concurrency, TransactionIsolation isolation, long timeout, boolean storeEnabled, int txSize) {
    assert sysCacheCtx == null || sysCacheCtx.systemTx();
    // TODO GG-9141 how to get subj ID?
    UUID subjId = null;
    int taskNameHash = cctx.kernalContext().job().currentTaskNameHash();
    GridNearTxLocal tx = new GridNearTxLocal(cctx, implicit, implicitSingle, sysCacheCtx != null, sysCacheCtx != null ? sysCacheCtx.ioPolicy() : SYSTEM_POOL, concurrency, isolation, timeout, storeEnabled, txSize, subjId, taskNameHash);
    if (tx.system()) {
        AffinityTopologyVersion topVer = cctx.tm().lockedTopologyVersion(Thread.currentThread().getId(), tx);
        // If there is another system transaction in progress, use it's topology version to prevent deadlock.
        if (topVer != null)
            tx.topologyVersion(topVer);
    }
    return onCreated(sysCacheCtx, tx);
}
Also used : AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) UUID(java.util.UUID)

Aggregations

GridNearTxLocal (org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal)48 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)20 IgniteUuid (org.apache.ignite.lang.IgniteUuid)10 IgniteException (org.apache.ignite.IgniteException)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 GridClosureException (org.apache.ignite.internal.util.lang.GridClosureException)7 TreeSet (java.util.TreeSet)6 UUID (java.util.UUID)6 Callable (java.util.concurrent.Callable)6 Nullable (org.jetbrains.annotations.Nullable)6 ClusterNode (org.apache.ignite.cluster.ClusterNode)5 IgfsException (org.apache.ignite.igfs.IgfsException)5 IgfsPathNotFoundException (org.apache.ignite.igfs.IgfsPathNotFoundException)5 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)5 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 IgfsPathAlreadyExistsException (org.apache.ignite.igfs.IgfsPathAlreadyExistsException)4 IgfsPathIsDirectoryException (org.apache.ignite.igfs.IgfsPathIsDirectoryException)4 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)4