Search in sources :

Example 96 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class GridP2PContinuousDeploymentClientDisconnectTest method testContinuousQueryRemoteFilter.

/**
 * Test starts 1 server node and 1 client node. Class-loading request for the {@link #P2P_TEST_OBJ_RSRC_NAME}
 * resource blocks on the client node. The client node tries to deploy CQ with remote filter for
 * the cache {@link #DEFAULT_CACHE_NAME}.
 * Expected that exception with 'Failed to unmarshal deployable object.' error message will be thrown and
 * the server node wouldn't be failed.
 *
 * @throws Exception If failed.
 */
@Test
public void testContinuousQueryRemoteFilter() throws Exception {
    final Class<CacheEntryEventSerializableFilter<Integer, Integer>> rmtFilterCls = (Class<CacheEntryEventSerializableFilter<Integer, Integer>>) getExternalClassLoader().loadClass(REMOTE_FILTER_CLS_NAME);
    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<Integer, Integer>().setLocalListener(evts -> {
    // No-op.
    }).setRemoteFilter(rmtFilterCls.newInstance());
    IgniteEx client = grid(1);
    LogListener lsnr = LogListener.matches("Failed to unmarshal deployable object.").build();
    testLog.registerListener(lsnr);
    IgniteCache<Integer, Integer> cache = client.cache(DEFAULT_CACHE_NAME);
    assertThrowsWithCause(() -> cache.query(qry), CacheException.class);
    assertTrue(lsnr.check());
    // Check that the failure handler was not called.
    assertFalse(failure.get());
}
Also used : ListeningTestLogger(org.apache.ignite.testframework.ListeningTestLogger) LogListener(org.apache.ignite.testframework.LogListener) AbstractContinuousQuery(org.apache.ignite.cache.query.AbstractContinuousQuery) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CacheEntryEventSerializableFilter(org.apache.ignite.cache.CacheEntryEventSerializableFilter) IgniteEx(org.apache.ignite.internal.IgniteEx) TOPIC_CLASSLOAD(org.apache.ignite.internal.GridTopic.TOPIC_CLASSLOAD) GridKernalContext(org.apache.ignite.internal.GridKernalContext) GridDeploymentManager(org.apache.ignite.internal.managers.deployment.GridDeploymentManager) AbstractFailureHandler(org.apache.ignite.failure.AbstractFailureHandler) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) FailureContext(org.apache.ignite.failure.FailureContext) IgniteClosure(org.apache.ignite.lang.IgniteClosure) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) GridDeploymentRequest(org.apache.ignite.internal.managers.deployment.GridDeploymentRequest) CacheException(javax.cache.CacheException) GridMessageListener(org.apache.ignite.internal.managers.communication.GridMessageListener) Factory(javax.cache.configuration.Factory) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) GridTestUtils.assertThrowsWithCause(org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause) EventType(org.apache.ignite.events.EventType) IgniteException(org.apache.ignite.IgniteException) Event(org.apache.ignite.events.Event) Test(org.junit.Test) UUID(java.util.UUID) Ignite(org.apache.ignite.Ignite) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQueryWithTransformer(org.apache.ignite.cache.query.ContinuousQueryWithTransformer) CacheEntryEventSerializableFilter(org.apache.ignite.cache.CacheEntryEventSerializableFilter) AbstractContinuousQuery(org.apache.ignite.cache.query.AbstractContinuousQuery) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) LogListener(org.apache.ignite.testframework.LogListener) IgniteEx(org.apache.ignite.internal.IgniteEx) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 97 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery 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)

Example 98 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class KillCommandsTests method doTestCancelContinuousQuery.

/**
 * Test cancel of the continuous query.
 *
 * @param cli Client node.
 * @param srvs Server nodes.
 * @param qryCanceler Query cancel closure.
 */
