Search in sources :

Example 1 with IgniteClosure

use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.

the class GridCacheQueryManager method runQuery.

/**
     * Processes cache query request.
     *
     * @param qryInfo Query info.
     */
@SuppressWarnings("unchecked")
protected void runQuery(GridCacheQueryInfo qryInfo) {
    assert qryInfo != null;
    assert qryInfo.query().type() != SCAN || !qryInfo.local() : qryInfo;
    if (!enterBusy()) {
        if (cctx.localNodeId().equals(qryInfo.senderId()))
            throw new IllegalStateException("Failed to process query request (grid is stopping).");
        // Ignore remote requests when when node is stopping.
        return;
    }
    try {
        boolean loc = qryInfo.local();
        QueryResult<K, V> res = null;
        if (log.isDebugEnabled())
            log.debug("Running query: " + qryInfo);
        boolean rmvIter = true;
        try {
            // Preparing query closures.
            IgniteClosure<Cache.Entry<K, V>, Object> trans = (IgniteClosure<Cache.Entry<K, V>, Object>) qryInfo.transformer();
            IgniteReducer<Cache.Entry<K, V>, Object> rdc = (IgniteReducer<Cache.Entry<K, V>, Object>) qryInfo.reducer();
            injectResources(trans);
            injectResources(rdc);
            GridCacheQueryAdapter<?> qry = qryInfo.query();
            int pageSize = qry.pageSize();
            boolean incBackups = qry.includeBackups();
            String taskName = cctx.kernalContext().task().resolveTaskName(qry.taskHash());
            IgniteSpiCloseableIterator<IgniteBiTuple<K, V>> iter;
            GridCacheQueryType type;
            res = loc ? executeQuery(qry, qryInfo.arguments(), loc, qry.subjectId(), taskName, recipient(qryInfo.senderId(), qryInfo.requestId())) : queryResult(qryInfo, taskName);
            if (res == null)
                return;
            iter = res.iterator(recipient(qryInfo.senderId(), qryInfo.requestId()));
            type = res.type();
            final GridCacheAdapter<K, V> cache = cctx.cache();
            if (log.isDebugEnabled())
                log.debug("Received index iterator [iterHasNext=" + iter.hasNext() + ", cacheSize=" + cache.size() + ']');
            int cnt = 0;
            boolean stop = false;
            boolean pageSent = false;
            Collection<Object> data = new ArrayList<>(pageSize);
            AffinityTopologyVersion topVer = cctx.affinity().affinityTopologyVersion();
            final boolean statsEnabled = cctx.config().isStatisticsEnabled();
            final boolean readEvt = cctx.gridEvents().isRecordable(EVT_CACHE_QUERY_OBJECT_READ);
            while (!Thread.currentThread().isInterrupted() && iter.hasNext()) {
                long start = statsEnabled ? System.nanoTime() : 0L;
                IgniteBiTuple<K, V> row = iter.next();
                // Query is cancelled.
                if (row == null) {
                    onPageReady(loc, qryInfo, null, true, null);
                    break;
                }
                final K key = row.getKey();
                // Other types are filtered in indexing manager.
                if (!cctx.isReplicated() && qry.type() == SCAN && qry.partition() == null && cctx.config().getCacheMode() != LOCAL && !incBackups && !cctx.affinity().primaryByKey(cctx.localNode(), key, topVer)) {
                    if (log.isDebugEnabled())
                        log.debug("Ignoring backup element [row=" + row + ", cacheMode=" + cctx.config().getCacheMode() + ", incBackups=" + incBackups + ", primary=" + cctx.affinity().primaryByKey(cctx.localNode(), key, topVer) + ']');
                    continue;
                }
                V val = row.getValue();
                if (log.isDebugEnabled()) {
                    ClusterNode primaryNode = cctx.affinity().primaryByKey(key, cctx.affinity().affinityTopologyVersion());
                    log.debug(S.toString("Record", "key", key, true, "val", val, true, "incBackups", incBackups, false, "priNode", primaryNode != null ? U.id8(primaryNode.id()) : null, false, "node", U.id8(cctx.localNode().id()), false));
                }
                if (val == null) {
                    if (log.isDebugEnabled())
                        log.debug(S.toString("Unsuitable record value", "val", val, true));
                    continue;
                }
                if (statsEnabled) {
                    CacheMetricsImpl metrics = cctx.cache().metrics0();
                    metrics.onRead(true);
                    metrics.addGetTimeNanos(System.nanoTime() - start);
                }
                K key0 = null;
                V val0 = null;
                if (readEvt) {
                    key0 = (K) cctx.unwrapBinaryIfNeeded(key, qry.keepBinary());
                    val0 = (V) cctx.unwrapBinaryIfNeeded(val, qry.keepBinary());
                    switch(type) {
                        case SQL:
                            cctx.gridEvents().record(new CacheQueryReadEvent<>(cctx.localNode(), "SQL query entry read.", EVT_CACHE_QUERY_OBJECT_READ, CacheQueryType.SQL.name(), cctx.name(), qry.queryClassName(), qry.clause(), null, null, qryInfo.arguments(), qry.subjectId(), taskName, key0, val0, null, null));
                            break;
                        case TEXT:
                            cctx.gridEvents().record(new CacheQueryReadEvent<>(cctx.localNode(), "Full text query entry read.", EVT_CACHE_QUERY_OBJECT_READ, CacheQueryType.FULL_TEXT.name(), cctx.name(), qry.queryClassName(), qry.clause(), null, null, null, qry.subjectId(), taskName, key0, val0, null, null));
                            break;
                        case SCAN:
                            cctx.gridEvents().record(new CacheQueryReadEvent<>(cctx.localNode(), "Scan query entry read.", EVT_CACHE_QUERY_OBJECT_READ, CacheQueryType.SCAN.name(), cctx.name(), null, null, qry.scanFilter(), null, null, qry.subjectId(), taskName, key0, val0, null, null));
                            break;
                    }
                }
                if (rdc != null || trans != null) {
                    if (key0 == null)
                        key0 = (K) cctx.unwrapBinaryIfNeeded(key, qry.keepBinary());
                    if (val0 == null)
                        val0 = (V) cctx.unwrapBinaryIfNeeded(val, qry.keepBinary());
                    Cache.Entry<K, V> entry = new CacheEntryImpl(key0, val0);
                    // Reduce.
                    if (rdc != null) {
                        if (!rdc.collect(entry) || !iter.hasNext()) {
                            onPageReady(loc, qryInfo, Collections.singletonList(rdc.reduce()), true, null);
                            pageSent = true;
                            break;
                        } else
                            continue;
                    }
                    data.add(trans != null ? trans.apply(entry) : !loc ? new GridCacheQueryResponseEntry<>(key, val) : F.t(key, val));
                } else
                    data.add(!loc ? new GridCacheQueryResponseEntry<>(key, val) : F.t(key, val));
                if (!loc) {
                    if (++cnt == pageSize || !iter.hasNext()) {
                        boolean finished = !iter.hasNext();
                        onPageReady(loc, qryInfo, data, finished, null);
                        pageSent = true;
                        if (!finished)
                            rmvIter = false;
                        if (!qryInfo.allPages())
                            return;
                        data = new ArrayList<>(pageSize);
                        if (stop)
                            // while
                            break;
                    }
                }
            }
            if (!pageSent) {
                if (rdc == null)
                    onPageReady(loc, qryInfo, data, true, null);
                else
                    onPageReady(loc, qryInfo, Collections.singletonList(rdc.reduce()), true, null);
            }
        } catch (Throwable e) {
            if (!X.hasCause(e, GridDhtUnreservedPartitionException.class))
                U.error(log, "Failed to run query [qry=" + qryInfo + ", node=" + cctx.nodeId() + "]", e);
            onPageReady(loc, qryInfo, null, true, e);
            if (e instanceof Error)
                throw (Error) e;
        } finally {
            if (loc) {
                // Local iterators are always removed.
                if (res != null) {
                    try {
                        res.closeIfNotShared(recipient(qryInfo.senderId(), qryInfo.requestId()));
                    } catch (IgniteCheckedException e) {
                        if (!X.hasCause(e, GridDhtUnreservedPartitionException.class))
                            U.error(log, "Failed to close local iterator [qry=" + qryInfo + ", node=" + cctx.nodeId() + "]", e);
                    }
                }
            } else if (rmvIter)
                removeQueryResult(qryInfo.senderId(), qryInfo.requestId());
        }
    } finally {
        leaveBusy();
    }
}
Also used : IgniteClosure(org.apache.ignite.lang.IgniteClosure) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) CacheMetricsImpl(org.apache.ignite.internal.processors.cache.CacheMetricsImpl) ArrayList(java.util.ArrayList) CacheEntryImpl(org.apache.ignite.internal.processors.cache.CacheEntryImpl) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteReducer(org.apache.ignite.lang.IgniteReducer) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) CacheObject(org.apache.ignite.internal.processors.cache.CacheObject) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) Cache(javax.cache.Cache) IgniteInternalCache(org.apache.ignite.internal.processors.cache.IgniteInternalCache)

