Search in sources :

Example 16 with IgniteCallable

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

the class IgniteTxOriginatingNodeFailureAbstractSelfTest method testTxOriginatingNodeFails.

/**
 * @param keys Keys to update.
 * @param partial Flag indicating whether to simulate partial prepared state.
 * @throws Exception If failed.
 */
protected void testTxOriginatingNodeFails(Collection<Integer> keys, final boolean partial) throws Exception {
    assertFalse(keys.isEmpty());
    final Collection<IgniteKernal> grids = new ArrayList<>();
    ClusterNode txNode = grid(originatingNode()).localNode();
    for (int i = 1; i < gridCount(); i++) grids.add((IgniteKernal) grid(i));
    final Map<Integer, String> map = new HashMap<>();
    final String initVal = "initialValue";
    for (Integer key : keys) {
        grid(originatingNode()).cache(DEFAULT_CACHE_NAME).put(key, initVal);
        map.put(key, String.valueOf(key));
    }
    Map<Integer, Collection<ClusterNode>> nodeMap = new HashMap<>();
    info("Node being checked: " + grid(1).localNode().id());
    for (Integer key : keys) {
        Collection<ClusterNode> nodes = new ArrayList<>();
        nodes.addAll(grid(1).affinity(DEFAULT_CACHE_NAME).mapKeyToPrimaryAndBackups(key));
        nodes.remove(txNode);
        nodeMap.put(key, nodes);
    }
    info("Starting optimistic tx " + "[values=" + map + ", topVer=" + (grid(1)).context().discovery().topologyVersion() + ']');
    if (partial)
        ignoreMessages(grid(1).localNode().id(), ignoreMessageClass());
    final Ignite txIgniteNode = G.ignite(txNode.id());
    GridTestUtils.runAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            IgniteCache<Integer, String> cache = txIgniteNode.cache(DEFAULT_CACHE_NAME);
            assertNotNull(cache);
            TransactionProxyImpl tx = (TransactionProxyImpl) txIgniteNode.transactions().txStart();
            GridNearTxLocal txEx = tx.tx();
            assertTrue(txEx.optimistic());
            cache.putAll(map);
            try {
                txEx.prepareNearTxLocal().get(3, TimeUnit.SECONDS);
            } catch (IgniteFutureTimeoutCheckedException ignored) {
                info("Failed to wait for prepare future completion: " + partial);
            }
            return null;
        }
    }).get();
    info("Stopping originating node " + txNode);
    G.stop(G.ignite(txNode.id()).name(), true);
    info("Stopped grid, waiting for transactions to complete.");
    boolean txFinished = GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            for (IgniteKernal g : grids) {
                GridCacheSharedContext<Object, Object> ctx = g.context().cache().context();
                int txNum = ctx.tm().idMapSize();
                if (txNum != 0)
                    return false;
            }
            return true;
        }
    }, 10000);
    assertTrue(txFinished);
    info("Transactions finished.");
    for (Map.Entry<Integer, Collection<ClusterNode>> e : nodeMap.entrySet()) {
        final Integer key = e.getKey();
        final String val = map.get(key);
        assertFalse(e.getValue().isEmpty());
        for (ClusterNode node : e.getValue()) {
            compute(G.ignite(node.id()).cluster().forNode(node)).call(new IgniteCallable<Void>() {

                /**
                 */
                @IgniteInstanceResource
                private Ignite ignite;

                @Override
                public Void call() throws Exception {
                    IgniteCache<Integer, String> cache = ignite.cache(DEFAULT_CACHE_NAME);
                    assertNotNull(cache);
                    assertEquals(partial ? initVal : val, cache.localPeek(key));
                    return null;
                }
            });
        }
    }
    for (Map.Entry<Integer, String> e : map.entrySet()) {
        for (Ignite g : G.allGrids()) {
            UUID locNodeId = g.cluster().localNode().id();
            assertEquals("Check failed for node: " + locNodeId, partial ? initVal : e.getValue(), g.cache(DEFAULT_CACHE_NAME).get(e.getKey()));
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GridCacheSharedContext(org.apache.ignite.internal.processors.cache.GridCacheSharedContext) Callable(java.util.concurrent.Callable) IgniteCallable(org.apache.ignite.lang.IgniteCallable) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) IgniteFutureTimeoutCheckedException(org.apache.ignite.internal.IgniteFutureTimeoutCheckedException) Ignite(org.apache.ignite.Ignite) UUID(java.util.UUID) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteKernal(org.apache.ignite.internal.IgniteKernal) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteException(org.apache.ignite.IgniteException) IgniteFutureTimeoutCheckedException(org.apache.ignite.internal.IgniteFutureTimeoutCheckedException) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) TransactionProxyImpl(org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl)

