anton-vinogradov commented on code in PR #10199:
URL: https://github.com/apache/ignite/pull/10199#discussion_r947868101


##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerConsistencyCountersTest.java:
##########
@@ -0,0 +1,575 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.file.OpenOption;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheAtomicityMode;
+import org.apache.ignite.cache.CachePeekMode;
+import org.apache.ignite.cache.ReadRepairStrategy;
+import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.WALMode;
+import org.apache.ignite.failure.StopNodeFailureHandler;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.TestRecordingCommunicationSpi;
+import org.apache.ignite.internal.commandline.consistency.ConsistencyCommand;
+import 
org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishRequest;
+import 
org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest;
+import 
org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicSingleUpdateRequest;
+import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
+import 
org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator;
+import 
org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.lang.IgniteBiPredicate;
+import org.apache.ignite.plugin.extensions.communication.Message;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.apache.ignite.testframework.LogListener;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+import static org.apache.ignite.cache.ReadRepairStrategy.PRIMARY;
+import static org.apache.ignite.cache.ReadRepairStrategy.RELATIVE_MAJORITY;
+import static org.apache.ignite.cache.ReadRepairStrategy.REMOVE;
+import static 
org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static 
org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.DFLT_WAL_MARGIN_FOR_ATOMIC_CACHE_HISTORICAL_REBALANCE;
+import static 
org.apache.ignite.internal.visor.consistency.VisorConsistencyRepairTask.CONSISTENCY_VIOLATIONS_FOUND;
+import static 
org.apache.ignite.internal.visor.consistency.VisorConsistencyRepairTask.NOTHING_FOUND;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.testframework.GridTestUtils.assertNotContains;
+import static org.apache.ignite.testframework.LogListener.matches;
+
+/**
+ *
+ */
+@RunWith(Parameterized.class)
+public class GridCommandHandlerConsistencyCountersTest extends 
GridCommandHandlerClusterPerMethodAbstractTest {
+    /** */
+    @Parameterized.Parameters(name = "strategy={0}, reuse={1}, historical={2}, 
atomicity={3}")
+    public static Iterable<Object[]> data() {
+        List<Object[]> res = new ArrayList<>();
+
+        for (ReadRepairStrategy strategy : ReadRepairStrategy.values()) {
+            for (boolean reuse : new boolean[] {false, true}) {
+                for (boolean historical : new boolean[] {false, true}) {
+                    for (CacheAtomicityMode atomicityMode : new 
CacheAtomicityMode[] {ATOMIC, TRANSACTIONAL})
+                        res.add(new Object[] {strategy, reuse, historical, 
atomicityMode});
+                }
+            }
+        }
+
+        return res;
+    }
+
+    /**
+     * ReadRepair strategy
+     */
+    @Parameterized.Parameter
+    public ReadRepairStrategy strategy;
+
+    /**
+     * When true, updates will reuse already existing keys.
+     */
+    @Parameterized.Parameter(1)
+    public boolean reuseKeys;
+
+    /**
+     * When true, historical rebalance will be used instead of full.
+     */
+    @Parameterized.Parameter(2)
+    public boolean historical;
+
+    /**
+     * Cache atomicity mode
+     */
+    @Parameterized.Parameter(3)
+    public CacheAtomicityMode atomicityMode;
+
+    /** Listening logger. */
+    protected final ListeningTestLogger listeningLog = new 
ListeningTestLogger(log);
+
+    /** File IO blocked flag. */
+    private static volatile boolean ioBlocked;
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        cleanPersistenceDir();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String 
igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(listeningLog);
+
+        cfg.getDataStorageConfiguration().setFileIOFactory(
+            new 
BlockableFileIOFactory(cfg.getDataStorageConfiguration().getFileIOFactory()));
+
+        cfg.getDataStorageConfiguration().setWalMode(WALMode.FSYNC); // Allows 
to use special IO at WAL as well.
+
+        cfg.setFailureHandler(new StopNodeFailureHandler()); // Helps to kill 
nodes on stop with disabled IO.
+
+        return cfg;
+    }
+
+    /**
+     *
+     */
+    private static class BlockableFileIOFactory implements FileIOFactory {
+        /** IO Factory. */
+        private final FileIOFactory factory;
+
+        /**
+         * @param factory Factory.
+         */
+        public BlockableFileIOFactory(FileIOFactory factory) {
+            this.factory = factory;
+        }
+
+        /** {@inheritDoc} */
+        @Override public FileIO create(File file, OpenOption... modes) throws 
IOException {
+            return new FileIODecorator(factory.create(file, modes)) {
+                @Override public int write(ByteBuffer srcBuf) throws 
IOException {
+                    if (ioBlocked)
+                        throw new IOException();
+
+                    return super.write(srcBuf);
+                }
+
+                @Override public int write(ByteBuffer srcBuf, long position) 
throws IOException {
+                    if (ioBlocked)
+                        throw new IOException();
+
+                    return super.write(srcBuf, position);
+                }
+
+                @Override public int write(byte[] buf, int off, int len) 
throws IOException {
+                    if (ioBlocked)
+                        throw new IOException();
+
+                    return super.write(buf, off, len);
+                }
+            };
+        }
+    }
+
+    /**
+     * Checks counters and behaviour on crash recovery.
+     */
+    @Test
+    public void testCountersOnCrachRecovery() throws Exception {
+        int nodes = 3;
+        int backupNodes = nodes - 1;
+
+        IgniteEx ignite = startGrids(nodes);
+
+        ignite.cluster().state(ClusterState.ACTIVE);
+
+        IgniteCache<Object, Object> cache = ignite.createCache(new 
CacheConfiguration<>()
+            .setAffinity(new RendezvousAffinityFunction(false, 1))
+            .setBackups(backupNodes)
+            .setName(DEFAULT_CACHE_NAME)
+            .setAtomicityMode(atomicityMode)
+            .setWriteSynchronizationMode(FULL_SYNC) // Allows to be sure that 
all messages are sent when put succeed.
+            .setReadFromBackup(true)); // Allows to check values on backups.
+
+        int updateCnt = 0;
+
+        // Initial preloading.
+        for (int i = 0; i < 2_000; i++) { // Enough to have historical 
rebalance when needed.
+            cache.put(i, i);
+
+            updateCnt++;
+        }
+
+        // Trick to have historical rebalance on cluster recovery (decreases 
percent of updates in comparison to cache size).
+        if (historical) {
+            stopAllGrids();
+            startGrids(nodes);
+        }
+
+        int preloadCnt = updateCnt;
+
+        Ignite prim = primaryNode(0L, DEFAULT_CACHE_NAME);
+        List<Ignite> backups = backupNodes(0L, DEFAULT_CACHE_NAME);
+
+        AtomicBoolean prepareBlock = new AtomicBoolean();
+        AtomicBoolean finishBlock = new AtomicBoolean();
+
+        AtomicReference<CountDownLatch> blockLatch = new AtomicReference<>();
+
+        TestRecordingCommunicationSpi.spi(prim).blockMessages(new 
IgniteBiPredicate<ClusterNode, Message>() {
+            @Override public boolean apply(ClusterNode node, Message msg) {
+                if ((msg instanceof GridDhtTxPrepareRequest && 
prepareBlock.get()) ||
+                    ((msg instanceof GridDhtTxFinishRequest || msg instanceof 
GridDhtAtomicSingleUpdateRequest) && finishBlock.get())) {
+                    CountDownLatch latch = blockLatch.get();
+
+                    assertTrue(latch.getCount() > 0);
+
+                    latch.countDown();
+
+                    return true; // Generating counter misses.
+                }
+                else
+                    return false;
+            }
+        });
+
+        int blockedFrom = reuseKeys ? 0 : preloadCnt;
+        int committedFrom = blockedFrom + 1_000;
+
+        int blockedKey = blockedFrom - 1; // None
+        int committedKey = committedFrom - 1; // None
+
+        List<String> backupMissed = new ArrayList<>();
+        List<String> primaryMissed = new ArrayList<>();
+
+        IgniteCache<Integer, Integer> primCache = 
prim.cache(DEFAULT_CACHE_NAME);
+
+        Consumer<Integer> cachePut = (key) -> primCache.put(key, -key);
+
+        Set<Thread> ths = ConcurrentHashMap.newKeySet();
+
+        Consumer<Integer> cachePutAsync = (key) -> {
+            Thread th = new Thread(() -> cachePut.accept(key));

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to