Search in sources :

Example 6 with P1

use of org.apache.ignite.internal.util.typedef.P1 in project ignite by apache.

the class GridTopologyCommandHandler method handleAsync.

/** {@inheritDoc} */
@Override
public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req) {
    assert req instanceof GridRestTopologyRequest : "Invalid command for topology handler: " + req;
    assert SUPPORTED_COMMANDS.contains(req.command());
    if (log.isDebugEnabled())
        log.debug("Handling topology REST request: " + req);
    GridRestTopologyRequest req0 = (GridRestTopologyRequest) req;
    GridRestResponse res = new GridRestResponse();
    boolean mtr = req0.includeMetrics();
    boolean attr = req0.includeAttributes();
    switch(req.command()) {
        case TOPOLOGY:
            {
                Collection<ClusterNode> allNodes = F.concat(false, ctx.discovery().allNodes(), ctx.discovery().daemonNodes());
                Collection<GridClientNodeBean> top = new ArrayList<>(allNodes.size());
                for (ClusterNode node : allNodes) top.add(createNodeBean(node, mtr, attr));
                res.setResponse(top);
                break;
            }
        case NODE:
            {
                UUID id = req0.nodeId();
                final String ip = req0.nodeIp();
                if (id == null && ip == null)
                    return new GridFinishedFuture<>(new IgniteCheckedException("Failed to handle request (either id or ip should be specified)."));
                ClusterNode node;
                if (id != null) {
                    // Always refresh topology so client see most up-to-date view.
                    ctx.discovery().alive(id);
                    node = ctx.grid().cluster().node(id);
                    if (ip != null && node != null && !containsIp(node.addresses(), ip))
                        node = null;
                } else
                    node = F.find(ctx.discovery().allNodes(), null, new P1<ClusterNode>() {

                        @Override
                        public boolean apply(ClusterNode n) {
                            return containsIp(n.addresses(), ip);
                        }
                    });
                if (node != null)
                    res.setResponse(createNodeBean(node, mtr, attr));
                else
                    res.setResponse(null);
                break;
            }
        default:
            assert false : "Invalid command for topology handler: " + req;
    }
    if (log.isDebugEnabled())
        log.debug("Handled topology REST request [res=" + res + ", req=" + req + ']');
    return new GridFinishedFuture<>(res);
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) P1(org.apache.ignite.internal.util.typedef.P1) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridRestTopologyRequest(org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest) GridRestResponse(org.apache.ignite.internal.processors.rest.GridRestResponse) Collection(java.util.Collection) UUID(java.util.UUID) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture)

Example 7 with P1

use of org.apache.ignite.internal.util.typedef.P1 in project ignite by apache.

the class GridJobStealingSelfTest method testProjectionPredicate.

/**
     * Tests that projection predicate is taken into account by Stealing SPI.
     *
     * @throws Exception If failed.
     */
public void testProjectionPredicate() throws Exception {
    final Ignite ignite3 = startGrid(3);
    executeAsync(compute(ignite1.cluster().forPredicate(new P1<ClusterNode>() {

        @Override
        public boolean apply(ClusterNode e) {
            return ignite1.cluster().localNode().id().equals(e.id()) || // Limit projection with only grid1 or grid3 node.
            ignite3.cluster().localNode().id().equals(e.id());
        }
    })), new JobStealingSpreadTask(4), null).get(TASK_EXEC_TIMEOUT_MS);
    // Verify that jobs were run only on grid1 and grid3 (not on grid2)
    assertEquals(2, jobDistrMap.keySet().size());
    assertEquals(2, jobDistrMap.get(ignite1.cluster().localNode().id()).size());
    assertEquals(2, jobDistrMap.get(ignite3.cluster().localNode().id()).size());
    assertFalse(jobDistrMap.containsKey(ignite2.cluster().localNode().id()));
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) P1(org.apache.ignite.internal.util.typedef.P1) Ignite(org.apache.ignite.Ignite)

Example 8 with P1

use of org.apache.ignite.internal.util.typedef.P1 in project ignite by apache.

the class GridCacheDhtPreloadSelfTest method checkActivePartitionTransfer.

/**
     * @param keyCnt Key count.
     * @param nodeCnt Node count.
     * @param sameCoord Same coordinator flag.
     * @param shuffle Shuffle flag.
     * @throws Exception If failed.
     */