Example 2 with IgniteClosure

use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.

the class IgniteCacheConfigVariationsFullApiTest method testInvokeException.

/**
     * @throws Exception If failed.
     */
public void testInvokeException() throws Exception {
    final IgniteCache cache = jcache();
    final IgniteFuture fut = cache.invokeAsync("key2", ERR_PROCESSOR);
    assertThrows(log, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            fut.chain(new IgniteClosure<IgniteFuture, Object>() {

                @Override
                public Object apply(IgniteFuture o) {
                    return o.get();
                }
            });
            fut.get();
            return null;
        }
    }, EntryProcessorException.class, null);
}
Also used : IgniteClosure(org.apache.ignite.lang.IgniteClosure) IgniteCache(org.apache.ignite.IgniteCache) IgniteFuture(org.apache.ignite.lang.IgniteFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) CacheEntryListenerException(javax.cache.event.CacheEntryListenerException) EntryProcessorException(javax.cache.processor.EntryProcessorException) CacheException(javax.cache.CacheException)

Example 3 with IgniteClosure

use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.

the class GridCacheQueryTransformerSelfTest method testLocalFiltered.

/**
     * @throws Exception If failed.
     */
public void testLocalFiltered() throws Exception {
    IgniteCache<Integer, Value> cache = grid().createCache("test-cache");
    try {
        for (int i = 0; i < 50; i++) cache.put(i, new Value("str" + i, i * 100));
        Collection<List<Integer>> lists = grid().compute().broadcast(new IgniteCallable<List<Integer>>() {

            @IgniteInstanceResource
            private Ignite ignite;

            @Override
            public List<Integer> call() throws Exception {
                IgniteBiPredicate<Integer, Value> filter = new IgniteBiPredicate<Integer, Value>() {

                    @Override
                    public boolean apply(Integer k, Value v) {
                        return v.idx % 1000 == 0;
                    }
                };
                IgniteClosure<Cache.Entry<Integer, Value>, Integer> transformer = new IgniteClosure<Cache.Entry<Integer, Value>, Integer>() {

                    @Override
                    public Integer apply(Cache.Entry<Integer, Value> e) {
                        return e.getValue().idx;
                    }
                };
                return ignite.cache("test-cache").query(new ScanQuery<>(filter).setLocal(true), transformer).getAll();
            }
        });
        List<Integer> res = new ArrayList<>(F.flatCollections(lists));
        assertEquals(5, res.size());
        Collections.sort(res);
        for (int i = 0; i < 5; i++) assertEquals(i * 1000, res.get(i).intValue());
    } finally {
        cache.destroy();
    }
}
Also used : IgniteClosure(org.apache.ignite.lang.IgniteClosure) IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) ArrayList(java.util.ArrayList) ScanQuery(org.apache.ignite.cache.query.ScanQuery) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) ArrayList(java.util.ArrayList) List(java.util.List) Ignite(org.apache.ignite.Ignite) Cache(javax.cache.Cache) IgniteCache(org.apache.ignite.IgniteCache)