public static void doTestCancelContinuousQuery(IgniteEx cli, List<IgniteEx> srvs, BiConsumer<UUID, UUID> qryCanceler) throws Exception {
    IgniteCache<Object, Object> cache = cli.cache(DEFAULT_CACHE_NAME);
    ContinuousQuery<Integer, Integer> cq = new ContinuousQuery<>();
    AtomicInteger cntr = new AtomicInteger();
    cq.setInitialQuery(new ScanQuery<>());
    cq.setTimeInterval(1_000L);
    cq.setPageSize(PAGE_SZ);
    cq.setLocalListener(events -> {
        for (CacheEntryEvent<? extends Integer, ? extends Integer> e : events) {
            assertNotNull(e);
            cntr.incrementAndGet();
        }
    });
    cache.query(cq);
    for (int i = 0; i < PAGE_SZ * PAGE_SZ; i++) cache.put(i, i);
    boolean res = waitForCondition(() -> cntr.get() == PAGE_SZ * PAGE_SZ, TIMEOUT);
    assertTrue(res);
    List<List<?>> cqQries = execute(cli, "SELECT NODE_ID, ROUTINE_ID FROM SYS.CONTINUOUS_QUERIES");
    assertEquals(1, cqQries.size());
    UUID nodeId = (UUID) cqQries.get(0).get(0);
    UUID routineId = (UUID) cqQries.get(0).get(1);
    qryCanceler.accept(nodeId, routineId);
    long cnt = cntr.get();
    for (int i = 0; i < PAGE_SZ * PAGE_SZ; i++) cache.put(i, i);
    res = waitForCondition(() -> cntr.get() > cnt, TIMEOUT);
    assertFalse(res);
    for (int i = 0; i < srvs.size(); i++) {
        IgniteEx srv = srvs.get(i);
        res = waitForCondition(() -> execute(srv, "SELECT ROUTINE_ID FROM SYS.CONTINUOUS_QUERIES").isEmpty(), TIMEOUT);
        assertTrue(srv.configuration().getIgniteInstanceName(), res);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteEx(org.apache.ignite.internal.IgniteEx) List(java.util.List) UUID(java.util.UUID)

Example 99 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class IgniteCacheContinuousQueryBackupQueueTest method testBackupQueueAutoUnsubscribeFalse.

/**
 * @throws Exception If failed.
 */
@Test
public void testBackupQueueAutoUnsubscribeFalse() throws Exception {
    try (Ignite client = startClientGrid(GRID_COUNT)) {
        awaitPartitionMapExchange();
        List<QueryCursor> qryCursors = new ArrayList<>();
        for (int i = 0; i < QUERY_COUNT; i++) {
            ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
            qry.setLocalListener(new CacheEventListener());
            qry.setRemoteFilterFactory(new AlwaysFalseFilterFactory());
            qry.setAutoUnsubscribe(false);
            qryCursors.add(client.cache(CACHE_NAME).query(qry));
        }
        for (int i = 0; i < KEYS_COUNT; i++) {
            log.info("Put key: " + i);
            grid(i % GRID_COUNT).cache(CACHE_NAME).put(i, new byte[1024 * 50]);
        }
        int size = backupQueueSize();
        assertTrue(size > 0);
        assertTrue(size <= BACKUP_ACK_THRESHOLD * QUERY_COUNT * /* partition count */
        1024);
        stopGrid(GRID_COUNT);
        awaitPartitionMapExchange();
        for (int i = 0; i < KEYS_COUNT; i++) {
            log.info("Put key: " + i);
            grid(i % GRID_COUNT).cache(CACHE_NAME).put(i, new byte[1024 * 50]);
        }
        size = backupQueueSize();
        assertEquals(-1, size);
    }
}
Also used : ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ArrayList(java.util.ArrayList) Ignite(org.apache.ignite.Ignite) QueryCursor(org.apache.ignite.cache.query.QueryCursor) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 100 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class IgniteCacheContinuousQueryBackupQueueTest method testManyQueryBackupQueue.

/**
 * @throws Exception If failed.
 */
@Test
public void testManyQueryBackupQueue() throws Exception {
    List<QueryCursor> qryCursors = new ArrayList<>();
    for (int i = 0; i < QUERY_COUNT; i++) {
        ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
        qry.setLocalListener(new CacheEventListener());
        qry.setRemoteFilterFactory(new AlwaysFalseFilterFactory());
        qryCursors.add(grid(0).cache(CACHE_NAME).query(qry));
    }
    for (int i = 0; i < KEYS_COUNT; i++) {
        log.info("Put key: " + i);
        for (int j = 0; j < 150; j++) grid(ThreadLocalRandom.current().nextInt(GRID_COUNT)).cache(CACHE_NAME).put(i, new byte[1024 * 50]);
    }
    int size = backupQueueSize();
    // Backup queues total size should not exceed one entry per query per partition. This is because
    // {@link CacheContinuousQueryEventBuffer} is optimized to store filtered events and
    // used in this test {@link AlwaysFalseFilterFactory} always declines updates.
    // Zero total size is possible when backup queue is cleaned by timeout.
    assertTrue(size <= QUERY_COUNT * /* partition count */
    1024);
    for (QueryCursor qry : qryCursors) qry.close();
}
Also used : ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ArrayList(java.util.ArrayList) QueryCursor(org.apache.ignite.cache.query.QueryCursor) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Aggregations

ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)123 Test (org.junit.Test)74 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)70 Ignite (org.apache.ignite.Ignite)60 CacheEntryEvent (javax.cache.event.CacheEntryEvent)58 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)53 CountDownLatch (java.util.concurrent.CountDownLatch)48 IgniteCache (org.apache.ignite.IgniteCache)43 QueryCursor (org.apache.ignite.cache.query.QueryCursor)38 ArrayList (java.util.ArrayList)32 IgniteException (org.apache.ignite.IgniteException)28 CacheEntryListenerException (javax.cache.event.CacheEntryListenerException)27 CacheEntryUpdatedListener (javax.cache.event.CacheEntryUpdatedListener)24 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)22 Cache (javax.cache.Cache)22 HashMap (java.util.HashMap)21 List (java.util.List)19 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)19 CacheException (javax.cache.CacheException)17 IgniteEx (org.apache.ignite.internal.IgniteEx)17