Java Code Examples for org.apache.ignite.internal.IgniteEx#createCache()

The following examples show how to use org.apache.ignite.internal.IgniteEx#createCache() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheMvccSqlTxModesTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed
 */
@Test
public void testSqlTransactionModesNoMvcc() throws Exception {
    IgniteEx node = startGrid(0);

    IgniteCache<Object, Object> nonMvccCache = node.createCache(new CacheConfiguration<>("no-mvcc-cache")
        .setAtomicityMode(TRANSACTIONAL).setIndexedTypes(Integer.class, Integer.class));

    nonMvccCache.put(1, 1);

    for (TransactionConcurrency conc : TransactionConcurrency.values()) {
        for (TransactionIsolation iso : TransactionIsolation.values()) {
            try (Transaction tx = node.transactions().txStart(conc, iso)) {
                nonMvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

                tx.commit();
            }
            catch (Throwable t) {
                log.error("Transaction failed: concurrency=" + conc + ", isolation=" + iso, t);

                throw t;
            }
        }
    }
}
 
Example 2
Source File: SqlIndexConsistencyAfterInterruptAtomicCacheOperationTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception On error.
 */
@Test
public void testRemoveAll() throws Exception {
    IgniteEx ign = startGrid(0);

    IgniteCache<Object, Object> cache = ign.createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)
        .setAtomicityMode(atomicity())
        .setIndexedTypes(Integer.class, Integer.class));

    final Map<Integer, Integer> batch = new HashMap<>();

    for (int i = 0; i < KEYS; ++i)
        batch.put(i, i);

    cache.putAll(batch);

    Thread t = new Thread(() -> {
        cache.removeAll(batch.keySet());
    });

    t.start();
    t.interrupt();
    t.join();

    assertEquals(cache.size(), cache.query(new SqlFieldsQuery("select * from Integer")).getAll().size());
}
 
Example 3
Source File: ScanQueriesTopologyMappingTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testLocalCacheQueryMapping() throws Exception {
    IgniteEx ign0 = startGrid(0);

    IgniteCache<Object, Object> cache = ign0.createCache(new CacheConfiguration<>(GridAbstractTest.DEFAULT_CACHE_NAME)
        .setCacheMode(CacheMode.LOCAL));

    cache.put(1, 2);

    startGrid(1);

    ScanQuery<Object, Object> qry = new ScanQuery<>();

    {
        List<Cache.Entry<Object, Object>> res0 = grid(0).cache(GridAbstractTest.DEFAULT_CACHE_NAME).query(qry).getAll();

        assertEquals(1, res0.size());
        assertEquals(1, res0.get(0).getKey());
        assertEquals(2, res0.get(0).getValue());
    }

    {
        List<Cache.Entry<Object, Object>> res1 = grid(1).cache(GridAbstractTest.DEFAULT_CACHE_NAME).query(qry).getAll();

        assertTrue(res1.isEmpty());
    }
}
 
Example 4
Source File: QueryDataPageScanTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
@Ignore("https://issues.apache.org/jira/browse/IGNITE-11998")
public void testDataPageScan() throws Exception {
    final String cacheName = "test";

    GridQueryProcessor.idxCls = DirectPageScanIndexing.class;
    IgniteEx server = startGrid(0);
    server.cluster().active(true);

    IgniteEx client = startClientGrid(1);

    CacheConfiguration<Long,TestData> ccfg = new CacheConfiguration<>(cacheName);
    ccfg.setIndexedTypes(Long.class, TestData.class);
    ccfg.setSqlFunctionClasses(QueryDataPageScanTest.class);

    IgniteCache<Long,TestData> clientCache = client.createCache(ccfg);

    final int keysCnt = 1000;

    for (long i = 0; i < keysCnt; i++)
        clientCache.put(i, new TestData(i));

    IgniteCache<Long,TestData> serverCache = server.cache(cacheName);

    doTestScanQuery(clientCache, keysCnt);
    doTestScanQuery(serverCache, keysCnt);

    doTestSqlQuery(clientCache);
    doTestSqlQuery(serverCache);

    doTestDml(clientCache);
    doTestDml(serverCache);

    doTestLazySql(clientCache, keysCnt);
    doTestLazySql(serverCache, keysCnt);
}
 
