Search in sources :

Example 26 with IgniteCompute

use of org.apache.ignite.IgniteCompute in project ignite by apache.

the class GridCacheQueueJoinedNodeSelfAbstractTest method testTakeFromJoined.

/**
 * @throws Exception If failed.
 */
public void testTakeFromJoined() throws Exception {
    String queueName = UUID.randomUUID().toString();
    IgniteQueue<Integer> queue = grid(0).queue(queueName, 0, config(true));
    assertNotNull(queue);
    assertTrue(queue.isEmpty());
    PutJob putJob = new PutJob(queueName);
    IgniteCompute comp = compute(grid(0).cluster().forLocal());
    IgniteFuture<?> fut = comp.runAsync(putJob);
    Collection<IgniteFuture<?>> futs = new ArrayList<>(GRID_CNT - 1);
    Collection<TakeJob> jobs = new ArrayList<>(GRID_CNT - 1);
    int itemsLeft = ITEMS_CNT;
    for (int i = 1; i < GRID_CNT; i++) {
        int cnt = ITEMS_CNT / (GRID_CNT - 1);
        TakeJob job = new TakeJob(queueName, cnt, 10);
        jobs.add(job);
        comp = compute(grid(i).cluster().forLocal());
        futs.add(comp.callAsync(job));
        itemsLeft -= cnt;
    }
    assertEquals("Not all items will be polled", 0, itemsLeft);
    // Wait for half of items to be polled.
    for (TakeJob job : jobs) job.awaitItems();
    log.info("Start one more grid.");
    Ignite joined = startGrid(GRID_CNT);
    // We expect at least one item to be taken.
    TakeJob joinedJob = new TakeJob(queueName, 1, 1);
    jobs.add(joinedJob);
    Integer polled = forLocal(joined).call(joinedJob);
    assertNotNull("Joined node should poll item", polled);
    info(">>> Joined node polled " + polled);
    for (IgniteFuture<?> f : futs) f.cancel();
    putJob.stop(true);
    fut.get();
    for (TakeJob job : jobs) job.awaitDone();
}
Also used : ArrayList(java.util.ArrayList) IgniteFuture(org.apache.ignite.lang.IgniteFuture) Ignite(org.apache.ignite.Ignite) IgniteCompute(org.apache.ignite.IgniteCompute)

Example 27 with IgniteCompute

use of org.apache.ignite.IgniteCompute in project ignite by apache.

the class GridCachePutAllFailoverSelfTest method checkPutAllFailover.

/**
 * Tests putAll() method along with failover and cache backup.
 *
 * Checks that the resulting primary cache size is the same as
 * expected.
 *
 * @param near Near enabled.
 * @param workerCnt Worker count.
 * @param shutdownCnt Shutdown count.
 * @throws Exception If failed.
 */
