Search in sources :

Example 6 with FULL_SYNC

use of org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC in project ignite by apache.

the class GridCommandHandlerTest method testKillHangingRemoteTransactions.

/**
 * Simulate uncommitted backup transactions and test rolling back using utility.
 */
@Test
public void testKillHangingRemoteTransactions() throws Exception {
    final int cnt = 3;
    startGridsMultiThreaded(cnt);
    Ignite[] clients = new Ignite[] { startGrid("client1"), startGrid("client2"), startGrid("client3"), startGrid("client4") };
    clients[0].getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME).setBackups(2).setAtomicityMode(TRANSACTIONAL).setWriteSynchronizationMode(FULL_SYNC).setAffinity(new RendezvousAffinityFunction(false, 64)));
    awaitPartitionMapExchange();
    for (Ignite client : clients) {
        assertTrue(client.configuration().isClientMode());
        assertNotNull(client.cache(DEFAULT_CACHE_NAME));
    }
    LongAdder progress = new LongAdder();
    AtomicInteger idx = new AtomicInteger();
    int tc = clients.length;
    CountDownLatch lockLatch = new CountDownLatch(1);
    CountDownLatch commitLatch = new CountDownLatch(1);
    Ignite prim = primaryNode(0L, DEFAULT_CACHE_NAME);
    TestRecordingCommunicationSpi primSpi = TestRecordingCommunicationSpi.spi(prim);
    primSpi.blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {

        @Override
        public boolean apply(ClusterNode node, Message message) {
            return message instanceof GridDhtTxFinishRequest;
        }
    });
    Set<IgniteUuid> xidSet = new GridConcurrentHashSet<>();
    IgniteInternalFuture<?> fut = multithreadedAsync(new Runnable() {

        @Override
        public void run() {
            int id = idx.getAndIncrement();
            Ignite client = clients[id];
            try (Transaction tx = client.transactions().txStart(PESSIMISTIC, READ_COMMITTED, 0, 1)) {
                xidSet.add(tx.xid());
                IgniteCache<Long, Long> cache = client.cache(DEFAULT_CACHE_NAME);
                if (id != 0)
                    U.awaitQuiet(lockLatch);
                cache.invoke(0L, new IncrementClosure(), null);
                if (id == 0) {
                    lockLatch.countDown();
                    U.awaitQuiet(commitLatch);
                    // Wait until candidates will enqueue.
                    doSleep(500);
                }
                tx.commit();
            } catch (Exception e) {
                assertTrue(X.hasCause(e, TransactionTimeoutException.class));
            }
            progress.increment();
        }
    }, tc, "invoke-thread");
    U.awaitQuiet(lockLatch);
    commitLatch.countDown();
    primSpi.waitForBlocked(clients.length);
    // Unblock only finish messages from clients from 2 to 4.
    primSpi.stopBlock(true, blockedMsg -> {
        GridIoMessage iom = blockedMsg.ioMessage();
        Message m = iom.message();
        if (m instanceof GridDhtTxFinishRequest) {
            GridDhtTxFinishRequest r = (GridDhtTxFinishRequest) m;
            return !r.nearNodeId().equals(clients[0].cluster().localNode().id());
        }
        return true;
    });
    // Wait until queue is stable
    for (Ignite ignite : G.allGrids()) {
        if (ignite.configuration().isClientMode())
            continue;
        Collection<IgniteInternalTx> txs = ((IgniteEx) ignite).context().cache().context().tm().activeTransactions();
        waitForCondition(new GridAbsPredicate() {

            @Override
            public boolean apply() {
                for (IgniteInternalTx tx : txs) if (!tx.local()) {
                    IgniteTxEntry entry = tx.writeEntries().iterator().next();
                    GridCacheEntryEx cached = entry.cached();
                    Collection<GridCacheMvccCandidate> candidates = cached.remoteMvccSnapshot();
                    if (candidates.size() != clients.length)
                        return false;
                }
                return true;
            }
        }, 10_000);
    }
    CommandHandler h = new CommandHandler();
    // Check listing.
    validate(h, map -> {
        for (int i = 0; i < cnt; i++) {
            IgniteEx grid = grid(i);
            // Skip primary.
            if (grid.localNode().id().equals(prim.cluster().localNode().id()))
                continue;
            VisorTxTaskResult res = map.get(grid.localNode());
            List<VisorTxInfo> infos = res.getInfos().stream().filter(info -> xidSet.contains(info.getNearXid())).collect(Collectors.toList());
            // Validate queue length on backups.
            assertEquals(clients.length, infos.size());
        }
    }, "--tx");
    // Check kill.
    validate(h, map -> {
    // No-op.
    }, "--tx", "--kill");
    // Wait for all remote txs to finish.
    for (Ignite ignite : G.allGrids()) {
        if (ignite.configuration().isClientMode())
            continue;
        Collection<IgniteInternalTx> txs = ((IgniteEx) ignite).context().cache().context().tm().activeTransactions();
        for (IgniteInternalTx tx : txs) if (!tx.local())
            tx.finishFuture().get();
    }
    // Unblock finish message from client1.
    primSpi.stopBlock(true);
    fut.get();
    Long cur = (Long) clients[0].cache(DEFAULT_CACHE_NAME).get(0L);
    assertEquals(tc - 1, cur.longValue());
    checkUserFutures();
}
Also used : RandomAccessFile(java.io.RandomAccessFile) BlockedWarmUpConfiguration(org.apache.ignite.internal.processors.cache.warmup.BlockedWarmUpConfiguration) Arrays(java.util.Arrays) GridCacheMvccCandidate(org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate) EVT_NODE_LEFT(org.apache.ignite.events.EventType.EVT_NODE_LEFT) UnaryOperator(java.util.function.UnaryOperator) GridConcurrentHashSet(org.apache.ignite.internal.client.util.GridConcurrentHashSet) EntryProcessor(javax.cache.processor.EntryProcessor) BooleanSupplier(java.util.function.BooleanSupplier) GridFunc(org.apache.ignite.internal.util.lang.GridFunc) GridTestUtils.runAsync(org.apache.ignite.testframework.GridTestUtils.runAsync) FileIO(org.apache.ignite.internal.processors.cache.persistence.file.FileIO) REENCRYPTION_RESUME(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.REENCRYPTION_RESUME) Matcher(java.util.regex.Matcher) EXIT_CODE_INVALID_ARGUMENTS(org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_INVALID_ARGUMENTS) Map(java.util.Map) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) Path(java.nio.file.Path) GridDhtTxFinishRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishRequest) VisorTxInfo(org.apache.ignite.internal.visor.tx.VisorTxInfo) IgniteCacheGroupsWithRestartsTest(org.apache.ignite.internal.processors.cache.persistence.db.IgniteCacheGroupsWithRestartsTest) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) INACTIVE(org.apache.ignite.cluster.ClusterState.INACTIVE) GridClientFactory(org.apache.ignite.internal.client.GridClientFactory) CommandHandler(org.apache.ignite.internal.commandline.CommandHandler) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) VisorFindAndDeleteGarbageInPersistenceTaskResult(org.apache.ignite.internal.visor.cache.VisorFindAndDeleteGarbageInPersistenceTaskResult) Set(java.util.Set) ChangeGlobalStateFinishMessage(org.apache.ignite.internal.processors.cluster.ChangeGlobalStateFinishMessage) READ_COMMITTED(org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED) MASTER_KEY_NAME_2(org.apache.ignite.internal.encryption.AbstractEncryptionTest.MASTER_KEY_NAME_2) IgniteCache(org.apache.ignite.IgniteCache) EXIT_CODE_CONNECTION_FAILED(org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_CONNECTION_FAILED) Serializable(java.io.Serializable) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) READ_ONLY_SAFE(org.apache.ignite.cache.PartitionLossPolicy.READ_ONLY_SAFE) REENCRYPTION_SUSPEND(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.REENCRYPTION_SUSPEND) AbstractSnapshotSelfTest.doSnapshotCancellationTest(org.apache.ignite.internal.processors.cache.persistence.snapshot.AbstractSnapshotSelfTest.doSnapshotCancellationTest) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) GridClientImpl(org.apache.ignite.internal.client.impl.GridClientImpl) GridClusterStateProcessor(org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor) Message(org.apache.ignite.plugin.extensions.communication.Message) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) TcpCommunicationSpi(org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) ClusterState(org.apache.ignite.cluster.ClusterState) U(org.apache.ignite.internal.util.typedef.internal.U) CACHE_GROUP_KEY_IDS(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.CACHE_GROUP_KEY_IDS) EntryProcessorException(javax.cache.processor.EntryProcessorException) EXIT_CODE_OK(org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) REENCRYPTION_RATE(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.REENCRYPTION_RATE) GridCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager) ClusterNode(org.apache.ignite.cluster.ClusterNode) BlockedWarmUpStrategy(org.apache.ignite.internal.processors.cache.warmup.BlockedWarmUpStrategy) ACTIVE_READ_ONLY(org.apache.ignite.cluster.ClusterState.ACTIVE_READ_ONLY) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) REENCRYPTION_STATUS(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.REENCRYPTION_STATUS) ACTIVE(org.apache.ignite.cluster.ClusterState.ACTIVE) DEFAULT_TARGET_FOLDER(org.apache.ignite.internal.processors.diagnostic.DiagnosticProcessor.DEFAULT_TARGET_FOLDER) Files(java.nio.file.Files) IOException(java.io.IOException) IgniteSnapshotManager(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager) VisorTxTaskResult(org.apache.ignite.internal.visor.tx.VisorTxTaskResult) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) Field(java.lang.reflect.Field) BaselineNode(org.apache.ignite.cluster.BaselineNode) File(java.io.File) TRANSACTIONAL(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL) IgniteTxEntry(org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry) GridNearLockResponse(org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse) WithSystemProperty(org.apache.ignite.testframework.junits.WithSystemProperty) AtomicLong(java.util.concurrent.atomic.AtomicLong) TransactionRollbackException(org.apache.ignite.transactions.TransactionRollbackException) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) IgniteFinishedFutureImpl(org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl) IgniteDataStreamer(org.apache.ignite.IgniteDataStreamer) LongMetric(org.apache.ignite.spi.metric.LongMetric) IgniteUuid(org.apache.ignite.lang.IgniteUuid) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteAtomicSequence(org.apache.ignite.IgniteAtomicSequence) CheckpointState(org.apache.ignite.internal.processors.cache.persistence.CheckpointState) GridNearTxFinishRequest(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishRequest) SNAPSHOT_METRICS(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.SNAPSHOT_METRICS) IgniteNodeAttributes(org.apache.ignite.internal.IgniteNodeAttributes) Transaction(org.apache.ignite.transactions.Transaction) CONFIRM_MSG(org.apache.ignite.internal.commandline.CommandHandler.CONFIRM_MSG) GridTestUtils.assertThrows(org.apache.ignite.testframework.GridTestUtils.assertThrows) IgniteEx(org.apache.ignite.internal.IgniteEx) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) MutableEntry(javax.cache.processor.MutableEntry) CHANGE_CACHE_GROUP_KEY(org.apache.ignite.internal.commandline.encryption.EncryptionSubcommands.CHANGE_CACHE_GROUP_KEY) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) X(org.apache.ignite.internal.util.typedef.X) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) TestStorageUtils.corruptDataEntry(org.apache.ignite.util.TestStorageUtils.corruptDataEntry) DEACTIVATE(org.apache.ignite.internal.commandline.CommandList.DEACTIVATE) IgniteFuture(org.apache.ignite.lang.IgniteFuture) File.separatorChar(java.io.File.separatorChar) Collection(java.util.Collection) IgniteException(org.apache.ignite.IgniteException) OPTIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC) UUID(java.util.UUID) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl) IGNITE_CLUSTER_NAME(org.apache.ignite.IgniteSystemProperties.IGNITE_CLUSTER_NAME) Collectors(java.util.stream.Collectors) GridIoMessage(org.apache.ignite.internal.managers.communication.GridIoMessage) GRID_NOT_IDLE_MSG(org.apache.ignite.internal.processors.cache.verify.IdleVerifyUtility.GRID_NOT_IDLE_MSG) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) EVT_NODE_FAILED(org.apache.ignite.events.EventType.EVT_NODE_FAILED) CU(org.apache.ignite.internal.util.typedef.internal.CU) Pattern(java.util.regex.Pattern) ShutdownPolicy(org.apache.ignite.ShutdownPolicy) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) ClusterStateTestUtils(org.apache.ignite.internal.processors.cache.ClusterStateTestUtils) NotNull(org.jetbrains.annotations.NotNull) IdleVerifyResultV2(org.apache.ignite.internal.processors.cache.verify.IdleVerifyResultV2) GridJobExecuteResponse(org.apache.ignite.internal.GridJobExecuteResponse) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) IntStream(java.util.stream.IntStream) LongAdder(java.util.concurrent.atomic.LongAdder) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IgniteSnapshotManager.resolveSnapshotWorkDirectory(org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteSnapshotManager.resolveSnapshotWorkDirectory) HashMap(java.util.HashMap) Function(java.util.function.Function) WarmUpTestPluginProvider(org.apache.ignite.internal.processors.cache.warmup.WarmUpTestPluginProvider) ToFileDumpProcessor(org.apache.ignite.internal.processors.cache.persistence.diagnostic.pagelocktracker.dumpprocessors.ToFileDumpProcessor) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) FileIOFactory(org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory) IGNITE_PDS_SKIP_CHECKPOINT_ON_NODE_STOP(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.IGNITE_PDS_SKIP_CHECKPOINT_ON_NODE_STOP) G(org.apache.ignite.internal.util.typedef.G) F(org.apache.ignite.internal.util.typedef.F) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) OpenOption(java.nio.file.OpenOption) AbstractSnapshotSelfTest.snp(org.apache.ignite.internal.processors.cache.persistence.snapshot.AbstractSnapshotSelfTest.snp) FindAndDeleteGarbageArg(org.apache.ignite.internal.commandline.cache.argument.FindAndDeleteGarbageArg) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) EXIT_CODE_UNEXPECTED_ERROR(org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_UNEXPECTED_ERROR) GridTestUtils.assertContains(org.apache.ignite.testframework.GridTestUtils.assertContains) TimeUnit(java.util.concurrent.TimeUnit) BitSet(java.util.BitSet) Collections(java.util.Collections) DataRegionConfiguration(org.apache.ignite.configuration.DataRegionConfiguration) TransactionTimeoutException(org.apache.ignite.transactions.TransactionTimeoutException) GridIoMessage(org.apache.ignite.internal.managers.communication.GridIoMessage) ChangeGlobalStateFinishMessage(org.apache.ignite.internal.processors.cluster.ChangeGlobalStateFinishMessage) Message(org.apache.ignite.plugin.extensions.communication.Message) GridIoMessage(org.apache.ignite.internal.managers.communication.GridIoMessage) GridDhtTxFinishRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishRequest) CommandHandler(org.apache.ignite.internal.commandline.CommandHandler) GridConcurrentHashSet(org.apache.ignite.internal.client.util.GridConcurrentHashSet) IgniteUuid(org.apache.ignite.lang.IgniteUuid) Ignite(org.apache.ignite.Ignite) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteTxEntry(org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) EntryProcessorException(javax.cache.processor.EntryProcessorException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IOException(java.io.IOException) TransactionRollbackException(org.apache.ignite.transactions.TransactionRollbackException) IgniteException(org.apache.ignite.IgniteException) TransactionTimeoutException(org.apache.ignite.transactions.TransactionTimeoutException) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheEntryEx(org.apache.ignite.internal.processors.cache.GridCacheEntryEx) LongAdder(java.util.concurrent.atomic.LongAdder) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteInternalTx(org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx) TransactionTimeoutException(org.apache.ignite.transactions.TransactionTimeoutException) IgniteEx(org.apache.ignite.internal.IgniteEx) AtomicLong(java.util.concurrent.atomic.AtomicLong) VisorTxInfo(org.apache.ignite.internal.visor.tx.VisorTxInfo) VisorTxTaskResult(org.apache.ignite.internal.visor.tx.VisorTxTaskResult) GridCacheMvccCandidate(org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate) IgniteCacheGroupsWithRestartsTest(org.apache.ignite.internal.processors.cache.persistence.db.IgniteCacheGroupsWithRestartsTest) AbstractSnapshotSelfTest.doSnapshotCancellationTest(org.apache.ignite.internal.processors.cache.persistence.snapshot.AbstractSnapshotSelfTest.doSnapshotCancellationTest) Test(org.junit.Test)

Example 7 with FULL_SYNC

use of org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC in project ignite by apache.

the class CacheMvccSqlTxQueriesAbstractTest method testUpdateExplicitPartitionsWithoutReducer.

/**
 * @throws Exception If failed.
 */
@Test
public void testUpdateExplicitPartitionsWithoutReducer() throws Exception {
    ccfg = cacheConfiguration(cacheMode(), FULL_SYNC, 2, 10).setIndexedTypes(Integer.class, Integer.class);
    Ignite ignite = startGridsMultiThreaded(4);
    awaitPartitionMapExchange();
    IgniteCache<Object, Object> cache = ignite.cache(DEFAULT_CACHE_NAME);
    Affinity<Object> affinity = internalCache0(cache).affinity();
    int keysCnt = 10, retryCnt = 0;
    Integer test = 0;
    Map<Integer, Integer> vals = new LinkedHashMap<>();
    while (vals.size() < keysCnt) {
        int partition = affinity.partition(test);
        if (partition == 1 || partition == 2)
            vals.put(test, 0);
        else
            assertTrue("Maximum retry number exceeded", ++retryCnt < 1000);
        test++;
    }
    cache.putAll(vals);
    SqlFieldsQuery qry = new SqlFieldsQuery("UPDATE Integer set _val=2").setPartitions(1, 2);
    List<List<?>> all = cache.query(qry).getAll();
    assertEquals(Long.valueOf(keysCnt), all.stream().findFirst().orElseThrow(AssertionError::new).get(0));
    List<List<?>> rows = cache.query(new SqlFieldsQuery("SELECT _val FROM Integer")).getAll();
    assertEquals(keysCnt, rows.size());
    assertTrue(rows.stream().map(r -> r.get(0)).map(Integer.class::cast).allMatch(v -> v == 2));
}
Also used : SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Transaction(org.apache.ignite.transactions.Transaction) Random(java.util.Random) IgniteEx(org.apache.ignite.internal.IgniteEx) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) EntryProcessor(javax.cache.processor.EntryProcessor) GridCursor(org.apache.ignite.internal.util.lang.GridCursor) GridTestUtils.runAsync(org.apache.ignite.testframework.GridTestUtils.runAsync) MutableEntry(javax.cache.processor.MutableEntry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) X(org.apache.ignite.internal.util.typedef.X) Cache(javax.cache.Cache) CyclicBarrier(java.util.concurrent.CyclicBarrier) QuerySqlField(org.apache.ignite.cache.query.annotations.QuerySqlField) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) TransactionConfiguration(org.apache.ignite.configuration.TransactionConfiguration) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) CacheDataRowAdapter(org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter) IgniteCache(org.apache.ignite.IgniteCache) IgniteCacheProxy(org.apache.ignite.internal.processors.cache.IgniteCacheProxy) Serializable(java.io.Serializable) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) SQL_SUM(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.ReadMode.SQL_SUM) Objects(java.util.Objects) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) MvccFeatureChecker(org.apache.ignite.testframework.MvccFeatureChecker) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) DML(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.WriteMode.DML) GridTestUtils.runMultiThreaded(org.apache.ignite.testframework.GridTestUtils.runMultiThreaded) Affinity(org.apache.ignite.cache.affinity.Affinity) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) EntryProcessorException(javax.cache.processor.EntryProcessorException) SQL(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.ReadMode.SQL) LinkedHashMap(java.util.LinkedHashMap) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) S(org.apache.ignite.internal.util.typedef.internal.S) CacheException(javax.cache.CacheException) TransactionSerializationException(org.apache.ignite.transactions.TransactionSerializationException) TransactionDuplicateKeyException(org.apache.ignite.transactions.TransactionDuplicateKeyException) F(org.apache.ignite.internal.util.typedef.F) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) Iterator(java.util.Iterator) SqlFieldsQueryEx(org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) IgniteQueryErrorCode(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) TimeUnit(java.util.concurrent.TimeUnit) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Phaser(java.util.concurrent.Phaser) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) LinkedHashMap(java.util.LinkedHashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Ignite(org.apache.ignite.Ignite) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) List(java.util.List) Test(org.junit.Test)

