Search in sources :

Example 51 with QueryCursor

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

the class IgniteCacheClusterReadOnlyModeSelfTest method testScanQueryAllowed.

/**
 */
@Test
public void testScanQueryAllowed() {
    performAction(cache -> {
        try (QueryCursor qry = cache.query(new ScanQuery<>())) {
            for (Object o : qry.getAll()) {
                IgniteBiTuple<Integer, Integer> tuple = (IgniteBiTuple<Integer, Integer>) o;
                assertEquals(o.toString(), kvMap.get(tuple.getKey()), tuple.getValue());
            }
        }
    });
}
Also used : IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) QueryCursor(org.apache.ignite.cache.query.QueryCursor) Test(org.junit.Test)

Example 52 with QueryCursor

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

the class CacheContinuousQueryBufferLimitTest method testPendingSendToClientOnLimitReached.

/**
 * @throws Exception If fails.
 */
@Test
public void testPendingSendToClientOnLimitReached() throws Exception {
    AtomicInteger keys = new AtomicInteger();
    AtomicReference<String> err = new AtomicReference<>();
    IgniteEx srv = startGrids(2);
    IgniteEx clnt = startClientGrid();
    IgniteCache<Integer, Integer> cache = clnt.cache(DEFAULT_CACHE_NAME);
    CacheEntryEventSerializableFilter<Integer, Integer> filter = evt -> evt.getKey() % 2 == 0;
    ContinuousQuery<Integer, Integer> cq = new ContinuousQuery<>();
    cq.setRemoteFilterFactory(FactoryBuilder.factoryOf(filter));
    cq.setLocalListener((events) -> events.forEach(e -> {
        if (!filter.evaluate(e))
            err.compareAndSet(null, "Key must be filtered [e=" + e + ']');
    }));
    cq.setLocal(false);
    spi(srv).blockMessages((nodeId, msg) -> (cachePutOperationRequestMessage(msg) && msgCntr.getAndIncrement() == 7) || msg instanceof CacheContinuousQueryBatchAck);
    IgniteInternalFuture<?> loadFut = null;
    try (QueryCursor<?> qry = cache.query(cq)) {
        awaitPartitionMapExchange();
        loadFut = GridTestUtils.runMultiThreadedAsync(() -> {
            while (!Thread.currentThread().isInterrupted()) cache.put(keys.incrementAndGet(), 0);
        }, 6, "cq-put-");
        // Entries are checked by CacheEntryUpdatedListener which has been set to CQ. Check that all
        // entries greater than pending limit filtered correctly (entries are sent to client on buffer overflow).
        boolean await = waitForCondition(() -> keys.get() > OVERFLOW_KEYS_COUNT, 30_000);
        assertTrue("Number of keys to put must reach the limit [keys=" + keys.get() + ", limit=" + OVERFLOW_KEYS_COUNT + ']', await);
    } finally {
        TestRecordingCommunicationSpi.stopBlockAll();
        if (loadFut != null)
            loadFut.cancel();
    }
    if (err.get() != null)
        throw new Exception(err.get());
}
Also used : CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) TestRecordingCommunicationSpi.spi(org.apache.ignite.internal.TestRecordingCommunicationSpi.spi) Arrays(java.util.Arrays) CacheEntryEventSerializableFilter(org.apache.ignite.cache.CacheEntryEventSerializableFilter) GridDhtAtomicUpdateRequest(org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicUpdateRequest) IgniteEx(org.apache.ignite.internal.IgniteEx) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) Parameterized(org.junit.runners.Parameterized) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) FactoryBuilder(javax.cache.configuration.FactoryBuilder) SystemView(org.apache.ignite.spi.systemview.view.SystemView) Collection(java.util.Collection) IgniteException(org.apache.ignite.IgniteException) UUID(java.util.UUID) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) CU(org.apache.ignite.internal.util.typedef.internal.CU) GridTestUtils.getFieldValue(org.apache.ignite.testframework.GridTestUtils.getFieldValue) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) GridContinuousProcessor(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) ContinuousQueryView(org.apache.ignite.spi.systemview.view.ContinuousQueryView) CacheQueryEntryEvent(org.apache.ignite.cache.query.CacheQueryEntryEvent) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) RunWith(org.junit.runner.RunWith) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterNode(org.apache.ignite.cluster.ClusterNode) S(org.apache.ignite.internal.util.typedef.internal.S) Before(org.junit.Before) Test(org.junit.Test) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) TRANSACTIONAL(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL) REPLICATED(org.apache.ignite.cache.CacheMode.REPLICATED) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) MAX_PENDING_BUFF_SIZE(org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryEventBuffer.MAX_PENDING_BUFF_SIZE) ATOMIC(org.apache.ignite.cache.CacheAtomicityMode.ATOMIC) CQ_SYS_VIEW(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor.CQ_SYS_VIEW) CacheMode(org.apache.ignite.cache.CacheMode) AtomicReference(java.util.concurrent.atomic.AtomicReference) IgniteException(org.apache.ignite.IgniteException) 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) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 53 with QueryCursor

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