public void checkPutAllFailover(boolean near, int workerCnt, int shutdownCnt) throws Exception {
    nearEnabled = near;
    backups = shutdownCnt;
    Collection<Integer> testKeys = generateTestKeys();
    final Ignite master = startGrid(MASTER);
    List<Ignite> workers = new ArrayList<>(workerCnt);
    for (int i = 1; i <= workerCnt; i++) workers.add(startGrid("worker" + i));
    info("Master: " + master.cluster().localNode().id());
    List<Ignite> runningWorkers = new ArrayList<>(workerCnt);
    for (int i = 1; i <= workerCnt; i++) {
        UUID id = workers.get(i - 1).cluster().localNode().id();
        info(String.format("Worker%d - %s", i, id));
        runningWorkers.add(workers.get(i - 1));
    }
    try {
        // Dummy call to fetch affinity function from remote node
        master.affinity(CACHE_NAME).mapKeyToNode("Dummy");
        Random rnd = new Random();
        Collection<Integer> dataChunk = new ArrayList<>(DATA_CHUNK_SIZE);
        int entryCntr = 0;
        int chunkCntr = 0;
        final AtomicBoolean jobFailed = new AtomicBoolean(false);
        int failoverPushGap = 0;
        final CountDownLatch emptyLatch = new CountDownLatch(1);
        final AtomicBoolean inputExhausted = new AtomicBoolean();
        IgniteCompute comp = compute(master.cluster().forPredicate(workerNodesFilter));
        for (Integer key : testKeys) {
            dataChunk.add(key);
            entryCntr++;
            if (entryCntr == DATA_CHUNK_SIZE) {
                // time to send data
                chunkCntr++;
                assert dataChunk.size() == DATA_CHUNK_SIZE;
                log.info("Pushing data chunk [chunkNo=" + chunkCntr + "]");
                ComputeTaskFuture<Void> fut = comp.executeAsync(new GridCachePutAllTask(runningWorkers.get(rnd.nextInt(runningWorkers.size())).cluster().localNode().id(), CACHE_NAME), dataChunk);
                // Blocks if queue is full.
                resQueue.put(fut);
                fut.listen(new CI1<IgniteFuture<Void>>() {

                    @Override
                    public void apply(IgniteFuture<Void> f) {
                        ComputeTaskFuture<?> taskFut = (ComputeTaskFuture<?>) f;
                        try {
                            // if something went wrong - we'll get exception here
                            taskFut.get();
                        } catch (IgniteException e) {
                            log.error("Job failed", e);
                            jobFailed.set(true);
                        }
                        // Remove complete future from queue to allow other jobs to proceed.
                        resQueue.remove(taskFut);
                        if (inputExhausted.get() && resQueue.isEmpty())
                            emptyLatch.countDown();
                    }
                });
                entryCntr = 0;
                dataChunk = new ArrayList<>(DATA_CHUNK_SIZE);
                if (chunkCntr >= FAIL_ON_CHUNK_NO) {
                    if (workerCnt - runningWorkers.size() < shutdownCnt) {
                        if (failoverPushGap > 0)
                            failoverPushGap--;
                        else {
                            Ignite victim = runningWorkers.remove(0);
                            info("Shutting down node: " + victim.cluster().localNode().id());
                            stopGrid(victim.name());
                            // Fail next node after some jobs have been pushed.
                            failoverPushGap = FAILOVER_PUSH_GAP;
                        }
                    }
                }
            }
        }
        inputExhausted.set(true);
        if (resQueue.isEmpty())
            emptyLatch.countDown();
        assert chunkCntr == TEST_MAP_SIZE / DATA_CHUNK_SIZE;
        // Wait for queue to empty.
        log.info("Waiting for empty queue...");
        boolean failedWait = false;
        if (!emptyLatch.await(AWAIT_TIMEOUT_SEC, TimeUnit.SECONDS)) {
            info(">>> Failed to wait for queue to empty.");
            failedWait = true;
        }
        if (!failedWait)
            assertFalse("One or more jobs have failed.", jobFailed.get());
        Collection<Integer> absentKeys = findAbsentKeys(runningWorkers.get(0), testKeys);
        if (!failedWait && !absentKeys.isEmpty()) {
            // Give some time to preloader.
            U.sleep(20000);
            absentKeys = findAbsentKeys(runningWorkers.get(0), testKeys);
        }
        info(">>> Absent keys: " + absentKeys);
        if (!F.isEmpty(absentKeys)) {
            for (Ignite g : runningWorkers) {
                IgniteKernal k = (IgniteKernal) g;
                info(">>>> Entries on node: " + k.getLocalNodeId());
                GridCacheAdapter<Object, Object> cache = k.internalCache("partitioned");
                for (Integer key : absentKeys) {
                    GridCacheEntryEx entry = cache.peekEx(key);
                    if (entry != null)
                        info(" >>> " + entry);
                    if (cache.context().isNear()) {
                        GridCacheEntryEx entry0 = cache.context().near().dht().peekEx(key);
                        if (entry0 != null)
                            info(" >>> " + entry);
                    }
                }
                info("");
            }
        }
        assertTrue(absentKeys.isEmpty());
        // Actual primary cache size.
        int primaryCacheSize = 0;
        for (Ignite g : runningWorkers) {
            info("Cache size [node=" + g.name() + ", localSize=" + g.cache(CACHE_NAME).localSize() + ", localPrimarySize=" + g.cache(CACHE_NAME).localSize(PRIMARY) + ']');
            primaryCacheSize += ((IgniteKernal) g).internalCache(CACHE_NAME).primarySize();
        }
        assertEquals(TEST_MAP_SIZE, primaryCacheSize);
        for (Ignite g : runningWorkers) assertEquals(TEST_MAP_SIZE, g.cache(CACHE_NAME).size(PRIMARY));
    } finally {
        stopAllGrids();
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteFuture(org.apache.ignite.lang.IgniteFuture) Random(java.util.Random) IgniteException(org.apache.ignite.IgniteException) ComputeTaskFuture(org.apache.ignite.compute.ComputeTaskFuture) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID) IgniteCompute(org.apache.ignite.IgniteCompute) IgniteKernal(org.apache.ignite.internal.IgniteKernal) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 28 with IgniteCompute

use of org.apache.ignite.IgniteCompute in project ignite by apache.

the class IgniteRejectConnectOnNodeStopTest method testNodeStop.

/**
 * @throws Exception If failed.
 */
public void testNodeStop() throws Exception {
    Ignite srv = startGrid(0);
    client = true;
    final Ignite c = startGrid(1);
    ClusterGroup grp = srv.cluster().forClients();
    IgniteCompute srvCompute = srv.compute(grp);
    srvCompute.call(new DummyClosure());
    IgniteInternalFuture fut = GridTestUtils.runAsync(new Runnable() {

        @Override
        public void run() {
            IgniteCache cache = c.cache(DEFAULT_CACHE_NAME);
            for (int i = 0; i < 100_000; i++) {
                try {
                    cache.put(1, 1);
                } catch (Exception ignore) {
                    break;
                }
            }
        }
    }, "cache-put");
    U.sleep(100);
    final CountDownLatch stopStartLatch = new CountDownLatch(1);
    IgniteInternalFuture<?> fut2 = GridTestUtils.runAsync(new Runnable() {

        @Override
        public void run() {
            stopStartLatch.countDown();
            c.close();
        }
    });
    boolean err = false;
    try {
        stopStartLatch.await();
        IgniteCacheMessageRecoveryAbstractTest.closeSessions(srv);
        long stopTime = U.currentTimeMillis() + 10_000;
        while (U.currentTimeMillis() < stopTime) {
            try {
                srvCompute.call(new DummyClosure());
            } catch (ClusterTopologyException e) {
                err = true;
                assertFalse(fut2.isDone());
                break;
            }
        }
    } finally {
        stopLatch.countDown();
    }
    fut.get();
    fut2.get();
    assertTrue("Failed to get excpected error", err);
}
Also used : IgniteCache(org.apache.ignite.IgniteCache) ClusterGroup(org.apache.ignite.cluster.ClusterGroup) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) CountDownLatch(java.util.concurrent.CountDownLatch) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) Ignite(org.apache.ignite.Ignite) ClusterTopologyException(org.apache.ignite.cluster.ClusterTopologyException) IgniteCompute(org.apache.ignite.IgniteCompute)

