Search in sources :

Example 1 with PESSIMISTIC

use of org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC in project ignite by apache.

the class FunctionalTest method testTransactionsWithLabel.

/**
 * Test transactions with label.
 */
@Test
public void testTransactionsWithLabel() throws Exception {
    try (IgniteEx ignite = (IgniteEx) Ignition.start(Config.getServerConfiguration());
        IgniteClient client = Ignition.startClient(getClientConfiguration())) {
        ClientCache<Integer, String> cache = client.createCache(new ClientCacheConfiguration().setName("cache").setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL));
        SystemView<TransactionView> txsView = ignite.context().systemView().view(TXS_MON_LIST);
        cache.put(0, "value1");
        try (ClientTransaction tx = client.transactions().withLabel("label").txStart()) {
            cache.put(0, "value2");
            assertEquals(1, F.size(txsView.iterator()));
            TransactionView txv = txsView.iterator().next();
            assertEquals("label", txv.label());
            assertEquals("value2", cache.get(0));
        }
        assertEquals("value1", cache.get(0));
        try (ClientTransaction tx = client.transactions().withLabel("label1").withLabel("label2").txStart()) {
            cache.put(0, "value2");
            assertEquals(1, F.size(txsView.iterator()));
            TransactionView txv = txsView.iterator().next();
            assertEquals("label2", txv.label());
            tx.commit();
        }
        assertEquals("value2", cache.get(0));
        // Test concurrent with label and without label transactions.
        try (ClientTransaction tx = client.transactions().withLabel("label").txStart(PESSIMISTIC, READ_COMMITTED)) {
            CyclicBarrier barrier = new CyclicBarrier(2);
            cache.put(0, "value3");
            IgniteInternalFuture<?> fut = GridTestUtils.runAsync(() -> {
                try (ClientTransaction tx1 = client.transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
                    cache.put(1, "value3");
                    barrier.await();
                    assertEquals("value2", cache.get(0));
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException ignore) {
                // No-op.
                }
            });
            barrier.await();
            assertNull(cache.get(1));
            assertEquals(1, F.size(txsView.iterator(), txv -> txv.label() == null));
            assertEquals(1, F.size(txsView.iterator(), txv -> "label".equals(txv.label())));
            barrier.await();
            fut.get();
        }
        // Test nested transactions is not possible.
        try (ClientTransaction tx = client.transactions().withLabel("label1").txStart()) {
            try (ClientTransaction tx1 = client.transactions().txStart()) {
                fail();
            } catch (ClientException expected) {
            // No-op.
            }
            try (ClientTransaction tx1 = client.transactions().withLabel("label2").txStart()) {
                fail();
            } catch (ClientException expected) {
            // No-op.
            }
        }
    }
}
Also used : CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) ModifiedExpiryPolicy(javax.cache.expiry.ModifiedExpiryPolicy) BinaryObject(org.apache.ignite.binary.BinaryObject) Arrays(java.util.Arrays) AbstractBinaryArraysTest(org.apache.ignite.internal.binary.AbstractBinaryArraysTest) SERIALIZABLE(org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE) CacheKeyConfiguration(org.apache.ignite.cache.CacheKeyConfiguration) Date(java.util.Date) Transaction(org.apache.ignite.transactions.Transaction) IgniteEx(org.apache.ignite.internal.IgniteEx) TestEnum(org.apache.ignite.internal.processors.cache.CacheEnumOperationsAbstractTest.TestEnum) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) AccessedExpiryPolicy(javax.cache.expiry.AccessedExpiryPolicy) CacheRebalanceMode(org.apache.ignite.cache.CacheRebalanceMode) GridTestUtils.runAsync(org.apache.ignite.testframework.GridTestUtils.runAsync) VAL3(org.apache.ignite.internal.processors.cache.CacheEnumOperationsAbstractTest.TestEnum.VAL3) VAL1(org.apache.ignite.internal.processors.cache.CacheEnumOperationsAbstractTest.TestEnum.VAL1) VAL2(org.apache.ignite.internal.processors.cache.CacheEnumOperationsAbstractTest.TestEnum.VAL2) Map(java.util.Map) QueryEntity(org.apache.ignite.cache.QueryEntity) ClientStatus(org.apache.ignite.internal.processors.platform.client.ClientStatus) GridTestUtils.assertThrowsAnyCause(org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause) CyclicBarrier(java.util.concurrent.CyclicBarrier) ImmutableSet(com.google.common.collect.ImmutableSet) CachePeekMode(org.apache.ignite.cache.CachePeekMode) SystemView(org.apache.ignite.spi.systemview.view.SystemView) TransactionView(org.apache.ignite.spi.systemview.view.TransactionView) Set(java.util.Set) OPTIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC) READ_COMMITTED(org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED) ClientListenerProcessor(org.apache.ignite.internal.processors.odbc.ClientListenerProcessor) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Stream(java.util.stream.Stream) ClientConfiguration(org.apache.ignite.configuration.ClientConfiguration) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) IntStream(java.util.stream.IntStream) TransactionIsolation(org.apache.ignite.transactions.TransactionIsolation) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) ClientServerError(org.apache.ignite.internal.client.thin.ClientServerError) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) PartitionLossPolicy(org.apache.ignite.cache.PartitionLossPolicy) PlatformExpiryPolicy(org.apache.ignite.internal.processors.platform.cache.expiry.PlatformExpiryPolicy) ClientProcessorMXBean(org.apache.ignite.mxbean.ClientProcessorMXBean) CacheWriteSynchronizationMode(org.apache.ignite.cache.CacheWriteSynchronizationMode) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Timeout(org.junit.rules.Timeout) DataStorageConfiguration(org.apache.ignite.configuration.DataStorageConfiguration) LinkedList(java.util.LinkedList) SimpleEntry(java.util.AbstractMap.SimpleEntry) Duration(javax.cache.expiry.Duration) F(org.apache.ignite.internal.util.typedef.F) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) Iterator(java.util.Iterator) TXS_MON_LIST(org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager.TXS_MON_LIST) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) T2(org.apache.ignite.internal.util.typedef.T2) TimeUnit(java.util.concurrent.TimeUnit) Ignition(org.apache.ignite.Ignition) Rule(org.junit.Rule) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) Collections(java.util.Collections) QueryIndex(org.apache.ignite.cache.QueryIndex) DataRegionConfiguration(org.apache.ignite.configuration.DataRegionConfiguration) CacheMode(org.apache.ignite.cache.CacheMode) ClientConnectorConfiguration(org.apache.ignite.configuration.ClientConnectorConfiguration) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CyclicBarrier(java.util.concurrent.CyclicBarrier) IgniteEx(org.apache.ignite.internal.IgniteEx) TransactionView(org.apache.ignite.spi.systemview.view.TransactionView) AbstractBinaryArraysTest(org.apache.ignite.internal.binary.AbstractBinaryArraysTest) Test(org.junit.Test)