the class CacheContinuousQueryBufferLimitTest method doTestContinuousQueryPendingBufferLimit.

/**
 * @param locBlockPred Block predicate on local node to emulate message delivery issues.
 * @param pendingLimit Test limit of pending entries.
 * @throws Exception If fails.
 */
private void doTestContinuousQueryPendingBufferLimit(IgniteBiPredicate<ClusterNode, Message> locBlockPred, int pendingLimit) throws Exception {
    AtomicInteger keys = new AtomicInteger();
    IgniteEx locIgnite = startGrid(0);
    IgniteEx rmtIgnite = startGrid(1);
    IgniteCache<Integer, Integer> cache = locIgnite.cache(DEFAULT_CACHE_NAME);
    CacheConfiguration<Integer, Integer> ccfg = cache.getConfiguration(CacheConfiguration.class);
    for (int i = 0; i < TOTAL_KEYS; i++) cache.put(i, i);
    assertEquals(PARTS, ccfg.getAffinity().partitions());
    GridAtomicLong lastAcked = new GridAtomicLong();
    ContinuousQuery<Integer, Integer> cq = new ContinuousQuery<>();
    cq.setRemoteFilterFactory(FactoryBuilder.factoryOf(RMT_FILTER));
    cq.setLocalListener((events) -> events.forEach(e -> lastAcked.setIfGreater(((CacheQueryEntryEvent<?, ?>) e).getPartitionUpdateCounter())));
    cq.setLocal(false);
    IgniteInternalFuture<?> updFut = null;
    try (QueryCursor<?> qry = locIgnite.cache(DEFAULT_CACHE_NAME).query(cq)) {
        awaitPartitionMapExchange();
        // Partition Id, Update Counter, Continuous Entry.
        ConcurrentMap<Long, CacheContinuousQueryEntry> pending = getContinuousQueryPendingBuffer(rmtIgnite, CU.cacheId(DEFAULT_CACHE_NAME), 0);
        spi(locIgnite).blockMessages(locBlockPred);
        updFut = GridTestUtils.runMultiThreadedAsync(() -> {
            while (keys.get() <= OVERFLOW_KEYS_COUNT) cache.put(keys.incrementAndGet(), 0);
        }, 3, "cq-put-");
        assertNotNull("Partition remote buffers must be inited", pending);
        log.warning("Waiting for pending buffer being overflowed within " + OVERFLOW_KEYS_COUNT + " number of keys.");
        boolean await = waitForCondition(() -> pending.size() > pendingLimit, () -> keys.get() <= OVERFLOW_KEYS_COUNT);
        assertFalse("Pending buffer exceeded the limit despite entries have been acked " + "[lastAcked=" + lastAcked + ", pending=" + S.compact(pending.keySet(), i -> i + 1) + ']', await);
    } finally {
        spi(locIgnite).stopBlock();
        if (updFut != null)
            updFut.cancel();
    }
}
Also used : CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) TestRecordingCommunicationSpi.spi(org.apache.ignite.internal.TestRecordingCommunicationSpi.spi) Arrays(java.util.Arrays) CacheEntryEventSerializableFilter(org.apache.ignite.cache.CacheEntryEventSerializableFilter) GridDhtAtomicUpdateRequest(org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicUpdateRequest) IgniteEx(org.apache.ignite.internal.IgniteEx) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) Parameterized(org.junit.runners.Parameterized) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) FactoryBuilder(javax.cache.configuration.FactoryBuilder) SystemView(org.apache.ignite.spi.systemview.view.SystemView) Collection(java.util.Collection) IgniteException(org.apache.ignite.IgniteException) UUID(java.util.UUID) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) CU(org.apache.ignite.internal.util.typedef.internal.CU) GridTestUtils.getFieldValue(org.apache.ignite.testframework.GridTestUtils.getFieldValue) Message(org.apache.ignite.plugin.extensions.communication.Message) TestRecordingCommunicationSpi(org.apache.ignite.internal.TestRecordingCommunicationSpi) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) GridContinuousProcessor(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) ContinuousQueryView(org.apache.ignite.spi.systemview.view.ContinuousQueryView) CacheQueryEntryEvent(org.apache.ignite.cache.query.CacheQueryEntryEvent) GridDhtTxPrepareRequest(org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) RunWith(org.junit.runner.RunWith) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentMap(java.util.concurrent.ConcurrentMap) ClusterNode(org.apache.ignite.cluster.ClusterNode) S(org.apache.ignite.internal.util.typedef.internal.S) Before(org.junit.Before) Test(org.junit.Test) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) TRANSACTIONAL(org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL) REPLICATED(org.apache.ignite.cache.CacheMode.REPLICATED) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) MAX_PENDING_BUFF_SIZE(org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryEventBuffer.MAX_PENDING_BUFF_SIZE) ATOMIC(org.apache.ignite.cache.CacheAtomicityMode.ATOMIC) CQ_SYS_VIEW(org.apache.ignite.internal.processors.continuous.GridContinuousProcessor.CQ_SYS_VIEW) CacheMode(org.apache.ignite.cache.CacheMode) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong) 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) GridAtomicLong(org.apache.ignite.internal.util.GridAtomicLong)