Example 5
Source File: GridCommandHandlerTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCacheIdleVerifyPrintLostPartitions() throws Exception {
    IgniteEx ignite = startGrids(3);

    ignite.cluster().active(true);

    ignite.createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)
        .setAffinity(new RendezvousAffinityFunction(false, 16))
        .setCacheMode(PARTITIONED)
        .setPartitionLossPolicy(READ_ONLY_SAFE)
        .setBackups(1));

    try (IgniteDataStreamer streamer = ignite.dataStreamer(DEFAULT_CACHE_NAME)) {
        for (int i = 0; i < 10000; i++)
            streamer.addData(i, new byte[i]);
    }

    String g1Name = grid(1).name();

    stopGrid(1);

    cleanPersistenceDir(g1Name);

    //Start node 2 with empty PDS. Rebalance will be started.
    startGrid(1);

    //During rebalance stop node 3. Rebalance will be stopped which lead to lost partitions.
    stopGrid(2);

    injectTestSystemOut();

    assertEquals(EXIT_CODE_OK, execute("--cache", "idle_verify", "--yes"));

    assertContains(log, testOut.toString(), "LOST partitions:");
}
 
Example 6
Source File: IgniteCacheGroupsWithRestartsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Ignore("https://issues.apache.org/jira/browse/IGNITE-8717")
@Test
public void testNodeRestartRightAfterCacheStop() throws Exception {
    IgniteEx ex = startGrids(3);

    prepareCachesAndData(ex);

    ex.destroyCache(getCacheName(0));

    assertNull(ex.cachex(getCacheName(0)));

    stopGrid(2, true);

    startGrid(2);

    assertNull(ex.cachex(getCacheName(0)));

    IgniteCache<Object, Object> cache = ex.createCache(getCacheConfiguration(0));

    awaitPartitionMapExchange();

    assertEquals(0, cache.size());
}
 
Example 7
Source File: CacheMvccSqlLockTimeoutTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** */
private void checkLockTimeoutsAfterDefaultTxTimeout(CacheConfiguration<?, ?> ccfg) throws Exception {
    cfgCustomizer = cfg ->
        cfg.setTransactionConfiguration(new TransactionConfiguration().setDefaultTxTimeout(TIMEOUT_MILLIS));

    startGridsMultiThreaded(2);

    IgniteEx ignite = grid(0);

    ignite.createCache(ccfg);

    AtomicInteger keyCntr = new AtomicInteger();

    int nearKey = keyForNode(ignite.affinity("test"), keyCntr, ignite.localNode());
    int otherKey = keyForNode(ignite.affinity("test"), keyCntr, grid(1).localNode());

    TimeoutChecker timeoutChecker = new TimeoutChecker(ignite, "test");

    timeoutChecker.checkScenario(TimeoutMode.TX_DEFAULT, TxStartMode.EXPLICIT, nearKey);

    timeoutChecker.checkScenario(TimeoutMode.TX_DEFAULT, TxStartMode.EXPLICIT, otherKey);

    timeoutChecker.checkScenario(TimeoutMode.TX_DEFAULT, TxStartMode.IMPLICIT, nearKey);

    timeoutChecker.checkScenario(TimeoutMode.TX_DEFAULT, TxStartMode.IMPLICIT, otherKey);
}
 