Example 29 with IgniteCompute

use of org.apache.ignite.IgniteCompute in project ignite by apache.

the class IgfsMetaManager method clientCompute.

/**
 * Get compute facade for client tasks.
 *
 * @return Compute facade.
 */
private IgniteCompute clientCompute() {
    assert client;
    IgniteCompute cliCompute0 = cliCompute;
    if (cliCompute0 == null) {
        IgniteEx ignite = igfsCtx.kernalContext().grid();
        ClusterGroup cluster = ignite.cluster().forIgfsMetadataDataNodes(cfg.getName(), metaCacheName);
        cliCompute0 = ignite.compute(cluster);
        cliCompute = cliCompute0;
    }
    assert cliCompute0 != null;
    return cliCompute0;
}
Also used : IgniteEx(org.apache.ignite.internal.IgniteEx) ClusterGroup(org.apache.ignite.cluster.ClusterGroup) IgniteCompute(org.apache.ignite.IgniteCompute)

Example 30 with IgniteCompute

use of org.apache.ignite.IgniteCompute in project ignite by apache.

the class ComputeAsyncExample method main.

/**
 * Executes example.
 *
 * @param args Command line arguments, none required.
 * @throws IgniteException If example execution failed.
 */
public static void main(String[] args) throws IgniteException {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println();
        System.out.println("Compute asynchronous example started.");
        // Enable asynchronous mode.
        IgniteCompute compute = ignite.compute().withAsync();
        Collection<IgniteFuture<?>> futs = new ArrayList<>();
        // Iterate through all words in the sentence and create runnable jobs.
        for (final String word : "Print words using runnable".split(" ")) {
            // Execute runnable on some node.
            compute.run(() -> {
                System.out.println();
                System.out.println(">>> Printing '" + word + "' on this node from ignite job.");
            });
            futs.add(compute.future());
        }
        // Wait for completion of all futures.
        futs.forEach(IgniteFuture::get);
        System.out.println();
        System.out.println(">>> Finished printing words using runnable execution.");
        System.out.println(">>> Check all nodes for output (this node is also part of the cluster).");
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteFuture(org.apache.ignite.lang.IgniteFuture) Ignite(org.apache.ignite.Ignite) IgniteCompute(org.apache.ignite.IgniteCompute)

Aggregations

IgniteCompute (org.apache.ignite.IgniteCompute)41 Ignite (org.apache.ignite.Ignite)19 IgniteException (org.apache.ignite.IgniteException)14 ArrayList (java.util.ArrayList)10 IgniteFuture (org.apache.ignite.lang.IgniteFuture)9 UUID (java.util.UUID)6 ClusterGroup (org.apache.ignite.cluster.ClusterGroup)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)4 IgniteEx (org.apache.ignite.internal.IgniteEx)4 IgniteCallable (org.apache.ignite.lang.IgniteCallable)4 Nullable (org.jetbrains.annotations.Nullable)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 ClusterNode (org.apache.ignite.cluster.ClusterNode)3 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)3 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)3 Collection (java.util.Collection)2 Callable (java.util.concurrent.Callable)2 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2