Example 4 with IgniteClosure

use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.

the class IgniteClientReconnectComputeTest method testReconnectApplyInProgress.

/**
     * @throws Exception If failed.
     */
public void testReconnectApplyInProgress() throws Exception {
    final Ignite client = grid(serverCount());
    assertTrue(client.cluster().localNode().isClient());
    Ignite srv = clientRouter(client);
    BlockTcpCommunicationSpi commSpi = commSpi(srv);
    commSpi.blockMessage(GridJobExecuteResponse.class);
    final IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try {
                client.compute().apply(new IgniteClosure<Integer, Integer>() {

                    @Override
                    public Integer apply(Integer o) {
                        return o + 1;
                    }
                }, Arrays.asList(1, 2, 3));
            } catch (IgniteClientDisconnectedException e) {
                checkAndWait(e);
                return true;
            }
            return false;
        }
    });
    // Check that client waiting operation.
    GridTestUtils.assertThrows(log, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            return fut.get(200);
        }
    }, IgniteFutureTimeoutCheckedException.class, null);
    assertNotDone(fut);
    commSpi.unblockMessage();
    reconnectClientNode(client, srv, null);
    assertTrue((Boolean) fut.get(2, TimeUnit.SECONDS));
}
Also used : IgniteClosure(org.apache.ignite.lang.IgniteClosure) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) Ignite(org.apache.ignite.Ignite) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException)