Example 17 with IgniteCallable

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

the class ComputeCallableExample 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 callable example started.");
        Collection<IgniteCallable<Integer>> calls = new ArrayList<>();
        // Iterate through all words in the sentence and create callable jobs.
        for (String word : "Count characters using callable".split(" ")) {
            calls.add(() -> {
                System.out.println();
                System.out.println(">>> Printing '" + word + "' on this node from ignite job.");
                return word.length();
            });
        }
        // Execute collection of callables on the ignite.
        Collection<Integer> res = ignite.compute().call(calls);
        int sum = res.stream().mapToInt(i -> i).sum();
        System.out.println();
        System.out.println(">>> Total number of characters in the phrase is '" + sum + "'.");
        System.out.println(">>> Check all nodes for output (this node is also part of the cluster).");
    }
}
Also used : Ignition(org.apache.ignite.Ignition) Collection(java.util.Collection) IgniteException(org.apache.ignite.IgniteException) Ignite(org.apache.ignite.Ignite) ExampleNodeStartup(org.apache.ignite.examples.ExampleNodeStartup) ArrayList(java.util.ArrayList) IgniteCallable(org.apache.ignite.lang.IgniteCallable) IgniteCallable(org.apache.ignite.lang.IgniteCallable) ArrayList(java.util.ArrayList) Ignite(org.apache.ignite.Ignite)

Example 18 with IgniteCallable

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

the class GridCacheSetAbstractSelfTest method testAffinityCall.

/**
 * @throws Exception If failed.
 */
public void testAffinityCall() throws Exception {
    final CollectionConfiguration colCfg = collectionConfiguration();
    colCfg.setCollocated(false);
    colCfg.setCacheMode(CacheMode.PARTITIONED);
    colCfg.setGroupName("testGroup");
    try (final IgniteSet<Integer> set1 = grid(0).set("Set1", colCfg)) {
        GridTestUtils.assertThrows(log, new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                set1.affinityCall(new IgniteCallable<Object>() {

                    @Override
                    public Object call() {
                        return null;
                    }
                });
                return null;
            }
        }, IgniteException.class, "Failed to execute affinityCall() for non-collocated set: " + set1.name() + ". This operation is supported only for collocated sets.");
    }
    colCfg.setCollocated(true);
    try (final IgniteSet<Integer> set2 = grid(0).set("Set2", colCfg)) {
        set2.add(100);
        final String cacheName = cctx(set2).name();
        Integer res = set2.affinityCall(new IgniteCallable<Integer>() {

            @IgniteInstanceResource
            private IgniteEx ignite;

            @Override
            public Integer call() {
                assertTrue(ignite.cachex(cacheName).affinity().isPrimaryOrBackup(ignite.cluster().localNode(), "Set2"));
                return set2.iterator().next();
            }
        });
        assertEquals(100, res.intValue());
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) IgniteCallable(org.apache.ignite.lang.IgniteCallable) IgniteEx(org.apache.ignite.internal.IgniteEx) CollectionConfiguration(org.apache.ignite.configuration.CollectionConfiguration) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException)

