Search in sources :

Example 46 with Affinity

use of org.apache.ignite.cache.affinity.Affinity in project ignite by apache.

the class CacheMvccSqlTxQueriesAbstractTest method testUpdateExplicitPartitionsWithoutReducer.

/**
 * @throws Exception If failed.
 */
@Test
public void testUpdateExplicitPartitionsWithoutReducer() throws Exception {
    ccfg = cacheConfiguration(cacheMode(), FULL_SYNC, 2, 10).setIndexedTypes(Integer.class, Integer.class);
    Ignite ignite = startGridsMultiThreaded(4);
    awaitPartitionMapExchange();
    IgniteCache<Object, Object> cache = ignite.cache(DEFAULT_CACHE_NAME);
    Affinity<Object> affinity = internalCache0(cache).affinity();
    int keysCnt = 10, retryCnt = 0;
    Integer test = 0;
    Map<Integer, Integer> vals = new LinkedHashMap<>();
    while (vals.size() < keysCnt) {
        int partition = affinity.partition(test);
        if (partition == 1 || partition == 2)
            vals.put(test, 0);
        else
            assertTrue("Maximum retry number exceeded", ++retryCnt < 1000);
        test++;
    }
    cache.putAll(vals);
    SqlFieldsQuery qry = new SqlFieldsQuery("UPDATE Integer set _val=2").setPartitions(1, 2);
    List<List<?>> all = cache.query(qry).getAll();
    assertEquals(Long.valueOf(keysCnt), all.stream().findFirst().orElseThrow(AssertionError::new).get(0));
    List<List<?>> rows = cache.query(new SqlFieldsQuery("SELECT _val FROM Integer")).getAll();
    assertEquals(keysCnt, rows.size());
    assertTrue(rows.stream().map(r -> r.get(0)).map(Integer.class::cast).allMatch(v -> v == 2));
}
Also used : SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Transaction(org.apache.ignite.transactions.Transaction) Random(java.util.Random) IgniteEx(org.apache.ignite.internal.IgniteEx) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) EntryProcessor(javax.cache.processor.EntryProcessor) GridCursor(org.apache.ignite.internal.util.lang.GridCursor) GridTestUtils.runAsync(org.apache.ignite.testframework.GridTestUtils.runAsync) MutableEntry(javax.cache.processor.MutableEntry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) X(org.apache.ignite.internal.util.typedef.X) Cache(javax.cache.Cache) CyclicBarrier(java.util.concurrent.CyclicBarrier) QuerySqlField(org.apache.ignite.cache.query.annotations.QuerySqlField) IgniteTxTimeoutCheckedException(org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) TransactionConfiguration(org.apache.ignite.configuration.TransactionConfiguration) CacheDataRow(org.apache.ignite.internal.processors.cache.persistence.CacheDataRow) CacheDataRowAdapter(org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter) IgniteCache(org.apache.ignite.IgniteCache) IgniteCacheProxy(org.apache.ignite.internal.processors.cache.IgniteCacheProxy) Serializable(java.io.Serializable) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) SQL_SUM(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.ReadMode.SQL_SUM) Objects(java.util.Objects) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) MvccFeatureChecker(org.apache.ignite.testframework.MvccFeatureChecker) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) FieldsQueryCursor(org.apache.ignite.cache.query.FieldsQueryCursor) DML(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.WriteMode.DML) GridTestUtils.runMultiThreaded(org.apache.ignite.testframework.GridTestUtils.runMultiThreaded) Affinity(org.apache.ignite.cache.affinity.Affinity) GridCompoundFuture(org.apache.ignite.internal.util.future.GridCompoundFuture) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) EntryProcessorException(javax.cache.processor.EntryProcessorException) SQL(org.apache.ignite.internal.processors.cache.mvcc.CacheMvccAbstractTest.ReadMode.SQL) LinkedHashMap(java.util.LinkedHashMap) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) S(org.apache.ignite.internal.util.typedef.internal.S) CacheException(javax.cache.CacheException) TransactionSerializationException(org.apache.ignite.transactions.TransactionSerializationException) TransactionDuplicateKeyException(org.apache.ignite.transactions.TransactionDuplicateKeyException) F(org.apache.ignite.internal.util.typedef.F) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) Iterator(java.util.Iterator) SqlFieldsQueryEx(org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) IgniteQueryErrorCode(org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) TimeUnit(java.util.concurrent.TimeUnit) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) Phaser(java.util.concurrent.Phaser) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) LinkedHashMap(java.util.LinkedHashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Ignite(org.apache.ignite.Ignite) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject) List(java.util.List) Test(org.junit.Test)