Example 5 with IgniteClosure

use of org.apache.ignite.lang.IgniteClosure in project ignite by apache.

the class GridMarshallerAbstractTest method testMarshallingAnonymousClassInstance.

/**
     * Tests marshal anonymous class instance.
     *
     * @throws Exception If test failed.
     */
public void testMarshallingAnonymousClassInstance() throws Exception {
    final Ignite g = grid();
    GridMarshallerTestBean inBean = newTestBean(new IgniteClosure() {

        /** */
        private Iterable<ClusterNode> nodes = g.cluster().nodes();

        /** {@inheritDoc} */
        @Override
        public Object apply(Object o) {
            return nodes;
        }
    });
    byte[] buf = marshal(inBean);
    GridMarshallerTestBean outBean = unmarshal(buf);
    assert inBean.getObjectField() != null;
    assert outBean.getObjectField() != null;
    assert IgniteClosure.class.isAssignableFrom(inBean.getObjectField().getClass());
    assert IgniteClosure.class.isAssignableFrom(outBean.getObjectField().getClass());
    assert inBean.getObjectField() != outBean.getObjectField();
    assert inBean != outBean;
    assert inBean.equals(outBean);
    outBean.checkNullResources();
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteClosure(org.apache.ignite.lang.IgniteClosure) Ignite(org.apache.ignite.Ignite)

Aggregations

IgniteClosure (org.apache.ignite.lang.IgniteClosure)17 Ignite (org.apache.ignite.Ignite)9 Cache (javax.cache.Cache)6 ArrayList (java.util.ArrayList)5 IgniteCache (org.apache.ignite.IgniteCache)5 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)5 IgniteException (org.apache.ignite.IgniteException)5 List (java.util.List)4 ScanQuery (org.apache.ignite.cache.query.ScanQuery)4 ClusterNode (org.apache.ignite.cluster.ClusterNode)4 IOException (java.io.IOException)3 IgniteBiPredicate (org.apache.ignite.lang.IgniteBiPredicate)3 IgniteInstanceResource (org.apache.ignite.resources.IgniteInstanceResource)3 UUID (java.util.UUID)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 IgniteCountDownLatch (org.apache.ignite.IgniteCountDownLatch)2 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)2 IgniteLock (org.apache.ignite.IgniteLock)2 BinaryObject (org.apache.ignite.binary.BinaryObject)2 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)2