Example 8 with FULL_SYNC

use of org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC in project ignite by apache.

the class CacheMvccBasicContinuousQueryTest method checkUpdateCountersGapIsProcessedSimple.

/**
 * @throws Exception if failed.
 */
private void checkUpdateCountersGapIsProcessedSimple(CacheMode cacheMode) throws Exception {
    testSpi = true;
    final int srvCnt = 4;
    final int backups = srvCnt - 1;
    startGridsMultiThreaded(srvCnt);
    client = true;
    IgniteEx nearNode = startGrid(srvCnt);
    IgniteCache<Object, Object> cache = nearNode.createCache(cacheConfiguration(cacheMode, FULL_SYNC, backups, srvCnt).setIndexedTypes(Integer.class, Integer.class));
    IgniteEx primary = grid(0);
    List<Integer> keys = primaryKeys(primary.cache(DEFAULT_CACHE_NAME), 3);
    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
    List<CacheEntryEvent> arrivedEvts = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(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);
    // Initial value.
    cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(keys.get(0))).getAll();
    // prevent first transaction prepare on backups
    TestRecordingCommunicationSpi spi = TestRecordingCommunicationSpi.spi(primary);
    final AtomicInteger dhtPrepMsgLimiter = new AtomicInteger();
    spi.blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {

        @Override
        public boolean apply(ClusterNode node, Message msg) {
            if (msg instanceof GridDhtTxPrepareRequest)
                return dhtPrepMsgLimiter.getAndIncrement() < backups;
            if (msg instanceof GridContinuousMessage)
                return true;
            return false;
        }
    });
    // First tx. Expect it will be prepared only on the primary node and GridDhtTxPrepareRequests to remotes
    // will be swallowed.
    Transaction txA = nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ);
    cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(keys.get(1))).getAll();
    txA.commitAsync();
    // Wait until first tx changes it's status to PREPARING.
    GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            boolean preparing = nearNode.context().cache().context().tm().activeTransactions().stream().allMatch(tx -> tx.state() == PREPARING);
            boolean allPrepsSwallowed = dhtPrepMsgLimiter.get() == backups;
            return preparing && allPrepsSwallowed;
        }
    }, 3_000);
    // Second tx.
    GridTestUtils.runAsync(() -> {
        try (Transaction txB = nearNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
            cache.query(new SqlFieldsQuery("insert into Integer(_key, _val) values(?, 42)").setArgs(keys.get(2)));
            txB.commit();
        }
    }).get();
    long primaryUpdCntr = getUpdateCounter(primary, keys.get(0));
    // There were three updates: init, first and second.
    assertEquals(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(2, size);
        assertEquals(primaryUpdCntr, backupCntr);
    }
    assertTrue(latch.await(3, SECONDS));
    assertEquals(2, arrivedEvts.size());
    assertEquals(keys.get(0), arrivedEvts.get(0).getKey());
    assertEquals(keys.get(2), arrivedEvts.get(1).getKey());
    cur.close();
    nearNode.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) ClusterNode(org.apache.ignite.cluster.ClusterNode) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) GridContinuousMessage(org.apache.ignite.internal.processors.continuous.GridContinuousMessage) 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)

Aggregations

IgniteCache (org.apache.ignite.IgniteCache)8 FULL_SYNC (org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC)8 IgniteEx (org.apache.ignite.internal.IgniteEx)8 GridTestUtils (org.apache.ignite.testframework.GridTestUtils)8 Test (org.junit.Test)8 Map (java.util.Map)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 Ignite (org.apache.ignite.Ignite)7 HashMap (java.util.HashMap)6 List (java.util.List)6 Callable (java.util.concurrent.Callable)6 Cache (javax.cache.Cache)6 Transaction (org.apache.ignite.transactions.Transaction)6 PESSIMISTIC (org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC)6 CacheException (javax.cache.CacheException)5 ClusterNode (org.apache.ignite.cluster.ClusterNode)5 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)5 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)4