Example 2 with PESSIMISTIC

use of org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC in project ignite by apache.

the class CacheMvccAbstractBasicCoordinatorFailoverTest method checkCoordinatorsLeft.

/**
 * @param num Number of coordinators to stop.
 * @throws Exception If failed.
 */
@SuppressWarnings("unchecked")
private void checkCoordinatorsLeft(int num, boolean stopCrdFirst) throws Exception {
    disableScheduledVacuum = true;
    final int DATA_NODES = 3;
    final int NODES = num + DATA_NODES;
    nodeAttr = CRD_ATTR;
    // Do not use startMultithreaded here.
    startGrids(num);
    nodeAttr = null;
    startGridsMultiThreaded(num, DATA_NODES);
    List<Ignite> victims = new ArrayList<>(num);
    List<Ignite> survivors = new ArrayList<>(DATA_NODES);
    for (int i = 0; i < NODES; i++) {
        if (i < num)
            victims.add(grid(i));
        else
            survivors.add(grid(i));
    }
    if (log.isInfoEnabled()) {
        log.info("Nodes to be stopped [" + victims.stream().map(n -> n.cluster().localNode().id().toString()).collect(Collectors.joining(", ")) + ']');
        log.info("Nodes not to be stopped [" + survivors.stream().map(n -> n.cluster().localNode().id().toString()).collect(Collectors.joining(", ")) + ']');
    }
    Ignite nearNode = survivors.get(0);
    if (persistence)
        nearNode.cluster().active(true);
    CacheConfiguration ccfg = cacheConfiguration(cacheMode(), FULL_SYNC, DATA_NODES - 1, DFLT_PARTITION_COUNT).setNodeFilter(new CoordinatorNodeFilter());
    IgniteCache cache = nearNode.createCache(ccfg);
    try (Transaction tx = nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int key = 0; key < 10; key++) cache.put(key, 1);
        tx.commit();
    }
    List<Thread> stopThreads = victims.stream().map(v -> new Thread(() -> stopGrid(v.name()))).collect(Collectors.toList());
    ScanQuery<Object, Object> scan = new ScanQuery<>();
    QueryCursor<Cache.Entry<Object, Object>> cur = survivors.get(0).cache(DEFAULT_CACHE_NAME).query(scan);
    Iterator<Cache.Entry<Object, Object>> it = cur.iterator();
    assertTrue(it.hasNext());
    assertEquals(1, it.next().getValue());
    if (log.isInfoEnabled())
        log.info("Start stopping nodes.");
    // Stop nodes and join threads.
    if (stopCrdFirst) {
        for (Thread t : stopThreads) t.start();
    } else {
        // We should stop the oldest node last.
        GridCachePartitionExchangeManager exch = ((IgniteEx) survivors.get(1)).context().cache().context().exchange();
        GridDhtTopologyFuture lastFinished = exch.lastFinishedFuture();
        for (int i = 1; i < stopThreads.size(); i++) stopThreads.get(i).start();
        while (lastFinished == exch.lastTopologyFuture()) doSleep(1);
        stopThreads.get(0).start();
    }
    for (Thread t : stopThreads) t.join();
    if (log.isInfoEnabled())
        log.info("All nodes stopped.");
    assertTrue(it.hasNext());
    assertEquals(1, it.next().getValue());
    for (Ignite node : survivors) {
        for (int key = 0; key < 10; key++) assertEquals(1, node.cache(DEFAULT_CACHE_NAME).get(key));
    }
    try (Transaction tx = nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int key = 0; key < 10; key++) cache.put(key, 2);
        tx.commit();
    } catch (Exception e) {
        stopAllGrids(true);
        fail(X.getFullStackTrace(e));
    }
    for (Ignite node : survivors) {
        for (int key = 0; key < 10; key++) assertEquals(2, node.cache(DEFAULT_CACHE_NAME).get(key));
    }
    try (Transaction tx = nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        for (int key = 0; key < 10; key++) cache.put(key, 3);
        tx.commit();
    } catch (Exception e) {
        stopAllGrids(true);
        fail(X.getFullStackTrace(e));
    }
    for (Ignite node : survivors) {
        for (int key = 0; key < 10; key++) assertEquals(3, node.cache(DEFAULT_CACHE_NAME).get(key));
    }
    while (it.hasNext()) assertEquals(1, (int) it.next().getValue());
    cur.close();
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) TransactionIsolation(org.apache.ignite.transactions.TransactionIsolation) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) MvccSnapshotResponse(org.apache.ignite.internal.processors.cache.mvcc.msg.MvccSnapshotResponse) Transaction(org.apache.ignite.transactions.Transaction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) U(org.apache.ignite.internal.util.typedef.internal.U) Callable(java.util.concurrent.Callable) IgniteEx(org.apache.ignite.internal.IgniteEx) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) IgniteBiInClosure(org.apache.ignite.lang.IgniteBiInClosure) ClusterNode(org.apache.ignite.cluster.ClusterNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) X(org.apache.ignite.internal.util.typedef.X) Cache(javax.cache.Cache) CacheException(javax.cache.CacheException) GridNearGetRequest(org.apache.ignite.internal.processors.cache.distributed.near.GridNearGetRequest) G(org.apache.ignite.internal.util.typedef.G) GridDhtTopologyFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture) F(org.apache.ignite.internal.util.typedef.F) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) Iterator(java.util.Iterator) TestCacheNodeExcludingFilter(org.apache.ignite.internal.processors.cache.distributed.TestCacheNodeExcludingFilter) TransactionConcurrency(org.apache.ignite.transactions.TransactionConcurrency) Set(java.util.Set) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) Collectors(java.util.stream.Collectors) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) ScanQuery(org.apache.ignite.cache.query.ScanQuery) GridCachePartitionExchangeManager(org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager) GridCachePartitionExchangeManager(org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager) ArrayList(java.util.ArrayList) IgniteCache(org.apache.ignite.IgniteCache) ScanQuery(org.apache.ignite.cache.query.ScanQuery) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) CacheException(javax.cache.CacheException) GridDhtTopologyFuture(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture) Transaction(org.apache.ignite.transactions.Transaction) Ignite(org.apache.ignite.Ignite) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration)