Example 47 with Affinity

use of org.apache.ignite.cache.affinity.Affinity in project ignite by apache.

the class CacheMvccSqlUpdateCountersTest method testUpdateCountersRollback.

/**
 * @throws Exception If failed.
 */
@Test
public void testUpdateCountersRollback() throws Exception {
    ccfg = cacheConfiguration(cacheMode(), FULL_SYNC, 2, DFLT_PARTITION_COUNT).setIndexedTypes(Integer.class, Integer.class);
    Ignite node = startGridsMultiThreaded(3);
    IgniteCache cache = node.cache(DEFAULT_CACHE_NAME);
    Affinity aff = affinity(cache);
    int key1 = 1;
    int part1 = aff.partition(key1);
    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        SqlFieldsQuery qry = new SqlFieldsQuery("INSERT INTO Integer (_key, _val) values (" + key1 + ",1)");
        cache.query(qry).getAll();
        qry = new SqlFieldsQuery("UPDATE Integer SET _val=2 WHERE _key=" + key1);
        cache.query(qry).getAll();
        tx.rollback();
    }
    checkUpdateCounters(DEFAULT_CACHE_NAME, part1, 0);
    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        SqlFieldsQuery qry = new SqlFieldsQuery("MERGE INTO Integer (_key, _val) values (" + key1 + ",1)");
        cache.query(qry).getAll();
        qry = new SqlFieldsQuery("UPDATE Integer SET _val=2 WHERE _key=" + key1);
        cache.query(qry).getAll();
        tx.rollback();
    }
    checkUpdateCounters(DEFAULT_CACHE_NAME, part1, 0);
}
Also used : Transaction(org.apache.ignite.transactions.Transaction) IgniteCache(org.apache.ignite.IgniteCache) Affinity(org.apache.ignite.cache.affinity.Affinity) Ignite(org.apache.ignite.Ignite) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Test(org.junit.Test)

Example 48 with Affinity

use of org.apache.ignite.cache.affinity.Affinity in project ignite by apache.

the class CacheMvccSqlUpdateCountersTest method testUpdateCountersMultithreaded.

/**
 * @throws Exception If failed.
 */