private void checkActivePartitionTransfer(int keyCnt, int nodeCnt, boolean sameCoord, boolean shuffle) throws Exception {
    try {
        Ignite ignite1 = startGrid(0);
        IgniteCache<Integer, String> cache1 = ignite1.cache(DEFAULT_CACHE_NAME);
        putKeys(cache1, keyCnt);
        checkKeys(cache1, keyCnt, F.asList(ignite1));
        List<Ignite> ignites = new ArrayList<>(nodeCnt + 1);
        startGrids(nodeCnt, 1, ignites);
        // Check all nodes.
        for (Ignite g : ignites) {
            IgniteCache<Integer, String> c = g.cache(DEFAULT_CACHE_NAME);
            checkKeys(c, keyCnt, ignites);
        }
        if (shuffle)
            Collections.shuffle(ignites);
        if (sameCoord)
            // Add last.
            ignites.add(ignite1);
        else
            // Add first.
            ignites.add(0, ignite1);
        if (!sameCoord && shuffle)
            Collections.shuffle(ignites);
        checkActiveState(ignites);
        info(">>> Finished checking nodes [keyCnt=" + keyCnt + ", nodeCnt=" + nodeCnt + ", grids=" + U.grids2names(ignites) + ']');
        Collection<IgniteFuture<?>> futs = new LinkedList<>();
        Ignite last = F.last(ignites);
        for (Iterator<Ignite> it = ignites.iterator(); it.hasNext(); ) {
            Ignite g = it.next();
            if (!it.hasNext()) {
                assert last == g;
                break;
            }
            checkActiveState(ignites);
            final UUID nodeId = g.cluster().localNode().id();
            it.remove();
            futs.add(waitForLocalEvent(last.events(), new P1<Event>() {

                @Override
                public boolean apply(Event e) {
                    CacheRebalancingEvent evt = (CacheRebalancingEvent) e;
                    ClusterNode node = evt.discoveryNode();
                    return evt.type() == EVT_CACHE_REBALANCE_STOPPED && node.id().equals(nodeId) && (evt.discoveryEventType() == EVT_NODE_LEFT || evt.discoveryEventType() == EVT_NODE_FAILED);
                }
            }, EVT_CACHE_REBALANCE_STOPPED));
            info("Before grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites));
            stopGrid(g.name());
            info("After grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites));
            // Check all left nodes.
            checkActiveState(ignites);
        }
        info("Waiting for preload futures: " + F.view(futs, new IgnitePredicate<IgniteFuture<?>>() {

            @Override
            public boolean apply(IgniteFuture<?> fut) {
                return !fut.isDone();
            }
        }));
        X.waitAll(futs);
        info("Finished waiting for preload futures.");
        assert last != null;
        IgniteCache<Integer, String> lastCache = last.cache(DEFAULT_CACHE_NAME);
        GridDhtCacheAdapter<Integer, String> dht = dht(lastCache);
        Affinity<Integer> aff = affinity(lastCache);
        info("Finished waiting for all exchange futures...");
        for (int i = 0; i < keyCnt; i++) {
            if (aff.mapPartitionToPrimaryAndBackups(aff.partition(i)).contains(last.cluster().localNode())) {
                GridDhtPartitionTopology top = dht.topology();
                for (GridDhtLocalPartition p : top.localPartitions()) {
                    Collection<ClusterNode> moving = top.moving(p.id());
                    assert moving.isEmpty() : "Nodes with partition in moving state [part=" + p + ", moving=" + moving + ']';
                    assert OWNING == p.state() : "Invalid partition state for partition [part=" + p + ", map=" + top.partitionMap(false) + ']';
                }
            }
        }
        checkActiveState(ignites);
    } catch (Error | Exception e) {
        error("Test failed.", e);
        throw e;
    } finally {
        stopAllGrids();
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteFuture(org.apache.ignite.lang.IgniteFuture) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID) ClusterNode(org.apache.ignite.cluster.ClusterNode) P1(org.apache.ignite.internal.util.typedef.P1) LinkedList(java.util.LinkedList) Event(org.apache.ignite.events.Event) CacheRebalancingEvent(org.apache.ignite.events.CacheRebalancingEvent) CacheRebalancingEvent(org.apache.ignite.events.CacheRebalancingEvent)

Example 9 with P1

use of org.apache.ignite.internal.util.typedef.P1 in project ignite by apache.

the class F0 method and.

/**
     * Get a predicate (non peer-deployable) that evaluates to {@code true} if each of its component predicates
     * evaluates to {@code true}. The components are evaluated in order they are supplied.
     * Evaluation will be stopped as soon as first predicate evaluates to {@code false}.
     * Passed in predicates are NOT copied. If no predicates are passed in the returned
     * predicate will always evaluate to {@code false}.
     *
     * @param p1 Passed in predicates.
     * @param p2 Passed in predicates.
     * @param <T> Type of the free variable, i.e. the element the predicate is called on.
     * @return Predicate that evaluates to {@code true} if each of its component predicates
     *      evaluates to {@code true}.
     */
@SuppressWarnings({ "unchecked", "ConfusingArgumentToVarargsMethod" })
public static <T> IgnitePredicate<T> and(@Nullable final IgnitePredicate<? super T>[] p1, @Nullable final IgnitePredicate<? super T>... p2) {
    if (F.isAlwaysFalse(p1) || F.isAlwaysFalse(p2))
        return F.alwaysFalse();
    if (F.isAlwaysTrue(p1) && F.isAlwaysTrue(p2))
        return F.alwaysTrue();
    final boolean e1 = F.isEmpty(p1);
    final boolean e2 = F.isEmpty(p2);
    if (e1 && e2)
        return F.alwaysTrue();
    if (e1) {
        if (p2.length == 1)
            return (IgnitePredicate<T>) p2[0];
    }
    if (!e1 && e2) {
        if (p1.length == 1)
            return (IgnitePredicate<T>) p1[0];
    }
    if ((e1 || isAllNodePredicates(p1)) && (e2 || isAllNodePredicates(p2))) {
        Set<UUID> ids = new GridLeanSet<>();
        if (!e1) {
            for (IgnitePredicate<? super T> p : p1) ids.addAll(((GridNodePredicate) p).nodeIds());
        }
        if (!e2) {
            for (IgnitePredicate<? super T> p : p2) ids.addAll(((GridNodePredicate) p).nodeIds());
        }
        // T must be <T extends ClusterNode>.
        return (IgnitePredicate<T>) new GridNodePredicate(ids);
    } else {
        return new P1<T>() {

            @Override
            public boolean apply(T t) {
                if (!e1) {
                    for (IgnitePredicate<? super T> p : p1) if (p != null && !p.apply(t))
                        return false;
                }
                if (!e2) {
                    for (IgnitePredicate<? super T> p : p2) if (p != null && !p.apply(t))
                        return false;
                }
                return true;
            }
        };
    }
}
Also used : P1(org.apache.ignite.internal.util.typedef.P1) GridNodePredicate(org.apache.ignite.internal.util.lang.GridNodePredicate) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) UUID(java.util.UUID)

Example 10 with P1

use of org.apache.ignite.internal.util.typedef.P1 in project ignite by apache.

the class F0 method and.

/**
     * Get a predicate (not peer-deployable) that evaluates to {@code true} if each of its component predicates
     * evaluates to {@code true}. The components are evaluated in order they are supplied.
     * Evaluation will be stopped as soon as first predicate evaluates to {@code false}.
     * Passed in predicates are NOT copied. If no predicates are passed in the returned
     * predicate will always evaluate to {@code false}.
     *
     * @param ps Passed in predicate. If none provided - always-{@code false} predicate is
     *      returned.
     * @param <T> Type of the free variable, i.e. the element the predicate is called on.
     * @return Predicate that evaluates to {@code true} if each of its component predicates
     *      evaluates to {@code true}.
     */
@SuppressWarnings({ "unchecked", "ConfusingArgumentToVarargsMethod", "ConstantConditions" })
public static <T> IgnitePredicate<T> and(@Nullable final IgnitePredicate<? super T> p, @Nullable final IgnitePredicate<? super T>... ps) {
    if (p == null && F.isEmptyOrNulls(ps))
        return F.alwaysTrue();
    if (F.isAlwaysFalse(p) && F.isAlwaysFalse(ps))
        return F.alwaysFalse();
    if (F.isAlwaysTrue(p) && F.isAlwaysTrue(ps))
        return F.alwaysTrue();
    if (isAllNodePredicates(p) && isAllNodePredicates(ps)) {
        assert ps != null;
        Set<UUID> ids = new GridLeanSet<>();
        for (IgnitePredicate<? super T> p0 : ps) {
            Collection<UUID> list = ((GridNodePredicate) p0).nodeIds();
            if (ids.isEmpty())
                ids.addAll(list);
            else
                ids.retainAll(list);
        }
        Collection<UUID> list = ((GridNodePredicate) p).nodeIds();
        if (ids.isEmpty())
            ids.addAll(list);
        else
            ids.retainAll(list);
        // T must be <T extends ClusterNode>.
        return (IgnitePredicate<T>) new GridNodePredicate(ids);
    } else {
        return new P1<T>() {

            @Override
            public boolean apply(T t) {
                assert ps != null;
                if (p != null && !p.apply(t))
                    return false;
                for (IgnitePredicate<? super T> p : ps) if (p != null && !p.apply(t))
                    return false;
                return true;
            }
        };
    }
}
Also used : P1(org.apache.ignite.internal.util.typedef.P1) GridNodePredicate(org.apache.ignite.internal.util.lang.GridNodePredicate) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) UUID(java.util.UUID)

Aggregations

P1 (org.apache.ignite.internal.util.typedef.P1)11 UUID (java.util.UUID)6 ClusterNode (org.apache.ignite.cluster.ClusterNode)5 Event (org.apache.ignite.events.Event)4 Ignite (org.apache.ignite.Ignite)3 LinkedList (java.util.LinkedList)2 DiscoveryEvent (org.apache.ignite.events.DiscoveryEvent)2 JobEvent (org.apache.ignite.events.JobEvent)2 GridNodePredicate (org.apache.ignite.internal.util.lang.GridNodePredicate)2 P2 (org.apache.ignite.internal.util.typedef.P2)2 IgniteFuture (org.apache.ignite.lang.IgniteFuture)2 IgnitePredicate (org.apache.ignite.lang.IgnitePredicate)2 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashSet (java.util.HashSet)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Lock (java.util.concurrent.locks.Lock)1 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)1 CacheRebalancingEvent (org.apache.ignite.events.CacheRebalancingEvent)1