Example 8
Source File: EncryptedCacheGroupCreateTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** @throws Exception If failed. */
@Test
public void testCreateEncryptedCacheGroup() throws Exception {
    KeystoreEncryptionKey key = createEncryptedCache(ENCRYPTED_CACHE, ENCRYPTED_GROUP);

    CacheConfiguration<Long, String> ccfg = new CacheConfiguration<>(ENCRYPTED_CACHE + "2");

    ccfg.setEncryptionEnabled(true);
    ccfg.setGroupName(ENCRYPTED_GROUP);

    IgniteEx grid = grid(0);

    grid.createCache(ccfg);

    IgniteInternalCache<Object, Object> encrypted2 = grid.cachex(ENCRYPTED_CACHE + "2");

    GridEncryptionManager encMgr = encrypted2.context().kernalContext().encryption();

    KeystoreEncryptionKey key2 = (KeystoreEncryptionKey)encMgr.groupKey(CU.cacheGroupId(ENCRYPTED_CACHE, ENCRYPTED_GROUP));

    assertNotNull(key2);
    assertNotNull(key2.key());

    assertEquals(key.key(), key2.key());
}
 
Example 9
Source File: GridCommandHandlerTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** */
@Test
public void testIdleVerifyCheckCrcFailsOnNotIdleCluster() throws Exception {
    checkpointFreq = 1000L;

    IgniteEx node = startGrids(2);

    node.cluster().active(true);

    IgniteCache cache = node.createCache(new CacheConfiguration<>()
        .setAffinity(new RendezvousAffinityFunction(false, 32))
        .setBackups(1)
        .setName(DEFAULT_CACHE_NAME)
    );

    AtomicBoolean stopFlag = new AtomicBoolean();

    Thread loadThread = new Thread(() -> {
        ThreadLocalRandom rnd = ThreadLocalRandom.current();

        while (!stopFlag.get()) {
            cache.put(rnd.nextInt(1000), rnd.nextInt(1000));

            if (Thread.interrupted())
                break;
        }
    });

    try {
        loadThread.start();

        doSleep(checkpointFreq);

        injectTestSystemOut();

        assertEquals(EXIT_CODE_OK, execute("--cache", "idle_verify", "--check-crc"));
    }
    finally {
        doSleep(checkpointFreq);

        stopFlag.set(true);

        loadThread.join();
    }

    String out = testOut.toString();

    assertContains(log, out, "idle_verify failed");
    assertContains(log, out, "See log for additional information.");

    String logFileName = (out.split("See log for additional information. ")[1]).split(".txt")[0];

    String logFile = new String(Files.readAllBytes(new File(logFileName + ".txt").toPath()));

    assertContains(log, logFile, GRID_NOT_IDLE_MSG);
}
 
Example 10
Source File: IgniteDynamicEnableIndexingRestoreTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param startFromEnabledIndexing If @{code true}, start grid from node with enabled indexing.
 *
 * @throws Exception if failed.
 */
private void testReconnectClient(boolean startFromEnabledIndexing) throws Exception {
    IgniteEx srv0 = startGrids(2);

    IgniteEx cli = startClientGrid(2);

    cli.cluster().state(ClusterState.ACTIVE);

    IgniteCache<?, ?> cache = srv0.createCache(testCacheConfiguration(POI_CACHE_NAME));

    loadData(srv0, 0, NUM_ENTRIES);

    stopGrid(1);

    createTable(cache, POI_SCHEMA_NAME, CacheConfiguration.DFLT_QUERY_PARALLELISM);

    performQueryingIntegrityCheck(srv0);

    IgniteClientReconnectAbstractTest.reconnectClientNode(log, cli, srv0, () -> {
        try {
            stopGrid(0);

            if (startFromEnabledIndexing)
                startGrid(0);
            else
                startGrid(1);
        }
        catch (Exception e) {
            throw new IgniteException("Failed to restart cluster", e);
        }
    });

    assertEquals(2, cli.cluster().nodes().size());
    cli.cluster().state(ClusterState.ACTIVE);

    if (startFromEnabledIndexing) {
        awaitPartitionMapExchange();

        performQueryingIntegrityCheck(cli);
    }
    else
        assertEquals(NUM_ENTRIES, cli.getOrCreateCache(POI_CACHE_NAME).size(CachePeekMode.PRIMARY));
}
 
Example 11
Source File: GridCommandHandlerClusterByClassTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Common method for idle_verify tests with multiple options.
 */