Example 54 with QueryCursor

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

the class CacheContinuousQueryOrderingEventTest method doOrderingTest.

/**
 * @param ccfg Cache configuration.
 * @param async Async filter.
 * @throws Exception If failed.
 */
protected void doOrderingTest(final CacheConfiguration ccfg, final boolean async) throws Exception {
    ignite(0).createCache(ccfg);
    List<QueryCursor<?>> qries = new ArrayList<>();
    try {
        List<BlockingQueue<CacheEntryEvent<QueryTestKey, QueryTestValue>>> rcvdEvts = new ArrayList<>(LISTENER_CNT * NODES);
        final AtomicInteger qryCntr = new AtomicInteger(0);
        final int threadCnt = 20;
        for (int idx = 0; idx < NODES; idx++) {
            for (int i = 0; i < LISTENER_CNT; i++) {
                BlockingQueue<CacheEntryEvent<QueryTestKey, QueryTestValue>> queue = new ArrayBlockingQueue<>(ITERATION_CNT * threadCnt);
                ContinuousQuery qry = new ContinuousQuery();
                if (async) {
                    qry.setLocalListener(new TestCacheAsyncEventListener(queue, qryCntr));
                    qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(new CacheTestRemoteFilterAsync(ccfg.getName())));
                } else {
                    qry.setLocalListener(new TestCacheEventListener(queue, qryCntr));
                    qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(new CacheTestRemoteFilter(ccfg.getName())));
                }
                rcvdEvts.add(queue);
                IgniteCache<Object, Object> cache = grid(idx).cache(ccfg.getName());
                QueryCursor qryCursor = cache.query(qry);
                qries.add(qryCursor);
            }
        }
        IgniteInternalFuture<Long> f = GridTestUtils.runMultiThreadedAsync(new Runnable() {

            @Override
            public void run() {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                for (int i = 0; i < ITERATION_CNT; i++) {
                    IgniteCache<QueryTestKey, QueryTestValue> cache = grid(rnd.nextInt(NODES)).cache(ccfg.getName());
                    QueryTestKey key = new QueryTestKey(rnd.nextInt(KEYS));
                    boolean startTx = atomicityMode(cache) != ATOMIC && rnd.nextBoolean();
                    Transaction tx = null;
                    boolean committed = false;
                    while (!committed && !Thread.currentThread().isInterrupted()) {
                        try {
                            if (startTx)
                                tx = cache.unwrap(Ignite.class).transactions().txStart(PESSIMISTIC, REPEATABLE_READ);
                            if ((cache.get(key) == null) || rnd.nextBoolean()) {
                                cache.invoke(key, new CacheEntryProcessor<QueryTestKey, QueryTestValue, Object>() {

                                    @Override
                                    public Object process(MutableEntry<QueryTestKey, QueryTestValue> entry, Object... arguments) throws EntryProcessorException {
                                        if (entry.exists())
                                            entry.setValue(new QueryTestValue(entry.getValue().val1 + 1));
                                        else
                                            entry.setValue(new QueryTestValue(0));
                                        return null;
                                    }
                                });
                            } else {
                                QueryTestValue val;
                                QueryTestValue newVal;
                                do {
                                    val = cache.get(key);
                                    newVal = val == null ? new QueryTestValue(0) : new QueryTestValue(val.val1 + 1);
                                } while (!cache.replace(key, val, newVal));
                            }
                            if (tx != null)
                                tx.commit();
                            committed = true;
                        } catch (CacheException e) {
                            assertTrue(e.getCause() instanceof TransactionSerializationException);
                            assertEquals(atomicityMode(cache), TRANSACTIONAL_SNAPSHOT);
                        } finally {
                            if (tx != null)
                                tx.close();
                        }
                    }
                }
            }
        }, threadCnt, "put-thread");
        f.get(15, TimeUnit.SECONDS);
        GridTestUtils.waitForCondition(new PA() {

            @Override
            public boolean apply() {
                return qryCntr.get() >= ITERATION_CNT * threadCnt * LISTENER_CNT * NODES;
            }
        }, 1000L);
        for (BlockingQueue<CacheEntryEvent<QueryTestKey, QueryTestValue>> queue : rcvdEvts) checkEvents(queue, ITERATION_CNT * threadCnt);
        assertFalse("Ordering invocations of filter broken.", fail);
    } finally {
        for (QueryCursor<?> qry : qries) qry.close();
        ignite(0).destroyCache(ccfg.getName());
    }
}
Also used : TransactionSerializationException(org.apache.ignite.transactions.TransactionSerializationException) CacheException(javax.cache.CacheException) ArrayList(java.util.ArrayList) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Ignite(org.apache.ignite.Ignite) MutableEntry(javax.cache.processor.MutableEntry) QueryCursor(org.apache.ignite.cache.query.QueryCursor) BlockingQueue(java.util.concurrent.BlockingQueue) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) IgniteCache(org.apache.ignite.IgniteCache) PA(org.apache.ignite.internal.util.typedef.PA) Transaction(org.apache.ignite.transactions.Transaction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryProcessor(org.apache.ignite.cache.CacheEntryProcessor)

Example 55 with QueryCursor

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

the class CacheContinuousQueryConcurrentPartitionUpdateTest method startListener.

/**
 * @param cache Cache.
 * @return Event counter.
 */
private T2<AtomicInteger, QueryCursor> startListener(IgniteCache<Object, Object> cache) {
    final AtomicInteger evtCnt = new AtomicInteger();
    ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
    qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {

        @Override
        public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
            for (CacheEntryEvent evt : evts) {
                assertNotNull(evt.getKey());
                assertNotNull(evt.getValue());
                if ((Integer) evt.getValue() >= 0)
                    evtCnt.incrementAndGet();
            }
        }
    });
    QueryCursor cur = cache.query(qry);
    return new T2<>(evtCnt, cur);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryEvent(javax.cache.event.CacheEntryEvent) QueryCursor(org.apache.ignite.cache.query.QueryCursor) T2(org.apache.ignite.internal.util.typedef.T2)

Aggregations

QueryCursor (org.apache.ignite.cache.query.QueryCursor)72 IgniteCache (org.apache.ignite.IgniteCache)44 Ignite (org.apache.ignite.Ignite)38 ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)36 Cache (javax.cache.Cache)33 Test (org.junit.Test)29 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)28 ScanQuery (org.apache.ignite.cache.query.ScanQuery)26 ArrayList (java.util.ArrayList)24 IgniteException (org.apache.ignite.IgniteException)22 List (java.util.List)19 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)19 Map (java.util.Map)17 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)17 CacheConfiguration (org.apache.ignite.configuration.CacheConfiguration)17 CacheException (javax.cache.CacheException)16 GridTestUtils (org.apache.ignite.testframework.GridTestUtils)16 Collection (java.util.Collection)15 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)15 Transaction (org.apache.ignite.transactions.Transaction)15