Example 3 with PESSIMISTIC

use of org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC in project ignite by apache.

the class CacheMvccBasicContinuousQueryTest method checkUpdateCountersGapsClosed.

/**
 * @throws Exception If failed.
 */
private void checkUpdateCountersGapsClosed(CacheMode cacheMode) throws Exception {
    testSpi = true;
    int srvCnt = 4;
    startGridsMultiThreaded(srvCnt);
    IgniteEx nearNode = grid(srvCnt - 1);
    IgniteCache<Object, Object> cache = nearNode.createCache(cacheConfiguration(cacheMode, FULL_SYNC, srvCnt - 1, srvCnt).setIndexedTypes(Integer.class, Integer.class));
    IgniteEx primary = grid(0);
    Affinity<Object> aff = nearNode.affinity(cache.getName());
    int[] nearBackupParts = aff.backupPartitions(nearNode.localNode());
    int[] primaryParts = aff.primaryPartitions(primary.localNode());
    Collection<Integer> nearSet = new HashSet<>();
    for (int part : nearBackupParts) nearSet.add(part);
    Collection<Integer> primarySet = new HashSet<>();
    for (int part : primaryParts) primarySet.add(part);
    // We need backup partitions on the near node.
    nearSet.retainAll(primarySet);
    List<Integer> keys = singlePartKeys(primary.cache(DEFAULT_CACHE_NAME), 20, nearSet.iterator().next());
    int range = 3;
    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
    List<CacheEntryEvent> arrivedEvts = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(range * 2);
    qry.setLocalListener(new CacheEntryUpdatedListener<Integer, Integer>() {

        @Override
        public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) {
            for (CacheEntryEvent e : evts) {
                arrivedEvts.add(e);
                latch.countDown();
            }
        }
    });
    QueryCursor<Cache.Entry<Integer, Integer>> cur = nearNode.cache(DEFAULT_CACHE_NAME).query(qry);
    // prevent first transaction prepare on backups
    TestRecordingCommunicationSpi spi = TestRecordingCommunicationSpi.spi(primary);
    spi.blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {

        private final AtomicInteger limiter = new AtomicInteger();

        @Override
        public boolean apply(ClusterNode node, Message msg) {
            if (msg instanceof GridDhtTxPrepareRequest)
                return limiter.getAndIncrement() < srvCnt - 1;
            return false;
        }
    });
    Transaction txA = primary.transactions().txStart(PESSIMISTIC, REPEATABLE_READ);
    for (int i = 0; i < range; i++) primary.cache(DEFAULT_CACHE_NAME).put(keys.get(i), 2);
    txA.commitAsync();
    GridTestUtils.runAsync(() -> {
        try (Transaction tx = primary.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
            for (int i = range; i < range * 2; i++) primary.cache(DEFAULT_CACHE_NAME).put(keys.get(i), 1);
            tx.commit();
        }
    }).get();
    GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            return primary.context().cache().context().tm().activeTransactions().stream().allMatch(tx -> tx.state() == PREPARING);
        }
    }, 3_000);
    GridTestUtils.runAsync(() -> {
        try (Transaction txB = primary.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
            for (int i = range * 2; i < range * 3; i++) primary.cache(DEFAULT_CACHE_NAME).put(keys.get(i), 3);
            txB.commit();
        }
    }).get();
    long primaryUpdCntr = getUpdateCounter(primary, keys.get(0));
    assertEquals(range * 3, primaryUpdCntr);
    // drop primary
    stopGrid(primary.name());
    // Wait all txs are rolled back.
    GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            boolean allRolledBack = true;
            for (int i = 1; i < srvCnt; i++) {
                boolean rolledBack = grid(i).context().cache().context().tm().activeTransactions().stream().allMatch(tx -> tx.state() == ROLLED_BACK);
                allRolledBack &= rolledBack;
            }
            return allRolledBack;
        }
    }, 3_000);
    for (int i = 1; i < srvCnt; i++) {
        IgniteCache backupCache = grid(i).cache(DEFAULT_CACHE_NAME);
        int size = backupCache.query(new SqlFieldsQuery("select * from Integer")).getAll().size();
        long backupCntr = getUpdateCounter(grid(i), keys.get(0));
        assertEquals(range * 2, size);
        assertEquals(primaryUpdCntr, backupCntr);
    }
    assertTrue(latch.await(5, SECONDS));
    assertEquals(range * 2, arrivedEvts.size());
    cur.close();
}
Also used : GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Affinity(org.apache.ignite.cache.affinity.Affinity) CacheContinuousQueryManager(org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager) Transaction(org.apache.ignite.transactions.Transaction) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) IgniteEx(org.apache.ignite.internal.IgniteEx) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterNode(org.apache.ignite.cluster.ClusterNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) Cache(javax.cache.Cache) CacheException(javax.cache.CacheException) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) G(org.apache.ignite.internal.util.typedef.G) Collection(java.util.Collection) ROLLED_BACK(org.apache.ignite.transactions.TransactionState.ROLLED_BACK) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) PREPARING(org.apache.ignite.transactions.TransactionState.PREPARING) GridContinuousMessage(org.apache.ignite.internal.processors.continuous.GridContinuousMessage) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) CountDownLatch(java.util.concurrent.CountDownLatch) GridDhtLocalPartition(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition) List(java.util.List) CacheEntryEvent(javax.cache.event.CacheEntryEvent) QueryCursor(org.apache.ignite.cache.query.QueryCursor) TX_SIZE_THRESHOLD(org.apache.ignite.internal.processors.cache.mvcc.MvccCachingManager.TX_SIZE_THRESHOLD) PA(org.apache.ignite.internal.util.typedef.PA) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridContinuousProcessor(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor) SECONDS(java.util.concurrent.TimeUnit.SECONDS) CacheMode(org.apache.ignite.cache.CacheMode) GridContinuousMessage(org.apache.ignite.internal.processors.continuous.GridContinuousMessage) Message(org.apache.ignite.plugin.extensions.communication.Message) ArrayList(java.util.ArrayList) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) HashSet(java.util.HashSet) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) CountDownLatch(java.util.concurrent.CountDownLatch) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteEx(org.apache.ignite.internal.IgniteEx)