@Test
public void testCacheIdleVerifyMultipleCacheFilterOptions()
        throws Exception {
    IgniteEx ignite = crd;

    ignite.createCache(new CacheConfiguration<>()
            .setAffinity(new RendezvousAffinityFunction(false, 32))
            .setGroupName("shared_grp")
            .setBackups(1)
            .setName(DEFAULT_CACHE_NAME));

    ignite.createCache(new CacheConfiguration<>()
            .setAffinity(new RendezvousAffinityFunction(false, 32))
            .setGroupName("shared_grp")
            .setBackups(1)
            .setName(DEFAULT_CACHE_NAME + "_second"));

    ignite.createCache(new CacheConfiguration<>()
            .setAffinity(new RendezvousAffinityFunction(false, 64))
            .setBackups(1)
            .setName(DEFAULT_CACHE_NAME + "_third"));

    ignite.createCache(new CacheConfiguration<>()
            .setAffinity(new RendezvousAffinityFunction(false, 128))
            .setBackups(1)
            .setName("wrong_cache"));

    injectTestSystemOut();

    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found",
        "idle_verify task was executed with the following args: caches=[], excluded=[wrong.*], cacheFilter=[SYSTEM]",
        "--cache", "idle_verify", "--dump", "--cache-filter", "SYSTEM", "--exclude-caches", "wrong.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found 96 partitions",
        null,
        "--cache", "idle_verify", "--dump", "--exclude-caches", "wrong.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found 32 partitions",
        null,
        "--cache", "idle_verify", "--dump", "shared.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found 160 partitions",
        null,
        "--cache", "idle_verify", "--dump", "shared.*,wrong.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found 160 partitions",
        null,
        "--cache", "idle_verify", "--dump", "shared.*,wrong.*", "--cache-filter", "USER"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, found 160 partitions",
        null,
        "--cache", "idle_verify", "--dump", "shared.*,wrong.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "There are no caches matching given filter options",
        null,
        "--cache", "idle_verify", "--exclude-caches", ".*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        false,
        "Invalid cache name regexp",
        null,
        "--cache", "idle_verify", "--dump", "--exclude-caches", "["
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, no conflicts have been found.",
        null,
        "--cache", "idle_verify", "--exclude-caches", "wrong.*"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "idle_verify check has finished, no conflicts have been found.",
        null,
        "--cache", "idle_verify", "--dump", "--cache-filter", "PERSISTENT"
    );
    testCacheIdleVerifyMultipleCacheFilterOptionsCommon(
        true,
        "There are no caches matching given filter options.",
        null,
        "--cache", "idle_verify", "--cache-filter", "NOT_PERSISTENT"
    );
}
 
Example 12
Source File: CacheMvccSqlTxModesTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed
 */
@Test
public void testSqlTransactionModesMvcc() throws Exception {
    IgniteEx node = startGrid(0);

    IgniteCache<Object, Object> mvccCache = node.createCache(new CacheConfiguration<>("mvcc-cache")
        .setAtomicityMode(TRANSACTIONAL_SNAPSHOT).setIndexedTypes(Integer.class, Integer.class));

    mvccCache.put(1,1);

    GridTestUtils.assertThrows(log, new Callable<Void>() {
        @Override public Void call() throws Exception {
            try (Transaction tx = node.transactions().txStart(OPTIMISTIC, READ_COMMITTED)) {
                mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

                tx.commit();
            }

            return null;
        }
    }, TransactionUnsupportedConcurrencyException.class, "Only pessimistic transactions are supported when MVCC is enabled");

    GridTestUtils.assertThrows(log, new Callable<Void>() {
        @Override public Void call() throws Exception {
            try (Transaction tx = node.transactions().txStart(OPTIMISTIC, REPEATABLE_READ)) {
                mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

                tx.commit();
            }

            return null;
        }
    }, TransactionUnsupportedConcurrencyException.class, "Only pessimistic transactions are supported when MVCC is enabled");

    GridTestUtils.assertThrows(log, new Callable<Void>() {
        @Override public Void call() throws Exception {
            try (Transaction tx = node.transactions().txStart(OPTIMISTIC, SERIALIZABLE)) {
                mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

                tx.commit();
            }

            return null;
        }
    }, TransactionUnsupportedConcurrencyException.class, "Only pessimistic transactions are supported when MVCC is enabled");

    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, READ_COMMITTED)) {
        mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

        tx.commit();
    }

    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

        tx.commit();
    }

    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, SERIALIZABLE)) {
        mvccCache.query(new SqlFieldsQuery("SELECT * FROM Integer")).getAll();

        tx.commit();
    }
}
 