@Test
public void testUpdateCountersMultithreaded() throws Exception {
    final int writers = 4;
    final int readers = 0;
    int parts = 8;
    int keys = 20;
    final Map<Integer, AtomicLong> tracker = new ConcurrentHashMap<>();
    for (int i = 0; i < keys; i++) tracker.put(i, new AtomicLong(1));
    final IgniteInClosure<IgniteCache<Object, Object>> init = new IgniteInClosure<IgniteCache<Object, Object>>() {

        @Override
        public void apply(IgniteCache<Object, Object> cache) {
            final IgniteTransactions txs = cache.unwrap(Ignite.class).transactions();
            try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
                SqlFieldsQuery qry = new SqlFieldsQuery("INSERT INTO MvccTestAccount(_key, val, updateCnt) VALUES " + "(?, 0, 1)");
                for (int i = 0; i < keys; i++) {
                    try (FieldsQueryCursor<List<?>> cur = cache.query(qry.setArgs(i))) {
                        assertEquals(1L, cur.iterator().next().get(0));
                    }
                    tx.commit();
                }
            }
        }
    };
    GridInClosure3<Integer, List<TestCache>, AtomicBoolean> writer = new GridInClosure3<Integer, List<TestCache>, AtomicBoolean>() {

        @Override
        public void apply(Integer idx, List<TestCache> caches, AtomicBoolean stop) {
            ThreadLocalRandom rnd = ThreadLocalRandom.current();
            Map<Integer, AtomicLong> acc = new HashMap<>();
            int v = 0;
            while (!stop.get()) {
                int cnt = rnd.nextInt(keys / 3);
                if (cnt == 0)
                    cnt = 2;
                // Generate key set to be changed in tx.
                while (acc.size() < cnt) acc.put(rnd.nextInt(cnt), new AtomicLong());
                TestCache<Integer, Integer> cache = randomCache(caches, rnd);
                boolean success = true;
                try {
                    IgniteTransactions txs = cache.cache.unwrap(Ignite.class).transactions();
                    try (Transaction tx = txs.txStart(PESSIMISTIC, REPEATABLE_READ)) {
                        Map<Integer, MvccTestAccount> allVals = readAllByMode(cache.cache, tracker.keySet(), SQL, ACCOUNT_CODEC);
                        boolean rmv = allVals.size() > keys * 2 / 3;
                        for (Map.Entry<Integer, AtomicLong> e : acc.entrySet()) {
                            int key = e.getKey();
                            AtomicLong accCntr = e.getValue();
                            boolean exists = allVals.containsKey(key);
                            int delta = 0;
                            boolean createdInTx = false;
                            if (rmv && rnd.nextBoolean()) {
                                if (exists)
                                    delta = 1;
                                SqlFieldsQuery qry = new SqlFieldsQuery("DELETE FROM MvccTestAccount WHERE _key=" + key);
                                cache.cache.query(qry).getAll();
                            } else {
                                delta = 1;
                                if (!exists)
                                    createdInTx = true;
                                SqlFieldsQuery qry = new SqlFieldsQuery("MERGE INTO MvccTestAccount " + "(_key, val, updateCnt) VALUES (" + key + ",  " + rnd.nextInt(100) + ", 1)");
                                cache.cache.query(qry).getAll();
                            }
                            if (rnd.nextBoolean()) {
                                if (createdInTx)
                                    // Do not count cases when key created and removed in the same tx.
                                    delta = 0;
                                SqlFieldsQuery qry = new SqlFieldsQuery("DELETE FROM MvccTestAccount WHERE _key=" + key);
                                cache.cache.query(qry).getAll();
                            } else {
                                delta = 1;
                                SqlFieldsQuery qry = new SqlFieldsQuery("MERGE INTO MvccTestAccount " + "(_key, val, updateCnt) VALUES (" + key + ",  " + rnd.nextInt(100) + ", 1)");
                                cache.cache.query(qry).getAll();
                            }
                            accCntr.addAndGet(delta);
                        }
                        tx.commit();
                    }
                } catch (Exception e) {
                    handleTxException(e);
                    success = false;
                    int r = 0;
                    for (Map.Entry<Integer, AtomicLong> en : acc.entrySet()) {
                        if (((IgniteCacheProxy) cache.cache).context().affinity().partition(en.getKey()) == 0)
                            r += en.getValue().intValue();
                    }
                } finally {
                    cache.readUnlock();
                    if (success) {
                        v++;
                        for (Map.Entry<Integer, AtomicLong> e : acc.entrySet()) {
                            int k = e.getKey();
                            long updCntr = e.getValue().get();
                            tracker.get(k).addAndGet(updCntr);
                        }
                        int r = 0;
                        for (Map.Entry<Integer, AtomicLong> en : acc.entrySet()) {
                            if (((IgniteCacheProxy) cache.cache).context().affinity().partition(en.getKey()) == 0)
                                r += en.getValue().intValue();
                        }
                    }
                    acc.clear();
                }
            }
            info("Writer done, updates: " + v);
        }
    };
    GridInClosure3<Integer, List<TestCache>, AtomicBoolean> reader = new GridInClosure3<Integer, List<TestCache>, AtomicBoolean>() {

        @Override
        public void apply(Integer idx, List<TestCache> caches, AtomicBoolean stop) {
        // No-op.
        }
    };
    readWriteTest(null, 4, 1, 2, parts, writers, readers, DFLT_TEST_TIME, new InitIndexing(Integer.class, MvccTestAccount.class), init, writer, reader);
    Map<Integer, AtomicLong> updPerParts = new HashMap<>(parts);
    Affinity aff = grid(1).cachex(DEFAULT_CACHE_NAME).affinity();
    for (Map.Entry<Integer, AtomicLong> e : tracker.entrySet()) {
        int k = e.getKey();
        long updCntr = e.getValue().get();
        int p = aff.partition(k);
        AtomicLong cntr = updPerParts.get(p);
        if (cntr == null) {
            cntr = new AtomicLong();
            updPerParts.putIfAbsent(p, cntr);
        }
        cntr.addAndGet(updCntr);
    }
    for (Map.Entry<Integer, AtomicLong> e : updPerParts.entrySet()) checkUpdateCounters(DEFAULT_CACHE_NAME, e.getKey(), e.getValue().get());
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IgniteCacheProxy(org.apache.ignite.internal.processors.cache.IgniteCacheProxy) IgniteTransactions(org.apache.ignite.IgniteTransactions) GridInClosure3(org.apache.ignite.internal.util.lang.GridInClosure3) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Ignite(org.apache.ignite.Ignite) List(java.util.List) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IgniteCache(org.apache.ignite.IgniteCache) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Transaction(org.apache.ignite.transactions.Transaction) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) Affinity(org.apache.ignite.cache.affinity.Affinity) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Example 49 with Affinity