Example 4 with PESSIMISTIC

use of org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC in project ignite by apache.

the class CacheMvccTxRecoveryTest method testUpdateCountersGapIsClosed.

/**
 * @throws Exception if failed.
 */
@Test
public void testUpdateCountersGapIsClosed() throws Exception {
    int srvCnt = 3;
    startGridsMultiThreaded(srvCnt);
    client = true;
    IgniteEx ign = startGrid(srvCnt);
    IgniteCache<Object, Object> cache = ign.getOrCreateCache(basicCcfg().setBackups(2));
    int vid = 1;
    IgniteEx victim = grid(vid);
    ArrayList<Integer> keys = new ArrayList<>();
    Integer part = null;
    Affinity<Object> aff = ign.affinity(DEFAULT_CACHE_NAME);
    for (int i = 0; i < 2000; i++) {
        int p = aff.partition(i);
        if (aff.isPrimary(victim.localNode(), i)) {
            if (part == null)
                part = p;
            if (p == part)
                keys.add(i);
            if (keys.size() == 2)
                break;
        }
    }
    assert keys.size() == 2;
    Transaction txA = ign.transactions().txStart(PESSIMISTIC, REPEATABLE_READ);
    // prevent first transaction prepare on backups
    ((TestRecordingCommunicationSpi) victim.configuration().getCommunicationSpi()).blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {

        final AtomicInteger limiter = new AtomicInteger();

        @Override
        public boolean apply(ClusterNode node, Message msg) {
            if (msg instanceof GridDhtTxPrepareRequest)
                return limiter.getAndIncrement() < 2;
            return false;
        }
    });
    cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(keys.get(0)));
    txA.commitAsync();
    GridCacheVersion aXidVer = ((TransactionProxyImpl) txA).tx().xidVersion();
    assertConditionEventually(() -> txsOnNode(victim, aXidVer).stream().anyMatch(tx -> tx.state() == PREPARING));
    GridTestUtils.runAsync(() -> {
        try (Transaction txB = ign.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
            cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(keys.get(1)));
            txB.commit();
        }
    }).get();
    long victimUpdCntr = updateCounter(victim.cachex(DEFAULT_CACHE_NAME).context(), keys.get(0));
    List<IgniteEx> backupNodes = grids(srvCnt, i -> i != vid);
    List<IgniteInternalTx> backupTxsA = backupNodes.stream().map(node -> txsOnNode(node, aXidVer)).flatMap(Collection::stream).collect(Collectors.toList());
    // drop primary
    victim.close();
    assertConditionEventually(() -> backupTxsA.stream().allMatch(tx -> tx.state() == ROLLED_BACK));
    backupNodes.stream().map(node -> node.cache(DEFAULT_CACHE_NAME)).forEach(c -> {
        assertEquals(1, c.query(new SqlFieldsQuery("select * from Integer")).getAll().size());
    });
    backupNodes.forEach(node -> {
        for (Integer k : keys) assertEquals(victimUpdCntr, updateCounter(node.cachex(DEFAULT_CACHE_NAME).context(), k));
    });
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Transaction(org.apache.ignite.transactions.Transaction) TRANSACTIONAL_SNAPSHOT(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT) IgniteEx(org.apache.ignite.internal.IgniteEx) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) IntPredicate(java.util.function.IntPredicate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) ROLLBAK(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.TxEndResult.ROLLBAK) Collection(java.util.Collection) CLIENT(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.NodeMode.CLIENT) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) IgniteCacheOffheapManager(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Optional(java.util.Optional) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) IntStream(java.util.stream.IntStream) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) Affinity(org.apache.ignite.cache.affinity.Affinity) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ArrayList(java.util.ArrayList) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) GridNearTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest) StreamSupport(java.util.stream.StreamSupport) SERVER(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.NodeMode.SERVER) IgniteTxManager(org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager) G(org.apache.ignite.internal.util.typedef.G) PREPARED(org.apache.ignite.transactions.TransactionState.PREPARED) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) GridNearTxFinishResponse(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishResponse) ROLLED_BACK(org.apache.ignite.transactions.TransactionState.ROLLED_BACK) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) COMMITTED(org.apache.ignite.transactions.TransactionState.COMMITTED) PREPARING(org.apache.ignite.transactions.TransactionState.PREPARING) TRANSACTIONAL(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL) COMMIT(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.TxEndResult.COMMIT) TimeUnit(java.util.concurrent.TimeUnit) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) GridDhtPartitionsFullMessage(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage) CacheMode(org.apache.ignite.cache.CacheMode) Message(org.apache.ignite.plugin.extensions.communication.Message) GridDhtPartitionsFullMessage(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage) ArrayList(java.util.ArrayList) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) IgniteEx(org.apache.ignite.internal.IgniteEx) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) Test(org.junit.Test)