Example 13
Source File: GridCacheRebalancingCancelTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Test rebalance not cancelled when client node join to cluster.
 *
 * @throws Exception Exception.
 */
@Test
public void testClientNodeJoinAtRebalancing() throws Exception {
    final IgniteEx ignite0 = startGrid(0);

    IgniteCache<Integer, Integer> cache = ignite0.createCache(
        new CacheConfiguration<Integer, Integer>(DHT_PARTITIONED_CACHE)
            .setCacheMode(CacheMode.PARTITIONED)
            .setRebalanceMode(CacheRebalanceMode.ASYNC)
            .setBackups(1)
            .setRebalanceOrder(2)
            .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)
            .setAffinity(new RendezvousAffinityFunction(false)));

    for (int i = 0; i < 2048; i++)
        cache.put(i, i);

    TestRecordingCommunicationSpi.spi(ignite0)
        .blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {
            @Override public boolean apply(ClusterNode node, Message msg) {
                return (msg instanceof GridDhtPartitionSupplyMessage)
                    && ((GridCacheGroupIdMessage)msg).groupId() == groupIdForCache(ignite0, DHT_PARTITIONED_CACHE);
            }
        });

    final IgniteEx ignite1 = startGrid(1);

    TestRecordingCommunicationSpi.spi(ignite0).waitForBlocked();

    GridDhtPartitionDemander.RebalanceFuture fut = (GridDhtPartitionDemander.RebalanceFuture)ignite1.context().
        cache().internalCache(DHT_PARTITIONED_CACHE).preloader().rebalanceFuture();

    String igniteClntName = getTestIgniteInstanceName(2);

    startClientGrid(igniteClntName, optimize(getConfiguration(igniteClntName)));

    // Resend delayed rebalance messages.
    TestRecordingCommunicationSpi.spi(ignite0).stopBlock(true);

    awaitPartitionMapExchange();

    // Previous rebalance future should not be cancelled.
    assertTrue(fut.result());
}
 
Example 14
Source File: SqlTwoCachesInGroupWithSameEntryTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception On error.
 */
@SuppressWarnings("unchecked")
@Test
public void test() throws Exception {
    IgniteEx ign = startGrid(0);

    ign.cluster().active(true);

    IgniteCache cache0 = ign.createCache(new CacheConfiguration<>("cache0")
        .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)
        .setGroupName("grp0")
        .setSqlSchema("CACHE0")
        .setIndexedTypes(Integer.class, Integer.class));

    IgniteCache cache1 = ign.createCache(new CacheConfiguration<>("cache1")
        .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)
        .setGroupName("grp0")
        .setSqlSchema("CACHE1")
        .setIndexedTypes(Integer.class, Integer.class));

    for (int i = 0; i < KEYS; ++i) {
        cache0.put(i, i);
        cache1.put(i, i);
    }

    if (useOnlyPkHashIndex) {
        for (GridH2Table t : ((IgniteH2Indexing)grid(0).context().query().getIndexing()).schemaManager().dataTables())
            GridTestUtils.setFieldValue(t, "rebuildFromHashInProgress", 1);
    }

    assertEquals(KEYS, cache0.size());
    assertEquals(KEYS, cache1.size());
    assertEquals(KEYS, sql("select * FROM cache0.Integer").getAll().size());
    assertEquals(KEYS, sql("select * FROM cache1.Integer").getAll().size());

    cache0.clear();

    assertEquals(0, cache0.size());
    assertEquals(KEYS, cache1.size());
    assertEquals(0, sql("select * FROM cache0.Integer").getAll().size());
    assertEquals(KEYS, sql("select * FROM cache1.Integer").getAll().size());
}
 