Example 19 with IgniteCallable

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

the class IgniteCountDownLatchAbstractSelfTest method checkLatch.

/**
 * @throws Exception If failed.
 */
private void checkLatch() throws Exception {
    // Test API.
    checkAutoDelete();
    checkAwait();
    checkCountDown();
    // Test main functionality.
    IgniteCountDownLatch latch1 = grid(0).countDownLatch("latch", 2, false, true);
    assertEquals(2, latch1.count());
    IgniteFuture<Object> fut = grid(0).compute().callAsync(new IgniteCallable<Object>() {

        @IgniteInstanceResource
        private Ignite ignite;

        @LoggerResource
        private IgniteLogger log;

        @Nullable
        @Override
        public Object call() throws Exception {
            // Test latch in multiple threads on each node.
            IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {

                @Nullable
                @Override
                public Object call() throws Exception {
                    IgniteCountDownLatch latch = ignite.countDownLatch("latch", 2, false, true);
                    assert latch != null && latch.count() == 2;
                    log.info("Thread is going to wait on latch: " + Thread.currentThread().getName());
                    assert latch.await(1, MINUTES);
                    log.info("Thread is again runnable: " + Thread.currentThread().getName());
                    return null;
                }
            }, 5, "test-thread");
            fut.get();
            return null;
        }
    });
    Thread.sleep(3000);
    assert latch1.countDown() == 1;
    assert latch1.countDown() == 0;
    // Ensure there are no hangs.
    fut.get();
    // Test operations on removed latch.
    latch1.close();
    checkRemovedLatch(latch1);
}
Also used : LoggerResource(org.apache.ignite.resources.LoggerResource) IgniteCountDownLatch(org.apache.ignite.IgniteCountDownLatch) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) IgniteCallable(org.apache.ignite.lang.IgniteCallable) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) Ignite(org.apache.ignite.Ignite) IgniteLogger(org.apache.ignite.IgniteLogger) Nullable(org.jetbrains.annotations.Nullable)

Example 20 with IgniteCallable

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

the class GridClosureSerializationTest method testExceptionSerializationFailure.

/**
 * @throws Exception If failed.
 */
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored", "Convert2Lambda" })
public void testExceptionSerializationFailure() throws Exception {
    final IgniteEx ignite0 = grid(0);
    final IgniteEx ignite1 = grid(1);
    GridTestUtils.assertThrows(null, new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            ignite1.compute(ignite1.cluster().forNode(ignite0.localNode())).call(new IgniteCallable<Object>() {

                @Override
                public Object call() throws Exception {
                    throw new BrokenException();
                }
            });
            return null;
        }
    }, IgniteException.class, null);
}
Also used : IgniteEx(org.apache.ignite.internal.IgniteEx) IgniteCallable(org.apache.ignite.lang.IgniteCallable) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException) BinaryObjectException(org.apache.ignite.binary.BinaryObjectException)

Aggregations

IgniteCallable (org.apache.ignite.lang.IgniteCallable)24 Ignite (org.apache.ignite.Ignite)15 IgniteException (org.apache.ignite.IgniteException)13 ArrayList (java.util.ArrayList)8 IOException (java.io.IOException)7 IgniteInstanceResource (org.apache.ignite.resources.IgniteInstanceResource)7 Collection (java.util.Collection)6 Callable (java.util.concurrent.Callable)6 IgniteEx (org.apache.ignite.internal.IgniteEx)6 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Nullable (org.jetbrains.annotations.Nullable)4 UUID (java.util.UUID)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)3 IgniteCompute (org.apache.ignite.IgniteCompute)3 IgniteLogger (org.apache.ignite.IgniteLogger)3 BinaryObjectException (org.apache.ignite.binary.BinaryObjectException)3 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)3 IgniteFuture (org.apache.ignite.lang.IgniteFuture)3