Example 5 with PESSIMISTIC

use of org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC in project ignite by apache.

the class CacheMvccTxRecoveryTest method checkRecoveryPrimaryFailure.

/**
 */
private void checkRecoveryPrimaryFailure(TxEndResult endRes, boolean mvccCrd) throws Exception {
    int gridCnt = 4;
    int baseCnt = gridCnt - 1;
    boolean commit = endRes == COMMIT;
    startGridsMultiThreaded(baseCnt);
    client = true;
    IgniteEx nearNode = startGrid(baseCnt);
    IgniteCache<Object, Object> cache = nearNode.getOrCreateCache(basicCcfg().setBackups(1));
    Affinity<Object> aff = nearNode.affinity(DEFAULT_CACHE_NAME);
    List<Integer> keys = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        if (aff.isPrimary(grid(0).localNode(), i) && aff.isBackup(grid(1).localNode(), i)) {
            keys.add(i);
            break;
        }
    }
    for (int i = 0; i < 100; i++) {
        if (aff.isPrimary(grid(1).localNode(), i) && aff.isBackup(grid(2).localNode(), i)) {
            keys.add(i);
            break;
        }
    }
    assert keys.size() == 2;
    int victim, victimBackup;
    if (mvccCrd) {
        victim = 0;
        victimBackup = 1;
    } else {
        victim = 1;
        victimBackup = 2;
    }
    TestRecordingCommunicationSpi victimComm = (TestRecordingCommunicationSpi) grid(victim).configuration().getCommunicationSpi();
    if (commit)
        victimComm.blockMessages(GridNearTxFinishResponse.class, nearNode.name());
    else
        victimComm.blockMessages(GridDhtTxPrepareRequest.class, grid(victimBackup).name());
    GridNearTxLocal nearTx = ((TransactionProxyImpl) nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)).tx();
    for (Integer k : keys) cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(k));
    List<IgniteInternalTx> txs = IntStream.range(0, baseCnt).filter(i -> i != victim).mapToObj(i -> txsOnNode(grid(i), nearTx.xidVersion())).flatMap(Collection::stream).collect(Collectors.toList());
    IgniteInternalFuture<IgniteInternalTx> commitFut = nearTx.commitAsync();
    if (commit)
        assertConditionEventually(() -> txs.stream().allMatch(tx -> tx.state() == COMMITTED));
    else
        assertConditionEventually(() -> txs.stream().anyMatch(tx -> tx.state() == PREPARED));
    // drop victim
    grid(victim).close();
    awaitPartitionMapExchange();
    assertConditionEventually(() -> txs.stream().allMatch(tx -> tx.state() == (commit ? COMMITTED : ROLLED_BACK)));
    assert victimComm.hasBlockedMessages();
    if (commit) {
        assertConditionEventually(() -> {
            int rowsCnt = G.allGrids().get(0).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery("select * from Integer")).getAll().size();
            return rowsCnt == keys.size();
        });
    } else {
        int rowsCnt = G.allGrids().get(0).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery("select * from Integer")).getAll().size();
        assertEquals(0, rowsCnt);
    }
    assertTrue(commitFut.isDone());
    assertPartitionCountersAreConsistent(keys, grids(baseCnt, i -> i != victim));
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Transaction(org.apache.ignite.transactions.Transaction) TRANSACTIONAL_SNAPSHOT(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT) IgniteEx(org.apache.ignite.internal.IgniteEx) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) IntPredicate(java.util.function.IntPredicate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) ROLLBAK(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.TxEndResult.ROLLBAK) Collection(java.util.Collection) CLIENT(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.NodeMode.CLIENT) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) IgniteCacheOffheapManager(org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManager) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) Optional(java.util.Optional) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) IntStream(java.util.stream.IntStream) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) Affinity(org.apache.ignite.cache.affinity.Affinity) GridCacheVersion(org.apache.ignite.internal.processors.cache.version.GridCacheVersion) ArrayList(java.util.ArrayList) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) GridNearTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest) StreamSupport(java.util.stream.StreamSupport) SERVER(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.NodeMode.SERVER) IgniteTxManager(org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager) G(org.apache.ignite.internal.util.typedef.G) PREPARED(org.apache.ignite.transactions.TransactionState.PREPARED) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) GridNearTxFinishResponse(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishResponse) ROLLED_BACK(org.apache.ignite.transactions.TransactionState.ROLLED_BACK) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) COMMITTED(org.apache.ignite.transactions.TransactionState.COMMITTED) PREPARING(org.apache.ignite.transactions.TransactionState.PREPARING) TRANSACTIONAL(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL) COMMIT(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest.TxEndResult.COMMIT) TimeUnit(java.util.concurrent.TimeUnit) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) GridDhtPartitionsFullMessage(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage) CacheMode(org.apache.ignite.cache.CacheMode) ArrayList(java.util.ArrayList) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) GridNearTxFinishResponse(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) IgniteEx(org.apache.ignite.internal.IgniteEx) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl)

Aggregations

IgniteEx (org.apache.ignite.internal.IgniteEx)20 Transaction (org.apache.ignite.transactions.Transaction)20 PESSIMISTIC (org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC)20 Test (org.junit.Test)20 Collectors (java.util.stream.Collectors)16 IgniteCache (org.apache.ignite.IgniteCache)12 Arrays (java.util.Arrays)11 List (java.util.List)11 Set (java.util.Set)11 CountDownLatch (java.util.concurrent.CountDownLatch)11 Ignite (org.apache.ignite.Ignite)11 GridTestUtils (org.apache.ignite.testframework.GridTestUtils)11 Collections (java.util.Collections)10 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)10 TestRecordingCommunicationSpi (org.apache.ignite.internal.TestRecordingCommunicationSpi)10 G (org.apache.ignite.internal.util.typedef.G)10 REPEATABLE_READ (org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ)10 ArrayList (java.util.ArrayList)9 Collection (java.util.Collection)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9