Example 15
Source File: CacheMvccProcessorTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
private void checkTreeOperations() throws Exception {
    IgniteEx grid = startGrid(0);

    grid.cluster().active(true);

    grid.createCache(new CacheConfiguration<>("test").setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT));

    MvccProcessorImpl mvccProcessor = mvccProcessor(grid);

    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 1, MvccUtils.MVCC_OP_COUNTER_NA)));

    grid.context().cache().context().database().checkpointReadLock();
    try {
        mvccProcessor.updateState(new MvccVersionImpl(1, 1, MvccUtils.MVCC_OP_COUNTER_NA), TxState.PREPARED);
        mvccProcessor.updateState(new MvccVersionImpl(1, 2, MvccUtils.MVCC_OP_COUNTER_NA), TxState.PREPARED);
        mvccProcessor.updateState(new MvccVersionImpl(1, 3, MvccUtils.MVCC_OP_COUNTER_NA), TxState.COMMITTED);
        mvccProcessor.updateState(new MvccVersionImpl(1, 4, MvccUtils.MVCC_OP_COUNTER_NA), TxState.ABORTED);
        mvccProcessor.updateState(new MvccVersionImpl(1, 5, MvccUtils.MVCC_OP_COUNTER_NA), TxState.ABORTED);
        mvccProcessor.updateState(new MvccVersionImpl(1, 6, MvccUtils.MVCC_OP_COUNTER_NA), TxState.PREPARED);
    }
    finally {
        grid.context().cache().context().database().checkpointReadUnlock();
    }

    if (persistence) {
        stopGrid(0, false);
        grid = startGrid(0);

        grid.cluster().active(true);

        mvccProcessor = mvccProcessor(grid);
    }

    assertEquals(TxState.PREPARED, mvccProcessor.state(new MvccVersionImpl(1, 1, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.PREPARED, mvccProcessor.state(new MvccVersionImpl(1, 2, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.COMMITTED, mvccProcessor.state(new MvccVersionImpl(1, 3, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.ABORTED, mvccProcessor.state(new MvccVersionImpl(1, 4, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.ABORTED, mvccProcessor.state(new MvccVersionImpl(1, 5, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.PREPARED, mvccProcessor.state(new MvccVersionImpl(1, 6, MvccUtils.MVCC_OP_COUNTER_NA)));

    mvccProcessor.removeUntil(new MvccVersionImpl(1, 5, MvccUtils.MVCC_OP_COUNTER_NA));

    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 1, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 2, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 3, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 4, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.NA, mvccProcessor.state(new MvccVersionImpl(1, 5, MvccUtils.MVCC_OP_COUNTER_NA)));
    assertEquals(TxState.PREPARED, mvccProcessor.state(new MvccVersionImpl(1, 6, MvccUtils.MVCC_OP_COUNTER_NA)));
}
 
Example 16
Source File: CacheContinuousQueryFilterDeploymentFailedTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Tests continuous query behavior in case of filter deployment obtaining failure.
 *
 * @throws Exception If failed.
 */
@Test
@SuppressWarnings({"ThrowableNotThrown"})
public void testContinuousQueryFilterDeploymentFailed() throws Exception {
    startGrids(NODES_CNT - 1);

    IgniteEx cli = startClientGrid(NODES_CNT - 1);

    IgniteCache<Integer, Integer> cache = cli.createCache(DEFAULT_CACHE_NAME);

    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();

    Class<Factory<CacheEntryEventFilter<Integer, Integer>>> rmtFilterFactoryCls =
        (Class<Factory<CacheEntryEventFilter<Integer, Integer>>>)getExternalClassLoader()
            .loadClass("org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilterFactory");

    qry.setRemoteFilterFactory(rmtFilterFactoryCls.newInstance());

    spi(grid(1)).blockMessages((node, msg) -> msg instanceof GridDeploymentRequest);

    assertThrowsWithCause(() -> cache.query(qry), CacheException.class);

    assertTrue(stopRoutineLatch.await(getTestTimeout(), MILLISECONDS));

    assertTrue(allGrids().stream().allMatch(g ->
        ((IgniteEx)g).context().systemView().view(CQ_SYS_VIEW).size() == 0));
}
 
Example 17
Source File: CacheBlockOnCreateDestoryIndexTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @param ignite Ignite instance.
 * @return 3 pairs {@code {cacheName, tableName, indexName}} for further sql operations.
 */
@NotNull private List<T3<String, String, String>> createCaches(IgniteEx ignite) {
    List<T3<String, String, String>> caches = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        String tblName = "TABLE_" + UUID.randomUUID().toString().replace('-', '_');

        String cacheName = "CACHE_" + tblName;

        CacheConfiguration<?, ?> ccfg = new CacheConfiguration<>(cacheName).setSqlSchema("PUBLIC");

        IgniteCache<?, ?> cache = ignite.createCache(ccfg);

        String createTblQryStr = String.format(
            "CREATE TABLE %s (id LONG, name VARCHAR, city_id LONG, PRIMARY KEY (id, city_id)) " +
                "WITH \"backups=1, affinityKey=city_id\"",
            tblName
        );

        cache.query(new SqlFieldsQuery(createTblQryStr)).getAll();

        String idxName = "IDX_" + tblName;

        caches.add(new T3<>(cacheName, tblName, idxName));
    }

    return caches;
}
 
Example 18
Source File: IgniteStandByClientReconnectTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testInActiveClientReconnectToActiveCluster() throws Exception {
    CountDownLatch activateLatch = new CountDownLatch(1);

    startNodes(activateLatch);

    IgniteEx ig1 = grid(node1);
    IgniteEx ig2 = grid(node2);
    IgniteEx client = grid(nodeClient);

    assertTrue(!ig1.cluster().active());
    assertTrue(!ig2.cluster().active());
    assertTrue(!client.cluster().active());

    final CountDownLatch disconnectedLatch = new CountDownLatch(1);
    final CountDownLatch reconnectedLatch = new CountDownLatch(1);

    addDisconnectListener(disconnectedLatch, reconnectedLatch);

    stopGrid(node2);

    disconnectedLatch.await();

    ig2 = startGrid(getConfiguration(node2));

    ig1.cluster().active(true);

    assertTrue(ig1.cluster().active());
    assertTrue(ig2.cluster().active());

    checkDescriptors(ig1, staticCacheNames);
    checkDescriptors(ig2, staticCacheNames);

    activateLatch.countDown();

    reconnectedLatch.await();

    assertTrue(ig1.cluster().active());
    assertTrue(ig2.cluster().active());
    assertTrue(client.cluster().active());

    checkDescriptors(ig1, staticCacheNames);
    checkDescriptors(ig2, staticCacheNames);

    client.createCache(ccfgDynamic);

    client.createCache(ccfgDynamicWithFilter);

    checkDescriptors(ig1, allCacheNames);
    checkDescriptors(ig2, allCacheNames);
    checkDescriptors(client, allCacheNames);

    checkAllCaches();
}
 
Example 19
Source File: SqlSystemViewsSelfTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Test running queries system view.
 */
@Test
public void testRunningQueriesView() throws Exception {
    IgniteEx ignite = startGrid(0);

    IgniteCache cache = ignite.createCache(
        new CacheConfiguration<>(DEFAULT_CACHE_NAME).setIndexedTypes(Integer.class, String.class)
    );

    cache.put(100,"200");

    String sql = "SELECT SQL, QUERY_ID, SCHEMA_NAME, LOCAL, START_TIME, DURATION FROM " +
        systemSchemaName() + ".SQL_QUERIES";

    FieldsQueryCursor notClosedFieldQryCursor = cache.query(new SqlFieldsQuery(sql).setLocal(true));

    List<?> cur = cache.query(new SqlFieldsQuery(sql).setLocal(true)).getAll();

    assertEquals(2, cur.size());

    List<?> res0 = (List<?>)cur.get(0);
    List<?> res1 = (List<?>)cur.get(1);

    Timestamp ts = (Timestamp)res0.get(4);

    Instant now = Instant.now();

    long diffInMillis = now.minusMillis(ts.getTime()).toEpochMilli();

    assertTrue(diffInMillis < 3000);

    assertEquals(sql, res0.get(0));

    assertEquals(sql, res1.get(0));

    assertTrue((Boolean)res0.get(3));

    String id0 = (String)res0.get(1);
    String id1 = (String)res1.get(1);

    assertNotEquals(id0, id1);

    String qryPrefix = ignite.localNode().id() + "_";

    String qryId1 = qryPrefix + "1";
    String qryId2 = qryPrefix + "2";

    assertTrue(id0.equals(qryId1) || id1.equals(qryId1));

    assertTrue(id0.equals(qryId2) || id1.equals(qryId2));

    assertEquals(2, cache.query(new SqlFieldsQuery(sql)).getAll().size());

    notClosedFieldQryCursor.close();

    assertEquals(1, cache.query(new SqlFieldsQuery(sql)).getAll().size());

    cache.put(100,"200");

    QueryCursor notClosedQryCursor = cache.query(new SqlQuery<>(String.class, "_key=100"));

    String expSqlQry = "SELECT \"default\".\"STRING\"._KEY, \"default\".\"STRING\"._VAL FROM " +
        "\"default\".\"STRING\" WHERE _key=100";

    cur = cache.query(new SqlFieldsQuery(sql)).getAll();

    assertEquals(2, cur.size());

    res0 = (List<?>)cur.get(0);
    res1 = (List<?>)cur.get(1);

    assertTrue(expSqlQry, res0.get(0).equals(expSqlQry) || res1.get(0).equals(expSqlQry));

    assertFalse((Boolean)res0.get(3));

    assertFalse((Boolean)res1.get(3));

    notClosedQryCursor.close();

    sql = "SELECT SQL, QUERY_ID FROM " + systemSchemaName() + ".SQL_QUERIES WHERE QUERY_ID='" + qryPrefix + "7'";

    assertEquals(qryPrefix + "7", ((List<?>)cache.query(new SqlFieldsQuery(sql)).getAll().get(0)).get(1));

    sql = "SELECT SQL FROM " + systemSchemaName() + ".SQL_QUERIES WHERE DURATION > 100000";

    assertTrue(cache.query(new SqlFieldsQuery(sql)).getAll().isEmpty());

    sql = "SELECT SQL FROM " + systemSchemaName() + ".SQL_QUERIES WHERE QUERY_ID='UNKNOWN'";

    assertTrue(cache.query(new SqlFieldsQuery(sql)).getAll().isEmpty());
}
 
Example 20
Source File: CacheMvccProcessorLazyStartTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testMvccRestartedWithDynamicCache() throws Exception {
    persistence = true;

    IgniteEx node1 = startGrid(1);
    IgniteEx node2 = startGrid(2);

    assertFalse(mvccEnabled(node1));
    assertFalse(mvccEnabled(node2));

    node1.cluster().active(true);

    assertFalse(mvccEnabled(node1));
    assertFalse(mvccEnabled(node2));

    CacheConfiguration ccfg = cacheConfiguration(CacheMode.PARTITIONED, CacheWriteSynchronizationMode.FULL_SYNC, 0, 1);

    IgniteCache cache = node1.createCache(ccfg);

    cache.put(1, 1);
    cache.put(1, 2);

    assertTrue(mvccEnabled(node1));
    assertTrue(mvccEnabled(node2));

    stopGrid(1);
    stopGrid(2);

    node1 = startGrid(1);
    node2 = startGrid(2);

    node1.cluster().active(true);

    assertTrue(mvccEnabled(node1));
    assertTrue(mvccEnabled(node2));

    cache = node1.cache(ccfg.getName());

    cache.put(1, 1);
    cache.put(1, 2);

    assertTrue(mvccEnabled(node1));
    assertTrue(mvccEnabled(node2));
}