use of org.apache.ignite.cache.affinity.Affinity in project ignite by apache.

the class CacheMvccSqlUpdateCountersTest method testUpdateCountersInsertSimple.

/**
 * @throws Exception If failed.
 */
@Test
public void testUpdateCountersInsertSimple() throws Exception {
    ccfg = cacheConfiguration(cacheMode(), FULL_SYNC, 2, DFLT_PARTITION_COUNT).setIndexedTypes(Integer.class, Integer.class);
    Ignite node = startGridsMultiThreaded(3);
    IgniteCache cache = node.cache(DEFAULT_CACHE_NAME);
    Affinity aff = affinity(cache);
    Integer key1 = 1;
    int part1 = aff.partition(key1);
    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        SqlFieldsQuery qry = new SqlFieldsQuery("INSERT INTO Integer (_key, _val) values (" + key1 + ",1)");
        cache.query(qry).getAll();
        tx.commit();
    }
    checkUpdateCounters(DEFAULT_CACHE_NAME, part1, 1);
    try (Transaction tx = node.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
        SqlFieldsQuery qry = new SqlFieldsQuery("UPDATE Integer SET _val=2 WHERE _key=" + key1);
        cache.query(qry).getAll();
        tx.commit();
    }
    checkUpdateCounters(DEFAULT_CACHE_NAME, part1, 2);
}
Also used : Transaction(org.apache.ignite.transactions.Transaction) IgniteCache(org.apache.ignite.IgniteCache) Affinity(org.apache.ignite.cache.affinity.Affinity) Ignite(org.apache.ignite.Ignite) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) Test(org.junit.Test)

Aggregations

Affinity (org.apache.ignite.cache.affinity.Affinity)49 Ignite (org.apache.ignite.Ignite)30 IgniteCache (org.apache.ignite.IgniteCache)29 ClusterNode (org.apache.ignite.cluster.ClusterNode)28 ArrayList (java.util.ArrayList)20 Test (org.junit.Test)18 Collection (java.util.Collection)16 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)16 Transaction (org.apache.ignite.transactions.Transaction)16 List (java.util.List)15 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)14 Map (java.util.Map)13 Cache (javax.cache.Cache)13 HashMap (java.util.HashMap)10 IgniteEx (org.apache.ignite.internal.IgniteEx)10 IgniteBiTuple (org.apache.ignite.lang.IgniteBiTuple)10 Collections (java.util.Collections)8 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)8 Ignition (org.apache.ignite.Ignition)8 ScanQuery (org.apache.ignite.cache.query.ScanQuery)8