repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/core/src/test/java/org/infinispan/lock/LockManagerTest.java
package org.infinispan.lock; import static org.infinispan.factories.KnownComponentNames.NON_BLOCKING_EXECUTOR; import static org.infinispan.factories.KnownComponentNames.TIMEOUT_SCHEDULE_EXECUTOR; import static org.infinispan.test.TestingUtil.named; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.infinispan.util.concurrent.locks.LockManager; import org.infinispan.util.concurrent.locks.LockPromise; import org.infinispan.util.concurrent.locks.impl.DefaultLockManager; import org.infinispan.util.concurrent.locks.impl.PerKeyLockContainer; import org.infinispan.util.concurrent.locks.impl.StripedLockContainer; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Unit tests for {@link LockManagerTest}. * * @author Pedro Ruivo * @since 8.0 */ @Test(groups = "unit", testName = "lock.LockManagerTest") public class LockManagerTest extends AbstractInfinispanTest { private final ExecutorService asyncExecutor; private final ScheduledExecutorService mockScheduledExecutor; public LockManagerTest() { asyncExecutor = new WithinThreadExecutor(); mockScheduledExecutor = mock(ScheduledExecutorService.class); ScheduledFuture future = mock(ScheduledFuture.class); when(future.cancel(anyBoolean())).thenReturn(true); //noinspection unchecked when(mockScheduledExecutor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))).thenReturn(future); //noinspection unchecked when(mockScheduledExecutor.schedule(any(Callable.class), anyLong(), any(TimeUnit.class))).thenReturn(future); } public void testSingleCounterPerKey() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); PerKeyLockContainer lockContainer = new PerKeyLockContainer(); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, named(NON_BLOCKING_EXECUTOR, asyncExecutor), named(TIMEOUT_SCHEDULE_EXECUTOR, mockScheduledExecutor)); doSingleCounterTest(lockManager); } public void testSingleCounterStripped() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); StripedLockContainer lockContainer = new StripedLockContainer(16); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, asyncExecutor, mockScheduledExecutor); doSingleCounterTest(lockManager); } public void testMultipleCounterPerKey() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); PerKeyLockContainer lockContainer = new PerKeyLockContainer(); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, asyncExecutor, mockScheduledExecutor); doMultipleCounterTest(lockManager); } public void testMultipleCounterStripped() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); StripedLockContainer lockContainer = new StripedLockContainer(16); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, asyncExecutor, mockScheduledExecutor); doMultipleCounterTest(lockManager); } public void testTimeoutPerKey() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); PerKeyLockContainer lockContainer = new PerKeyLockContainer(); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, asyncExecutor, mockScheduledExecutor); doTestWithFailAcquisition(lockManager); } public void testTimeoutStripped() throws ExecutionException, InterruptedException { DefaultLockManager lockManager = new DefaultLockManager(); StripedLockContainer lockContainer = new StripedLockContainer(16); TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE); TestingUtil.inject(lockManager, lockContainer, asyncExecutor, mockScheduledExecutor); doTestWithFailAcquisition(lockManager); } private void doSingleCounterTest(LockManager lockManager) throws ExecutionException, InterruptedException { final NotThreadSafeCounter counter = new NotThreadSafeCounter(); final String key = "key"; final int numThreads = 8; final int maxCounterValue = 100; final CyclicBarrier barrier = new CyclicBarrier(numThreads); List<Future<Collection<Integer>>> callableResults = new ArrayList<>(numThreads); for (int i = 0; i < numThreads; ++i) { callableResults.add(fork(() -> { final Thread lockOwner = Thread.currentThread(); AssertJUnit.assertEquals(0, counter.getCount()); List<Integer> seenValues = new LinkedList<>(); barrier.await(); while (true) { lockManager.lock(key, lockOwner, 1, TimeUnit.MINUTES).lock(); AssertJUnit.assertEquals(lockOwner, lockManager.getOwner(key)); AssertJUnit.assertTrue(lockManager.isLocked(key)); AssertJUnit.assertTrue(lockManager.ownsLock(key, lockOwner)); try { int value = counter.getCount(); if (value == maxCounterValue) { return seenValues; } seenValues.add(value); counter.setCount(value + 1); } finally { lockManager.unlock(key, lockOwner); } } })); } Set<Integer> seenResults = new HashSet<>(); for (Future<Collection<Integer>> future : callableResults) { for (Integer integer : future.get()) { AssertJUnit.assertTrue(seenResults.add(integer)); } } AssertJUnit.assertEquals(maxCounterValue, seenResults.size()); for (int i = 0; i < maxCounterValue; ++i) { AssertJUnit.assertTrue(seenResults.contains(i)); } AssertJUnit.assertEquals(0, lockManager.getNumberOfLocksHeld()); } private void doMultipleCounterTest(LockManager lockManager) throws ExecutionException, InterruptedException { final int numCounters = 8; final NotThreadSafeCounter[] counters = new NotThreadSafeCounter[numCounters]; final String[] keys = new String[numCounters]; final int numThreads = 8; final int maxCounterValue = 100; final CyclicBarrier barrier = new CyclicBarrier(numThreads); for (int i = 0; i < numCounters; ++i) { counters[i] = new NotThreadSafeCounter(); keys[i] = "key-" + i; } List<Future<Collection<Integer>>> callableResults = new ArrayList<>(numThreads); for (int i = 0; i < numThreads; ++i) { final List<String> threadKeys = new ArrayList<>(Arrays.asList(keys)); Collections.shuffle(threadKeys); callableResults.add(fork(() -> { final Thread lockOwner = Thread.currentThread(); List<Integer> seenValues = new LinkedList<>(); barrier.await(); while (true) { lockManager.lockAll(threadKeys, lockOwner, 1, TimeUnit.MINUTES).lock(); for (String key : threadKeys) { AssertJUnit.assertEquals(lockOwner, lockManager.getOwner(key)); AssertJUnit.assertTrue(lockManager.isLocked(key)); AssertJUnit.assertTrue(lockManager.ownsLock(key, lockOwner)); } try { int value = -1; for (NotThreadSafeCounter counter : counters) { if (value == -1) { value = counter.getCount(); if (value == maxCounterValue) { return seenValues; } seenValues.add(value); } else { AssertJUnit.assertEquals(value, counter.getCount()); } counter.setCount(value + 1); } } finally { lockManager.unlockAll(threadKeys, lockOwner); } } })); } Set<Integer> seenResults = new HashSet<>(); for (Future<Collection<Integer>> future : callableResults) { for (Integer integer : future.get()) { AssertJUnit.assertTrue(seenResults.add(integer)); } } AssertJUnit.assertEquals(maxCounterValue, seenResults.size()); for (int i = 0; i < maxCounterValue; ++i) { AssertJUnit.assertTrue(seenResults.contains(i)); } AssertJUnit.assertEquals(0, lockManager.getNumberOfLocksHeld()); } private void doTestWithFailAcquisition(LockManager lockManager) throws InterruptedException { final String lockOwner1 = "LO1"; final String lockOwner2 = "LO2"; final String key = "key"; final String key2 = "key2"; final String key3 = "key2"; lockManager.lock(key, lockOwner1, 0, TimeUnit.MILLISECONDS).lock(); AssertJUnit.assertEquals(lockOwner1, lockManager.getOwner(key)); AssertJUnit.assertTrue(lockManager.isLocked(key)); AssertJUnit.assertTrue(lockManager.ownsLock(key, lockOwner1)); try { lockManager.lockAll(Arrays.asList(key, key2, key3), lockOwner2, 0, TimeUnit.MILLISECONDS).lock(); AssertJUnit.assertEquals(1, lockManager.getNumberOfLocksHeld()); AssertJUnit.fail(); } catch (TimeoutException t) { //expected } AssertJUnit.assertEquals(lockOwner1, lockManager.getOwner(key)); AssertJUnit.assertTrue(lockManager.isLocked(key)); AssertJUnit.assertTrue(lockManager.ownsLock(key, lockOwner1)); LockPromise lockPromise = lockManager.lockAll(Arrays.asList(key, key2, key3), lockOwner2, 1, TimeUnit.MINUTES); AssertJUnit.assertFalse(lockPromise.isAvailable()); lockManager.unlock(key, lockOwner1); AssertJUnit.assertTrue(lockPromise.isAvailable()); lockPromise.lock(); AssertJUnit.assertEquals(lockOwner2, lockManager.getOwner(key)); AssertJUnit.assertTrue(lockManager.isLocked(key)); AssertJUnit.assertTrue(lockManager.ownsLock(key, lockOwner2)); lockManager.unlockAll(Arrays.asList(key, key2, key3), lockOwner2); AssertJUnit.assertEquals(0, lockManager.getNumberOfLocksHeld()); } private static class NotThreadSafeCounter { private int count; public int getCount() { return count; } public void setCount(int count) { this.count = count; } } }
11,855
41.494624
117
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/SimpleLockContainerTest.java
package org.infinispan.lock; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.TimeoutException; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.infinispan.util.concurrent.locks.impl.PerKeyLockContainer; import org.testng.annotations.Test; @Test (groups = "functional", testName = "lock.SimpleLockContainerTest") public class SimpleLockContainerTest extends AbstractInfinispanTest { private final ExecutorService executor = new WithinThreadExecutor(); PerKeyLockContainer lc = new PerKeyLockContainer(); public void simpleTest() throws Exception { TestingUtil.inject(lc, AbstractCacheTest.TIME_SERVICE); final String k1 = ab(); final String k2 = ab2(); assert k1 != k2 && k1.equals(k2); Object owner = new Object(); lc.acquire(k1, owner, 0, TimeUnit.MILLISECONDS).lock(); assert lc.getLock(k1).isLocked(); Future<Void> f = fork(new Callable<Void>() { @Override public Void call() throws InterruptedException, TimeoutException { final Object otherOwner = new Object(); for (int i =0; i < 10; i++) { try { lc.acquire(k2, otherOwner, 500, TimeUnit.MILLISECONDS).lock(); return null; } catch (TimeoutException e) { //ignored } } throw new TimeoutException("We should have acquired lock!"); } }); Thread.sleep(200); lc.release(k1, owner); f.get(10, TimeUnit.SECONDS); } private String ab2() { return "ab"; } public String ab() { StringBuilder sb = new StringBuilder("a"); return sb.append("b").toString(); } }
2,010
30.421875
80
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/APITest.java
package org.infinispan.lock; import static org.infinispan.context.Flag.FAIL_SILENTLY; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import jakarta.transaction.Status; import jakarta.transaction.TransactionManager; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.interceptors.locking.AbstractLockingInterceptor; import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.ReplicatedControlledConsistentHashFactory; import org.infinispan.util.concurrent.TimeoutException; import org.testng.annotations.Test; @Test(testName = "lock.APITest", groups = "functional") @CleanupAfterMethod public class APITest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true); cfg.clustering().hash().numSegments(1) .consistentHashFactory(new ReplicatedControlledConsistentHashFactory(0)); cfg.transaction().lockingMode(LockingMode.PESSIMISTIC) .cacheStopTimeout(0) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); createCluster(cfg, 2); } public void testProperties() { Properties p = new Properties(); Object v = new Object(); p.put("bla", v); assertEquals(v, p.get("bla")); System.out.println(p.get("bla")); } public void testLockSuccess() throws Exception { Cache<String, String> cache1 = cache(0); cache1.put("k", "v"); tm(0).begin(); assert cache1.getAdvancedCache().lock("k"); tm(0).rollback(); } @Test (expectedExceptions = TimeoutException.class) public void testLockFailure() throws Exception { Cache<String, String> cache1 = cache(0), cache2 = cache(1); cache1.put("k", "v"); tm(1).begin(); cache2.put("k", "v2"); tm(1).suspend(); tm(0).begin(); cache1.getAdvancedCache().lock("k"); tm(0).rollback(); } public void testSilentLockFailure() throws Exception { Cache<String, String> cache1 = cache(0), cache2 = cache(1); cache1.put("k", "v"); tm(1).begin(); cache2.put("k", "v2"); tm(1).suspend(); tm(0).begin(); assert !cache1.getAdvancedCache().withFlags(FAIL_SILENTLY).lock("k"); tm(0).rollback(); } public void testSilentLockFailureAffectsPostOperations() throws Exception { final Cache<Integer, String> cache = cache(0); final TransactionManager tm = cache.getAdvancedCache().getTransactionManager(); final CountDownLatch waitLatch = new CountDownLatch(1); final CountDownLatch continueLatch = new CountDownLatch(1); cache.put(1, "v1"); Future<Void> f1 = fork(new Callable<Void>() { @Override public Void call() throws Exception { tm.begin(); try { cache.put(1, "v2"); waitLatch.countDown(); continueLatch.await(); } catch (Exception e) { tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); } return null; } }); Future<Void> f2 = fork(new Callable<Void>() { @Override public Void call() throws Exception { waitLatch.await(); tm.begin(); try { AdvancedCache<Integer, String> silentCache = cache.getAdvancedCache().withFlags( Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); silentCache.put(1, "v3"); assert !silentCache.lock(1); String object = cache.get(1); assert "v1".equals(object) : "Expected v1 but got " + object; cache.get(1); } catch (Exception e) { tm.setRollbackOnly(); throw e; } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); else tm.rollback(); continueLatch.countDown(); } return null; } }); f1.get(); f2.get(); } public void testMultiLockSuccess() throws Exception { Cache<String, String> cache1 = cache(0); cache1.put("k1", "v"); cache1.put("k2", "v"); cache1.put("k3", "v"); tm(0).begin(); assert cache1.getAdvancedCache().lock(Arrays.asList("k1", "k2", "k3")); tm(0).rollback(); } @Test (expectedExceptions = TimeoutException.class) public void testMultiLockFailure() throws Exception { Cache<String, String> cache1 = cache(0), cache2 = cache(1); cache1.put("k1", "v"); cache1.put("k2", "v"); cache1.put("k3", "v"); tm(1).begin(); cache2.put("k3", "v2"); tm(1).suspend(); tm(0).begin(); cache1.getAdvancedCache().lock(Arrays.asList("k1", "k2", "k3")); tm(0).rollback(); } public void testSilentMultiLockFailure() throws Exception { Cache<String, String> cache1 = cache(0), cache2 = cache(1); cache1.put("k1", "v"); cache1.put("k2", "v"); cache1.put("k3", "v"); tm(1).begin(); cache2.put("k3", "v2"); tm(1).suspend(); tm(0).begin(); assert !cache1.getAdvancedCache().withFlags(FAIL_SILENTLY).lock(Arrays.asList("k1", "k2", "k3")); tm(0).rollback(); } @Test(expectedExceptions = UnsupportedOperationException.class) public void testLockOnNonTransactionalCache() { withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(false)) { @Override public void call() { cm.getCache().getAdvancedCache().lock("k"); } }); } public void testLockingInterceptorType() { ConfigurationBuilder builder = new ConfigurationBuilder(); withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(builder)) { @Override public void call() { AbstractLockingInterceptor lockingInterceptor = TestingUtil.findInterceptor( cm.getCache(), AbstractLockingInterceptor.class); assertTrue(lockingInterceptor instanceof NonTransactionalLockingInterceptor); } }); } }
7,186
31.373874
103
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/APIDistTest.java
package org.infinispan.lock; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; @Test(testName = "lock.APIDistTest", groups = "functional") @CleanupAfterMethod public class APIDistTest extends MultipleCacheManagersTest { MagicKey key; // guaranteed to be mapped to cache2 @Override protected void createCacheManagers() throws Throwable { createCluster(TestDataSCI.INSTANCE, createConfig(), 2); waitForClusterToForm(); key = new MagicKey("Key mapped to Cache2", cache(1)); } protected ConfigurationBuilder createConfig() { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); cfg .transaction().lockingMode(LockingMode.PESSIMISTIC) .clustering().l1().disable().hash().numOwners(1) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); return cfg; } public void testLockAndGet() throws SystemException, NotSupportedException { Cache<MagicKey, String> cache1 = cache(0), cache2 = cache(1); cache1.put(key, "v"); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; assert "v".equals(cache2.get(key)) : "Could not find key " + key + " on cache2"; tm(0).begin(); log.trace("About to lock"); cache1.getAdvancedCache().lock(key); log.trace("About to get"); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; tm(0).rollback(); } public void testLockAndGetAndPut() throws SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException { Cache<MagicKey, String> cache1 = cache(0), cache2 = cache(1); cache1.put(key, "v"); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; assert "v".equals(cache2.get(key)) : "Could not find key " + key + " on cache2"; tm(0).begin(); cache1.getAdvancedCache().lock(key); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; String old = cache1.put(key, "new_value"); assert "v".equals(old) : "Expected v, was " + old; log.trace("Before commit!"); tm(0).commit(); assertEquals("Could not find key " + key + " on cache 1.", "new_value", cache1.get(key)); assertEquals("Could not find key " + key + " on cache 2.", "new_value", cache2.get(key)); } public void testLockAndPutRetval() throws SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException { Cache<MagicKey, String> cache1 = cache(0), cache2 = cache(1); cache1.put(key, "v"); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; assert "v".equals(cache2.get(key)) : "Could not find key " + key + " on cache2"; tm(0).begin(); cache1.getAdvancedCache().lock(key); String old = cache1.put(key, "new_value"); assert "v".equals(old) : "Expected v, was " + old; tm(0).commit(); assertEquals("Could not find key " + key + " on cache 1.", "new_value", cache1.get(key)); assertEquals("Could not find key " + key + " on cache 2.", "new_value", cache2.get(key)); } public void testLockAndRemoveRetval() throws SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException { Cache<MagicKey, String> cache1 = cache(0), cache2 = cache(1); cache1.put(key, "v"); assert "v".equals(cache1.get(key)) : "Could not find key " + key + " on cache1"; assert "v".equals(cache2.get(key)) : "Could not find key " + key + " on cache2"; tm(0).begin(); cache1.getAdvancedCache().lock(key); String old = cache1.remove(key); assert "v".equals(old) : "Expected v, was " + old; tm(0).commit(); assertNull("Could not find key " + key + " on cache 1.", cache1.get(key)); assertNull("Could not find key " + key + " on cache 2.", cache2.get(key)); } }
4,793
39.974359
160
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/CheckNoRemoteCallForLocalKeyTest.java
package org.infinispan.lock; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import static org.testng.Assert.assertEquals; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * Checks that if a key's lock is the node where the transaction runs, then no remote RPC takes place. * * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.CheckNoRemoteCallForLocalKeyTest") public class CheckNoRemoteCallForLocalKeyTest extends MultipleCacheManagersTest { protected CheckRemoteLockAcquiredOnlyOnceTest.ControlInterceptor controlInterceptor; protected CacheMode mode = CacheMode.REPL_SYNC; protected Object key; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder c = getDefaultClusteredCacheConfig(mode, true); c.transaction().lockingMode(LockingMode.PESSIMISTIC); createCluster(c, 2); waitForClusterToForm(); key = new MagicKey(cache(0)); controlInterceptor = new CheckRemoteLockAcquiredOnlyOnceTest.ControlInterceptor(); extractInterceptorChain(cache(1)).addInterceptor(controlInterceptor, 1); } public void testLocalPut() throws Exception { testLocalOperation(new CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation() { @Override public void execute() { cache(0).put(key, "v"); } }); } public void testLocalRemove() throws Exception { testLocalOperation(new CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation() { @Override public void execute() { cache(0).remove(key); } }); } public void testLocalReplace() throws Exception { testLocalOperation(new CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation() { @Override public void execute() { cache(0).replace(key, "", ""); } }); } public void testLocalLock() throws Exception { testLocalOperation(new CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation() { @Override public void execute() { cache(0).getAdvancedCache().lock(key); } }); } private void testLocalOperation(CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation o) throws Exception { assert !advancedCache(1).getRpcManager().getTransport().isCoordinator(); assert advancedCache(0).getRpcManager().getTransport().isCoordinator(); tm(0).begin(); o.execute(); assert lockManager(0).isLocked(key); assert !lockManager(1).isLocked(key); assertEquals(controlInterceptor.remoteInvocations, 0); tm(0).rollback(); } }
2,913
32.113636
107
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/L1LockTest.java
package org.infinispan.lock; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.testng.annotations.Test; /** * @author Mircea Markus &lt;mircea.markus@jboss.com&gt; (C) 2011 Red Hat Inc. * @since 5.1 */ @Test(groups = "functional", testName = "lock.L1LockTest") public class L1LockTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); config.clustering().hash().numOwners(1).transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); createCluster( TestDataSCI.INSTANCE, config, 2); waitForClusterToForm(); } public void testConsistency() throws Exception { Object localKey = getKeyForCache(0); cache(0).put(localKey, "foo"); assertNotLocked(localKey); assertEquals("foo", cache(0).get(localKey)); assertNotLocked(localKey); log.trace("About to perform 2nd get..."); assertEquals("foo", cache(1).get(localKey)); assertNotLocked(localKey); cache(0).put(localKey, "foo2"); assertNotLocked(localKey); assertEquals("foo2", cache(0).get(localKey)); assertEquals("foo2", cache(1).get(localKey)); cache(1).put(localKey, "foo3"); assertEquals("foo3", cache(0).get(localKey)); assertEquals("foo3", cache(1).get(localKey)); } }
1,724
30.944444
125
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/StaleLocksTransactionTest.java
package org.infinispan.lock; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; @Test(testName = "lock.StaleLocksTransactionTest", groups = "functional") @CleanupAfterMethod public class StaleLocksTransactionTest extends MultipleCacheManagersTest { Cache<String, String> c1, c2; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); cfg .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()) .transaction().lockingMode(LockingMode.PESSIMISTIC); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(cfg); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(cfg); registerCacheManager(cm1, cm2); c1 = cm1.getCache(); c2 = cm2.getCache(); } public void testNoModsCommit() throws Exception { doTest(false, true); } public void testModsRollback() throws Exception { doTest(true, false); } public void testNoModsRollback() throws Exception { doTest(false, false); } public void testModsCommit() throws Exception { doTest(true, true); } private void doTest(boolean mods, boolean commit) throws Exception { tm(c1).begin(); c1.getAdvancedCache().lock("k"); assert c1.get("k") == null; if (mods) c1.put("k", "v"); if (commit) tm(c1).commit(); else tm(c1).rollback(); assertEventuallyNotLocked(c1, "k"); assertEventuallyNotLocked(c2, "k"); } }
2,030
31.238095
91
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/ExplicitUnlockTest.java
package org.infinispan.lock; import static java.lang.String.valueOf; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.locks.LockManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * Contributed by Dmitry Udalov * * @author Dmitry Udalov * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "lock.ExplicitUnlockTest") @CleanupAfterMethod public class ExplicitUnlockTest extends SingleCacheManagerTest { private static final Log log = LogFactory.getLog(ExplicitUnlockTest.class); private static final int NUMBER_OF_KEYS = 10; public void testLock() throws Exception { doTestLock(true, 10); } public void testLockTwoTasks() throws Exception { doTestLock(true, 2); } public void testLockNoExplicitUnlock() throws Exception { doTestLock(false, 10); } public void testLockNoExplicitUnlockTwoTasks() throws Exception { doTestLock(false, 10); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = getDefaultStandaloneCacheConfig(true); builder.transaction().lockingMode(LockingMode.PESSIMISTIC); return TestCacheManagerFactory.createCacheManager(builder); } private void doTestLock(boolean withUnlock, int nThreads) throws Exception { for (int key = 1; key <= NUMBER_OF_KEYS; key++) { cache.put("" + key, "value"); } List<Future<Boolean>> results = new ArrayList<>(nThreads); for (int i = 1; i <= nThreads; i++) { results.add(fork(new Worker(i, cache, withUnlock, 10))); } boolean success = true; for (Future<Boolean> next : results) { success = success && next.get(30, TimeUnit.SECONDS); } assertTrue("All worker should complete without exceptions", success); assertNoTransactions(); for (int i = 0; i < NUMBER_OF_KEYS; ++i) { assertEventuallyNotLocked(cache, valueOf(i)); } } private static class Worker implements Callable<Boolean> { private static final String lockKey = "0"; // there is no cached Object with such key private final Cache<Object, Object> cache; private final boolean withUnlock; private final long stepDelayMsec; private final int index; public Worker(int index, final Cache<Object, Object> cache, boolean withUnlock, long stepDelayMsec) { this.index = index; this.cache = cache; this.withUnlock = withUnlock; this.stepDelayMsec = stepDelayMsec; } @Override public Boolean call() throws Exception { boolean success; try { doRun(); success = true; } catch (Throwable t) { log.errorf(t, "Error in Worker[%s, unlock? %s]", index, withUnlock); success = false; } return success; } private void log(String method, String msg) { log.debugf("Worker[%s, unlock? %s] %s %s", index, withUnlock, method, msg); } private void doRun() throws Exception { final String methodName = "run"; TransactionManager mgr = cache.getAdvancedCache().getTransactionManager(); if (null == mgr) { throw new UnsupportedOperationException("TransactionManager was not configured for the cache " + cache.getName()); } mgr.begin(); try { if (acquireLock()) { log(methodName, "acquired lock"); // renaming all Objects from 1 to NUMBER_OF_KEYS String newName = "value-" + index; log(methodName, "Changing value to " + newName); for (int key = 1; key <= NUMBER_OF_KEYS; key++) { cache.put(valueOf(key), newName); Thread.sleep(stepDelayMsec); } validateCache(); if (withUnlock) { unlock(); } } else { log(methodName, "Failed to acquired lock"); } mgr.commit(); } catch (Exception t) { mgr.rollback(); throw t; } } private boolean acquireLock() { return cache.getAdvancedCache().lock(lockKey); } private void unlock() { LockManager lockManager = cache.getAdvancedCache().getLockManager(); Object lockOwner = lockManager.getOwner(lockKey); lockManager.unlock(lockKey, lockOwner); } /** * Checks if all cache entries are consistent */ private void validateCache() throws InterruptedException { String value = getCachedValue(1); for (int key = 1; key <= NUMBER_OF_KEYS; key++) { String nextValue = getCachedValue(key); if (!value.equals(nextValue)) { String msg = String.format("Cache inconsistent: value=%s, nextValue=%s", value, nextValue); log("validate_cache", msg); throw new ConcurrentModificationException(msg); } Thread.sleep(stepDelayMsec); } log("validate_cache", "passed: " + value); } private String getCachedValue(int index) { String value = (String) cache.get(valueOf(index)); if (null == value) { throw new ConcurrentModificationException("Missed entry for " + index); } return value; } } }
6,202
30.974227
126
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/CheckRemoteLockAcquiredOnlyOnceDistTest.java
package org.infinispan.lock; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.CheckRemoteLockAcquiredOnlyOnceDistTest") public class CheckRemoteLockAcquiredOnlyOnceDistTest extends CheckRemoteLockAcquiredOnlyOnceTest{ public CheckRemoteLockAcquiredOnlyOnceDistTest() { mode = CacheMode.DIST_SYNC; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); key = getKeyForCache(0); } }
594
24.869565
97
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/MainOwnerChangesPessimisticLockTest.java
package org.infinispan.lock.singlelock; import static org.testng.AssertJUnit.assertEquals; import java.util.HashMap; import java.util.Map; import jakarta.transaction.Transaction; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * Main owner changes due to state transfer in a distributed cluster using pessimistic locking. * * @since 5.2 */ @Test(groups = "functional", testName = "lock.singlelock.MainOwnerChangesPessimisticLockTest") @CleanupAfterMethod public class MainOwnerChangesPessimisticLockTest extends MultipleCacheManagersTest { public static final int NUM_KEYS = 10; private ConfigurationBuilder dccc; @Override protected void createCacheManagers() throws Throwable { dccc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true, true); dccc.transaction() .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .lockingMode(LockingMode.PESSIMISTIC) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()) .clustering().hash().numOwners(1).numSegments(3) .l1().disable() .stateTransfer().fetchInMemoryState(true); createCluster(TestDataSCI.INSTANCE, dccc, 2); waitForClusterToForm(); } public void testLocalLockMigrationTxCommit() throws Exception { testLockMigration(0, true); } public void testLocalLockMigrationTxRollback() throws Exception { testLockMigration(0, false); } public void testRemoteLockMigrationTxCommit() throws Exception { testLockMigration(1, true); } public void testRemoteLockMigrationTxRollback() throws Exception { testLockMigration(1, false); } private void testLockMigration(int nodeThatPuts, boolean commit) throws Exception { Map<Object, Transaction> key2Tx = new HashMap<>(); for (int i = 0; i < NUM_KEYS; i++) { Object key = getKeyForCache(0); if (key2Tx.containsKey(key)) continue; // put a key to have some data in cache cache(nodeThatPuts).put(key, key); // start a TX that locks the key and then we suspend it tm(nodeThatPuts).begin(); Transaction tx = tm(nodeThatPuts).getTransaction(); advancedCache(nodeThatPuts).lock(key); tm(nodeThatPuts).suspend(); key2Tx.put(key, tx); assertLocked(0, key); } log.trace("Lock transfer happens here"); // add a third node hoping that some of the previously created keys will be migrated to it addClusterEnabledCacheManager(TestDataSCI.INSTANCE, dccc); waitForClusterToForm(); // search for a key that was migrated to third node and the suspended TX that locked it Object migratedKey = null; Transaction migratedTransaction = null; LocalizedCacheTopology cacheTopology = advancedCache(2).getDistributionManager().getCacheTopology(); for (Object key : key2Tx.keySet()) { if (cacheTopology.getDistribution(key).isPrimary()) { migratedKey = key; migratedTransaction = key2Tx.get(key); log.trace("Migrated key = " + migratedKey); log.trace("Migrated transaction = " + ((EmbeddedTransaction) migratedTransaction).getEnlistedResources()); break; } } // we do not focus on the other transactions so we commit them now log.trace("Committing all transactions except the migrated one."); for (Object key : key2Tx.keySet()) { if (!key.equals(migratedKey)) { Transaction tx = key2Tx.get(key); tm(nodeThatPuts).resume(tx); tm(nodeThatPuts).commit(); } } if (migratedKey == null) { // this could happen in extreme cases log.trace("No key migrated to new owner - test cannot be performed!"); } else { // the migrated TX is resumed and committed or rolled back. we expect the migrated key to be unlocked now tm(nodeThatPuts).resume(migratedTransaction); if (commit) { tm(nodeThatPuts).commit(); } else { tm(nodeThatPuts).rollback(); } // there should not be any locks assertEventuallyNotLocked(cache(0), migratedKey); assertEventuallyNotLocked(cache(1), migratedKey); assertEventuallyNotLocked(cache(2), migratedKey); // if a new TX tries to write to the migrated key this should not fail, the key should not be locked tm(nodeThatPuts).begin(); cache(nodeThatPuts).put(migratedKey, "someValue"); // this should not result in TimeoutException due to key still locked tm(nodeThatPuts).commit(); } log.trace("Checking the values from caches..."); for (Object key : key2Tx.keySet()) { log.tracef("Checking key: %s", key); Object expectedValue = key; if (key.equals(migratedKey)) { expectedValue = "someValue"; } // check them directly in data container InternalCacheEntry d0 = advancedCache(0).getDataContainer().get(key); InternalCacheEntry d1 = advancedCache(1).getDataContainer().get(key); InternalCacheEntry d2 = advancedCache(2).getDataContainer().get(key); int c = 0; if (d0 != null && !d0.isExpired(TIME_SERVICE.wallClockTime())) { assertEquals(expectedValue, d0.getValue()); c++; } if (d1 != null && !d1.isExpired(TIME_SERVICE.wallClockTime())) { assertEquals(expectedValue, d1.getValue()); c++; } if (d2 != null && !d2.isExpired(TIME_SERVICE.wallClockTime())) { assertEquals(expectedValue, d2.getValue()); c++; } assertEquals(1, c); // look at them also via cache API assertEquals(expectedValue, cache(0).get(key)); assertEquals(expectedValue, cache(1).get(key)); assertEquals(expectedValue, cache(2).get(key)); } } }
6,594
37.794118
129
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/AbstractCrashTest.java
package org.infinispan.lock.singlelock; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import java.util.Collection; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.function.Function; import org.infinispan.AdvancedCache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.ResponseCollector; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.infinispan.util.AbstractDelegatingRpcManager; import org.infinispan.util.concurrent.IsolationLevel; /** * @author Mircea Markus * @since 5.1 */ public abstract class AbstractCrashTest extends MultipleCacheManagersTest { protected CacheMode cacheMode; protected LockingMode lockingMode; protected Boolean useSynchronization; protected AbstractCrashTest(CacheMode cacheMode, LockingMode lockingMode, Boolean useSynchronization) { this.cacheMode = cacheMode; this.lockingMode = lockingMode; this.useSynchronization = useSynchronization; } @Override protected void createCacheManagers() { ConfigurationBuilder c = buildConfiguration(); createCluster(TestDataSCI.INSTANCE, c, 3); waitForClusterToForm(); } protected ConfigurationBuilder buildConfiguration() { ConfigurationBuilder c = getDefaultClusteredCacheConfig(cacheMode, true); c.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .useSynchronization(useSynchronization) .lockingMode(lockingMode) .recovery().disable() .clustering() .l1().disable() .hash().numOwners(3) .stateTransfer().fetchInMemoryState(false) .locking().isolationLevel(IsolationLevel.READ_COMMITTED); return c; } protected Future<Void> beginAndPrepareTx(final Object k, final int cacheIndex) { return fork(() -> { try { tm(cacheIndex).begin(); cache(cacheIndex).put(k,"v"); final EmbeddedTransaction transaction = (EmbeddedTransaction) tm(cacheIndex).getTransaction(); transaction.runPrepare(); } catch (Throwable e) { log.errorf(e, "Error preparing transaction for key %s on cache %s", k, cache(cacheIndex)); } }); } protected Future<Void> beginAndCommitTx(final Object k, final int cacheIndex) { return fork(() -> { try { tm(cacheIndex).begin(); cache(cacheIndex).put(k, "v"); tm(cacheIndex).commit(); } catch (Throwable e) { log.errorf(e, "Error committing transaction for key %s on cache %s", k, cache(cacheIndex)); } }); } public static class TxControlInterceptor extends DDAsyncInterceptor { public CountDownLatch prepareProgress = new CountDownLatch(1); public CountDownLatch preparedReceived = new CountDownLatch(1); public CountDownLatch commitReceived = new CountDownLatch(1); public CountDownLatch commitProgress = new CountDownLatch(1); @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, throwable) -> { preparedReceived.countDown(); prepareProgress.await(); }); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { commitReceived.countDown(); commitProgress.await(); return invokeNext(ctx, command); } } protected void skipTxCompletion(final AdvancedCache<Object, Object> cache, final CountDownLatch releaseLocksLatch) { RpcManager rpcManager = new AbstractDelegatingRpcManager(cache.getRpcManager()) { @Override protected <T> void performSend(Collection<Address> targets, ReplicableCommand command, Function<ResponseCollector<T>, CompletionStage<T>> invoker) { if (command instanceof TxCompletionNotificationCommand) { releaseLocksLatch.countDown(); log.tracef("Skipping TxCompletionNotificationCommand"); } else { super.performSend(targets, command, invoker); } } }; //not too nice: replace the rpc manager in the class that builds the Sync objects final TransactionTable transactionTable = TestingUtil.getTransactionTable(cache(1)); TestingUtil.replaceField(rpcManager, "rpcManager", transactionTable, TransactionTable.class); TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); txControlInterceptor.prepareProgress.countDown(); txControlInterceptor.commitProgress.countDown(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); } }
5,810
39.354167
119
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/MinViewIdCalculusTest.java
package org.infinispan.lock.singlelock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.DistributionManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.MinViewIdCalculusTest") @CleanupAfterMethod public class MinViewIdCalculusTest extends MultipleCacheManagersTest { private ConfigurationBuilder c; @Override protected void createCacheManagers() throws Throwable { c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); c .transaction() .lockingMode(LockingMode.PESSIMISTIC) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .clustering() .hash().numOwners(3); createCluster(TestDataSCI.INSTANCE, c, 2); waitForClusterToForm(); } private void createNewNode() { //add a new cache and check that min view is updated log.trace("Adding new node .."); addClusterEnabledCacheManager(TestDataSCI.INSTANCE, c); waitForClusterToForm(); log.trace("New node added."); } public void testMinViewId1() throws Exception { final TransactionTable tt0 = TestingUtil.getTransactionTable(cache(0)); final TransactionTable tt1 = TestingUtil.getTransactionTable(cache(1)); DistributionManager distributionManager0 = advancedCache(0).getDistributionManager(); final int topologyId = distributionManager0.getCacheTopology().getTopologyId(); assertEquals(tt0.getMinTopologyId(), topologyId); assertEquals(tt1.getMinTopologyId(), topologyId); createNewNode(); final int topologyId2 = distributionManager0.getCacheTopology().getTopologyId(); assertTrue(topologyId2 > topologyId); final TransactionTable tt2 = TestingUtil.getTransactionTable(cache(2)); eventually(() -> tt0.getMinTopologyId() == topologyId2 && tt1.getMinTopologyId() == topologyId2 && tt2.getMinTopologyId() == topologyId2); } public void testMinViewId2() throws Exception { final TransactionTable tt0 = TestingUtil.getTransactionTable(cache(0)); final TransactionTable tt1 = TestingUtil.getTransactionTable(cache(1)); DistributionManager distributionManager0 = advancedCache(0).getDistributionManager(); final int topologyId = distributionManager0.getCacheTopology().getTopologyId(); tm(1).begin(); cache(1).put(getKeyForCache(0),"v"); final EmbeddedTransaction t = (EmbeddedTransaction) tm(1).getTransaction(); t.runPrepare(); tm(1).suspend(); eventually(() -> checkTxCount(0, 0, 1)); createNewNode(); final int topologyId2 = distributionManager0.getCacheTopology().getTopologyId(); assertTrue(topologyId2 > topologyId); assertEquals(tt0.getMinTopologyId(), topologyId); assertEquals(tt1.getMinTopologyId(), topologyId); tm(1).resume(t); t.runCommit(false); eventually(() -> tt0.getMinTopologyId() == topologyId2 && tt1.getMinTopologyId() == topologyId2); } }
3,703
35.673267
103
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/AbstractInitiatorCrashTest.java
package org.infinispan.lock.singlelock; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional") public abstract class AbstractInitiatorCrashTest extends AbstractCrashTest { public AbstractInitiatorCrashTest(CacheMode cacheMode, LockingMode lockingMode, Boolean useSynchronization) { super(cacheMode, lockingMode, useSynchronization); } public void testInitiatorCrashesBeforeReleasingLock() throws Exception { final CountDownLatch releaseLocksLatch = new CountDownLatch(1); skipTxCompletion(advancedCache(1), releaseLocksLatch); Object k = getKeyForCache(2); Future<Void> future = beginAndCommitTx(k, 1); releaseLocksLatch.await(30, TimeUnit.SECONDS); assert checkTxCount(0, 0, 1); eventuallyEquals(0, () -> getLocalTxCount(1)); assert checkTxCount(1, 0, 0); assert checkTxCount(2, 0, 1); assertEventuallyNotLocked(cache(0), k); assertEventuallyNotLocked(cache(1), k); assertLocked(cache(2), k); killMember(1); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); assertNotLocked(k); future.get(30, TimeUnit.SECONDS); } public void testInitiatorNodeCrashesBeforeCommit() throws Exception { Object k = getKeyForCache(2); tm(1).begin(); cache(1).put(k,"v"); final EmbeddedTransaction transaction = (EmbeddedTransaction) tm(1).getTransaction(); transaction.runPrepare(); tm(1).suspend(); assertEventuallyNotLocked(cache(0), k); assertEventuallyNotLocked(cache(1), k); assertLocked(cache(2), k); checkTxCount(0, 0, 1); checkTxCount(1, 1, 0); checkTxCount(2, 0, 1); killMember(1); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); } }
2,138
28.708333
112
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/NoPrepareRpcForPessimisticTransactionsTest.java
package org.infinispan.lock.singlelock; import static org.testng.Assert.assertEquals; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.transaction.LockingMode; import org.infinispan.util.mocks.ControlledCommandFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional", testName = "lock.singlelock.NoPrepareRpcForPessimisticTransactionsTest") public class NoPrepareRpcForPessimisticTransactionsTest extends MultipleCacheManagersTest { private Object k1; private ControlledCommandFactory commandFactory; @Override protected void createCacheManagers() throws Throwable { final ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); c .transaction().lockingMode(LockingMode.PESSIMISTIC) .clustering() .hash().numOwners(1) .l1().disable(); createCluster(TestDataSCI.INSTANCE, c, 2); waitForClusterToForm(); k1 = getKeyForCache(1); commandFactory = ControlledCommandFactory.registerControlledCommandFactory(cache(1), CommitCommand.class); } @BeforeMethod void clearStats() { commandFactory.remoteCommandsReceived.set(0); } public void testSingleGetOnPut() throws Exception { Operation o = new Operation() { @Override public void execute() { cache(0).put(k1, "v0"); } }; runtTest(o); } public void testSingleGetOnRemove() throws Exception { Operation o = new Operation() { @Override public void execute() { cache(0).remove(k1); } }; runtTest(o); } private void runtTest(Operation o) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException { log.trace("Here is where the fun starts.."); tm(0).begin(); o.execute(); assertKeyLockedCorrectly(k1); assertEquals(commandFactory.remoteCommandsReceived.get(), 2, "2 = cluster get + lock"); tm(0).commit(); eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { //prepare + tx completion notification return commandFactory.remoteCommandsReceived.get() == 4; } }); } private interface Operation { void execute(); } }
2,933
28.34
157
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/MainOwnerChangesLockTest.java
package org.infinispan.lock.singlelock; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import java.util.HashMap; import java.util.Map; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.testng.annotations.Test; /** * Main owner changes due to state transfer in a distributed cluster using optimistic locking. * * @since 5.1 */ @Test(groups = "functional", testName = "lock.singlelock.MainOwnerChangesLockTest") @CleanupAfterMethod public class MainOwnerChangesLockTest extends MultipleCacheManagersTest { public static final int NUM_KEYS = 100; private ConfigurationBuilder dccc; @Override protected void createCacheManagers() throws Throwable { dccc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true, true); dccc.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); dccc.clustering().hash().l1().disable().locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); dccc.clustering().stateTransfer().fetchInMemoryState(true); createCluster(TestDataSCI.INSTANCE, dccc, 2); waitForClusterToForm(); } public void testLocalTxLockMigration() throws Exception { testLockMigration(0); } public void testRemoteTxLockMigration() throws Exception { testLockMigration(1); } private void testLockMigration(int nodeThatPuts) throws Exception { Map<Object, EmbeddedTransaction> key2Tx = new HashMap<>(); for (int i = 0; i < NUM_KEYS; i++) { Object key = getKeyForCache(0); if (key2Tx.containsKey(key)) continue; embeddedTm(nodeThatPuts).begin(); cache(nodeThatPuts).put(key, key); EmbeddedTransaction tx = embeddedTm(nodeThatPuts).getTransaction(); tx.runPrepare(); embeddedTm(nodeThatPuts).suspend(); key2Tx.put(key, tx); assertLocked(0, key); } log.trace("Lock transfer happens here"); addClusterEnabledCacheManager(TestDataSCI.INSTANCE, dccc); waitForClusterToForm(); Object migratedKey = null; LocalizedCacheTopology cacheTopology = advancedCache(2).getDistributionManager().getCacheTopology(); for (Object key : key2Tx.keySet()) { if (cacheTopology.getDistribution(key).isPrimary()) { migratedKey = key; break; } } if (migratedKey == null) { log.trace("No key migrated to new owner."); } else { log.trace("migratedKey = " + migratedKey); embeddedTm(2).begin(); cache(2).put(migratedKey, "someValue"); try { embeddedTm(2).commit(); fail("RollbackException should have been thrown here."); } catch (RollbackException e) { //expected } } log.trace("About to commit existing transactions."); log.trace("Committing the tx to the new node."); for (Transaction tx : key2Tx.values()) { tm(nodeThatPuts).resume(tx); embeddedTm(nodeThatPuts).getTransaction().runCommit(false); } for (Object key : key2Tx.keySet()) { Object value = getValue(key);//make sure that data from the container, just to make sure all replicas are correctly set assertEquals(key, value); } } private Object getValue(Object key) { log.tracef("Checking key: %s", key); InternalCacheEntry d0 = advancedCache(0).getDataContainer().get(key); InternalCacheEntry d1 = advancedCache(1).getDataContainer().get(key); InternalCacheEntry d2 = advancedCache(2).getDataContainer().get(key); if (d0 == null) { assert sameValue(d1, d2); return d1.getValue(); } else if (d1 == null) { assert sameValue(d0, d2); return d0.getValue(); } else if (d2 == null) { assert sameValue(d0, d1); return d0.getValue(); } throw new RuntimeException(); } private boolean sameValue(InternalCacheEntry d1, InternalCacheEntry d2) { return d1.getValue().equals(d2.getValue()); } private EmbeddedTransactionManager embeddedTm(int cacheIndex) { return (EmbeddedTransactionManager) tm(cacheIndex); } }
4,893
34.463768
128
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/SinglePhaseCommitForPessimisticCachesTest.java
package org.infinispan.lock.singlelock; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import static org.testng.Assert.assertEquals; import java.util.List; import org.infinispan.commands.control.LockControlCommand; import org.infinispan.commands.read.GetKeyValueCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * Single phase commit is used with pessimistic caches. * * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.SinglePhaseCommitForPessimisticCachesTest") public class SinglePhaseCommitForPessimisticCachesTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { final ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); c .clustering().hash().numOwners(3) .transaction().lockingMode(LockingMode.PESSIMISTIC); createCluster(TestDataSCI.INSTANCE, c, 3); waitForClusterToForm(); } public void testSinglePhaseCommit() throws Exception { final Object k0_1 = getKeyForCache(0); final Object k0_2 = getKeyForCache(0); final List<Address> members = advancedCache(0).getRpcManager().getTransport().getMembers(); assert cacheTopology(0).getDistribution(k0_1).writeOwners().containsAll(members); assert cacheTopology(0).getDistribution(k0_2).writeOwners().containsAll(members); TxCountInterceptor interceptor0 = new TxCountInterceptor(); TxCountInterceptor interceptor1 = new TxCountInterceptor(); extractInterceptorChain(advancedCache(0)).addInterceptor(interceptor0, 1); extractInterceptorChain(advancedCache(1)).addInterceptor(interceptor1, 2); tm(2).begin(); cache(2).put(k0_1, "v"); cache(2).put(k0_2, "v"); tm(2).commit(); assertEquals(interceptor0.lockCount, 2); assertEquals(interceptor1.lockCount, 2); assertEquals(interceptor0.prepareCount, 1); assertEquals(interceptor1.prepareCount, 1); assertEquals(interceptor0.commitCount, 0); assertEquals(interceptor1.commitCount, 0); } public static class TxCountInterceptor extends DDAsyncInterceptor { public volatile int prepareCount; public volatile int commitCount; public volatile int lockCount; public volatile int putCount; public volatile int getCount; @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { prepareCount++; return super.visitPrepareCommand(ctx, command); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { commitCount++; return super.visitCommitCommand(ctx, command); } @Override public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable { lockCount++; return super.visitLockControlCommand(ctx, command); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { putCount++; return super.visitPutKeyValueCommand(ctx, command); } @Override public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { getCount++; return super.visitGetKeyValueCommand(ctx, command); } } }
4,109
36.363636
115
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/OriginatorBecomesOwnerLockTest.java
package org.infinispan.lock.singlelock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import org.infinispan.Cache; import org.infinispan.commands.remote.ClusteredGetCommand; import org.infinispan.commands.remote.recovery.TxCompletionNotificationCommand; import org.infinispan.commands.statetransfer.StateTransferGetTransactionsCommand; import org.infinispan.commands.statetransfer.StateTransferStartCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.MagicKey; import org.infinispan.commands.statetransfer.StateResponseCommand; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.ControlledRpcManager; import org.testng.annotations.Test; /** * Test what happens if the originator becomes an owner during a prepare or commit RPC. * @since 5.2 */ @Test(groups = "functional", testName = "lock.singlelock.OriginatorBecomesOwnerLockTest") @CleanupAfterMethod public class OriginatorBecomesOwnerLockTest extends MultipleCacheManagersTest { private ConfigurationBuilder configurationBuilder; private static final int ORIGINATOR_INDEX = 0; private static final int OTHER_INDEX = 1; private static final int KILLED_INDEX = 2; private Cache<Object, String> originatorCache; private Cache<Object, String> killedCache; private Cache<Object, String> otherCache; // Pseudo-configuration // TODO Test fails (expected RollbackException isn't raised) if waitForStateTransfer == false because of https://issues.jboss.org/browse/ISPN-2510 private boolean waitForStateTransfer = true; // TODO Tests fails with SuspectException if stopCacheOnly == false because of https://issues.jboss.org/browse/ISPN-2402 private boolean stopCacheOnly = true; @Override protected void createCacheManagers() throws Throwable { configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true, true); configurationBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); configurationBuilder.clustering().remoteTimeout(30000, TimeUnit.MILLISECONDS); configurationBuilder.clustering().hash().l1().disable(); configurationBuilder.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); configurationBuilder.clustering().stateTransfer().fetchInMemoryState(true); ControlledConsistentHashFactory consistentHashFactory = new ControlledConsistentHashFactory.Default(new int[][]{{KILLED_INDEX, ORIGINATOR_INDEX}, {KILLED_INDEX, OTHER_INDEX}}); configurationBuilder.clustering().hash().numSegments(2).consistentHashFactory(consistentHashFactory); createCluster(TestDataSCI.INSTANCE, configurationBuilder, 3); waitForClusterToForm(); originatorCache = cache(ORIGINATOR_INDEX); killedCache = cache(KILLED_INDEX); otherCache = cache(OTHER_INDEX); // Set up the consistent hash after node 1 is killed consistentHashFactory.setOwnerIndexes(new int[][]{{ORIGINATOR_INDEX, OTHER_INDEX}, {OTHER_INDEX, ORIGINATOR_INDEX}}); // TODO Add another test method with ownership changing from [KILLED_INDEX, OTHER_INDEX] to [ORIGINATOR_INDEX, OTHER_INDEX] // i.e. the originator is a non-owner at first, and becomes the primary owner when the prepare is retried } public void testOriginatorBecomesPrimaryOwnerDuringPrepare() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationDuringPrepare(key); } public void testOriginatorBecomesBackupOwnerDuringPrepare() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationDuringPrepare(key); } private void testLockMigrationDuringPrepare(final Object key) throws Exception { ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(originatorCache); controlledRpcManager.excludeCommands(StateTransferStartCommand.class, StateTransferGetTransactionsCommand.class, StateResponseCommand.class); final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); Future<EmbeddedTransaction> f = fork(() -> { tm.begin(); originatorCache.put(key, "value"); EmbeddedTransaction tx = tm.getTransaction(); boolean success = tx.runPrepare(); assertTrue(success); tm.suspend(); return tx; }); if (!originatorCache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key)) { controlledRpcManager.expectCommand(ClusteredGetCommand.class).send().receiveAll(); } ControlledRpcManager.BlockedRequest blockedPrepare = controlledRpcManager.expectCommand(PrepareCommand.class); // Allow the tx thread to send the prepare command to the owners Thread.sleep(2000); log.trace("Lock transfer happens here"); killCache(); log.trace("Allow the prepare RPC to proceed"); blockedPrepare.send().receiveAll(); // Also allow the retry to proceed controlledRpcManager.expectCommand(PrepareCommand.class).send().receiveAll(); // Ensure the prepare finished on the other node EmbeddedTransaction tx = f.get(); log.tracef("Prepare finished"); checkNewTransactionFails(key); log.trace("About to commit existing transactions."); controlledRpcManager.excludeCommands(CommitCommand.class, TxCompletionNotificationCommand.class); tm.resume(tx); tx.runCommit(false); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); controlledRpcManager.stopBlocking(); } public void testOriginatorBecomesPrimaryOwnerAfterPrepare() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationAfterPrepare(key); } public void testOriginatorBecomesBackupOwnerAfterPrepare() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationAfterPrepare(key); } private void testLockMigrationAfterPrepare(Object key) throws Exception { final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); tm.begin(); originatorCache.put(key, "value"); EmbeddedTransaction tx = tm.getTransaction(); boolean prepareSuccess = tx.runPrepare(); assert prepareSuccess; tm.suspend(); log.trace("Lock transfer happens here"); killCache(); checkNewTransactionFails(key); log.trace("About to commit existing transaction."); tm.resume(tx); tx.runCommit(false); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); } public void testOriginatorBecomesPrimaryOwnerDuringCommit() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationDuringCommit(key); } public void testOriginatorBecomesBackupOwnerDuringCommit() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationDuringCommit(key); } private void testLockMigrationDuringCommit(final Object key) throws Exception { ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(originatorCache); controlledRpcManager.excludeCommands(StateTransferStartCommand.class, StateTransferGetTransactionsCommand.class, StateResponseCommand.class); final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); Future<EmbeddedTransaction> f = fork(() -> { tm.begin(); originatorCache.put(key, "value"); final EmbeddedTransaction tx = tm.getTransaction(); final boolean success = tx.runPrepare(); assert success; log.trace("About to commit transaction."); tx.runCommit(false); return null; }); if (!originatorCache.getAdvancedCache().getDistributionManager().getCacheTopology().isReadOwner(key)) { controlledRpcManager.expectCommand(ClusteredGetCommand.class).send().receiveAll(); } controlledRpcManager.expectCommand(PrepareCommand.class).send().receiveAll(); // Wait for the tx thread to block sending the commit ControlledRpcManager.BlockedRequest blockedCommit = controlledRpcManager.expectCommand(CommitCommand.class); log.trace("Lock transfer happens here"); killCache(); log.trace("Allow the commit RPC to proceed"); blockedCommit.send().receiveAll(); // Process the retry and the completion notification normally controlledRpcManager.expectCommand(CommitCommand.class).send().receiveAll(); controlledRpcManager.expectCommand(TxCompletionNotificationCommand.class).send(); // Ensure the commit finished on the other node f.get(30, TimeUnit.SECONDS); log.tracef("Commit finished"); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); assertNoLocksOrTxs(key, originatorCache); assertNoLocksOrTxs(key, otherCache); controlledRpcManager.stopBlocking(); } private void assertNoLocksOrTxs(Object key, Cache<Object, String> cache) { assertEventuallyNotLocked(originatorCache, key); final TransactionTable transactionTable = TestingUtil.extractComponent(cache, TransactionTable.class); eventuallyEquals(0, transactionTable::getLocalTxCount); eventuallyEquals(0, transactionTable::getRemoteTxCount); } private void killCache() { if (stopCacheOnly) { killedCache.stop(); } else { manager(KILLED_INDEX).stop(); } if (waitForStateTransfer) { TestingUtil.waitForNoRebalance(originatorCache, otherCache); } } private void checkValue(Object key, String value) { if (!waitForStateTransfer) { TestingUtil.waitForNoRebalance(originatorCache, otherCache); } log.tracef("Checking key: %s", key); InternalCacheEntry d0 = advancedCache(ORIGINATOR_INDEX).getDataContainer().get(key); InternalCacheEntry d1 = advancedCache(OTHER_INDEX).getDataContainer().get(key); assertEquals(d0.getValue(), value); assertEquals(d1.getValue(), value); } private void checkNewTransactionFails(Object key) throws NotSupportedException, SystemException, HeuristicMixedException, HeuristicRollbackException { EmbeddedTransactionManager otherTM = embeddedTm(OTHER_INDEX); otherTM.begin(); otherCache.put(key, "should fail"); try { otherTM.commit(); fail("RollbackException should have been thrown here."); } catch (RollbackException e) { //expected } } private EmbeddedTransactionManager embeddedTm(int cacheIndex) { return (EmbeddedTransactionManager) tm(cacheIndex); } }
12,170
40.539249
153
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/AbstractLockOwnerCrashTest.java
package org.infinispan.lock.singlelock; import jakarta.transaction.Transaction; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional") public abstract class AbstractLockOwnerCrashTest extends AbstractCrashTest { public AbstractLockOwnerCrashTest(CacheMode cacheMode, LockingMode lockingMode, Boolean useSynchronization) { super(cacheMode, lockingMode, useSynchronization); } protected EmbeddedTransaction transaction; public void testOwnerChangesAfterPrepare1() throws Exception { testOwnerChangesAfterPrepare(0); } public void testOwnerChangesAfterPrepare2() throws Exception { testOwnerChangesAfterPrepare(1); } private void testOwnerChangesAfterPrepare(final int secondTxNode) throws Exception { final Object k = getKeyForCache(2); fork(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); log.trace("Before preparing"); transaction.runPrepare(); tm(1).suspend(); } catch (Throwable e) { log.errorf(e, "Error preparing transaction for key %s", k); } }); eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); killMember(2); assert caches().size() == 2; tm(secondTxNode).begin(); final Transaction suspend = tm(secondTxNode).suspend(); fork(() -> { try { log.trace("This thread runs a different tx"); tm(secondTxNode).resume(suspend); cache(secondTxNode).put(k, "v2"); tm(secondTxNode).commit(); } catch (Exception e) { log.errorf(e, "Error committing transaction for key %s", k); } }); // this 'ensures' transaction called 'suspend' has the chance to start the prepare phase and is waiting to acquire the locks on k held by first transaction before it gets resumed Thread.sleep(1000); log.trace("Before completing the transaction!"); tm(1).resume(transaction); transaction.runCommit(false); //make sure the 2nd transaction succeeds as well eventually eventually(() -> cache(0).get(k).equals("v2") && cache(1).get(k).equals("v2"), 15000); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); } }
2,617
31.320988
184
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/AbstractNoCrashTest.java
package org.infinispan.lock.singlelock; import static org.testng.Assert.assertEquals; import java.util.Collections; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional") public abstract class AbstractNoCrashTest extends MultipleCacheManagersTest { protected CacheMode cacheMode; protected LockingMode lockingMode; protected Boolean useSynchronization; protected AbstractNoCrashTest(CacheMode cacheMode, LockingMode lockingMode, Boolean useSynchronization) { this.cacheMode = cacheMode; this.lockingMode = lockingMode; this.useSynchronization = useSynchronization; } @Override protected final void createCacheManagers() { assert cacheMode != null && lockingMode != null && useSynchronization != null; ConfigurationBuilder config = getDefaultClusteredCacheConfig(cacheMode, true); config.transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .lockingMode(lockingMode) .useSynchronization(useSynchronization); config.clustering().hash().numOwners(3) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); createCluster(TestDataSCI.INSTANCE, config, 3); waitForClusterToForm(); } protected interface Operation { void perform(Object key, int cacheIndex); } public void testTxAndLockOnDifferentNodesPut() throws Exception { testTxAndLockOnDifferentNodes((key, cacheIndex) -> cache(cacheIndex).put(key, "v"), false, false); } public void testTxAndLockOnDifferentNodesPutAll() throws Exception { testTxAndLockOnDifferentNodes((key, cacheIndex) -> cache(cacheIndex).putAll(Collections.singletonMap(key, "v")), false, false); } public void testTxAndLockOnDifferentNodesReplace() throws Exception { testTxAndLockOnDifferentNodes((key, cacheIndex) -> cache(cacheIndex).replace(key, "v"), true, false); } public void testTxAndLockOnDifferentNodesRemove() throws Exception { testTxAndLockOnDifferentNodes((key, cacheIndex) -> cache(cacheIndex).remove(key), true, true); } public void testTxAndLockOnSameNode() throws Exception { final Object k = getKeyForCache(0); tm(0).begin(); cache(0).put(k, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert lockManager(0).isLocked(k); assert !lockManager(1).isLocked(k); assert !lockManager(2).isLocked(k); dtm.runCommit(false); assertNotLocked(k); assertValue(k, false); } protected abstract void testTxAndLockOnDifferentNodes(Operation operation, boolean addFirst, boolean removed) throws Exception; protected boolean noPendingTransactions(int i) { return checkTxCount(i, 0, 0); } protected void assertValue(Object k, boolean isRemove) { eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); final String expected = isRemove ? null : "v"; assertEquals(cache(0).get(k), expected); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); assertEquals(cache(1).get(k), expected); assertEquals(cache(2).get(k), expected); } }
3,870
35.518868
133
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/pessimistic/SyncBasicSingleLockPessimisticTest.java
package org.infinispan.lock.singlelock.pessimistic; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.pessimistic.SyncBasicSingleLockPessimisticTest") public class SyncBasicSingleLockPessimisticTest extends BasicSingleLockPessimisticTest { public SyncBasicSingleLockPessimisticTest() { useSynchronization = true; } }
422
27.2
106
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/pessimistic/BasicSingleLockPessimisticTest.java
package org.infinispan.lock.singlelock.pessimistic; import static org.testng.Assert.assertEquals; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractNoCrashTest; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.pessimistic.BasicSingleLockPessimisticTest") public class BasicSingleLockPessimisticTest extends AbstractNoCrashTest { public BasicSingleLockPessimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.PESSIMISTIC, false); } protected void testTxAndLockOnDifferentNodes(Operation operation, boolean addFirst, boolean removed) throws Exception { final Object k = getKeyForCache(1); if (addFirst) cache(0).put(k, "v_initial"); assertNotLocked(k); tm(0).begin(); operation.perform(k, 0); assert !lockManager(0).isLocked(k); assert lockManager(1).isLocked(k); assert !lockManager(2).isLocked(k); tm(0).commit(); assertNotLocked(k); assertValue(k, removed); } public void testMultipleLocksInSameTx() throws Exception { final Object k1 = getKeyForCache(1); final Object k2 = getKeyForCache(2); assertEquals(cacheTopology(0).getDistribution(k1).primary(), address(1)); log.tracef("k1=%s, k2=%s", k1, k2); tm(0).begin(); cache(0).put(k1, "v"); cache(0).put(k2, "v"); assert !lockManager(0).isLocked(k1); assert lockManager(1).isLocked(k1); assert !lockManager(2).isLocked(k1); assert !lockManager(0).isLocked(k2); assert !lockManager(1).isLocked(k2); assert lockManager(2).isLocked(k2); tm(0).commit(); assertNotLocked(k1); assertNotLocked(k2); assertValue(k1, false); assertValue(k2, false); } public void testSecondTxCannotPrepare() throws Exception { final Object k = getKeyForCache(0); final Object k1= getKeyForCache(1); tm(0).begin(); cache(0).put(k, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); tm(0).suspend(); assert checkTxCount(0, 1, 0); assert checkTxCount(1, 0, 0); assert checkTxCount(2, 0, 0); tm(0).begin(); cache(0).put(k1, "some"); try { cache(0).put(k, "other"); } catch (Throwable e) { //ignore } finally { tm(0).rollback(); } assertNotLocked(k1); eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 0) && checkTxCount(2, 0, 0)); log.info("Before second failure"); tm(1).begin(); cache(1).put(k1, "some"); try { cache(1).put(k, "other"); assert false; } catch (Throwable e) { //expected } finally { tm(1).rollback(); } assertNotLocked(k1); eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 0) && checkTxCount(1, 0, 0)); log.trace("about to commit transaction."); tm(0).resume(dtm); tm(0).commit(); assertValue(k, false); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); } }
3,336
26.352459
122
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/pessimistic/InitiatorCrashPessimisticTest.java
package org.infinispan.lock.singlelock.pessimistic; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractInitiatorCrashTest; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional", testName = "lock.singlelock.pessimistic.InitiatorCrashPessimisticTest") @CleanupAfterMethod public class InitiatorCrashPessimisticTest extends AbstractInitiatorCrashTest { public InitiatorCrashPessimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.PESSIMISTIC, false); } public void testInitiatorNodeCrashesBeforePrepare2() throws Exception { Object k0 = getKeyForCache(0); Object k1 = getKeyForCache(1); Object k2 = getKeyForCache(2); tm(1).begin(); cache(1).put(k0, "v0"); cache(1).put(k1, "v1"); cache(1).put(k2, "v2"); assertLocked(cache(0), k0); assertEventuallyNotLocked(cache(1), k0); assertEventuallyNotLocked(cache(2), k0); assertEventuallyNotLocked(cache(0), k1); assertLocked(cache(1), k1); assertEventuallyNotLocked(cache(2), k1); assertEventuallyNotLocked(cache(0), k2); assertEventuallyNotLocked(cache(1), k2); assertLocked(cache(2), k2); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 1, 0); assert checkTxCount(2, 0, 1); killMember(1); assert caches().size() == 2; assertNotLocked(k0); assertNotLocked(k1); assertNotLocked(k2); eventually(new AbstractInfinispanTest.Condition() { @Override public boolean isSatisfied() throws Exception { return checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0); } }); } }
1,885
28.46875
100
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/pessimistic/LockOwnerCrashPessimisticTest.java
package org.infinispan.lock.singlelock.pessimistic; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.InvalidTransactionException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractLockOwnerCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.pessimistic.LockOwnerCrashPessimisticTest") @CleanupAfterMethod public class LockOwnerCrashPessimisticTest extends AbstractLockOwnerCrashTest { public LockOwnerCrashPessimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.PESSIMISTIC, false); } public void testLockOwnerCrashesBeforePrepare() throws Exception { final Object k = getKeyForCache(2); inNewThread(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); } catch (Throwable e) { log.errorf(e, "Error starting transaction for key %s", k); } }); eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); eventually(() -> !checkLocked(0, k) && !checkLocked(1, k) && checkLocked(2, k)); killMember(2); assert caches().size() == 2; tm(1).resume(transaction); tm(1).commit(); assertEquals("v", cache(0).get(k)); assertEquals("v", cache(1).get(k)); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); } public void testLockOwnerCrashesBeforePrepareAndLockIsStillHeld() throws Exception { final Object k = getKeyForCache(2); inNewThread(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); } catch (Throwable e) { log.errorf(e, "Error starting transaction for key %s", k); } }); eventually(() -> !checkLocked(0, k) && !checkLocked(1, k) && checkLocked(2, k)); killMember(2); assert caches().size() == 2; tm(0).begin(); try { cache(0).put(k, "v1"); assert false; } catch (Exception e) { tm(0).rollback(); } tm(1).resume(transaction); tm(1).commit(); assertEquals("v", cache(0).get(k)); assertEquals("v", cache(1).get(k)); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); } public void lockOwnerCrasherBetweenPrepareAndCommit1() throws Exception { testCrashBeforeCommit(true); } public void lockOwnerCrasherBetweenPrepareAndCommit2() throws Exception { testCrashBeforeCommit(false); } private void testCrashBeforeCommit(final boolean crashBeforePrepare) throws NotSupportedException, SystemException, InvalidTransactionException, HeuristicMixedException, RollbackException, HeuristicRollbackException { final Object k = getKeyForCache(2); inNewThread(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); if (!crashBeforePrepare) { transaction.runPrepare(); } } catch (Throwable e) { log.errorf(e, "Error preparing transaction for key %s", k); } }); eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); eventually(() -> !checkLocked(0, k) && !checkLocked(1, k) && checkLocked(2, k)); killMember(2); assertEquals(2, caches().size()); tm(1).begin(); try { cache(1).put(k, "v2"); fail("Exception expected as lock cannot be acquired on k=" + k); } catch (Exception e) { tm(1).rollback(); } tm(0).begin(); try { cache(0).put(k, "v3"); fail("Exception expected as lock cannot be acquired on k=" + k); } catch (Exception e) { tm(0).rollback(); } tm(1).resume(transaction); if (!crashBeforePrepare) { transaction.runCommit(false); } else { tm(1).commit(); } assertEquals("v", cache(0).get(k)); assertEquals("v", cache(1).get(k)); assertNotLocked(k); } }
4,832
29.588608
220
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/optimistic/SyncBasicSingleLockOptimisticTest.java
package org.infinispan.lock.singlelock.optimistic; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.optimistic.SyncBasicSingleLockOptimisticTest") public class SyncBasicSingleLockOptimisticTest extends BasicSingleLockOptimisticTest { public SyncBasicSingleLockOptimisticTest() { useSynchronization = true; } @Override public void testSecondTxCannotPrepare() throws Exception { } }
498
23.95
104
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/optimistic/BasicSingleLockOptimisticTest.java
package org.infinispan.lock.singlelock.optimistic; import static org.testng.Assert.assertEquals; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractNoCrashTest; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional",testName = "lock.singlelock.optimistic.BasicSingleLockOptimisticTest") public class BasicSingleLockOptimisticTest extends AbstractNoCrashTest { public BasicSingleLockOptimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.OPTIMISTIC, false); } protected void testTxAndLockOnDifferentNodes(Operation operation, boolean addFirst, boolean removed) throws Exception { final Object k = getKeyForCache(1); if (addFirst) cache(0).put(k, "v_initial"); assertNotLocked(k); tm(0).begin(); operation.perform(k, 0); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert !lockManager(0).isLocked(k); assert lockManager(1).isLocked(k); assert !lockManager(2).isLocked(k); dtm.runCommit(false); assertNotLocked(k); assertValue(k, removed); } public void testMultipleLocksInSameTx() throws Exception { final Object k1 = getKeyForCache(1); final Object k2 = getKeyForCache(2); assertEquals(cacheTopology(0).getDistribution(k1).primary(), address(1)); log.tracef("k1=%s, k2=%s", k1, k2); tm(0).begin(); cache(0).put(k1, "v"); cache(0).put(k2, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert !lockManager(0).isLocked(k1); assert lockManager(1).isLocked(k1); assert !lockManager(2).isLocked(k1); assert !lockManager(0).isLocked(k2); assert !lockManager(1).isLocked(k2); assert lockManager(2).isLocked(k2); dtm.runCommit(false); assertNotLocked(k1); assertNotLocked(k2); assertValue(k1, false); assertValue(k2, false); } public void testSecondTxCannotPrepare() throws Exception { final Object k = getKeyForCache(0); tm(0).begin(); cache(0).put(k, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); tm(0).suspend(); assert checkTxCount(0, 1, 0); assert checkTxCount(1, 0, 1); assert checkTxCount(2, 0, 1); tm(0).begin(); cache(0).put(k, "other"); try { tm(0).commit(); assert false; } catch (Throwable e) { //ignore } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 1) && checkTxCount(2, 0, 1)); log.info("Before second failure"); tm(1).begin(); cache(1).put(k, "other"); try { tm(1).commit(); assert false; } catch (Throwable e) { //expected } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 1) && checkTxCount(2, 0, 1)); tm(0).resume(dtm); dtm.runCommit(false); assertValue(k, false); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); } }
3,345
26.883333
123
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/optimistic/LockOwnerCrashOptimisticTest.java
package org.infinispan.lock.singlelock.optimistic; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractLockOwnerCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.optimistic.LockOwnerCrashOptimisticTest") @CleanupAfterMethod public class LockOwnerCrashOptimisticTest extends AbstractLockOwnerCrashTest { public LockOwnerCrashOptimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.OPTIMISTIC, false); } private EmbeddedTransaction transaction; public void testLockOwnerCrashesBeforePrepare() throws Exception { final Object k = getKeyForCache(2); inNewThread(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); } catch (Throwable e) { log.errorf(e, "Error starting transaction for key %s", k); } }); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 1, 0)&& checkTxCount(2, 0, 0)); killMember(2); assert caches().size() == 2; tm(1).resume(transaction); tm(1).commit(); assertEquals("v", cache(0).get(k)); assertEquals("v", cache(1).get(k)); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); } public void lockOwnerCrasherBetweenPrepareAndCommit() throws Exception { final Object k = getKeyForCache(2); inNewThread(() -> { try { tm(1).begin(); cache(1).put(k, "v"); transaction = (EmbeddedTransaction) tm(1).getTransaction(); transaction.runPrepare(); } catch (Throwable e) { log.errorf(e, "Error preparing transaction for key %s", k); } }); eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); killMember(2); assert caches().size() == 2; tm(1).begin(); cache(1).put(k, "v3"); try { tm(1).commit(); fail("Exception expected as lock cannot be acquired on k=" + k); } catch (Exception e) { log.debugf(e, "Expected error committing transaction for key %s", k); } tm(0).begin(); cache(0).put(k, "v2"); try { tm(0).commit(); fail("Exception expected as lock cannot be acquired on k=" + k); } catch (Exception e) { log.debugf(e, "Expected error committing transaction for key %s", k); } tm(1).resume(transaction); transaction.runPrepare(); } }
2,924
28.846939
99
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/optimistic/InitiatorCrashOptimisticTest.java
package org.infinispan.lock.singlelock.optimistic; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractInitiatorCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.optimistic.InitiatorCrashOptimisticTest") @CleanupAfterMethod public class InitiatorCrashOptimisticTest extends AbstractInitiatorCrashTest { public InitiatorCrashOptimisticTest() { super(CacheMode.DIST_SYNC, LockingMode.OPTIMISTIC, false); } public void testInitiatorNodeCrashesBeforePrepare() throws Exception { TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); Object k = getKeyForCache(2); //prepare is sent, but is not precessed on other nodes because of the txControlInterceptor.preparedReceived Future<Void> future = beginAndPrepareTx(k, 1); txControlInterceptor.preparedReceived.await(); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 1, 0); assert checkTxCount(2, 0, 1); killMember(1); assert caches().size() == 2; txControlInterceptor.prepareProgress.countDown(); assertNotLocked(k); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); future.get(30, TimeUnit.SECONDS); } }
1,682
32.66
113
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/pessimistic/InitiatorCrashPessimisticReplTest.java
package org.infinispan.lock.singlelock.replicated.pessimistic; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.MagicKey; import org.infinispan.lock.singlelock.replicated.optimistic.InitiatorCrashOptimisticReplTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "unstable", testName = "lock.singlelock.replicated.pessimistic.InitiatorCrashPessimisticReplTest", description = "See ISPN-2161 -- original group: functional") @CleanupAfterMethod public class InitiatorCrashPessimisticReplTest extends InitiatorCrashOptimisticReplTest { public InitiatorCrashPessimisticReplTest() { super(CacheMode.REPL_SYNC, LockingMode.PESSIMISTIC, false); } public void testInitiatorNodeCrashesBeforeCommit() throws Exception { TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); txControlInterceptor.prepareProgress.countDown(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); MagicKey key = new MagicKey("k", cache(0)); Future<Void> future = beginAndCommitTx(key, 1); txControlInterceptor.preparedReceived.await(); assertLocked(cache(0), key); assertEventuallyNotLocked(cache(1), key); assertEventuallyNotLocked(cache(2), key); checkTxCount(0, 0, 1); checkTxCount(1, 1, 0); checkTxCount(2, 0, 1); killMember(1); assertNotLocked(key); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); future.get(30, TimeUnit.SECONDS); } public void testInitiatorCrashesBeforeReleasingLock() throws Exception { final CountDownLatch releaseLocksLatch = new CountDownLatch(1); skipTxCompletion(advancedCache(1), releaseLocksLatch); MagicKey key = new MagicKey("k", cache(0)); Future<Void> future = beginAndCommitTx(key, 1); releaseLocksLatch.await(); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 0, 0); assert checkTxCount(2, 0, 1); assertLocked(cache(0), key); assertEventuallyNotLocked(cache(1), key); assertEventuallyNotLocked(cache(2), key); killMember(1); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); assertNotLocked(key); assert cache(0).get(key).equals("v"); assert cache(1).get(key).equals("v"); future.get(30, TimeUnit.SECONDS); } public void testInitiatorNodeCrashesBeforePrepare() throws Exception { MagicKey key = new MagicKey("a", cache(0)); cache(0).put(key, "b"); assert cache(0).get(key).equals("b"); assert cache(1).get(key).equals("b"); assert cache(2).get(key).equals("b"); TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); //prepare is sent, but is not precessed on other nodes because of the txControlInterceptor.preparedReceived Future<Void> future = beginAndPrepareTx("k", 1); eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); killMember(1); assert caches().size() == 2; txControlInterceptor.prepareProgress.countDown(); assertNotLocked("k"); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); future.get(30, TimeUnit.SECONDS); } }
3,707
35
174
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/pessimistic/BasicSingleLockRepPessimisticTest.java
package org.infinispan.lock.singlelock.replicated.pessimistic; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.MagicKey; import org.infinispan.lock.singlelock.AbstractNoCrashTest; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.replicated.pessimistic.BasicSingleLockRepPessimisticTest") public class BasicSingleLockRepPessimisticTest extends AbstractNoCrashTest { public BasicSingleLockRepPessimisticTest() { super(CacheMode.REPL_SYNC, LockingMode.PESSIMISTIC, false); } protected void testTxAndLockOnDifferentNodes(AbstractNoCrashTest.Operation operation, boolean addFirst, boolean removed) throws Exception { Object k = new MagicKey("k", cache(0)); if (addFirst) cache(0).put(k, "v_initial"); assertNotLocked(k); tm(0).begin(); operation.perform(k, 0); assert lockManager(0).isLocked(k); assert !lockManager(1).isLocked(k); assert !lockManager(2).isLocked(k); tm(0).commit(); assertNotLocked(k); assertValue(k, removed); } public void testMultipleLocksInSameTx() throws Exception { Object k1 = new MagicKey("k1", cache(0)); Object k2 = new MagicKey("k2", cache(0)); tm(0).begin(); cache(0).put(k1, "v"); cache(0).put(k2, "v"); assert lockManager(0).isLocked(k1); assert lockManager(0).isLocked(k2); assert !lockManager(1).isLocked(k1); assert !lockManager(1).isLocked(k2); assert !lockManager(1).isLocked(k2); assert !lockManager(2).isLocked(k2); tm(0).commit(); assertNotLocked(k1); assertNotLocked(k2); assertValue(k1, false); assertValue(k2, false); } public void testTxAndLockOnSameNode() throws Exception { Object k0 = new MagicKey("k0", cache(0)); tm(0).begin(); cache(0).put(k0, "v"); assert lockManager(0).isLocked(k0); assert !lockManager(1).isLocked(k0); assert !lockManager(2).isLocked(k0); tm(0).commit(); assertNotLocked(k0); assertValue(k0, false); } public void testSecondTxCannotPrepare1() throws Exception { Object k0 = new MagicKey("k0", cache(0)); tm(0).begin(); cache(0).put(k0, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).suspend(); assert checkTxCount(0, 1, 0); assert checkTxCount(1, 0, 0); assert checkTxCount(2, 0, 0); tm(0).begin(); try { cache(0).put(k0, "other"); assert false; } catch (Throwable e) { tm(0).rollback(); } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 0) && checkTxCount(2, 0, 0)); tm(1).begin(); try { cache(1).put(k0, "other"); assert false; } catch (Throwable e) { tm(0).rollback(); } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 0) && checkTxCount(2, 0, 0)); tm(0).resume(dtm); tm(0).commit(); assertValue(k0, false); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); } public void testSecondTxCannotPrepare2() throws Exception { Object k0 = new MagicKey("k0", cache(0)); tm(1).begin(); cache(1).put(k0, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(1).suspend(); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 1, 0); assert checkTxCount(2, 0, 1); tm(0).begin(); try { cache(0).put(k0, "other"); assert false; } catch (Throwable e) { tm(0).rollback(); } eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); tm(1).begin(); try { cache(1).put(k0, "other"); assert false; } catch (Throwable e) { tm(0).rollback(); } eventually(() -> checkTxCount(0, 0, 1) && checkTxCount(1, 1, 0) && checkTxCount(2, 0, 1)); tm(0).resume(dtm); tm(0).commit(); assertValue(k0, false); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); } }
4,372
26.853503
142
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/pessimistic/LockOwnerCrashPessimisticReplTest.java
package org.infinispan.lock.singlelock.replicated.pessimistic; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractLockOwnerCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "functional", testName = "lock.singlelock.replicated.pessimistic.LockOwnerCrashPessimisticReplTest") @CleanupAfterMethod public class LockOwnerCrashPessimisticReplTest extends AbstractLockOwnerCrashTest { public LockOwnerCrashPessimisticReplTest() { super(CacheMode.REPL_SYNC, LockingMode.PESSIMISTIC, false); } }
707
32.714286
115
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/optimistic/BasicSingleLockReplOptTest.java
package org.infinispan.lock.singlelock.replicated.optimistic; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.MagicKey; import org.infinispan.lock.singlelock.AbstractNoCrashTest; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.replicated.optimistic.BasicSingleLockReplOptTest") public class BasicSingleLockReplOptTest extends AbstractNoCrashTest { public BasicSingleLockReplOptTest() { super(CacheMode.REPL_SYNC, LockingMode.OPTIMISTIC, false); } protected void testTxAndLockOnDifferentNodes(Operation operation, boolean addFirst, boolean removed) throws Exception { MagicKey k = new MagicKey("k", cache(0)); if (addFirst) cache(0).put(k, "v_initial"); assertNotLocked(k); tm(0).begin(); operation.perform(k, 0); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert lockManager(0).isLocked(k); assert !lockManager(1).isLocked(k); assert !lockManager(2).isLocked(k); dtm.runCommit(false); assertNotLocked(k); assertValue(k, removed); } public void testMultipleLocksInSameTx() throws Exception { final Object k1 = new MagicKey("k1", cache(0)); final Object k2 = new MagicKey("k2", cache(0)); tm(0).begin(); cache(0).put(k1, "v"); cache(0).put(k2, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert lockManager(0).isLocked(k1); assert lockManager(0).isLocked(k2); assert !lockManager(1).isLocked(k1); assert !lockManager(1).isLocked(k2); assert !lockManager(1).isLocked(k2); assert !lockManager(2).isLocked(k2); dtm.runCommit(false); assertNotLocked(k1); assertNotLocked(k2); assertValue(k1, false); assertValue(k2, false); } public void testTxAndLockOnSameNode() throws Exception { Object k0 = new MagicKey("k0", cache(0)); tm(0).begin(); cache(0).put(k0, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); assert lockManager(0).isLocked(k0); assert !lockManager(1).isLocked(k0); assert !lockManager(2).isLocked(k0); dtm.runCommit(false); assertNotLocked(k0); assertValue(k0, false); } public void testSecondTxCannotPrepare() throws Exception { Object k0 = new MagicKey("k0", cache(0)); tm(0).begin(); cache(0).put(k0, "v"); EmbeddedTransaction dtm = (EmbeddedTransaction) tm(0).getTransaction(); dtm.runPrepare(); tm(0).suspend(); assert checkTxCount(0, 1, 0); assert checkTxCount(1, 0, 1); assert checkTxCount(2, 0, 1); tm(0).begin(); cache(0).put(k0, "other"); try { tm(0).commit(); assert false; } catch (Throwable e) { //ignore } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 1) && checkTxCount(2, 0, 1)); tm(1).begin(); cache(1).put(k0, "other"); try { tm(1).commit(); assert false; } catch (Throwable e) { //expected } eventually(() -> checkTxCount(0, 1, 0) && checkTxCount(1, 0, 1) && checkTxCount(2, 0, 1)); tm(0).resume(dtm); dtm.runCommit(false); assertValue(k0, false); eventually(() -> noPendingTransactions(0) && noPendingTransactions(1) && noPendingTransactions(2)); } }
3,712
26.917293
122
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/optimistic/InitiatorCrashOptimisticReplTest.java
package org.infinispan.lock.singlelock.replicated.optimistic; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test(groups = "unstable", testName = "lock.singlelock.replicated.optimistic.InitiatorCrashOptimisticReplTest", description = "See ISPN-2161 -- original group: functional") @CleanupAfterMethod public class InitiatorCrashOptimisticReplTest extends AbstractCrashTest { public InitiatorCrashOptimisticReplTest() { super(CacheMode.REPL_SYNC, LockingMode.OPTIMISTIC, false); } public InitiatorCrashOptimisticReplTest(CacheMode mode, LockingMode locking, boolean useSync) { super(mode, locking, useSync); } public void testInitiatorNodeCrashesBeforeCommit() throws Exception { TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); txControlInterceptor.prepareProgress.countDown(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); Future<Void> future = beginAndCommitTx("k", 1); txControlInterceptor.commitReceived.await(); assertLocked(cache(0), "k"); assertEventuallyNotLocked(cache(1), "k"); assertEventuallyNotLocked(cache(2), "k"); checkTxCount(0, 0, 1); checkTxCount(1, 1, 0); checkTxCount(2, 0, 1); killMember(1); assertNotLocked("k"); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); future.get(30, TimeUnit.SECONDS); } public void testInitiatorCrashesBeforeReleasingLock() throws Exception { final CountDownLatch releaseLocksLatch = new CountDownLatch(1); skipTxCompletion(advancedCache(1), releaseLocksLatch); Future<Void> future = beginAndCommitTx("k", 1); releaseLocksLatch.await(); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 0, 0); assert checkTxCount(2, 0, 1); assertLocked(cache(0), "k"); assertEventuallyNotLocked(cache(1), "k"); assertEventuallyNotLocked(cache(2), "k"); killMember(1); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); assertNotLocked("k"); assert cache(0).get("k").equals("v"); assert cache(1).get("k").equals("v"); future.get(30, TimeUnit.SECONDS); } public void testInitiatorNodeCrashesBeforePrepare() throws Exception { TxControlInterceptor txControlInterceptor = new TxControlInterceptor(); extractInterceptorChain(advancedCache(1)).addInterceptor(txControlInterceptor, 1); //prepare is sent, but is not precessed on other nodes because of the txControlInterceptor.preparedReceived Future<Void> future = beginAndPrepareTx("k", 1); txControlInterceptor.preparedReceived.await(); assert checkTxCount(0, 0, 1); assert checkTxCount(1, 1, 0); assert checkTxCount(2, 0, 1); killMember(1); assert caches().size() == 2; txControlInterceptor.prepareProgress.countDown(); assertNotLocked("k"); eventually(() -> checkTxCount(0, 0, 0) && checkTxCount(1, 0, 0)); future.get(30, TimeUnit.SECONDS); } }
3,496
32.951456
172
java
null
infinispan-main/core/src/test/java/org/infinispan/lock/singlelock/replicated/optimistic/LockOwnerCrashOptimisticReplTest.java
package org.infinispan.lock.singlelock.replicated.optimistic; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.lock.singlelock.AbstractLockOwnerCrashTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.1 */ @Test (groups = "functional", testName = "lock.singlelock.replicated.optimistic.LockOwnerCrashOptimisticReplTest") @CleanupAfterMethod public class LockOwnerCrashOptimisticReplTest extends AbstractLockOwnerCrashTest { public LockOwnerCrashOptimisticReplTest() { super(CacheMode.REPL_SYNC, LockingMode.OPTIMISTIC, false); } @Override protected Object getKeyForCache(int nodeIndex) { return "k" + nodeIndex; } }
803
29.923077
114
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BaseSiteUnreachableTest.java
package org.infinispan.xsite; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.TestDataSCI; public abstract class BaseSiteUnreachableTest extends AbstractXSiteTest { public static final String LON = "LON-1"; public static final String NYC = "NYC-2"; protected BackupFailurePolicy lonBackupFailurePolicy = BackupFailurePolicy.WARN; protected BackupConfiguration.BackupStrategy lonBackupStrategy = BackupConfiguration.BackupStrategy.SYNC; protected String lonCustomFailurePolicyClass = null; protected int failures = 0; @Override protected void createSites() { GlobalConfigurationBuilder lonGc = GlobalConfigurationBuilder.defaultClusteredBuilder(); lonGc.serialization().addContextInitializer(TestDataSCI.INSTANCE); ConfigurationBuilder lon = getLonActiveConfig(); lon.sites().addBackup() .site(NYC) .backupFailurePolicy(lonBackupFailurePolicy) .replicationTimeout(100) //keep it small so that the test doesn't take long to run .takeOffline().afterFailures(failures). backup() .strategy(lonBackupStrategy) .failurePolicyClass(lonCustomFailurePolicyClass); createSite(LON, 2, lonGc, lon); } protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } }
1,684
39.119048
108
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/AbstractTwoSitesTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.TestDataSCI; import org.infinispan.transaction.LockingMode; /** * @author Mircea Markus * @since 5.2 */ public abstract class AbstractTwoSitesTest extends AbstractXSiteTest { protected static final String LON = "LON-1"; protected static final String NYC = "NYC-2"; protected BackupFailurePolicy lonBackupFailurePolicy = BackupFailurePolicy.WARN; protected boolean isLonBackupTransactional = false; protected BackupConfiguration.BackupStrategy lonBackupStrategy = BackupConfiguration.BackupStrategy.SYNC; protected BackupConfiguration.BackupStrategy nycBackupStrategy = BackupConfiguration.BackupStrategy.SYNC; protected String lonCustomFailurePolicyClass = null; protected boolean use2Pc = false; protected int initialClusterSize = 2; /** * If true, the caches from one site will backup to a cache having the same name remotely (mirror) and the backupFor * config element won't be used. */ protected boolean implicitBackupCache = false; protected CacheMode cacheMode; protected boolean transactional; protected LockingMode lockingMode; @Override protected void createSites() { ConfigurationBuilder lon = lonConfigurationBuilder(); ConfigurationBuilder nyc = getNycActiveConfig(); nyc.sites().addBackup() .site(LON) .strategy(nycBackupStrategy); nyc.sites().addBackup() .site(NYC) .strategy(nycBackupStrategy); createSite(LON, initialClusterSize, globalConfigurationBuilderForSite(LON), lon); createSite(NYC, initialClusterSize, globalConfigurationBuilderForSite(NYC), nyc); if (!implicitBackupCache) { ConfigurationBuilder nycBackup = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); nycBackup.sites().backupFor().remoteSite(NYC).remoteCache(getDefaultCacheName()); startCache(LON, "nycBackup", nycBackup); ConfigurationBuilder lonBackup = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, isLonBackupTransactional); lonBackup.sites().backupFor().remoteSite(LON).remoteCache(getDefaultCacheName()); startCache(NYC, "lonBackup", lonBackup); Configuration lonBackupConfig = cache(NYC, "lonBackup", 0).getCacheConfiguration(); assertTrue(lonBackupConfig.sites().backupFor().isBackupFor(LON, getDefaultCacheName())); } waitForSites(LON, NYC); } protected ConfigurationBuilder lonConfigurationBuilder() { ConfigurationBuilder lon = getLonActiveConfig(); BackupConfigurationBuilder lonBackupConfigurationBuilder = lon.sites().addBackup(); lonBackupConfigurationBuilder .site(NYC) .backupFailurePolicy(lonBackupFailurePolicy) .strategy(lonBackupStrategy) .failurePolicyClass(lonCustomFailurePolicyClass) .useTwoPhaseCommit(use2Pc) .stateTransfer().maxRetries(1).waitTime(500); adaptLONConfiguration(lonBackupConfigurationBuilder); // it shouldn't backup to itself lon.sites().addBackup().site(LON).strategy(lonBackupStrategy); return lon; } protected GlobalConfigurationBuilder globalConfigurationBuilderForSite(String siteName) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { //no-op } protected Cache<Object, Object> backup(String site) { return backup(site, 0); } protected Cache<Object, Object> backup(String site, int offset) { if (site.equals(LON)) return implicitBackupCache ? cache(NYC, offset) : cache(NYC, "lonBackup", offset); if (site.equals(NYC)) return implicitBackupCache ? cache(LON, offset) : cache(LON, "nycBackup", offset); throw new IllegalArgumentException("No such site: " + site); } protected String val(String site) { return "v_" + site; } protected String key(String site) { return "k_" + site; } public AbstractTwoSitesTest cacheMode(CacheMode cacheMode) { this.cacheMode = cacheMode; return this; } public AbstractTwoSitesTest transactional(boolean transactional) { this.transactional = transactional; return this; } public AbstractTwoSitesTest lockingMode(LockingMode lockingMode) { this.lockingMode = lockingMode; return this; } public AbstractTwoSitesTest use2Pc(boolean use2Pc) { this.use2Pc = use2Pc; return this; } @Override protected String[] parameterNames() { return new String[] {null, "tx", "lockingMode", null}; } @Override protected Object[] parameterValues() { return new Object[] {cacheMode, transactional, lockingMode, use2Pc ? "2PC" : null}; } protected abstract ConfigurationBuilder getNycActiveConfig(); protected abstract ConfigurationBuilder getLonActiveConfig(); }
5,592
36.790541
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BackupReceiverDelegator.java
package org.infinispan.xsite; import java.util.concurrent.CompletionStage; import org.infinispan.commands.VisitableCommand; import org.infinispan.metadata.Metadata; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand; import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; /** * {@link org.infinispan.xsite.BackupReceiver} delegator. Mean to be overridden. For test purpose only! * * @author Pedro Ruivo * @since 7.0 */ public abstract class BackupReceiverDelegator implements BackupReceiver { protected final BackupReceiver delegate; protected BackupReceiverDelegator(BackupReceiver delegate) { if (delegate == null) { throw new NullPointerException("Delegate cannot be null"); } this.delegate = delegate; } @Override public <O> CompletionStage<O> handleRemoteCommand(VisitableCommand command, boolean preserveOrder) { return delegate.handleRemoteCommand(command, preserveOrder); } @Override public CompletionStage<Void> putKeyValue(Object key, Object value, Metadata metadata, IracMetadata iracMetadata) { return delegate.putKeyValue(key, value, metadata, iracMetadata); } @Override public CompletionStage<Void> removeKey(Object key, IracMetadata iracMetadata, boolean expiration) { return delegate.removeKey(key, iracMetadata, expiration); } @Override public CompletionStage<Void> clearKeys() { return delegate.clearKeys(); } @Override public CompletionStage<Void> handleStartReceivingStateTransfer(XSiteStateTransferStartReceiveCommand command) { return delegate.handleStartReceivingStateTransfer(command); } @Override public CompletionStage<Void> handleEndReceivingStateTransfer(XSiteStateTransferFinishReceiveCommand command) { return delegate.handleEndReceivingStateTransfer(command); } @Override public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) { return delegate.handleStateTransferState(cmd); } @Override public CompletionStage<Boolean> touchEntry(Object key) { return delegate.touchEntry(key); } }
2,283
31.628571
114
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/NoFailureAsyncReplWarnFailurePolicyTest.java
package org.infinispan.xsite; import static org.testng.Assert.assertNull; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test (groups = "xsite", testName = "xsite.NoFailureAsyncReplWarnFailurePolicyTest") public class NoFailureAsyncReplWarnFailurePolicyTest extends BaseSiteUnreachableTest { public NoFailureAsyncReplWarnFailurePolicyTest() { lonBackupStrategy = BackupConfiguration.BackupStrategy.SYNC; lonBackupFailurePolicy = BackupFailurePolicy.WARN; } public void testNoFailures() { cache(LON, 0).put("k", "v"); assertEquals(cache(LON, 0).get("k"), "v"); assertEquals(cache(LON, 1).get("k"), "v"); cache(LON, 1).remove("k"); assertNull(cache(LON, 0).get("k")); assertNull(cache(LON, 1).get("k")); cache(LON, 0).putAll(Collections.singletonMap("k", "v")); assertEquals(cache(LON, 0).get("k"), "v"); assertEquals(cache(LON, 1).get("k"), "v"); } protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } }
1,386
33.675
86
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/RollbackNoPreparePessimisticTest.java
package org.infinispan.xsite; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; @Test (groups = "xsite", testName = "xsite.RollbackNoPreparePessimisticTest") public class RollbackNoPreparePessimisticTest extends RollbackNoPrepareOptimisticTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return getPessimisticDistTxConnfig(); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getPessimisticDistTxConnfig(); } private ConfigurationBuilder getPessimisticDistTxConnfig() { ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); cb.transaction().lockingMode(LockingMode.PESSIMISTIC); return cb; } }
879
31.592593
90
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/AbstractXSiteTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.api.Lifecycle; import org.infinispan.commons.configuration.Combine; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.versioning.irac.DefaultIracTombstoneManager; import org.infinispan.container.versioning.irac.IracTombstoneManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.xsite.irac.DefaultIracManager; import org.infinispan.xsite.irac.IracManager; import org.infinispan.xsite.irac.ManualIracManager; import org.infinispan.xsite.status.DefaultTakeOfflineManager; import org.infinispan.xsite.status.TakeOfflineManager; import org.jgroups.protocols.relay.RELAY2; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; /** * @author Mircea Markus */ public abstract class AbstractXSiteTest extends AbstractCacheTest { protected final List<TestSite> sites = new ArrayList<>(); private final Map<String, Integer> siteName2index = new HashMap<>(); @BeforeMethod(alwaysRun = true) // run even for tests in the unstable group public void createBeforeMethod() { if (cleanupAfterMethod()) createSites(); } @BeforeClass(alwaysRun = true) // run even for tests in the unstable group public void createBeforeClass() { if (cleanupAfterTest()) createSites(); } @AfterMethod(alwaysRun = true) // run even if the test failed protected void clearContent() throws Throwable { if (cleanupAfterTest()) { clearSites(); } else { killSites(); } } private void clearSites() { for (TestSite ts : sites) { clearSite(ts); } } protected void clearSite(TestSite ts) { TestingUtil.clearContent(ts.cacheManagers); } @AfterClass(alwaysRun = true) // run even if the test failed protected void destroy() { if (cleanupAfterTest()) { killSites(); } } protected void killSites() { for (TestSite ts : sites) { killSite(ts); } sites.clear(); siteName2index.clear(); } protected void killSite(String siteName) { Integer index = siteName2index.remove(siteName); if (index == null) { return; } TestSite site = sites.remove(index.intValue()); killSite(site); } protected void killSite(TestSite ts) { ts.cacheManagers.forEach(Lifecycle::stop); } protected void stopSite(int siteIndex) { TestSite site = site(siteIndex); List<EmbeddedCacheManager> cacheManagers = site.cacheManagers; while (!cacheManagers.isEmpty()) { cacheManagers.remove(cacheManagers.size() - 1).stop(); if (!cacheManagers.isEmpty()) { site.waitForClusterToForm(null); } } assertTrue(site.cacheManagers.isEmpty()); } protected abstract void createSites(); protected TestSite createSite(String siteName, int numNodes, GlobalConfigurationBuilder gcb, ConfigurationBuilder cb) { return createSite(siteName, numNodes, gcb, null, cb); } protected TestSite createSite(String siteName, int numNodes, GlobalConfigurationBuilder gcb, String cacheName, ConfigurationBuilder cb) { TestSite testSite = addSite(siteName); testSite.createClusteredCaches(numNodes, cacheName, gcb, cb); return testSite; } protected TestSite addSite(String siteName) { TestSite testSite = new TestSite(siteName, sites.size()); sites.add(testSite); siteName2index.put(siteName, sites.size() - 1); return testSite; } public void waitForSites() { waitForSites(10, TimeUnit.SECONDS, siteName2index.keySet().toArray(new String[0])); } /** * Wait for all the site masters to see a specific list of sites. */ public void waitForSites(String... siteNames) { waitForSites(10, TimeUnit.SECONDS, siteNames); } /** * Wait for all the site masters to see a specific list of sites. */ public void waitForSites(long timeout, TimeUnit unit, String... siteNames) { long deadlineNanos = System.nanoTime() + unit.toNanos(timeout); Set<String> expectedSites = new HashSet<>(Arrays.asList(siteNames)); sites.forEach(site -> { site.cacheManagers.forEach(manager -> { RELAY2 relay2 = ((JGroupsTransport) manager.getTransport()).getChannel().getProtocolStack() .findProtocol(RELAY2.class); if (!relay2.isSiteMaster()) return; while (System.nanoTime() - deadlineNanos < 0) { if (expectedSites.equals(manager.getTransport().getSitesView())) break; LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); } Set<String> currentSitesView = manager.getTransport().getSitesView(); if (!expectedSites.equals(currentSitesView)) { throw new AssertionError(String.format("Timed out waiting for bridge view %s on %s after %d %s. Current bridge view is %s", expectedSites, manager.getAddress(), timeout, unit, currentSitesView)); } }); }); } protected TestSite site(int index) { return sites.get(index); } protected EmbeddedCacheManager manager(int siteIndex, int managerIndex) { return sites.get(siteIndex).cacheManagers().get(managerIndex); } protected TestSite site(String name) { return sites.get(siteName2index.get(name)); } protected <K,V> Cache<K,V> cache(String site, int index) { return site(site).cache(index); } protected <K,V> Cache<K,V> cache(String site, String cacheName, int index) { return site(site).cache(cacheName, index); } protected <K,V> Cache<K,V> cache(int siteIndex, String cacheName, int nodeIndex) { return site(siteIndex).cache(cacheName, nodeIndex); } protected <K,V> List<Cache<K,V>> caches(String site) { return caches(site, null); } protected <K,V> List<Cache<K,V>> caches(String site, String cacheName) { return Collections.unmodifiableList(site(site).getCaches(cacheName)); } protected <K,V> List<Cache<K,V>> caches(int siteIndex) { return caches(siteIndex, null); } protected <K,V> List<Cache<K,V>> caches(int siteIndex, String cacheName) { return Collections.unmodifiableList(site(siteIndex).getCaches(cacheName)); } protected <K, V> Cache<K,V> cache(int siteIndex, int cacheIndex) { return site(siteIndex).cache(cacheIndex); } protected <K, V> Cache<K,V> cache(int siteIndex, int cacheIndex, String cacheName) { return site(siteIndex).cache(cacheName, cacheIndex); } protected void startCache(String siteName, String cacheName, ConfigurationBuilder configurationBuilder) { TestSite site = site(siteName); for (EmbeddedCacheManager ecm : site.cacheManagers) { Configuration config = configurationBuilder.build(); ecm.defineConfiguration(cacheName, getDefaultCacheName(), config); } site.waitForClusterToForm(cacheName); } protected final <K, V> void assertInSite(String siteName, AssertCondition<K, V> condition) { for (Cache<K, V> cache : this.<K, V>caches(siteName)) { condition.assertInCache(cache); } } protected final <K, V> void assertInSite(String siteName, String cacheName, AssertCondition<K, V> condition) { for (Cache<K, V> cache : this.<K, V>caches(siteName, cacheName)) { condition.assertInCache(cache); } } protected final <K, V> void assertEventuallyInSite(final String siteName, final EventuallyAssertCondition<K, V> condition, long timeout, TimeUnit timeUnit) { eventually(() -> { for (Cache<K, V> cache : AbstractXSiteTest.this.<K, V>caches(siteName)) { if (!condition.assertInCache(cache)) { return false; } } return true; }, timeUnit.toMillis(timeout)); } protected final <K, V> void assertEventuallyInSite(final String siteName, final String cacheName, final EventuallyAssertCondition<K, V> condition, long timeout, TimeUnit timeUnit) { eventually(() -> { for (Cache<K, V> cache : AbstractXSiteTest.this.<K, V>caches(siteName, cacheName)) { if (!condition.assertInCache(cache)) { return false; } } return true; }, timeUnit.toMillis(timeout)); } protected RELAY2 getRELAY2(EmbeddedCacheManager cacheManager) { JGroupsTransport transport = (JGroupsTransport) cacheManager.getTransport(); return transport.getChannel().getProtocolStack().findProtocol(RELAY2.class); } protected interface AssertCondition<K, V> { void assertInCache(Cache<K, V> cache); } protected interface EventuallyAssertCondition<K, V> { boolean assertInCache(Cache<K, V> cache); } protected void decorateGlobalConfiguration(GlobalConfigurationBuilder builder, int siteIndex, int nodeIndex) { } protected void decorateCacheConfiguration(ConfigurationBuilder builder, int siteIndex, int nodeIndex) { } public class TestSite { protected List<EmbeddedCacheManager> cacheManagers = new ArrayList<>(); private final String siteName; private final int siteIndex; public TestSite(String siteName, int siteIndex) { this.siteName = siteName; this.siteIndex = siteIndex; } public String getSiteName() { return siteName; } public int getSiteIndex() { return siteIndex; } public EmbeddedCacheManager addCacheManager(String cacheName, GlobalConfigurationBuilder globalTemplate, ConfigurationBuilder cacheTemplate, boolean waitForCluster) { final int i = cacheManagers.size(); final TransportFlags flags = transportFlags(); GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.read(globalTemplate.build()); decorateGlobalConfiguration(gcb, siteIndex, i); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.read(cacheTemplate.build(), Combine.DEFAULT); decorateCacheConfiguration(builder, siteIndex, i); ConfigurationBuilder defaultBuilder = cacheName == null ? builder : null; EmbeddedCacheManager cm = addClusterEnabledCacheManager(flags, gcb, defaultBuilder); if (cacheName != null) { cm.defineConfiguration(cacheName, builder.build()); cm.getCache(cacheName); } if (waitForCluster) { waitForClusterToForm(cacheName); } return cm; } private TransportFlags transportFlags() { return new TransportFlags().withSiteIndex(siteIndex).withSiteName(siteName).withFD(true); } protected <K, V> List<Cache<K, V>> createClusteredCaches(int numMembersInCluster, String cacheName, GlobalConfigurationBuilder globalTemplate, ConfigurationBuilder cacheTemplate) { return createClusteredCaches(numMembersInCluster, cacheName, globalTemplate, cacheTemplate, false); } protected <K, V> List<Cache<K, V>> createClusteredCaches(int numMembersInCluster, String cacheName, GlobalConfigurationBuilder globalTemplate, ConfigurationBuilder cacheTemplate, boolean waitBetweenCacheManager) { List<Cache<K, V>> caches = new ArrayList<>(numMembersInCluster); for (int i = 0; i < numMembersInCluster; i++) { EmbeddedCacheManager cm = addCacheManager(cacheName, globalTemplate, cacheTemplate, waitBetweenCacheManager); if (cacheName != null) { caches.add(cm.getCache(cacheName)); } else { caches.add(cm.getCache()); } } waitForClusterToForm(cacheName); return caches; } protected EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags, GlobalConfigurationBuilder gcb, ConfigurationBuilder builder) { GlobalConfigurationBuilder clone = GlobalConfigurationBuilder.defaultClusteredBuilder(); //get the transport here as clone.read below would inject the same transport reference into the clone // which we don't want Transport transport = clone.transport().getTransport(); GlobalConfiguration original = gcb.build(); clone.read(original); clone.transport().transport(transport); clone.transport().clusterName("ISPN(SITE " + siteName + ")"); if (original.jmx().enabled()) { clone.jmx().enabled(true).domain(original.jmx().domain() + cacheManagers.size()); } EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(clone, builder, flags); cacheManagers.add(cm); return cm; } public void waitForClusterToForm(String cacheName) { List<Cache<Object, Object>> caches = getCaches(cacheName); Cache<Object, Object> cache = caches.get(0); TestingUtil.blockUntilViewsReceived(10000, caches); if (cache.getCacheConfiguration().clustering().cacheMode().isDistributed()) { TestingUtil.waitForNoRebalance(caches); } } public void waitForClusterToForm(String cacheName, long timeout, TimeUnit timeUnit) { List<Cache<Object, Object>> caches = getCaches(cacheName); Cache<Object, Object> cache = caches.get(0); TestingUtil.blockUntilViewsReceived((int) timeUnit.toMillis(timeout), false, caches); if (cache.getCacheConfiguration().clustering().cacheMode().isDistributed()) { TestingUtil.waitForNoRebalance(caches); } } public <K, V> List<Cache<K, V>> getCaches(String cacheName) { List<Cache<K,V>> caches = new ArrayList<>(cacheManagers.size()); for (EmbeddedCacheManager cm : cacheManagers) { caches.add(cacheName == null ? cm.getCache() : cm.getCache(cacheName)); } return caches; } public void addCache(GlobalConfigurationBuilder gBuilder, ConfigurationBuilder builder) { addCache(null, gBuilder, builder); } public void addCache(String cacheName, GlobalConfigurationBuilder gBuilder, ConfigurationBuilder builder) { EmbeddedCacheManager cm = addClusterEnabledCacheManager(transportFlags(), gBuilder, builder); if (cacheName != null) cm.defineConfiguration(cacheName, builder.build()); } public void kill(int index) { TestingUtil.killCacheManagers(cacheManagers.remove(index)); } public <K,V> Cache<K,V> cache(int index) { return cacheManagers.get(index).getCache(); } public <K,V> AdvancedCache<K,V> advancedCache(int index) { Cache<K, V> cache = cache(index); return cache.getAdvancedCache(); } public <K, V> Cache<K, V> cache(String cacheName, int index) { return cacheName == null ? cache(index) : cacheManagers.get(index).getCache(cacheName); } public List<EmbeddedCacheManager> cacheManagers() { return Collections.unmodifiableList(cacheManagers); } } protected TransactionTable txTable(Cache cache) { return cache.getAdvancedCache().getComponentRegistry().getComponent(TransactionTable.class); } protected DefaultTakeOfflineManager takeOfflineManager(String site, String cacheName, int index) { return (DefaultTakeOfflineManager) cache(site, cacheName, index).getAdvancedCache() .getComponentRegistry() .getComponent(TakeOfflineManager.class); } protected DefaultTakeOfflineManager takeOfflineManager(String site, int index) { return (DefaultTakeOfflineManager) cache(site, index).getAdvancedCache() .getComponentRegistry() .getComponent(TakeOfflineManager.class); } protected DefaultIracManager iracManager(String site, String cacheName, int index) { return (DefaultIracManager) TestingUtil.extractComponent(cache(site, cacheName, index), IracManager.class); } protected boolean isIracManagerEmpty(Cache<?, ?> cache) { IracManager manager = TestingUtil.extractComponent(cache, IracManager.class); if (manager instanceof ManualIracManager) { return ((ManualIracManager) manager).isEmpty(); } else if (manager instanceof DefaultIracManager) { return ((DefaultIracManager) manager).isEmpty(); } else { return true; } } protected DefaultIracTombstoneManager iracTombstoneManager(Cache<?, ?> cache) { return (DefaultIracTombstoneManager) TestingUtil.extractComponent(cache, IracTombstoneManager.class); } @Override protected final String parameters() { return defaultParametersString(parameterNames(), parameterValues()); } protected String[] parameterNames() { return new String[0]; } protected Object[] parameterValues() { return new Object[0]; } }
18,637
37.036735
210
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/CustomXSiteEntryMergePolicy.java
package org.infinispan.xsite; import java.util.Objects; import java.util.concurrent.CompletionStage; import org.infinispan.xsite.spi.SiteEntry; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; /** * @author Pedro Ruivo * @since 12.0 */ public class CustomXSiteEntryMergePolicy<K, V> implements XSiteEntryMergePolicy<K, V> { @Override public CompletionStage<SiteEntry<V>> merge(K key, SiteEntry<V> localEntry, SiteEntry<V> remoteEntry) { return null; //just for config test. not really used. } @Override public boolean equals(Object obj) { return obj != null && Objects.equals(obj.getClass(), getClass()); } }
653
25.16
105
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/ImplicitBackupCacheStoppedTest.java
package org.infinispan.xsite; import org.testng.annotations.Test; @Test(groups = "xsite", testName = "xsite.ImplicitBackupCacheStoppedTest") public class ImplicitBackupCacheStoppedTest extends BackupCacheStoppedTest { public ImplicitBackupCacheStoppedTest() { implicitBackupCache = true; } }
306
26.909091
76
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/XSiteCacheConfigurationTest.java
package org.infinispan.xsite; import static org.testng.Assert.assertEquals; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea.Markus@jboss.com * @since 5.2 */ @Test(groups = {"functional", "xsite"}, testName = "xsite.XSiteCacheConfigurationTest") public class XSiteCacheConfigurationTest { public static final String LON = "LON-1"; public static final String NYC = "NYC-2"; public static final String SFO = "SFO-3"; public void testApi() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.SYNC) .sites().addBackup() .site(SFO) .sites().addBackup() .site(NYC); assertEquals(cb.sites().backups().size(), 3); BackupConfigurationBuilder backup0 = cb.sites().backups().get(0); assertEquals(backup0.site(), LON); assertEquals(backup0.strategy(), BackupConfiguration.BackupStrategy.SYNC); BackupConfigurationBuilder backup1 = cb.sites().backups().get(1); assertEquals(backup1.site(), SFO); assertEquals(backup1.strategy(), BackupConfiguration.BackupStrategy.ASYNC); BackupConfigurationBuilder backup2 = cb.sites().backups().get(2); assertEquals(backup2.site(), NYC); assertEquals(backup2.strategy(), BackupConfiguration.BackupStrategy.ASYNC); Configuration b = cb.build(); assertEquals(b.sites().allBackups().size(), 3); BackupConfiguration b0 = b.sites().allBackups().get(0); assertEquals(b0.site(), LON); assertEquals(b0.strategy(), BackupConfiguration.BackupStrategy.SYNC); BackupConfiguration b1 = b.sites().allBackups().get(1); assertEquals(b1.site(), SFO); assertEquals(b1.strategy(), BackupConfiguration.BackupStrategy.ASYNC); BackupConfigurationBuilder b2 = cb.sites().backups().get(2); assertEquals(b2.site(), NYC); assertEquals(b2.strategy(), BackupConfiguration.BackupStrategy.ASYNC); } @Test (expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: Multiple sites have the same name 'LON-1'. This configuration is not valid.") public void testSameBackupDefinedMultipleTimes() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.SYNC) .sites().addBackup() .site(LON) .sites().addBackup() .site(NYC); cb.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: Backup configuration must include a 'site'.") public void testBackupSiteNotSpecified() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(); cb.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: You must specify a 'failure-policy-class' to use a custom backup failure policy for backup 'LON-1'.") public void testCustomBackupFailurePolicyClassNotSpecified() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(LON) .backupFailurePolicy(BackupFailurePolicy.CUSTOM) .failurePolicyClass(); cb.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: Two-phase commit can only be used with synchronous backup strategy.") public void testTwoPhaseCommitAsyncBackup() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.ASYNC) .useTwoPhaseCommit(true); cb.build(); } public void testMultipleCachesWithNoCacheName() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.clustering().cacheMode(CacheMode.DIST_SYNC); cb. sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.SYNC) .sites().addBackup() .site(SFO) .sites().addBackup() .site(NYC); cb.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: Cross-site replication not available for local cache.") public void testLocalCache() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.sites().addBackup().site(LON); builder.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: Cross-site replication not available for local cache.") public void testLocalCacheWithBackupFor() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.sites().backupFor().remoteCache("remote").remoteSite(LON); builder.build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN\\d+: The XSiteEntryMergePolicy is missing. The cache configuration must include a merge policy.") public void testNullXSiteEntryMergePolicy() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.sites().mergePolicy(null); builder.build(); } }
6,228
41.087838
211
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/CacheOperationsTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.functional.FunctionalMap.ReadWriteMap; import org.infinispan.functional.FunctionalMap.WriteOnlyMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.functional.impl.WriteOnlyMapImpl; import org.infinispan.marshall.core.MarshallableFunctions; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.CacheOperationsTest") public class CacheOperationsTest extends AbstractTwoSitesTest { @Factory public Object[] factory() { return new Object[] { new CacheOperationsTest().cacheMode(CacheMode.DIST_SYNC).transactional(false), new CacheOperationsTest().cacheMode(CacheMode.REPL_SYNC).transactional(false), new CacheOperationsTest().cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC).use2Pc(false), new CacheOperationsTest().cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC).use2Pc(true), new CacheOperationsTest().cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC), new CacheOperationsTest().cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC).use2Pc(false), new CacheOperationsTest().cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC).use2Pc(true), new CacheOperationsTest().cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC), }; } public CacheOperationsTest() { // We need both owner an non-owner setup initialClusterSize = 3; } protected ConfigurationBuilder getNycActiveConfig() { ConfigurationBuilder cb = getDefaultClusteredCacheConfig(cacheMode, transactional); if (lockingMode != null) { cb.transaction().lockingMode(lockingMode); } return cb; } protected ConfigurationBuilder getLonActiveConfig() { return getNycActiveConfig(); } public void testRemove() { testRemove(LON); testRemove(NYC); } public void testPutAndClear() { testPutAndClear(LON); testPutAndClear(NYC); } public void testReplace() { testReplace(LON); testReplace(NYC); } public void testPutAll() { testPutAll(LON); testPutAll(NYC); } private void testRemove(String site) { String key = key(site); String val = val(site); cache(site, 0).put(key, val); assertEquals(backup(site).get(key), val); cache(site, 0).remove(key); assertNull(backup(site).get(key)); cache(site, 0).put(key, val); assertEquals(backup(site).get(key), val); cache(site, 0).remove(key, val); assertNull(backup(site).get(key)); } private void testReplace(String site) { String key = key(site); String val = val(site); cache(site, 0).put(key, val); Cache<Object, Object> backup = backup(site); assertEquals(backup.get(key), val); String val2 = val + 1; cache(site, 0).replace(key, val2); assertEquals(backup.get(key), val2); String val3 = val+2; cache(site, 0).replace(key, "v_non", val3); assertEquals(backup.get(key), val2); cache(site, 0).replace(key, val2, val3); assertEquals(backup.get(key), val3); } private void testPutAndClear(String site) { String key = key(site); String val = val(site); cache(site, 0).put(key, val); assertEquals(backup(site).get(key), val); cache(site, 0).clear(); assertNull(backup(site).get(key+1)); assertNull(backup(site).get(key)); } private void testPutAll( String site) { Map all = new HashMap(); String key = key(site); String val = val(site); for (int i = 0; i < 10; i++) { all.put(key + i, val + i); } cache(site, 0).putAll(all); for (int i = 0; i < 10; i++) { assertEquals(backup(site).get(key + i), val + i); } } public void testDataGetsReplicated() { cache(LON, 0).put("k_lon", "v_lon"); assertNull(cache(NYC, 0).get("k_lon")); assertEquals(cache(LON, 1).get("k_lon"), "v_lon"); assertEquals(cache(NYC, "lonBackup", 0).get("k_lon"), "v_lon"); assertEquals(cache(NYC, "lonBackup", 1).get("k_lon"), "v_lon"); cache(NYC,1).put("k_nyc", "v_nyc"); assertEquals(cache(LON, 1).get("k_lon"), "v_lon"); assertEquals(cache(LON, "nycBackup", 0).get("k_nyc"), "v_nyc"); assertEquals(cache(LON, "nycBackup", 1).get("k_nyc"), "v_nyc"); assertNull(cache(LON, 0).get("k_nyc")); cache(LON, 1).remove("k_lon"); assertNull(cache(LON, 1).get("k_lon")); assertNull(cache(NYC, "lonBackup", 0).get("k_lon")); assertNull(cache(NYC, "lonBackup", 1).get("k_lon")); } public void testPutWithLocality() { MagicKey remoteOwnedKey = new MagicKey(cache(LON, 1)); cache(LON, 0).put(remoteOwnedKey, "v_LON"); assertEquals(cache(NYC, "lonBackup", 0).get(remoteOwnedKey), "v_LON"); assertEquals(cache(NYC, "lonBackup", 1).get(remoteOwnedKey), "v_LON"); MagicKey localOwnedKey = new MagicKey(cache(LON, 0)); cache(LON, 0).put(localOwnedKey, "v_LON"); assertEquals(cache(NYC, "lonBackup", 0).get(remoteOwnedKey), "v_LON"); assertEquals(cache(NYC, "lonBackup", 1).get(remoteOwnedKey), "v_LON"); } public void testFunctional() throws Exception { testFunctional(LON); testFunctional(NYC); } private void testFunctional(String site) throws Exception { FunctionalMapImpl<Object, Object> fmap = FunctionalMapImpl.create(cache(site, 0).getAdvancedCache()); WriteOnlyMap<Object, Object> wo = WriteOnlyMapImpl.create(fmap); ReadWriteMap<Object, Object> rw = ReadWriteMapImpl.create(fmap); Cache<Object, Object> backup = backup(site); Object[] keys = { new MagicKey("k0", cache(site, 0), cache(site, 1)), new MagicKey("k1", cache(site, 1), cache(site, 0)), new MagicKey("k2", cache(site, 1), cache(site, 2)) }; for (Object key : keys) { wo.eval(key, "v0", MarshallableFunctions.setValueConsumer()).join(); assertEquals("v0", backup.get(key)); } for (Object key : keys) { wo.eval(key, MarshallableFunctions.removeConsumer()).join(); assertEquals(null, backup.get(key)); } wo.evalMany(map(keys, "v1"), MarshallableFunctions.setValueConsumer()).join(); for (Object key : keys) { assertEquals("v1", backup.get(key)); } for (Object key : keys) { rw.eval(key, view -> view.set(view.get() + "+2")).join(); assertEquals("v1+2", backup.get(key)); } rw.evalMany(Util.asSet(keys), view -> view.set(view.get() + "+3")) .forEach(ret -> assertEquals(null, ret)); for (Object key : keys) { assertEquals("v1+2+3", backup.get(key)); } wo.evalMany(Util.asSet(keys), MarshallableFunctions.removeConsumer()).join(); for (Object key : keys) { assertEquals(null, backup.get(key)); } rw.evalMany(Util.asSet(keys), view -> view.find().orElse("none")) .forEach(ret -> assertEquals("none", ret)); for (Object key : keys) { assertEquals(null, backup.get(key)); } if (transactional) { TransactionManager tm = cache(site, 0).getAdvancedCache().getTransactionManager(); tm.begin(); rw.eval(keys[0], "v4", MarshallableFunctions.setValueReturnPrevOrNull()).join(); //read-only evalMany rw.evalMany(Util.asSet(keys[1], keys[2]), view -> view.find().orElse("none")) .forEach(ret -> assertEquals("none", ret)); tm.commit(); assertEquals("v4", backup.get(keys[0])); assertEquals(null, backup.get(keys[1])); assertEquals(null, backup.get(keys[2])); } } private static Map<Object, Object> map(Object[] keys, String value) { return Stream.of(keys).collect(Collectors.toMap(Function.identity(), ignored -> value)); } }
8,908
34.353175
139
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BackupCacheStoppedTest.java
package org.infinispan.xsite; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.util.ByteString.fromString; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.remoting.inboundhandler.GlobalInboundInvocationHandler; import org.infinispan.remoting.inboundhandler.InboundInvocationHandler; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.BackupCacheStoppedTest") public class BackupCacheStoppedTest extends AbstractTwoSitesTest { public void testCacheStopped() { final String site = LON; String key = key(site); String val = val(site); cache(site, 0).put(key, val); Cache<Object,Object> backup = backup(site); assertEquals(backup.get(key), val); assertTrue(backup.getStatus().allowInvocations()); GlobalInboundInvocationHandler handler = (GlobalInboundInvocationHandler) extractGlobalComponent(backup.getCacheManager(), InboundInvocationHandler.class); backup.stop(); eventually(() -> handler.getLocalCacheForRemoteSite(site, fromString(getDefaultCacheName())) == null); assertFalse(backup.getStatus().allowInvocations()); backup.start(); log.trace("About to put the 2nd value"); cache(site, 0).put(key, "v2"); assertEquals(backup(site).get(key), "v2"); assertTrue(backup.getStatus().allowInvocations()); } protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } }
1,985
33.842105
161
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BackupForNotSpecifiedTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.BackupForNotSpecifiedTest") public class BackupForNotSpecifiedTest extends AbstractXSiteTest { protected static final String LON = "LON-1"; protected static final String NYC = "NYC-2"; @Override protected void createSites() { GlobalConfigurationBuilder lonGc = GlobalConfigurationBuilder.defaultClusteredBuilder(); ConfigurationBuilder lonDefault = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); lonDefault.sites().addBackup() .site(NYC) .backupFailurePolicy(BackupFailurePolicy.FAIL) .strategy(BackupConfiguration.BackupStrategy.SYNC); ConfigurationBuilder someCache = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); GlobalConfigurationBuilder nycGc = GlobalConfigurationBuilder.defaultClusteredBuilder(); ConfigurationBuilder nycDefault = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); nycDefault.sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.SYNC); ConfigurationBuilder someCacheBackup = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); someCacheBackup.sites().backupFor().remoteCache("someCache").remoteSite(LON); createSite(LON, 2, lonGc, lonDefault); createSite(NYC, 2, nycGc, nycDefault); startCache(LON, "backup", getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true)); startCache(NYC, "backup", getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true)); startCache(LON, "someCache", someCache); startCache(NYC, "someCacheBackup", someCacheBackup); } public void testDataGetsReplicated() { cache(LON, 0).put("k_default_lon", "v_default_lon"); assertEquals("v_default_lon", cache(LON, 1).get("k_default_lon")); assertEquals("v_default_lon", cache(NYC, 0).get("k_default_lon")); assertEquals("v_default_lon", cache(NYC, 1).get("k_default_lon")); cache(NYC, 0).put("k_default_nyc", "v_default_nyc"); assertEquals("v_default_nyc", cache(NYC, 1).get("k_default_nyc")); assertEquals("v_default_nyc", cache(LON, 0).get("k_default_nyc")); assertEquals("v_default_nyc", cache(LON, 1).get("k_default_nyc")); cache(LON, "backup", 0).put("k_backup_lon", "v_backup_lon"); assertEquals("v_backup_lon", cache(LON, "backup", 1).get("k_backup_lon")); assertEquals("v_backup_lon", cache(NYC, "backup", 0).get("k_backup_lon")); assertEquals("v_backup_lon", cache(NYC, "backup", 1).get("k_backup_lon")); cache(NYC, "backup", 0).put("k_backup_nyc", "v_backup_nyc"); assertEquals("v_backup_nyc", cache(NYC, "backup", 1).get("k_backup_nyc")); assertEquals("v_backup_nyc", cache(LON, "backup", 0).get("k_backup_nyc")); assertEquals("v_backup_nyc", cache(LON, "backup", 1).get("k_backup_nyc")); cache(LON, "someCache", 0).put("k_someCache_lon", "v_someCache_lon"); assertEquals("v_someCache_lon", cache(LON, "someCache", 1).get("k_someCache_lon")); assertEquals("v_someCache_lon", cache(NYC, "someCacheBackup", 0).get("k_someCache_lon")); assertEquals("v_someCache_lon", cache(NYC, "someCacheBackup", 1).get("k_someCache_lon")); cache(NYC, "someCacheBackup", 0).put("k_lon_sb", "v_lon_sb"); assertEquals("v_lon_sb", cache(NYC, "someCacheBackup", 1).get("k_lon_sb")); } }
3,873
46.82716
103
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/CountingCustomFailurePolicy.java
package org.infinispan.xsite; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import jakarta.transaction.Transaction; /** * @author Mircea Markus * @since 5.2 */ public class CountingCustomFailurePolicy<K,V> extends AbstractCustomFailurePolicy<K,V> { public static volatile boolean PUT_INVOKED; public static volatile boolean REMOVE_INVOKED; public static volatile boolean REPLACE_INVOKED; public static volatile boolean COMPUTE_INVOKED; public static volatile boolean COMPUTE_IF_ABSENT_INVOKED; public static volatile boolean CLEAR_INVOKED; public static volatile boolean PUT_ALL_INVOKED; public static volatile boolean PREPARE_INVOKED; public static volatile boolean ROLLBACK_INVOKED; public static volatile boolean COMMIT_INVOKED; @Override public void handlePutFailure(String site, Object key, Object value, boolean putIfAbsent) { PUT_INVOKED = true; } @Override public void handleRemoveFailure(String site, Object key, Object oldValue) { REMOVE_INVOKED = true; } @Override public void handleReplaceFailure(String site, Object key, Object oldValue, Object newValue) { REPLACE_INVOKED = true; } @Override public void handleComputeFailure(String site, Object key, BiFunction remappingFunction, boolean computeIfPresent) { COMPUTE_INVOKED = true; } @Override public void handleComputeIfAbsentFailure(String site, Object key, Function mappingFunction) { COMPUTE_IF_ABSENT_INVOKED = true; } @Override public void handleClearFailure(String site) { CLEAR_INVOKED = true; } @Override public void handlePutAllFailure(String site, Map map) { PUT_ALL_INVOKED = true; } @Override public void handlePrepareFailure(String site, Transaction transaction) { if (transaction == null) throw new IllegalStateException(); PREPARE_INVOKED = true; throw new BackupFailureException(); } @Override public void handleRollbackFailure(String site, Transaction transaction) { ROLLBACK_INVOKED = true; } @Override public void handleCommitFailure(String site, Transaction transaction) { COMMIT_INVOKED = true; } }
2,253
27.531646
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BackupForConfigTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.SitesConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.BackupForConfigTest") public class BackupForConfigTest extends SingleCacheManagerTest { ConfigurationBuilder nycBackup; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder lonGc = GlobalConfigurationBuilder.defaultClusteredBuilder(); TestCacheManagerFactory.amendDefaultCache(lonGc); ConfigurationBuilder lon = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); lon.sites().addBackup() .site("NYC") .strategy(BackupConfiguration.BackupStrategy.SYNC); nycBackup = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); nycBackup.sites().backupFor().remoteSite("NYC").remoteCache(lonGc.defaultCacheName().get()); // creating the cache manager in order to avoid leaks return TestCacheManagerFactory.createClusteredCacheManager(lonGc, lon, TransportFlags.minimalXsiteFlags()); } public void testBackupForIsCorrect() { cacheManager.getCache(); //start default cache cacheManager.defineConfiguration("nycBackup", nycBackup.build()); cacheManager.getCache("nycBackup"); SitesConfiguration sitesConfig = cache("nycBackup").getCacheConfiguration().sites(); assertEquals(getDefaultCacheName(), sitesConfig.backupFor().remoteCache()); assertEquals("NYC", sitesConfig.backupFor().remoteSite()); sitesConfig.backupFor().isBackupFor("NYC", getDefaultCacheName()); } }
2,188
42.78
113
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/BackupWithSecurityTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.security.AuthorizationPermission; import org.infinispan.security.Security; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "xsite", testName = "xsite.BackupWithSecurityTest") public class BackupWithSecurityTest extends AbstractMultipleSitesTest { static final Subject ADMIN; static final Map<AuthorizationPermission, Subject> SUBJECTS; public static final String XSITECACHE = "XSITECACHE"; static { // Initialize one subject per permission SUBJECTS = new HashMap<>(AuthorizationPermission.values().length); for (AuthorizationPermission perm : AuthorizationPermission.values()) { SUBJECTS.put(perm, TestingUtil.makeSubject(perm.toString() + "_user", perm.toString())); } ADMIN = SUBJECTS.get(AuthorizationPermission.ALL); } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); AuthorizationConfigurationBuilder authConfig = builder.security().authorization().enable(); for (AuthorizationPermission perm : AuthorizationPermission.values()) { authConfig.role(perm.toString()); } return builder; } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder builder = super.defaultGlobalConfigurationForSite(siteIndex); GlobalAuthorizationConfigurationBuilder globalRoles = builder.security().authorization().enable().principalRoleMapper(new IdentityRoleMapper()); for (AuthorizationPermission perm : AuthorizationPermission.values()) { globalRoles.role(perm.toString()).permission(perm); } return builder; } @Override protected TestSite createSite(String siteName, int numNodes, GlobalConfigurationBuilder gcb, String cacheName, ConfigurationBuilder cb) { return Security.doAs(ADMIN, () -> BackupWithSecurityTest.super.createSite(siteName, numNodes, gcb, cacheName, cb)); } @Override protected void killSite(TestSite ts) { Security.doAs(ADMIN, () -> { BackupWithSecurityTest.super.killSite(ts); return null; }); } @Override protected void clearSite(TestSite ts) { Security.doAs(ADMIN, () -> BackupWithSecurityTest.super.clearSite(ts)); } @Override protected void afterSitesCreated() { super.afterSitesCreated(); Security.doAs(ADMIN, () -> { ConfigurationBuilder builder = defaultConfigurationForSite(0); builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.SYNC); defineInSite(site(0), XSITECACHE, builder.build()); site(0).waitForClusterToForm(XSITECACHE); builder = defaultConfigurationForSite(1); defineInSite(site(1), XSITECACHE, builder.build()); site(1).waitForClusterToForm(XSITECACHE); return null; }); } public void testBackupCacheAccess() { Security.doAs(SUBJECTS.get(AuthorizationPermission.WRITE), () -> { site(0).cache(XSITECACHE, 0).put("k1", "v1"); return null; }); String v = Security.doAs(SUBJECTS.get(AuthorizationPermission.READ), () -> (String) site(1).cache(XSITECACHE, 0).get("k1")); assertEquals("v1", v); } }
4,005
38.27451
150
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/GlobalXSiteAdminOpsTest.java
package org.infinispan.xsite; import static java.lang.String.format; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.BackupResponse; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterTest; import org.infinispan.util.NotifierLatch; import org.infinispan.xsite.statetransfer.XSiteStatePushCommand; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Test for {@link GlobalXSiteAdminOperations}. * * @author Pedro Ruivo * @since 8.1 */ @CleanupAfterTest @Test(groups = "xsite", testName = "xsite.GlobalXSiteAdminOpsTest") public class GlobalXSiteAdminOpsTest extends AbstractMultipleSitesTest { protected static ConfigurationBuilder newConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, false); } public void testTakeSiteOffline(Method m) { final String key = k(m); final String value = v(m); assertAllCachesEmpty(); assertSiteStatusInAllCaches(XSiteAdminOperations.ONLINE); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).takeSiteOffline(siteName(1)); assertSiteStatus(null, 1, XSiteAdminOperations.OFFLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, XSiteAdminOperations.OFFLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, XSiteAdminOperations.ONLINE); //double check with data putInAllCache(key, value); assertValueInAllCachesInPrimarySite(key, value); //all caches should have the value in primary site assertCacheEmpty(1, null); assertCacheEmpty(1, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertValueInCache(2, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertValueInCache(2, CacheType.BACKUP_TO_SITE_2.name(), key, value); } public void testBringSiteOnline(Method m) { final String key = k(m); final String value = v(m); assertAllCachesEmpty(); setSitesStatus(false); assertSiteStatusInAllCaches(XSiteAdminOperations.OFFLINE); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).bringSiteOnline(siteName(1)); assertSiteStatus(null, 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, XSiteAdminOperations.OFFLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, XSiteAdminOperations.OFFLINE); //double check with data putInAllCache(key, value); assertValueInAllCachesInPrimarySite(key, value); //all caches should have the value in primary site assertValueInCache(1, null, key, value); assertValueInCache(1, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); } public void testPushState(Method m) { final String key = k(m); final String value = v(m); assertAllCachesEmpty(); setSitesStatus(false); assertSiteStatusInAllCaches(XSiteAdminOperations.OFFLINE); putInAllCache(key, value); assertValueInAllCachesInPrimarySite(key, value); //check the value is not in the backups assertCacheEmpty(1, null); assertCacheEmpty(1, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).pushState(siteName(1)); awaitXSiteStateTransfer(); //check state and data assertSiteStatus(null, 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, XSiteAdminOperations.OFFLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, XSiteAdminOperations.OFFLINE); assertValueInCache(1, null, key, value); assertValueInCache(1, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).pushState(siteName(2)); awaitXSiteStateTransfer(); //check state and data assertSiteStatus(null, 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, XSiteAdminOperations.ONLINE); assertValueInCache(1, null, key, value); assertValueInCache(1, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertValueInCache(2, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertValueInCache(2, CacheType.BACKUP_TO_SITE_2.name(), key, value); } public void testCancelPushState(Method m) { final String key = k(m); final String value = v(m); assertAllCachesEmpty(); setSitesStatus(false); assertSiteStatusInAllCaches(XSiteAdminOperations.OFFLINE); putInAllCache(key, value); assertValueInAllCachesInPrimarySite(key, value); //check the value is not in the backups assertCacheEmpty(1, null); assertCacheEmpty(1, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); List<BlockingTransport> blockingTransportList = getBlockingTransport(true); blockingTransportList.forEach(BlockingTransport::blockCommands); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).pushState(siteName(1)); extractGlobalComponent(site(0).cacheManagers().get(0), GlobalXSiteAdminOperations.class).cancelPushState(siteName(1)); //check state and data assertSiteStatus(null, 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, XSiteAdminOperations.ONLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, XSiteAdminOperations.OFFLINE); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, XSiteAdminOperations.OFFLINE); assertCacheEmpty(1, null); assertCacheEmpty(1, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); blockingTransportList.forEach(BlockingTransport::unblockCommands); } @AfterMethod(alwaysRun = true) public void resetStatusAfterMethod() { setSitesStatus(true); getBlockingTransport(false).forEach(BlockingTransport::unblockCommands); } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { if (siteIndex == 0) { //default cache will backup to site_1 ConfigurationBuilder builder = newConfiguration(); builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.SYNC); return builder; } else { return newConfiguration(); } } @Override protected int defaultNumberOfSites() { return 3; } @Override protected void afterSitesCreated() { super.afterSitesCreated(); ConfigurationBuilder builder = newConfiguration(); builder.sites().addBackup().site(siteName(2)).strategy(BackupConfiguration.BackupStrategy.SYNC); defineInSite(site(0), CacheType.BACKUP_TO_SITE_2.name(), builder.build()); defineInSite(site(2), CacheType.BACKUP_TO_SITE_2.name(), newConfiguration().build()); builder = newConfiguration(); builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.SYNC); builder.sites().addBackup().site(siteName(2)).strategy(BackupConfiguration.BackupStrategy.SYNC); defineInSite(site(0), CacheType.BACKUP_TO_SITE_1_AND_2.name(), builder.build()); defineInSite(site(1), CacheType.BACKUP_TO_SITE_1_AND_2.name(), newConfiguration().build()); defineInSite(site(2), CacheType.BACKUP_TO_SITE_1_AND_2.name(), newConfiguration().build()); defineInSite(site(0), CacheType.NO_BACKUP.name(), newConfiguration().build()); //wait for caches in primary cluster site(0).waitForClusterToForm(null); site(0).waitForClusterToForm(CacheType.BACKUP_TO_SITE_1_AND_2.name()); site(0).waitForClusterToForm(CacheType.BACKUP_TO_SITE_1_AND_2.name()); site(0).waitForClusterToForm(CacheType.BACKUP_TO_SITE_2.name()); //wait for caches in backup site 1 site(1).waitForClusterToForm(null); site(1).waitForClusterToForm(CacheType.BACKUP_TO_SITE_1_AND_2.name()); //wait for caches in backup site 2 site(2).waitForClusterToForm(CacheType.BACKUP_TO_SITE_1_AND_2.name()); site(2).waitForClusterToForm(CacheType.BACKUP_TO_SITE_2.name()); } private void awaitXSiteStateTransfer() { awaitXSiteStateTransferFor(null); awaitXSiteStateTransferFor(CacheType.BACKUP_TO_SITE_1_AND_2.name()); awaitXSiteStateTransferFor(CacheType.BACKUP_TO_SITE_2.name()); } private void awaitXSiteStateTransferFor(String cacheName) { eventually(format("Failed to complete the x-site state transfer for cache '%s'", cacheName), () -> xSiteAdminOperations(cacheName).getRunningStateTransfer().isEmpty()); } private void setSitesStatus(boolean online) { if (online) { xSiteAdminOperations(null).bringSiteOnline(siteName(1)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_1_AND_2.name()).bringSiteOnline(siteName(1)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_1_AND_2.name()).bringSiteOnline(siteName(2)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_2.name()).bringSiteOnline(siteName(2)); } else { xSiteAdminOperations(null).takeSiteOffline(siteName(1)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_1_AND_2.name()).takeSiteOffline(siteName(1)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_1_AND_2.name()).takeSiteOffline(siteName(2)); xSiteAdminOperations(CacheType.BACKUP_TO_SITE_2.name()).takeSiteOffline(siteName(2)); } } private void putInAllCache(String key, String value) { cache(0, 0, null).put(key, value); cache(0, 0, CacheType.BACKUP_TO_SITE_1_AND_2.name()).put(key, value); cache(0, 0, CacheType.BACKUP_TO_SITE_2.name()).put(key, value); cache(0, 0, CacheType.NO_BACKUP.name()).put(key, value); } private void assertValueInAllCachesInPrimarySite(String key, String value) { assertValueInCache(0, null, key, value); assertValueInCache(0, CacheType.BACKUP_TO_SITE_1_AND_2.name(), key, value); assertValueInCache(0, CacheType.BACKUP_TO_SITE_2.name(), key, value); assertValueInCache(0, CacheType.NO_BACKUP.name(), key, value); } private void assertValueInCache(int siteIndex, String cacheName, String key, String value) { for (int nodeIndex = 0; nodeIndex < defaultNumberOfNodes(); nodeIndex++) { assertEquals(format("Wrong value for key '%s' in cache '%s' on site '%d' and node '%d'", key, cacheName, siteIndex, nodeIndex), value, cache(siteIndex, nodeIndex, cacheName).get(key)); } } private XSiteAdminOperations xSiteAdminOperations(String cacheName) { return TestingUtil.extractComponent(cache(0, 0, cacheName), XSiteAdminOperations.class); } private void assertCacheEmpty(int siteIndex, String cacheName) { assertTrue(format("Cache '%s' is not empty in site '%d'", cacheName, siteIndex), cache(siteIndex, 0, cacheName).isEmpty()); } private void assertAllCachesEmpty() { for (CacheType cacheType : CacheType.values()) { assertCacheEmpty(0, cacheType.name()); } assertCacheEmpty(1, null); assertCacheEmpty(1, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_1_AND_2.name()); assertCacheEmpty(2, CacheType.BACKUP_TO_SITE_2.name()); } private void assertSiteStatusInAllCaches(String status) { assertSiteStatus(null, 1, status); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 1, status); assertSiteStatus(CacheType.BACKUP_TO_SITE_1_AND_2.name(), 2, status); assertSiteStatus(CacheType.BACKUP_TO_SITE_2.name(), 2, status); } private void assertSiteStatus(String cacheName, int backupSiteIndex, String status) { assertEquals(format("Wrong site status for cache '%s' for backup site '%d'.", cacheName, backupSiteIndex), status, xSiteAdminOperations(cacheName).siteStatus(siteName(backupSiteIndex))); } private List<BlockingTransport> getBlockingTransport(boolean createIfAbsent) { List<EmbeddedCacheManager> cacheManagerList = site(0).cacheManagers(); List<BlockingTransport> blockingTransportList = new ArrayList<>(cacheManagerList.size()); cacheManagerList.forEach(cacheManager -> { Transport transport = cacheManager.getTransport(); if (transport instanceof BlockingTransport) { blockingTransportList.add((BlockingTransport) transport); } else if (createIfAbsent) { BlockingTransport blockingTransport = new BlockingTransport(transport); TestingUtil.replaceComponent(cacheManager, Transport.class, blockingTransport, true); blockingTransportList.add(blockingTransport); } }); return blockingTransportList.isEmpty() ? Collections.emptyList() : blockingTransportList; } protected enum CacheType { BACKUP_TO_SITE_2, BACKUP_TO_SITE_1_AND_2, NO_BACKUP } static class BlockingTransport extends AbstractDelegatingTransport { private final NotifierLatch notifierLatch; public BlockingTransport(Transport actual) { super(actual); notifierLatch = new NotifierLatch(toString()); notifierLatch.stopBlocking(); } public void blockCommands() { notifierLatch.startBlocking(); } public void unblockCommands() { notifierLatch.stopBlocking(); } @Override public void start() { //skip start it again. } @Override public XSiteResponse backupRemotely(XSiteBackup backup, XSiteReplicateCommand rpcCommand) { if (rpcCommand instanceof XSiteStatePushCommand) { notifierLatch.blockIfNeeded(); } return super.backupRemotely(backup, rpcCommand); } @Override public BackupResponse backupRemotely(Collection<XSiteBackup> backups, XSiteReplicateCommand rpcCommand) throws Exception { if (rpcCommand instanceof XSiteStatePushCommand) { notifierLatch.blockIfNeeded(); } return super.backupRemotely(backups, rpcCommand); } @Override public String toString() { return "BlockingTransport{" + "actual=" + actual + '}'; } } }
16,386
41.897906
124
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/AsyncBackupExpirationTest.java
package org.infinispan.xsite; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.distribution.MagicKey; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author William Burns * @since 12.0 */ @Test(groups = "xsite", testName = "xsite.AsyncBackupExpirationTest") public class AsyncBackupExpirationTest extends AbstractTwoSitesTest { private ConfigMode lonConfigMode; private ConfigMode nycConfigMode; private static ConfigurationBuilder getConfig(ConfigMode configMode) { if (configMode == ConfigMode.NON_TX) { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); switch (configMode) { case OPTIMISTIC_TX_RC: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED); break; case OPTIMISTIC_TX_RR: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); break; case PESSIMISTIC_TX: builder.transaction().lockingMode(LockingMode.PESSIMISTIC); break; } builder.expiration().wakeUpInterval(-1); return builder; } @Override protected GlobalConfigurationBuilder globalConfigurationBuilderForSite(String siteName) { return super.globalConfigurationBuilderForSite(siteName); } @Factory public Object[] factory() { List<AsyncBackupExpirationTest> tests = new LinkedList<>(); for (ConfigMode lon : ConfigMode.values()) { for (ConfigMode nyc : ConfigMode.values()) { tests.add(new AsyncBackupExpirationTest().setLonConfigMode(lon).setNycConfigMode(nyc)); } } return tests.toArray(); } @Override protected String[] parameterNames() { return new String[]{"LON", "NYC"}; } @Override protected Object[] parameterValues() { return new Object[]{lonConfigMode, nycConfigMode}; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getConfig(nycConfigMode); } @BeforeMethod public void ensureSitesOnline() { // Now we take the backup offline - which should refresh our access times XSiteAdminOperations adminOperations = extractComponent(cache(LON, 0), XSiteAdminOperations.class); if (XSiteAdminOperations.OFFLINE.equals(adminOperations.siteStatus(NYC))) { adminOperations.bringSiteOnline(NYC); } adminOperations = extractComponent(cache(NYC, 0), XSiteAdminOperations.class); if (XSiteAdminOperations.OFFLINE.equals(adminOperations.siteStatus(LON))) { adminOperations.bringSiteOnline(LON); } } public AsyncBackupExpirationTest() { super.lonBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; super.nycBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; super.implicitBackupCache = true; } @Override protected ConfigurationBuilder getLonActiveConfig() { return getConfig(lonConfigMode); } private AsyncBackupExpirationTest setLonConfigMode(ConfigMode configMode) { this.lonConfigMode = configMode; return this; } private AsyncBackupExpirationTest setNycConfigMode(ConfigMode configMode) { this.nycConfigMode = configMode; return this; } @DataProvider(name = "two boolean cross product") public Object[][] tx() { return new Object[][]{ {false, false}, {false, true}, {true, false}, {true, true} }; } private ControlledTimeService replaceTimeService() { ControlledTimeService timeService = new ControlledTimeService(); // Max idle requires all caches to show it as expired to be removed. for (Cache<?, ?> c : caches(LON)) { replaceComponent(c.getCacheManager(), TimeService.class, timeService, true); } for (Cache<?, ?> c : caches(NYC)) { replaceComponent(c.getCacheManager(), TimeService.class, timeService, true); } return timeService; } @Test(dataProvider = "two boolean cross product") public void testExpiredAccess(boolean lifespan, boolean readOnPrimary) { Cache<MagicKey, String> cache = cache(LON, 0); ControlledTimeService timeService = replaceTimeService(); MagicKey key = readOnPrimary ? new MagicKey(cache) : new MagicKey(cache(LON, 1)); if (lifespan) { cache.put(key, "v", 1, TimeUnit.SECONDS); } else { cache.put(key, "v", -1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); } // wait until all caches & sites see the new value assertEventuallyInSite(LON, c -> Objects.equals("v", c.get(key)), 20, TimeUnit.SECONDS); assertEventuallyInSite(NYC, c -> Objects.equals("v", c.get(key)), 20, TimeUnit.SECONDS); // then make sure the entry have the correct created/lastUsed value in all sites Stream.concat(caches(0).stream(), caches(1).stream()) .forEach(c -> { InternalCacheEntry<?, ?> ice = extractComponent(c, InternalDataContainer.class).peek(key); if (lifespan) { assertEquals(timeService.wallClockTime(), ice.getCreated()); } else { assertEquals(timeService.wallClockTime(), ice.getLastUsed()); } }); // Now expire the entry timeService.advance(TimeUnit.SECONDS.toMillis(2)); // check that the entry is null in all caches & sites assertInSite(LON, c -> assertNull(c.get(key))); assertInSite(NYC, c -> assertNull(c.get(key))); } @Test(dataProvider = "two boolean cross product") public void testMaxIdleWithRecentAccess(boolean readFromWrittenSite, boolean readOnAccessedSite) { Cache<Object, Object> mainSiteCache = cache(LON, 0); Cache<Object, Object> backupSiteCache = cache(NYC, 0); ControlledTimeService timeService = replaceTimeService(); Object key = new MagicKey(cache(LON, 1)); String value = "v"; long accessTime = 10; mainSiteCache.put(key, value, -1, TimeUnit.SECONDS, accessTime, TimeUnit.MILLISECONDS); // Wait for the value to be propagated to the xsite eventuallyEquals(value, () -> backupSiteCache.get(key)); // Just before it expires we read the key from a site timeService.advance(accessTime - 1); Cache<Object, Object> readSite = readFromWrittenSite ? mainSiteCache : backupSiteCache; Cache<Object, Object> expiredSite = readFromWrittenSite ? backupSiteCache : mainSiteCache; assertEquals(value, readSite.get(key)); // Now advance it and it should be "expired" from the non read site, but the other isn't timeService.advance(accessTime - 1); if (readOnAccessedSite) { assertEquals(value, readSite.get(key)); } else { assertEquals(value, expiredSite.get(key)); } // Now this will be expired on both nodes timeService.advance(accessTime + 1); assertNull(readSite.get(key)); assertNull(expiredSite.get(key)); } private void takeBothOffline() { // Now we take the backup offline - which should refresh our access times XSiteAdminOperations adminOperations = extractComponent(cache(LON, 0), XSiteAdminOperations.class); adminOperations.takeSiteOffline(NYC); adminOperations = extractComponent(cache(NYC, 0), XSiteAdminOperations.class); adminOperations.takeSiteOffline(LON); } @Test(dataProvider = "two boolean cross product") public void testAccessButSiteGoesDown(boolean readFromPrimary, boolean readFromPrimaryAfterTakeOffline) { Cache<Object, Object> mainSiteCache = cache(LON, 0); Cache<Object, Object> backupSiteCache = cache(NYC, 0); ControlledTimeService timeService = replaceTimeService(); Object key = "key"; String value = "v"; long accessTime = 10; mainSiteCache.put(key, value, -1, TimeUnit.SECONDS, accessTime, TimeUnit.MILLISECONDS); // Wait for the value to be propagated to the xsite eventuallyEquals(value, () -> backupSiteCache.get(key)); // Just before it expires we read the key from a site timeService.advance(accessTime - 1); assertEquals(value, readFromPrimary ? mainSiteCache.get(key) : backupSiteCache.get(key)); takeBothOffline(); // This will expire the entry if the access time wasn't refreshed from the other site being taken offline timeService.advance(accessTime - 1); assertEquals(value, readFromPrimaryAfterTakeOffline ? mainSiteCache.get(key) : backupSiteCache.get(key)); } private enum ConfigMode { NON_TX, PESSIMISTIC_TX, OPTIMISTIC_TX_RC, OPTIMISTIC_TX_RR, } }
9,970
35.126812
111
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/AbstractMultipleSitesTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; /** * Abstract test class that allows to create multiple combination of sites and nodes. * <p> * So far, each site only has the same number of nodes. But it can modified to support asymmetric number of nodes per * site. * * @author Pedro Ruivo * @since 8.1 */ public abstract class AbstractMultipleSitesTest extends AbstractXSiteTest { //if more sites are needed, you have to update these constants and the configuration file in config/xsite/relay-config.xml //the SITE_NAME should have the same site name as in configuration private static final int MAX_NUM_SITE = 3; private static final String[] SITE_NAME = { "LON-1", "NYC-2", "SFO-3"}; /** * It returns the number of sites to create. * <p> * It may be overwrite for different number of sites needed. The default value is 2 and it the value should be less * than {@link #MAX_NUM_SITE}. */ protected int defaultNumberOfSites() { return 2; } /** * @return the number of nodes per site. */ protected int defaultNumberOfNodes() { return 2; } /** * The default cache configuration for that site index. * * @param siteIndex the site index. */ protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); } /** * The default global configuration for a site. * * @param siteIndex the site index. */ protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { return GlobalConfigurationBuilder.defaultClusteredBuilder(); } /** * It converts the site index to a name. * * @param siteIndex the site index to be converted. * @return the site name corresponding to the site index. */ protected final String siteName(int siteIndex) { assertValidSiteIndex(siteIndex); return SITE_NAME[siteIndex]; } /** * Invoked after all the sites and default caches are created. */ protected void afterSitesCreated() { } @Override protected void createSites() { final int numberOfSites = defaultNumberOfSites(); if (numberOfSites <= 0) { throw new IllegalArgumentException("Default number of sites must be positive."); } else if (numberOfSites > MAX_NUM_SITE) { throw new IllegalArgumentException("Default number of sites must be less than the max number of configured sites."); } for (int siteIndex = 0; siteIndex < defaultNumberOfSites(); siteIndex++) { createSite(siteName(siteIndex), defaultNumberOfNodes(), defaultGlobalConfigurationForSite(siteIndex), defaultConfigurationForSite(siteIndex)); } waitForSites(); afterSitesCreated(); } protected void restartSite(int siteIndex) { TestSite site = site(siteIndex); assertTrue(site.cacheManagers.isEmpty()); site.createClusteredCaches(defaultNumberOfNodes(), null, defaultGlobalConfigurationForSite(siteIndex), defaultConfigurationForSite(siteIndex), true); waitForSites(); } private void assertValidSiteIndex(int index) { if (index < 0) { throw new IllegalArgumentException("Site index must be positive or zero."); } else if (index >= MAX_NUM_SITE) { throw new IllegalArgumentException("Site index must be less than the max number of configured sites."); } else if (index >= defaultNumberOfSites()) { throw new IllegalArgumentException("Site index must be less than the number of sites configured."); } } protected static void defineInSite(TestSite site, String cacheName, Configuration configuration) { site.cacheManagers().forEach(cacheManager -> cacheManager.defineConfiguration(cacheName, configuration)); } protected <K, V> void assertInAllSitesAndCaches(AssertCondition<K, V> condition) { assertInAllSitesAndCaches(null, condition); } protected <K, V> void assertInAllSitesAndCaches(String cacheName, AssertCondition<K, V> condition) { for (TestSite testSite : sites) { assertInSite(testSite.getSiteName(), cacheName, condition); } } protected <K, V> void eventuallyAssertInAllSitesAndCaches(EventuallyAssertCondition<K, V> condition) { eventuallyAssertInAllSitesAndCaches(null, condition); } protected <K, V> void eventuallyAssertInAllSitesAndCaches(String cacheName, EventuallyAssertCondition<K, V> condition) { for (TestSite testSite : sites) { assertEventuallyInSite(testSite.getSiteName(), cacheName, condition, 30, TimeUnit.SECONDS); } } protected void assertNoDataLeak(String cacheName) { // First, make sure the IRAC map is empty in all nodes before triggering a tombstone cleanup round for (TestSite site : sites) { for (Cache<?, ?> cache : site.getCaches(cacheName)) { eventually("Updated keys map is not empty!", () -> isIracManagerEmpty(cache)); } } // Second, trigger a tombstone cleanup round, it happens asynchronously in the background for (TestSite site : sites) { for (Cache<?, ?> cache : site.getCaches(cacheName)) { iracTombstoneManager(cache).startCleanupTombstone(); } } // Third, check if the tombstones are removed. for (TestSite site : sites) { for (Cache<?, ?> cache : site.getCaches(cacheName)) { eventually("Tombstone map is not empty!", iracTombstoneManager(cache)::isEmpty); } } } }
5,956
35.771605
125
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/PreloadWithXSiteTest.java
package org.infinispan.xsite; import static org.infinispan.distribution.DistributionTestHelper.addressOf; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import org.infinispan.Cache; import org.infinispan.commons.api.Lifecycle; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Tests if preload happens successfully when xsite is configured. * <p> * JIRA: ISPN-7265 * * @author Pedro Ruivo * @since 9.0 */ @Test(groups = "xsite", testName = "xsite.PreloadWithXSiteTest") public class PreloadWithXSiteTest extends AbstractTwoSitesTest { private static final String NYC_CACHE_STORE_NAME = "nyc-dummy-cache-store"; private static final String LON_CACHE_STORE_NAME = "lon-dummy-cache-store"; private static final int NR_KEYS = 5; public PreloadWithXSiteTest() { implicitBackupCache = true; initialClusterSize = 2; } public void testPreload(Method method) { for (int i = 0; i < NR_KEYS; ++i) { cache(NYC, 0).put(TestingUtil.k(method, i), TestingUtil.v(method, i)); } assertData(method); stopNYC(); reCreateNYC(); assertData(method); } @Override protected ConfigurationBuilder getNycActiveConfig() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true) .storeName(NYC_CACHE_STORE_NAME); return builder; } @Override protected ConfigurationBuilder getLonActiveConfig() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true) .storeName(LON_CACHE_STORE_NAME); return builder; } private void stopNYC() { site(NYC).cacheManagers.forEach(Lifecycle::stop); } private void reCreateNYC() { ConfigurationBuilder nyc = getNycActiveConfig(); nyc.sites().addBackup() .site(LON) .strategy(BackupConfiguration.BackupStrategy.SYNC); createSite(NYC, initialClusterSize, globalConfigurationBuilderForSite(NYC), nyc); } private void assertData(Method method) { assertDataForSite(method, NYC); assertDataForSite(method, LON); } private void assertDataForSite(Method method, String site) { for (Cache<String, String> cache : this.<String, String>caches(site)) { for (int i = 0; i < NR_KEYS; ++i) { assertEquals("Cache=" + addressOf(cache), TestingUtil.v(method, i), cache.get(TestingUtil.k(method, i))); } } } }
2,972
32.784091
117
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/XSiteMergePolicyUnitTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import java.util.Random; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.xsite.spi.AlwaysRemoveXSiteEntryMergePolicy; import org.infinispan.xsite.spi.DefaultXSiteEntryMergePolicy; import org.infinispan.xsite.spi.PreferNonNullXSiteEntryMergePolicy; import org.infinispan.xsite.spi.PreferNullXSiteEntryMergePolicy; import org.infinispan.xsite.spi.SiteEntry; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Unit test for all provided {@link XSiteEntryMergePolicy}. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "unit", testName = "xsite.XSiteMergePolicyUnitTest") public class XSiteMergePolicyUnitTest extends AbstractInfinispanTest { private static final Random RANDOM = new Random(System.currentTimeMillis()); private static Sync defaultMergePolicy() { return new Sync(DefaultXSiteEntryMergePolicy.getInstance()); } public static Sync preferNonNullMergePolicy() { return new Sync(PreferNonNullXSiteEntryMergePolicy.getInstance()); } public static Sync preferNullMergePolicy() { return new Sync(PreferNullXSiteEntryMergePolicy.getInstance()); } public static Sync alwaysRemoveMergePolicy() { return new Sync(AlwaysRemoveXSiteEntryMergePolicy.getInstance()); } @DataProvider(name = "alwaysRemoveData") private static Object[][] alwaysRemoveDataProvider() { //it create a new null entry with the lower site name (lower lexicographically) SiteEntryMode[] values = SiteEntryMode.values(); Object[][] result = new Object[values.length * 2][3]; int i = 0; for (SiteEntryMode mode : values) { result[i] = createInputs(mode, "LON", "NYC"); result[i++][2] = newNullSiteEntry("LON"); result[i] = createInputs(mode, "1NYC", "2LON"); result[i++][2] = newNullSiteEntry("1NYC"); } return result; } @DataProvider(name = "defaultData") private static Object[][] defaultDataProvider() { //by default, it resolves to s1 (lower lexicographically) SiteEntryMode[] values = SiteEntryMode.values(); Object[][] result = new Object[values.length * 2][3]; int i = 0; for (SiteEntryMode mode : values) { result[i] = createInputs(mode, "LON", "NYC"); result[i][2] = result[i][0]; ++i; result[i] = createInputs(mode, "1NYC", "2LON"); result[i][2] = result[i][0]; ++i; } return result; } @DataProvider(name = "preferNullData") private static Object[][] preferNullDataProvider() { //it resolves to the null entry (if any), otherwise it resolves to s1 (lower lexicographically) SiteEntryMode[] values = SiteEntryMode.values(); Object[][] result = new Object[values.length * 2][3]; int i = 0; for (SiteEntryMode mode : values) { result[i] = createInputs(mode, "LON", "NYC"); result[i][2] = mode == SiteEntryMode.S2_NULL ? result[i][1] : result[i][0]; ++i; result[i] = createInputs(mode, "1NYC", "2LON"); result[i][2] = mode == SiteEntryMode.S2_NULL ? result[i][1] : result[i][0]; ++i; } return result; } @DataProvider(name = "preferNonNullData") private static Object[][] preferNonNullDataProvider() { //it resolves to the non null entry (if any), otherwise it resolves to s1 (lower lexicographically) SiteEntryMode[] values = SiteEntryMode.values(); Object[][] result = new Object[values.length * 2][3]; int i = 0; for (SiteEntryMode mode : values) { result[i] = createInputs(mode, "LON", "NYC"); result[i][2] = mode == SiteEntryMode.S1_NULL ? result[i][1] : result[i][0]; ++i; result[i] = createInputs(mode, "1NYC", "2LON"); result[i][2] = mode == SiteEntryMode.S1_NULL ? result[i][1] : result[i][0]; ++i; } return result; } private static SiteEntry<String> newNullSiteEntry(String site) { return new SiteEntry<>(site, null, null); } private static SiteEntry<String> newSiteEntry(String site) { return new SiteEntry<>(site, TestingUtil.generateRandomString(8, RANDOM), null); } private static Object[] createInputs(SiteEntryMode mode, String lowerString, String upperString) { return new Object[]{mode.s1(lowerString), mode.s2(upperString), null}; } @Test(dataProvider = "preferNonNullData") public void testPreferNonNullMergePolicy(SiteEntry<String> s1, SiteEntry<String> s2, SiteEntry<String> r) { doTest(preferNonNullMergePolicy(), s1, s2, r); } @Test(dataProvider = "preferNullData") public void testPreferNullMergePolicy(SiteEntry<String> s1, SiteEntry<String> s2, SiteEntry<String> r) { doTest(preferNullMergePolicy(), s1, s2, r); } @Test(dataProvider = "defaultData") public void testDefaultMergePolicy(SiteEntry<String> s1, SiteEntry<String> s2, SiteEntry<String> r) { doTest(defaultMergePolicy(), s1, s2, r); } @Test(dataProvider = "alwaysRemoveData") public void testAlwaysNull(SiteEntry<String> s1, SiteEntry<String> s2, SiteEntry<String> r) { doTest(alwaysRemoveMergePolicy(), s1, s2, r); } private void doTest(Sync mergePolicy, SiteEntry<String> s1, SiteEntry<String> s2, SiteEntry<String> expected) { SiteEntry<String> result = mergePolicy.merge(s1, s2); assertEquals(expected, result); result = mergePolicy.merge(s2, s1); assertEquals(expected, result); } private enum SiteEntryMode { BOTH_NON_NULL { @Override SiteEntry<String> s1(String site) { return newSiteEntry(site); } @Override SiteEntry<String> s2(String site) { return newSiteEntry(site); } }, BOTH_NULL { @Override SiteEntry<String> s1(String site) { return newNullSiteEntry(site); } @Override SiteEntry<String> s2(String site) { return newNullSiteEntry(site); } }, S1_NULL { @Override SiteEntry<String> s1(String site) { return newNullSiteEntry(site); } @Override SiteEntry<String> s2(String site) { return newSiteEntry(site); } }, S2_NULL { @Override SiteEntry<String> s1(String site) { return newSiteEntry(site); } @Override SiteEntry<String> s2(String site) { return newNullSiteEntry(site); } }; abstract SiteEntry<String> s1(String site); abstract SiteEntry<String> s2(String site); } private static class Sync { private final XSiteEntryMergePolicy<String, String> mergePolicy; private Sync(XSiteEntryMergePolicy<String, String> mergePolicy) { this.mergePolicy = mergePolicy; } SiteEntry<String> merge(SiteEntry<String> s1, SiteEntry<String> s2) { return CompletionStages.join(mergePolicy.merge("key", s1, s2)); } } }
7,322
32.746544
114
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/XSiteAdminOperationsTest.java
package org.infinispan.xsite; import static java.lang.String.format; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.extractGlobalComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.HashSet; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.TakeOfflineConfigurationBuilder; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.infinispan.remoting.transport.Transport; import org.infinispan.xsite.status.TakeOfflineManager; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.XSiteAdminOperationsTest") public class XSiteAdminOperationsTest extends AbstractTwoSitesTest { public XSiteAdminOperationsTest() { //async LON=>NYC, sync NYC=>LON //the above doesn't make sense, and probably won't work, but we don't put any data //we are just testing XSiteAdminOperations class. this.lonBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } public void testSiteStatus() { assertEquals(admin(LON, 0).siteStatus(NYC), XSiteAdminOperations.ONLINE); assertEquals(admin(LON, 1).siteStatus(NYC), XSiteAdminOperations.ONLINE); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).takeSiteOffline(NYC)); assertEquals(admin(LON, 0).siteStatus(NYC), XSiteAdminOperations.OFFLINE); assertEquals(admin(LON, 1).siteStatus(NYC), XSiteAdminOperations.OFFLINE); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).bringSiteOnline(NYC)); assertEquals(admin(LON, 0).siteStatus(NYC), XSiteAdminOperations.ONLINE); assertEquals(admin(LON, 1).siteStatus(NYC), XSiteAdminOperations.ONLINE); } public void amendTakeOffline() { assertEquals(admin(LON, 0).siteStatus(NYC), XSiteAdminOperations.ONLINE); assertEquals(admin(LON, 1).siteStatus(NYC), XSiteAdminOperations.ONLINE); TakeOfflineManager tom = takeOfflineManager(LON, 0); assertEquals(tom.getConfiguration(NYC), new TakeOfflineConfigurationBuilder(null, null).afterFailures(0).minTimeToWait(0).create()); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).amendTakeOffline(NYC, 7, 12)); assertEquals(tom.getConfiguration(NYC), new TakeOfflineConfigurationBuilder(null, null).afterFailures(7).minTimeToWait(12).create()); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).setTakeOfflineAfterFailures(NYC, 8)); assertEquals(tom.getConfiguration(NYC), new TakeOfflineConfigurationBuilder(null, null).afterFailures(8).minTimeToWait(12).create()); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).setTakeOfflineMinTimeToWait(NYC, 13)); assertEquals(tom.getConfiguration(NYC), new TakeOfflineConfigurationBuilder(null, null).afterFailures(8).minTimeToWait(13).create()); assertEquals(admin(LON, 0).getTakeOfflineAfterFailures(NYC), "8"); assertEquals(admin(LON, 0).getTakeOfflineMinTimeToWait(NYC), "13"); assertEquals(admin(LON, 1).getTakeOfflineAfterFailures(NYC), "8"); assertEquals(admin(LON, 1).getTakeOfflineMinTimeToWait(NYC), "13"); } public void testStatus() { assertEquals(admin(LON, 0).status(), format("%s[ONLINE]", NYC)); assertEquals(admin(LON, 1).status(), format("%s[ONLINE]", NYC)); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).takeSiteOffline(NYC)); assertEquals(admin(LON, 0).status(), format("%s[OFFLINE]", NYC)); assertEquals(admin(LON, 1).status(), format("%s[OFFLINE]", NYC)); assertEquals(XSiteAdminOperations.SUCCESS, admin(LON, 1).bringSiteOnline(NYC)); assertEquals(admin(LON, 0).status(), format("%s[ONLINE]", NYC)); assertEquals(admin(LON, 1).status(), format("%s[ONLINE]", NYC)); } public void testStateTransferMode() { for (int i = 0; i < initialClusterSize; ++i) { //by default, it is manual assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(LON, i).getStateTransferMode(NYC)); assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(NYC, i).getStateTransferMode(LON)); } assertTrue(admin(LON, 0).setStateTransferMode(NYC, XSiteStateTransferMode.AUTO.toString())); for (int i = 0; i < initialClusterSize; ++i) { assertEquals(XSiteStateTransferMode.AUTO.toString(), admin(LON, i).getStateTransferMode(NYC)); assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(NYC, i).getStateTransferMode(LON)); } //sync mode throws an exception Exceptions.expectException(CacheConfigurationException.class, "ISPN000634.*", () -> admin(NYC, 0).setStateTransferMode(LON, XSiteStateTransferMode.AUTO.toString())); for (int i = 0; i < initialClusterSize; ++i) { assertEquals(XSiteStateTransferMode.AUTO.toString(), admin(LON, i).getStateTransferMode(NYC)); assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(NYC, i).getStateTransferMode(LON)); } assertTrue(admin(LON, 0).setStateTransferMode(NYC, XSiteStateTransferMode.MANUAL.toString())); for (int i = 0; i < initialClusterSize; ++i) { assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(LON, i).getStateTransferMode(NYC)); assertEquals(XSiteStateTransferMode.MANUAL.toString(), admin(NYC, i).getStateTransferMode(LON)); } // NYC already in manual mode, should return "false" assertFalse(admin(LON, 0).setStateTransferMode(NYC, XSiteStateTransferMode.MANUAL.toString())); } public void testSitesView() { assertEquals(new HashSet<>(Arrays.asList(LON, NYC)), extractGlobalComponent(site(LON).cacheManagers().get(0), Transport.class).getSitesView()); assertEquals(new HashSet<>(Arrays.asList(LON, NYC)), extractGlobalComponent(site(LON).cacheManagers().get(0), Transport.class).getSitesView()); } private XSiteAdminOperations admin(String site, int cache) { return extractComponent(cache(site, cache), XSiteAdminOperations.class); } }
6,799
46.222222
139
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/RollbackNoPrepareOptimisticTest.java
package org.infinispan.xsite; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.CompletionStage; import jakarta.transaction.TransactionManager; import org.infinispan.commands.VisitableCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "xsite", testName = "xsite.RollbackNoPrepareOptimisticTest") public class RollbackNoPrepareOptimisticTest extends AbstractTwoSitesTest { public RollbackNoPrepareOptimisticTest() { use2Pc = true; } public void testRollbackNoCommit() throws Throwable { String key = key(LON); String val = val(LON); LogBackupReceiver receiver = TestingUtil.wrapComponent(backup(LON), BackupReceiver.class, LogBackupReceiver::new); assertNull(receiver.received); cache(LON, 0).put(key, val); assertNotNull(receiver.received); assertEquals(backup(LON).get(key), val); receiver.received = null; TransactionManager tmLon0 = cache(LON, 0).getAdvancedCache().getTransactionManager(); assertNull(receiver.received); tmLon0.begin(); cache(LON, 0).put(key, val); log.trace("Before rollback!"); tmLon0.rollback(); assertNull(receiver.received); } public static class LogBackupReceiver extends BackupReceiverDelegator { volatile VisitableCommand received; protected LogBackupReceiver(BackupReceiver delegate) { super(delegate); } @Override public <O> CompletionStage<O> handleRemoteCommand(VisitableCommand command, boolean preserveOrder) { received = command; return super.handleRemoteCommand(command, preserveOrder); } } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); } }
2,215
29.777778
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/AsyncBackupTest.java
package org.infinispan.xsite; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.IracPutKeyValueCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.PutMapCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.ReplaceCommand; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.AsyncBackupTest") public class AsyncBackupTest extends AbstractTwoSitesTest { private BlockingInterceptor blockingInterceptor; private ConfigMode lonConfigMode; private ConfigMode nycConfigMode; private static ConfigurationBuilder getConfig(ConfigMode configMode) { if (configMode == ConfigMode.NON_TX) { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); switch (configMode) { case OPTIMISTIC_TX_RC: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED); break; case OPTIMISTIC_TX_RR: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); break; case PESSIMISTIC_TX: builder.transaction().lockingMode(LockingMode.PESSIMISTIC); break; } return builder; } @Factory public Object[] factory() { List<AsyncBackupTest> tests = new LinkedList<>(); for (ConfigMode lon : ConfigMode.values()) { for (ConfigMode nyc : ConfigMode.values()) { tests.add(new AsyncBackupTest().setLonConfigMode(lon).setNycConfigMode(nyc)); } } return tests.toArray(); } @Override protected String[] parameterNames() { return new String[]{"LON", "NYC"}; } @Override protected Object[] parameterValues() { return new Object[]{lonConfigMode, nycConfigMode}; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getConfig(nycConfigMode); } public AsyncBackupTest() { super.lonBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; super.nycBackupStrategy = BackupConfiguration.BackupStrategy.ASYNC; super.implicitBackupCache = true; } @Override protected void createSites() { super.createSites(); blockingInterceptor = new BlockingInterceptor(); extractInterceptorChain(backup(LON)).addInterceptor(blockingInterceptor, 1); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getConfig(lonConfigMode); } private AsyncBackupTest setLonConfigMode(ConfigMode configMode) { this.lonConfigMode = configMode; return this; } private AsyncBackupTest setNycConfigMode(ConfigMode configMode) { this.nycConfigMode = configMode; return this; } @BeforeMethod void resetBlockingInterceptor() { blockingInterceptor.reset(); } public void testPut() throws Exception { cache(LON, 0).put("k", "v"); assertReachedRemoteSite(); assertEquals("v", cache(LON, 0).get("k")); assertEquals("v", cache(LON, 1).get("k")); assertNull(backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals("v", () -> backup(LON).get("k")); assertDataContainerState("v"); assertNoDataLeak(); } public void testRemove() throws Exception { doPutWithDisabledBlockingInterceptor(); cache(LON, 1).remove("k"); assertReachedRemoteSite(); assertNull(cache(LON, 0).get("k")); assertNull(cache(LON, 1).get("k")); assertEquals("v", backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals(null, () -> backup(LON).get("k")); assertNoDataLeak(); } public void testClear() throws Exception { doPutWithDisabledBlockingInterceptor(); cache(LON, 1).clear(); assertReachedRemoteSite(); assertNull(cache(LON, 0).get("k")); assertNull(cache(LON, 1).get("k")); assertEquals("v", backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals(null, () -> backup(LON).get("k")); assertNoDataLeak(); } public void testReplace() throws Exception { doPutWithDisabledBlockingInterceptor(); cache(LON, 1).replace("k", "v2"); assertReachedRemoteSite(); assertEquals("v2", cache(LON, 0).get("k")); assertEquals("v2", cache(LON, 1).get("k")); assertEquals("v", backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals("v2", () -> backup(LON).get("k")); assertDataContainerState("v2"); assertNoDataLeak(); } public void testPutAll() throws Exception { cache(LON, 0).putAll(Collections.singletonMap("k", "v")); assertReachedRemoteSite(); assertEquals("v", cache(LON, 0).get("k")); assertEquals("v", cache(LON, 1).get("k")); assertNull(backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals("v", () -> backup(LON).get("k")); assertDataContainerState("v"); assertNoDataLeak(); } public void testPutForExternalRead() throws InterruptedException { cache(LON, 0).putForExternalRead("k", "v"); assertReachedRemoteSite(); // put for external read is async eventuallyEquals("v", () -> cache(LON, 0).get("k")); eventuallyEquals("v", () -> cache(LON, 1).get("k")); assertNull(backup(LON).get("k")); resumeRemoteSite(); eventuallyEquals("v", () -> backup(LON).get("k")); assertDataContainerState("v"); assertNoDataLeak(); } private void doPutWithDisabledBlockingInterceptor() { blockingInterceptor.isActive = false; cache(LON, 0).put("k", "v"); eventuallyEquals("v", () -> backup(LON).get("k")); blockingInterceptor.isActive = true; } private void assertReachedRemoteSite() throws InterruptedException { try { assertTrue(blockingInterceptor.invocationReceivedLatch.await(20000, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } } private void resumeRemoteSite() { blockingInterceptor.waitingLatch.countDown(); } private DistributionInfo getDistributionForKey(Cache<String, String> cache) { return extractComponent(cache, ClusteringDependentLogic.class) .getCacheTopology() .getDistribution("k"); } private boolean isNotWriteOwner(Cache<String, String> cache) { return !getDistributionForKey(cache).isWriteOwner(); } private Cache<String, String> findPrimaryOwner() { for (Cache<String, String> c : this.<String, String>caches(LON)) { if (getDistributionForKey(c).isPrimary()) { return c; } } throw new IllegalStateException(String.format("Unable to find primary owner for key %s", "k")); } private InternalDataContainer<String, String> getInternalDataContainer(Cache<String, String> cache) { //noinspection unchecked return extractComponent(cache, InternalDataContainer.class); } private IracMetadata extractMetadataFromPrimaryOwner() { Cache<String, String> cache = findPrimaryOwner(); InternalDataContainer<String, String> dataContainer = getInternalDataContainer(cache); InternalCacheEntry<String, String> entry = dataContainer.peek("k"); assertNotNull(entry); PrivateMetadata internalMetadata = entry.getInternalMetadata(); assertNotNull(internalMetadata); IracMetadata metadata = internalMetadata.iracMetadata(); assertNotNull(metadata); return metadata; } private void assertInDataContainer(String site, String value, IracMetadata metadata) { for (Cache<String, String> cache : this.<String, String>caches(site)) { if (isNotWriteOwner(cache)) { continue; } InternalDataContainer<String, String> dc = getInternalDataContainer(cache); InternalCacheEntry<String, String> ice = dc.peek("k"); log.debugf("Checking DataContainer in %s. entry=%s", DistributionTestHelper.addressOf(cache), ice); assertNotNull(String.format("Internal entry is null for key %s", "k"), ice); assertEquals("Internal entry wrong key", "k", ice.getKey()); assertEquals("Internal entry wrong value", value, ice.getValue()); assertEquals("Internal entry wrong metadata", metadata, ice.getInternalMetadata().iracMetadata()); } } private void assertDataContainerState(String value) { IracMetadata metadata = extractMetadataFromPrimaryOwner(); assertInDataContainer(LON, value, metadata); assertInDataContainer(NYC, value, metadata); } private void assertNoDataLeak() { for (int i = 0; i < initialClusterSize; ++i) { Cache<?,?> lonCache = cache(LON, null, i); Cache<?,?> nycCache = cache(NYC, null, i); eventually("Updated keys map is not empty in LON!", () -> isIracManagerEmpty(lonCache)); eventually("Updated keys map is not empty in NYC!", () -> isIracManagerEmpty(nycCache)); iracTombstoneManager(lonCache).startCleanupTombstone(); iracTombstoneManager(nycCache).startCleanupTombstone(); } for (int i = 0; i < initialClusterSize; ++i) { Cache<?,?> lonCache = cache(LON, null, i); Cache<?,?> nycCache = cache(NYC, null, i); eventually("Tombstone map is not empty in LON", iracTombstoneManager(lonCache)::isEmpty); eventually("Tombstone map is not empty in NYC", iracTombstoneManager(nycCache)::isEmpty); } } public static class BlockingInterceptor extends DDAsyncInterceptor { public volatile CountDownLatch invocationReceivedLatch = new CountDownLatch(1); public volatile CountDownLatch waitingLatch = new CountDownLatch(1); public volatile boolean isActive = true; void reset() { invocationReceivedLatch = new CountDownLatch(1); waitingLatch = new CountDownLatch(1); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitIracPutKeyValueCommand(InvocationContext ctx, IracPutKeyValueCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable { return handle(ctx, command); } @Override public Object visitWriteOnlyManyEntriesCommand(InvocationContext ctx, WriteOnlyManyEntriesCommand command) throws Throwable { return handle(ctx, command); } protected Object handle(InvocationContext ctx, VisitableCommand command) throws Throwable { if (isActive) { invocationReceivedLatch.countDown(); assertTrue(waitingLatch.await(30, TimeUnit.SECONDS)); } return super.handleDefault(ctx, command); } } private enum ConfigMode { NON_TX, PESSIMISTIC_TX, OPTIMISTIC_TX_RC, OPTIMISTIC_TX_RR, } }
13,957
35.254545
131
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracTombstoneUnitTest.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Queue; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CompletionStage; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import org.infinispan.commands.CommandsFactory; import org.infinispan.commands.irac.IracTombstoneCleanupCommand; import org.infinispan.commands.irac.IracTombstoneRemoteSiteCheckCommand; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.versioning.irac.DefaultIracTombstoneManager; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.WithinThreadExecutor; import org.infinispan.xsite.status.SiteState; import org.infinispan.xsite.status.TakeOfflineManager; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.testng.annotations.Test; /** * Tests the Scheduler in {@link DefaultIracTombstoneManager}. * * @author Pedro Ruivo * @since 14.0 */ @Test(groups = "unit", testName = "xsite.irac.IracTombstoneUnitTest") public class IracTombstoneUnitTest extends AbstractInfinispanTest { private static Configuration createConfiguration(int targetSize, long maxCleanupDelay) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.sites() .tombstoneMapSize(targetSize) .maxTombstoneCleanupDelay(maxCleanupDelay) .addBackup() .site("A") .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder.build(); } private static Collection<IracXSiteBackup> backups() { return Collections.singleton(new IracXSiteBackup("A", true, 1000L, false, (short) 0)); } private static DistributionManager createDistributionManager() { DistributionManager dm = Mockito.mock(DistributionManager.class); DistributionInfo dInfo = Mockito.mock(DistributionInfo.class); Mockito.when(dInfo.isPrimary()).thenReturn(true); Mockito.when(dInfo.isWriteOwner()).thenReturn(true); LocalizedCacheTopology cacheTopology = Mockito.mock(LocalizedCacheTopology.class); Mockito.when(cacheTopology.getSegmentDistribution(ArgumentMatchers.anyInt())).thenReturn(dInfo); Mockito.when(dm.getCacheTopology()).thenReturn(cacheTopology); return dm; } private static TakeOfflineManager createTakeOfflineManager() { TakeOfflineManager tom = Mockito.mock(TakeOfflineManager.class); // hack to prevent creating and mocking xsite commands. Local command needs to be mocked Mockito.when(tom.getSiteState(ArgumentMatchers.anyString())).thenReturn(SiteState.OFFLINE); return tom; } private static CommandsFactory createCommandFactory() { CommandsFactory factory = Mockito.mock(CommandsFactory.class); IracTombstoneRemoteSiteCheckCommand cmd = Mockito.mock(IracTombstoneRemoteSiteCheckCommand.class); Mockito.when(factory.buildIracTombstoneRemoteSiteCheckCommand(ArgumentMatchers.any())).thenReturn(cmd); IracTombstoneCleanupCommand cmd2 = Mockito.mock(IracTombstoneCleanupCommand.class); Mockito.when(cmd2.isEmpty()).thenReturn(false); Mockito.when(factory.buildIracTombstoneCleanupCommand(ArgumentMatchers.anyInt())).thenReturn(cmd2); return factory; } private static RpcManager createRpcManager() { RpcManager rpcManager = Mockito.mock(RpcManager.class); RpcOptions rpcOptions = Mockito.mock(RpcOptions.class); Transport transport = Mockito.mock(Transport.class); Mockito.doNothing().when(transport).checkCrossSiteAvailable(); Mockito.when(transport.localSiteName()).thenReturn("B"); Mockito.when(rpcManager.getTransport()).thenReturn(transport); Mockito.when(rpcManager.getSyncRpcOptions()).thenReturn(rpcOptions); Mockito.when(rpcManager.invokeCommand(ArgumentMatchers.anyCollection(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(CompletableFutures.completedNull()); return rpcManager; } private static IracManager createIracManager(AtomicBoolean keep) { IracManager im = Mockito.mock(IracManager.class); Mockito.when(im.containsKey(ArgumentMatchers.any())).thenAnswer(invocationOnMock -> keep.get()); return im; } private static ScheduledExecutorService createScheduledExecutorService(Queue<? super RunnableData> queue) { ScheduledExecutorService executorService = Mockito.mock(ScheduledExecutorService.class); Mockito.when(executorService.schedule(ArgumentMatchers.any(Runnable.class), ArgumentMatchers.anyLong(), ArgumentMatchers.any())).thenAnswer(invocationOnMock -> { queue.add(new RunnableData(invocationOnMock.getArgument(0), invocationOnMock.getArgument(1))); return null; }); return executorService; } private static IracMetadata createIracMetadata() { return Mockito.mock(IracMetadata.class); } private static BlockingManager createBlockingManager() { BlockingManager blockingManager = Mockito.mock(BlockingManager.class); Mockito.when(blockingManager.asExecutor(ArgumentMatchers.anyString())).thenReturn(new WithinThreadExecutor()); Mockito.when(blockingManager.thenComposeBlocking(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenAnswer(invocationOnMock -> { CompletionStage<Void> stage = invocationOnMock.getArgument(0); Function<Void, CompletionStage<Object>> f = invocationOnMock.getArgument(1); return stage.thenCompose(f); }); return blockingManager; } private static DefaultIracTombstoneManager createIracTombstoneManager(Queue<? super RunnableData> queue, int targetSize, long maxDelay, AtomicBoolean keep) { DefaultIracTombstoneManager manager = new DefaultIracTombstoneManager(createConfiguration(targetSize, maxDelay), backups()); TestingUtil.inject(manager, createDistributionManager(), createTakeOfflineManager(), createIracManager(keep), createBlockingManager(), createScheduledExecutorService(queue), createCommandFactory(), createRpcManager()); return manager; } public void testDelayIncreaseWithNoTombstones() throws InterruptedException { BlockingDeque<RunnableData> queue = new LinkedBlockingDeque<>(); DefaultIracTombstoneManager manager = createIracTombstoneManager(queue, 1, 1000, new AtomicBoolean(false)); manager.start(); RunnableData data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(500, data.delay); // check the max limit for (long expectedDelay : Arrays.asList(707, 841, 917, 958, 979, 989, 994, 997, 998, 999, 999, 999)) { data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(expectedDelay, data.delay); } manager.stop(); } public void testDelayAtSameRate() throws InterruptedException { int targetSize = 20; BlockingDeque<RunnableData> queue = new LinkedBlockingDeque<>(); DefaultIracTombstoneManager manager = createIracTombstoneManager(queue, targetSize, 2000, new AtomicBoolean(false)); manager.start(); RunnableData data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1000, data.delay); IracMetadata metadata = createIracMetadata(); insertTombstones(targetSize, manager, metadata); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1000, data.delay); manager.stop(); } public void testDelayAtHigherRate() throws InterruptedException { int targetSize = 10; BlockingDeque<RunnableData> queue = new LinkedBlockingDeque<>(); DefaultIracTombstoneManager manager = createIracTombstoneManager(queue, targetSize, 2000, new AtomicBoolean(false)); manager.start(); RunnableData data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1000, data.delay); IracMetadata metadata = createIracMetadata(); insertTombstones(targetSize * 2, manager, metadata); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(708, data.delay); } public void testDelayAtLowerRate() throws InterruptedException { int targetSize = 20; BlockingDeque<RunnableData> queue = new LinkedBlockingDeque<>(); DefaultIracTombstoneManager manager = createIracTombstoneManager(queue, targetSize, 2000, new AtomicBoolean(false)); manager.start(); RunnableData data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1000, data.delay); IracMetadata metadata = createIracMetadata(); insertTombstones(targetSize / 2, manager, metadata); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1414, data.delay); manager.stop(); } public void testCleanupCantKeepUp() throws InterruptedException { int targetSize = 5; BlockingDeque<RunnableData> queue = new LinkedBlockingDeque<>(); AtomicBoolean keep = new AtomicBoolean(true); DefaultIracTombstoneManager manager = createIracTombstoneManager(queue, targetSize, 1000, keep); manager.start(); RunnableData data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(500, data.delay); // Cleanup task didn't clean enough, delay goes down to 1ms IracMetadata metadata = createIracMetadata(); insertTombstones(targetSize * 2, manager, metadata); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1, data.delay); // Cleanup task didn't clean enough again, delay stays at 1ms insertTombstones(targetSize * 3, manager, metadata); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(1, data.delay); // Tombstones are now cleaned up, and the delay goes back up keep.set(false); data.runnable.run(); data = queue.poll(10, TimeUnit.SECONDS); assertNotNull(data); assertEquals(32, data.delay); manager.stop(); } private static void insertTombstones(int targetSize, DefaultIracTombstoneManager manager, IracMetadata metadata) { for (int i = 0; i < targetSize; ++i) { manager.storeTombstone(1, i, metadata); } } private static final class RunnableData { final Runnable runnable; final long delay; private RunnableData(Runnable runnable, long delay) { this.runnable = runnable; this.delay = delay; } } }
11,963
40.113402
198
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/ControlledIracManager.java
package org.infinispan.xsite.irac; import java.util.Collection; import java.util.Optional; import java.util.concurrent.CompletionStage; import org.infinispan.commons.util.IntSet; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.remoting.transport.Address; import org.infinispan.topology.CacheTopology; import org.infinispan.xsite.statetransfer.XSiteState; /** * An {@link IracManager} implementation that can be controlled for testing purpose. * * @author Pedro Ruivo * @since 11.0 */ @Scope(Scopes.NAMED_CACHE) public class ControlledIracManager implements IracManager { protected final IracManager actual; public ControlledIracManager(IracManager actual) { this.actual = actual; } @Override public void trackUpdatedKey(int segment, Object key, Object lockOwner) { actual.trackUpdatedKey(segment, key, lockOwner); } @Override public void trackExpiredKey(int segment, Object key, Object lockOwner) { actual.trackExpiredKey(segment, key, lockOwner); } @Override public CompletionStage<Void> trackForStateTransfer(Collection<XSiteState> stateList) { return actual.trackForStateTransfer(stateList); } @Override public void trackClear(boolean sendClear) { actual.trackClear(sendClear); } @Override public void removeState(IracManagerKeyInfo state) { actual.removeState(state); } @Override public void onTopologyUpdate(CacheTopology oldCacheTopology, CacheTopology newCacheTopology) { actual.onTopologyUpdate(oldCacheTopology, newCacheTopology); } @Override public void requestState(Address requestor, IntSet segments) { actual.requestState(requestor, segments); } @Override public void receiveState(int segment, Object key, Object lockOwner, IracMetadata tombstone) { actual.receiveState(segment, key, lockOwner, tombstone); } @Override public CompletionStage<Boolean> checkAndTrackExpiration(Object key) { return actual.checkAndTrackExpiration(key); } @Override public void incrementNumberOfDiscards() { actual.incrementNumberOfDiscards(); } @Override public void incrementNumberOfConflictLocalWins() { actual.incrementNumberOfConflictLocalWins(); } @Override public void incrementNumberOfConflictRemoteWins() { actual.incrementNumberOfConflictRemoteWins(); } @Override public void incrementNumberOfConflictMerged() { actual.incrementNumberOfConflictMerged(); } @Override public boolean containsKey(Object key) { return actual.containsKey(key); } protected Optional<DefaultIracManager> asDefaultIracManager() { return actual instanceof DefaultIracManager ? Optional.of((DefaultIracManager) actual) : Optional.empty(); } }
2,897
26.865385
112
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracRestartWithGlobalStateTest.java
package org.infinispan.xsite.irac; import static java.lang.String.format; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.container.versioning.InequalVersionComparisonResult.BEFORE; import static org.infinispan.container.versioning.InequalVersionComparisonResult.EQUAL; import static org.infinispan.distribution.DistributionTestHelper.addressOf; import static org.infinispan.test.TestingUtil.extractCacheTopology; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.versioning.InequalVersionComparisonResult; import org.infinispan.container.versioning.irac.DefaultIracVersionGenerator; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.IracVersionGenerator; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests the state transfer and checks the versions are kept consistent when a site restart. Global state is available * and versions should be stored there to survive the restart. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.IracRestartWithGlobalStateTest") public class IracRestartWithGlobalStateTest extends AbstractMultipleSitesTest { private static final int NUM_KEYS = 100; private final boolean persistent; public IracRestartWithGlobalStateTest(boolean persistent) { this.persistent = persistent; } @Factory public static Object[] defaultFactory() { return new Object[]{ new IracRestartWithGlobalStateTest(false), new IracRestartWithGlobalStateTest(true) }; } private static void forEachKeyValue(Method method, String prefix, BiConsumer<String, String> keyValueConsumer) { for (int i = 0; i < NUM_KEYS; ++i) { keyValueConsumer.accept(k(method, i), v(method, prefix, i)); } } @BeforeClass(alwaysRun = true) @Override public void createBeforeClass() { Util.recursiveFileRemove(tmpDirectory(getClass())); super.createBeforeClass(); } public void testRestart(Method method) { doTest(method, false); } public void testRestartReverse(Method method) { doTest(method, true); } @Override protected String[] parameterNames() { return new String[]{null}; } @Override protected Object[] parameterValues() { return new String[]{persistent ? "PERSISTENT" : "VOLATILE"}; } @Override protected int defaultNumberOfNodes() { return 3; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); if (siteIndex == 0) { builder.sites().addBackup() .site(siteName(1)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); if (persistent) { builder.persistence().addSoftIndexFileStore(); } } else { builder.sites().addBackup() .site(siteName(0)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected void decorateGlobalConfiguration(GlobalConfigurationBuilder builder, int siteIndex, int nodeIndex) { String stateDirectory = tmpDirectory(getClass().getSimpleName(), "site_" + siteIndex, "node_" + nodeIndex); builder.globalState().enable().persistentLocation(stateDirectory); } private void doTest(Method method, boolean reverse) { forEachKeyValue(method, "initial", (k, v) -> cache(0, 0).put(k, v)); forEachKeyValue(method, "initial", this::eventuallyAssertData); Map<Integer, IracEntryVersion> versionsBefore = snapshotPrimaryVersions(); Map<String, IracEntryVersion> entryVersionsBefore = snapshotKeyVersions(method, 0); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 1), EQUAL); log.debug("Stopping site_0"); stopSite(0); log.debug("Starting site_0"); restartSite(0); Map<Integer, IracEntryVersion> versionsAfter = snapshotPrimaryVersions(); assertVersions(versionsBefore, versionsAfter, EQUAL); forEachKeyValue(method, "final", (k, v) -> cache(reverse ? 1 : 0, 0).put(k, v)); forEachKeyValue(method, "final", this::eventuallyAssertData); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 0), BEFORE); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 1), BEFORE); } private Map<Integer, IracEntryVersion> snapshotPrimaryVersions() { Map<Integer, IracEntryVersion> versions = new HashMap<>(256); for (Cache<?, ?> cache : caches(0)) { DefaultIracVersionGenerator vGenerator = generator(cache); LocalizedCacheTopology topology = extractCacheTopology(cache); Map<Integer, IracEntryVersion> cacheVersions = vGenerator.peek(); log.tracef("Taking snapshot from %s (%s entries): %s", addressOf(cache), cacheVersions.size(), cacheVersions); cacheVersions.forEach((segment, version) -> { if (topology.getSegmentDistribution(segment).isPrimary()) { IracEntryVersion v = versions.putIfAbsent(segment, version); assertNull(v); } }); log.tracef("Global versions after %s (%s entries): %s", addressOf(cache), versions.size(), versions); } return versions; } private Map<String, IracEntryVersion> snapshotKeyVersions(Method method, int siteIndex) { Map<String, IracEntryVersion> versions = new HashMap<>(256); for (Cache<String, String> cache : this.<String, String>caches(siteIndex)) { LocalizedCacheTopology topology = extractCacheTopology(cache); //noinspection unchecked InternalDataContainer<String, String> dataContainer = extractComponent(cache, InternalDataContainer.class); for (int i = 0; i < NUM_KEYS; ++i) { String key = k(method, i); DistributionInfo distributionInfo = topology.getDistribution(key); if (distributionInfo.isPrimary()) { IracEntryVersion version = dataContainer.peek(distributionInfo.segmentId(), key).getInternalMetadata() .iracMetadata().getVersion(); AssertJUnit.assertNotNull(version); versions.put(key, version); } } } return versions; } private static DefaultIracVersionGenerator generator(Cache<?, ?> cache) { return (DefaultIracVersionGenerator) extractComponent(cache, IracVersionGenerator.class); } private static <K> void assertVersions(Map<K, IracEntryVersion> v1, Map<K, IracEntryVersion> v2, InequalVersionComparisonResult expected) { assertEquals(v1.size(), v2.size()); Iterator<K> iterator = Stream.concat(v1.keySet().stream(), v2.keySet().stream()) .distinct() .iterator(); while (iterator.hasNext()) { K key = iterator.next(); IracEntryVersion version1 = v1.get(key); IracEntryVersion version2 = v2.get(key); assertNotNull(format("'%s' version is null for Map 1", key), version1); assertNotNull(format("'%s' version is null for Map 2", key), version2); InequalVersionComparisonResult result = version1.compareTo(version2); assertEquals(format("'%s' version mismatch: %s and %s", key, version1, version2), expected, result); } } private void eventuallyAssertData(String key, String value) { eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(value, cache.get(key))); } }
8,760
39.560185
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracVersionUnitTest.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.Optional; import org.infinispan.commands.CommandsFactory; import org.infinispan.container.versioning.InequalVersionComparisonResult; import org.infinispan.container.versioning.irac.DefaultIracVersionGenerator; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.globalstate.GlobalStateManager; import org.infinispan.globalstate.ScopedPersistentState; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.topology.CacheTopology; import org.infinispan.xsite.XSiteNamedCache; import org.mockito.Mockito; import org.testng.annotations.Test; /** * Unit test for {@link IracEntryVersion}. * * @author Pedro Ruivo * @since 11.0 */ @Test(groups = "unit", testName = "xsite.irac.IracVersionUnitTest") public class IracVersionUnitTest extends AbstractInfinispanTest { private static final String SITE_1 = "site_1"; private static final String SITE_2 = "site_2"; private static DefaultIracVersionGenerator newGenerator(String site) { DefaultIracVersionGenerator generator = new DefaultIracVersionGenerator(2); TestingUtil.inject(generator, mockRpcManager(site), mockGlobalStateManager(), mockCommandFactory()); generator.start(); return generator; } private static Transport mockTransport(String siteName) { Transport t = Mockito.mock(Transport.class); Mockito.doNothing().when(t).checkCrossSiteAvailable(); Mockito.when(t.localSiteName()).thenReturn(siteName); return t; } private static RpcManager mockRpcManager(String siteName) { Transport transport = mockTransport(siteName); RpcManager rpcManager = Mockito.mock(RpcManager.class); Mockito.when(rpcManager.getTransport()).thenReturn(transport); return rpcManager; } private static CacheTopology mockCacheTopology() { CacheTopology t = Mockito.mock(CacheTopology.class); Mockito.when(t.getPhase()).thenReturn(CacheTopology.Phase.NO_REBALANCE); return t; } private static GlobalStateManager mockGlobalStateManager() { GlobalStateManager manager = Mockito.mock(GlobalStateManager.class); Mockito.doNothing().when(manager).writeScopedState(Mockito.any(ScopedPersistentState.class)); Mockito.when(manager.readScopedState(Mockito.anyString())).thenReturn(Optional.empty()); return manager; } private static CommandsFactory mockCommandFactory() { CommandsFactory factory = Mockito.mock(CommandsFactory.class); Mockito.when(factory.getCacheName()).thenReturn("unused"); return factory; } private static void assertSiteVersion(IracEntryVersion entryVersion, String site, int topologyId, long version) { assertNotNull(entryVersion); TopologyIracVersion iracVersion = entryVersion.getVersion(XSiteNamedCache.cachedByteString(site)); assertNotNull(iracVersion); assertEquals(topologyId, iracVersion.getTopologyId()); assertEquals(version, iracVersion.getVersion()); } private static void assertNoSiteVersion(IracEntryVersion entryVersion, String site) { assertNotNull(entryVersion); TopologyIracVersion iracVersion = entryVersion.getVersion(XSiteNamedCache.cachedByteString(site)); assertNull(iracVersion); } private static void triggerTopologyEvent(DefaultIracVersionGenerator generator) { generator.onTopologyChange(mockCacheTopology()); } public void testEquals() { IracMetadata m1 = newGenerator(SITE_1).generateNewMetadata(0); IracMetadata m2 = newGenerator(SITE_1).generateNewMetadata(0); assertEquals(InequalVersionComparisonResult.EQUAL, m1.getVersion().compareTo(m2.getVersion())); assertEquals(InequalVersionComparisonResult.EQUAL, m2.getVersion().compareTo(m1.getVersion())); } public void testCompareDifferentTopology() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); IracMetadata m1 = g1.generateNewMetadata(0); // (1,0) triggerTopologyEvent(g1); IracMetadata m2 = g1.generateNewMetadata(0); //(1+,0) assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertNoSiteVersion(m1.getVersion(), SITE_2); assertSiteVersion(m2.getVersion(), SITE_1, 2, 1); assertNoSiteVersion(m2.getVersion(), SITE_2); // we have m1=(1,0) and m2=(1+,0) assertEquals(InequalVersionComparisonResult.BEFORE, m1.getVersion().compareTo(m2.getVersion())); assertEquals(InequalVersionComparisonResult.AFTER, m2.getVersion().compareTo(m1.getVersion())); } public void testCompareSameTopology() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); IracMetadata m1 = g1.generateNewMetadata(0); // (1,0) IracMetadata m2 = g1.generateNewMetadata(0); // (2,0) assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertNoSiteVersion(m1.getVersion(), SITE_2); assertSiteVersion(m2.getVersion(), SITE_1, 1, 2); assertNoSiteVersion(m2.getVersion(), SITE_2); assertEquals(InequalVersionComparisonResult.BEFORE, m1.getVersion().compareTo(m2.getVersion())); assertEquals(InequalVersionComparisonResult.AFTER, m2.getVersion().compareTo(m1.getVersion())); } public void testCausality() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); DefaultIracVersionGenerator g2 = newGenerator(SITE_2); IracMetadata m2 = g2.generateNewMetadata(0); // (0,1) assertNoSiteVersion(m2.getVersion(), SITE_1); assertSiteVersion(m2.getVersion(), SITE_2, 1, 1); g1.updateVersion(0, m2.getVersion()); IracMetadata m1 = g1.generateNewMetadata(0); // (1,1) assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertSiteVersion(m1.getVersion(), SITE_2, 1, 1); //we have m1=(1,1) and m2=(0,1) assertEquals(InequalVersionComparisonResult.BEFORE, m2.getVersion().compareTo(m1.getVersion())); assertEquals(InequalVersionComparisonResult.AFTER, m1.getVersion().compareTo(m2.getVersion())); } public void testConflictSameTopology() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); DefaultIracVersionGenerator g2 = newGenerator(SITE_2); IracMetadata m1 = g1.generateNewMetadata(0); // (1,0) IracMetadata m2 = g2.generateNewMetadata(0); // (0,1) assertEquals(SITE_1, m1.getSite()); assertEquals(SITE_2, m2.getSite()); assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertNoSiteVersion(m1.getVersion(), SITE_2); assertNoSiteVersion(m2.getVersion(), SITE_1); assertSiteVersion(m2.getVersion(), SITE_2, 1, 1); //we have a conflict: (1,0) vs (0,1) assertEquals(InequalVersionComparisonResult.CONFLICTING, m1.getVersion().compareTo(m2.getVersion())); } public void testConflictDifferentTopology() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); DefaultIracVersionGenerator g2 = newGenerator(SITE_2); g2.generateNewMetadata(0); //(0,1) IracMetadata m2 = g2.generateNewMetadata(0); //(0,2) g1.updateVersion(0, m2.getVersion()); IracMetadata m1 = g1.generateNewMetadata(0); //(1,2) triggerTopologyEvent(g2); m2 = g2.generateNewMetadata(0); //(0,1+) //we should have a conflict m1=(1,2) & m2=(0,1+) assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertSiteVersion(m1.getVersion(), SITE_2, 1, 2); assertNoSiteVersion(m2.getVersion(), SITE_1); assertSiteVersion(m2.getVersion(), SITE_2, 2, 1); assertEquals(InequalVersionComparisonResult.CONFLICTING, m1.getVersion().compareTo(m2.getVersion())); assertEquals(InequalVersionComparisonResult.CONFLICTING, m2.getVersion().compareTo(m1.getVersion())); } public void testNoConflictDifferentTopology() { DefaultIracVersionGenerator g1 = newGenerator(SITE_1); DefaultIracVersionGenerator g2 = newGenerator(SITE_2); IracMetadata m3 = g2.generateNewMetadata(0); //(0,1) IracMetadata m2 = g2.generateNewMetadata(0); //(0,2) g1.updateVersion(0, m2.getVersion()); IracMetadata m1 = g1.generateNewMetadata(0); //(1,2) //we have m1=(1,2) & m3=(0,1). assertSiteVersion(m1.getVersion(), SITE_1, 1, 1); assertSiteVersion(m1.getVersion(), SITE_2, 1, 2); assertNoSiteVersion(m3.getVersion(), SITE_1); assertSiteVersion(m3.getVersion(), SITE_2, 1, 1); assertEquals(InequalVersionComparisonResult.AFTER, m1.getVersion().compareTo(m3.getVersion())); assertEquals(InequalVersionComparisonResult.BEFORE, m3.getVersion().compareTo(m1.getVersion())); } }
8,994
38.451754
116
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/ControlledTransport.java
package org.infinispan.xsite.irac; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; public class ControlledTransport extends AbstractDelegatingTransport { volatile Supplier<Throwable> throwableSupplier = () -> null; private final String local; private final Collection<String> connectedSites; private final Collection<String> disconnectedSites; ControlledTransport(Transport actual, String local, Collection<String> connectedSites, Collection<String> disconnectedSites) { super(actual); this.local = local; this.connectedSites = connectedSites; this.disconnectedSites = disconnectedSites; } ControlledTransport(Transport actual, String local, Collection<String> disconnectedSites) { this(actual, local, Collections.singleton(local), disconnectedSites); } @Override public void start() { //already started } @Override public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) { Throwable t = null; if (disconnectedSites.contains(backup.getSiteName())) t = throwableSupplier.get(); ControlledXSiteResponse<O> response = new ControlledXSiteResponse<>(backup, t); response.complete(); return response; } @Override public void checkCrossSiteAvailable() throws CacheConfigurationException { //no-op == it is available } @Override public String localSiteName() { return local; } @Override public Set<String> getSitesView() { return Set.copyOf(connectedSites); } private static class ControlledXSiteResponse<T> extends CompletableFuture<T> implements XSiteResponse<T> { private final XSiteBackup backup; private final Throwable result; private ControlledXSiteResponse(XSiteBackup backup, Throwable result) { this.backup = backup; this.result = result; } @Override public void whenCompleted(XSiteResponseCompleted listener) { listener.onCompleted(backup, System.currentTimeMillis(), 0, result); } void complete() { if (result == null) { complete(null); } else { completeExceptionally(result); } } } }
2,754
29.611111
109
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracAlwaysRemoveConflictTest.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.util.TestOperation; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.spi.AlwaysRemoveXSiteEntryMergePolicy; import org.infinispan.xsite.spi.XSiteMergePolicy; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Function test for {@link AlwaysRemoveXSiteEntryMergePolicy}. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.IracAlwaysRemoveConflictTest") public class IracAlwaysRemoveConflictTest extends AbstractMultipleSitesTest { private static final int N_SITES = 2; private static final int CLUSTER_SIZE = 3; private final List<ManualIracManager> iracManagerList; protected IracAlwaysRemoveConflictTest() { this.iracManagerList = new ArrayList<>(N_SITES * CLUSTER_SIZE); } public void testPutIfAbsent(Method method) { doTest(method, TestOperation.PUT_IF_ABSENT); } public void testPut(Method method) { doTest(method, TestOperation.PUT); } public void testReplace(Method method) { doTest(method, TestOperation.REPLACE); } public void testConditionalReplace(Method method) { doTest(method, TestOperation.REPLACE_CONDITIONAL); } public void testRemove(Method method) { doTest(method, TestOperation.REMOVE); } public void testConditionalRemove(Method method) { doTest(method, TestOperation.REMOVE_CONDITIONAL); } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.sites().mergePolicy(XSiteMergePolicy.ALWAYS_REMOVE); for (int i = 0; i < N_SITES; ++i) { if (i == siteIndex) { //don't add our site as backup. continue; } builder.sites() .addBackup() .site(siteName(i)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { iracManagerList.forEach(iracManager -> iracManager.disable(ManualIracManager.DisableMode.DROP)); super.clearContent(); } @Override protected void afterSitesCreated() { for (int i = 0; i < N_SITES; ++i) { for (Cache<?, ?> cache : caches(siteName(i))) { iracManagerList.add(ManualIracManager.wrapCache(cache)); } } } private void doTest(Method method, TestOperation testConfig) { final String key = TestingUtil.k(method, 0); final String initialValue = testConfig.requiresPreviousValue() ? TestingUtil.v(method, 0) : null; //init cache if needed! if (testConfig.requiresPreviousValue()) { cache(siteName(0), 0).put(key, initialValue); } eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(initialValue, cache.get(key))); //disable xsite so each site won't send anything to the others iracManagerList.forEach(ManualIracManager::enable); //put a conflict value. each site has a different value for the same key String[] finalValues = new String[N_SITES]; for (int i = 0; i < N_SITES; ++i) { String newValue = TestingUtil.v(method, (i + 1) * 2); if ((testConfig == TestOperation.REMOVE_CONDITIONAL || testConfig == TestOperation.REMOVE) && i > 0) { //to make sure remove works, we remove from LON only since it is the winning site. //the other sites put other value. cache(siteName(i), 0).put(key, newValue); finalValues[i] = newValue; } else { finalValues[i] = testConfig.execute(cache(siteName(i), 0), key, initialValue, newValue); } } //check if everything is correct for (int i = 0; i < N_SITES; ++i) { String fValue = finalValues[i]; assertInSite(siteName(i), cache -> assertEquals(fValue, cache.get(key))); } //enable xsite. this will send the keys! iracManagerList.forEach(manualIracManager -> manualIracManager.disable(ManualIracManager.DisableMode.SEND)); eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(null, cache.get(key))); assertNoDataLeak(null); } }
5,370
33.876623
114
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracOwnershipChangeTest.java
package org.infinispan.xsite.irac; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.FlagBitSets; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.interceptors.impl.NonTxIracLocalSiteInterceptor; import org.infinispan.test.TestingUtil; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.AssertJUnit; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests topology change while write command is executing. * * @since 14.0 */ @Test(groups = "functional", testName = "xsite.irac.IracOwnershipChangeTest") public class IracOwnershipChangeTest extends AbstractMultipleSitesTest { private final ControlledConsistentHashFactory<?> site0CHFactory = new ControlledConsistentHashFactory.Default(0, 1); private final ControlledConsistentHashFactory<?> site1CHFactory = new ControlledConsistentHashFactory.Default(0, 1); @Override protected int defaultNumberOfSites() { return 2; } @Override protected int defaultNumberOfNodes() { return 3; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.clustering().hash() .numSegments(1) .numOwners(2) .consistentHashFactory(siteIndex == 0 ? site0CHFactory : site1CHFactory); builder.sites().addBackup() .site(siteName(siteIndex == 0 ? 1 : 0)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder; } @BeforeMethod(alwaysRun = true) @Override public void createBeforeMethod() { super.createBeforeMethod(); // reset consistent hash site0CHFactory.setOwnerIndexes(0, 1); site1CHFactory.setOwnerIndexes(0, 1); site0CHFactory.triggerRebalance(cache(0, 0)); site1CHFactory.triggerRebalance(cache(1, 0)); site(0).waitForClusterToForm(null); site(1).waitForClusterToForm(null); } public void testPrimaryOwnerLosesOwnership() throws InterruptedException, ExecutionException, TimeoutException { String key = "key-1"; String value = "primary-loses-ownership"; assertOwnership(key, 0, 1, 2); BlockingInterceptor interceptor = blockingInterceptor(0, 0); CommandBlocker blocker = interceptor.blockCommand(); CompletableFuture<?> stage = cache(0, 0).putAsync(key, value); AssertJUnit.assertTrue(blocker.blocked.await(10, TimeUnit.SECONDS)); site0CHFactory.setOwnerIndexes(1, 2); site0CHFactory.triggerRebalance(cache(0, 0)); site(0).waitForClusterToForm(null); assertOwnership(key, 1, 2, 0); blocker.release(); stage.get(10, TimeUnit.SECONDS); eventuallyAssertInAllSitesAndCaches(cache -> value.equals(cache.get(key))); } public void testBackupOwnerLosesOwnership() throws InterruptedException, ExecutionException, TimeoutException { String key = "key-2"; String value = "backup-loses-ownership"; assertOwnership(key, 0, 1, 2); BlockingInterceptor interceptor = blockingInterceptor(0, 1); CommandBlocker blocker = interceptor.blockCommand(); CompletableFuture<?> stage = cache(0, 1).putAsync(key, value); AssertJUnit.assertTrue(blocker.blocked.await(10, TimeUnit.SECONDS)); site0CHFactory.setOwnerIndexes(0, 2); site0CHFactory.triggerRebalance(cache(0, 0)); site(0).waitForClusterToForm(null); assertOwnership(key, 0, 2, 1); blocker.release(); stage.get(10, TimeUnit.SECONDS); eventuallyAssertInAllSitesAndCaches(cache -> value.equals(cache.get(key))); } public void testPrimaryChangesOwnershipWithBackup() throws InterruptedException, ExecutionException, TimeoutException { String key = "key-3"; String value = "primary-backup-swap"; assertOwnership(key, 0, 1, 2); BlockingInterceptor interceptor = blockingInterceptor(0, 0); CommandBlocker blocker = interceptor.blockCommand(); CompletableFuture<?> stage = cache(0, 0).putAsync(key, value); AssertJUnit.assertTrue(blocker.blocked.await(10, TimeUnit.SECONDS)); site0CHFactory.setOwnerIndexes(1, 0); site0CHFactory.triggerRebalance(cache(0, 0)); site(0).waitForClusterToForm(null); assertOwnership(key, 1, 0, 2); blocker.release(); stage.get(10, TimeUnit.SECONDS); eventuallyAssertInAllSitesAndCaches(cache -> value.equals(cache.get(key))); } public void testNonOwnerBecomesBackup() throws InterruptedException, ExecutionException, TimeoutException { String key = "key-4"; String value = "non-owner-to-backup"; assertOwnership(key, 0, 1, 2); BlockingInterceptor interceptor = blockingInterceptor(0, 2); CommandBlocker blocker = interceptor.blockCommand(); CompletableFuture<?> stage = cache(0, 2).putAsync(key, value); AssertJUnit.assertTrue(blocker.blocked.await(10, TimeUnit.SECONDS)); site0CHFactory.setOwnerIndexes(0, 2); site0CHFactory.triggerRebalance(cache(0, 0)); site(0).waitForClusterToForm(null); assertOwnership(key, 0, 2, 1); blocker.release(); stage.get(10, TimeUnit.SECONDS); eventuallyAssertInAllSitesAndCaches(cache -> value.equals(cache.get(key))); } public void testNonOwnerBecomesPrimary() throws InterruptedException, ExecutionException, TimeoutException { String key = "key-5"; String value = "non-owner-to-backup"; assertOwnership(key, 0, 1, 2); BlockingInterceptor interceptor = blockingInterceptor(0, 2); CommandBlocker blocker = interceptor.blockCommand(); CompletableFuture<?> stage = cache(0, 2).putAsync(key, value); AssertJUnit.assertTrue(blocker.blocked.await(10, TimeUnit.SECONDS)); site0CHFactory.setOwnerIndexes(2, 1); site0CHFactory.triggerRebalance(cache(0, 0)); site(0).waitForClusterToForm(null); assertOwnership(key, 2, 1, 0); blocker.release(); stage.get(10, TimeUnit.SECONDS); eventuallyAssertInAllSitesAndCaches(cache -> value.equals(cache.get(key))); } private LocalizedCacheTopology cacheTopology(int site, int index) { return TestingUtil.extractCacheTopology(cache(site, index)); } private BlockingInterceptor blockingInterceptor(int site, int index) { AsyncInterceptorChain interceptorChain = TestingUtil.extractInterceptorChain(cache(site, index)); BlockingInterceptor interceptor = interceptorChain.findInterceptorExtending(BlockingInterceptor.class); if (interceptor != null) { return interceptor; } interceptor = new BlockingInterceptor(); AssertJUnit.assertTrue(interceptorChain.addInterceptorAfter(interceptor, NonTxIracLocalSiteInterceptor.class)); return interceptor; } private void assertOwnership(String key, int primary, int backup, int nonOwner) { AssertJUnit.assertTrue(cacheTopology(0, primary).getDistribution(key).isPrimary()); AssertJUnit.assertTrue(cacheTopology(0, backup).getDistribution(key).isWriteBackup()); AssertJUnit.assertFalse(cacheTopology(0, nonOwner).getDistribution(key).isWriteOwner()); } public static class BlockingInterceptor extends DDAsyncInterceptor { volatile CommandBlocker afterCompleted; @Override public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { CommandBlocker blocker = afterCompleted; if (blocker == null || blocker.delay.isDone() || command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)) { log.tracef("Skipping command %s", command); return invokeNext(ctx, command); } return invokeNextAndHandle(ctx, command, (rCtx, rCommand, rv, throwable) -> delayedValue(blocker.notifyBlocked(rCommand), rv, throwable)); } CommandBlocker blockCommand() { CommandBlocker existing; CommandBlocker newBlocker = new CommandBlocker(new CountDownLatch(1), new CompletableFuture<>()); synchronized (this) { existing = afterCompleted; afterCompleted = newBlocker; } if (existing != null) { existing.release(); } return newBlocker; } } private static class CommandBlocker { final CountDownLatch blocked; final CompletableFuture<Void> delay; CommandBlocker(CountDownLatch blocked, CompletableFuture<Void> delay) { this.blocked = Objects.requireNonNull(blocked); this.delay = Objects.requireNonNull(delay); } CompletableFuture<Void> notifyBlocked(Object command) { log.tracef("Blocking command %s", command); blocked.countDown(); return delay.thenRun(() -> log.tracef("Unblocking command %s", command)); } void release() { blocked.countDown(); delay.complete(null); } } }
9,709
35.231343
147
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/ControlledExponentialBackOff.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import org.infinispan.util.ExponentialBackOff; import org.testng.AssertJUnit; public class ControlledExponentialBackOff implements ExponentialBackOff { private String name; private final BlockingDeque<Event> backOffEvents; private volatile CompletableFuture<Void> backOff = new CompletableFuture<>(); ControlledExponentialBackOff() { backOffEvents = new LinkedBlockingDeque<>(); } ControlledExponentialBackOff(String name) { this(); this.name = name; } @Override public void reset() { backOffEvents.add(Event.RESET); } @Override public CompletionStage<Void> asyncBackOff() { CompletionStage<Void> stage = backOff; // add to the event after getting the completable future backOffEvents.add(Event.BACK_OFF); return stage; } void release() { backOff.complete(null); this.backOff = new CompletableFuture<>(); } void cleanupEvents() { backOffEvents.clear(); } void eventually(String message, Event... expected) { List<Event> events = new ArrayList<>(Arrays.asList(expected)); while (!events.isEmpty()) { Event current = null; try { current = backOffEvents.poll(30, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); AssertJUnit.fail(e.getMessage()); } assertTrue("At " + name + ": " + message + " Expected " + events + ", current " + current, events.contains(current)); events.remove(current); } } void containsOnly(String message, Event event) { while (!backOffEvents.isEmpty()) { eventually(message, event); } } void assertNoEvents() { assertTrue("At " + name + ": Expected no events, found: " + backOffEvents, backOffEvents.isEmpty()); } enum Event { BACK_OFF, RESET } }
2,294
26
126
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracMaxIdleTest.java
package org.infinispan.xsite.irac; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests if max-idle expiration works properly with x-site (ISPN-13057) * * @author Pedro Ruivo * @since 13.0 */ @Test(groups = "functional", testName = "xsite.irac.IracMaxIdleTest") public class IracMaxIdleTest extends AbstractMultipleSitesTest { private static final long MAX_IDLE = 1000; //milliseconds private final ControlledTimeService timeService = new ControlledTimeService(); @Override protected int defaultNumberOfSites() { return 2; } @Override protected int defaultNumberOfNodes() { return 1; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); builder.expiration().reaperEnabled(false); builder.sites().addBackup() .site(siteIndex == 0 ? siteName(1) : siteName(0)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder; } @DataProvider(name = "data") public Object[][] data() { return new Object[][]{ {TestData.NON_TX}, {TestData.PESSIMISTIC}, {TestData.OPTIMISTIC} }; } @Test(dataProvider = "data") public void testMaxIdle(TestData testData) { final String cacheName = createCaches(testData); List<ManualIracManager> iracManagers = caches(0, cacheName).stream() .map(ManualIracManager::wrapCache) .peek(m -> m.disable(ManualIracManager.DisableMode.DROP)) // reset state .collect(Collectors.toList()); final String key = createKeyOrValue(testData, "key"); final String value = createKeyOrValue(testData, "value"); cache(0, 0, cacheName).put(key, value, -1, TimeUnit.MILLISECONDS, MAX_IDLE, TimeUnit.MILLISECONDS); eventuallyAssertInAllSitesAndCaches(cacheName, c -> Objects.equals(value, c.get(key))); // block xsite replication (remove expired). // the touch command is not blocked iracManagers.forEach(ManualIracManager::enable); timeService.advance(MAX_IDLE + 1); // get should trigger the expiration assertNull(cache(0, 0, cacheName).get(key)); // one of them should have the key there assertTrue(iracManagers.stream().anyMatch(ManualIracManager::hasPendingKeys)); // let the key go iracManagers.forEach(ManualIracManager::sendKeys); // eventually it should go eventually(() -> iracManagers.stream().noneMatch(ManualIracManager::hasPendingKeys)); eventually(() -> iracManagers.stream().allMatch(ManualIracManager::isEmpty)); assertNoKeyInDataContainer(1, cacheName, key); assertNoKeyInDataContainer(0, cacheName, key); assertNoDataLeak(cacheName); } private static String createKeyOrValue(TestData testData, String prefix) { switch (testData) { case NON_TX: return prefix + "_ntx_"; case PESSIMISTIC: return prefix + "_pes_"; case OPTIMISTIC: return prefix + "_opt_"; default: throw new IllegalStateException(String.valueOf(testData)); } } private String createCaches(TestData testData) { String cacheName; LockingMode lockingMode; switch (testData) { case NON_TX: // default cache is fine return null; case PESSIMISTIC: cacheName = "pes_cache"; lockingMode = LockingMode.PESSIMISTIC; break; case OPTIMISTIC: cacheName = "opt_cache"; lockingMode = LockingMode.OPTIMISTIC; break; default: throw new IllegalStateException(String.valueOf(testData)); } for (int i = 0; i < defaultNumberOfSites(); ++i) { defineInSite(site(i), cacheName, defaultConfigurationForSite(i) .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(lockingMode) .build()); site(i).waitForClusterToForm(cacheName); } return cacheName; } private void assertNoKeyInDataContainer(int siteIndex, String cacheName, String key) { for (Cache<String, String> c : this.<String, String>caches(siteIndex, cacheName)) { assertNull(internalDataContainer(c).peek(key)); } } private InternalDataContainer<String, String> internalDataContainer(Cache<String, String> c) { //noinspection unchecked return extractComponent(c, InternalDataContainer.class); } @Override protected void afterSitesCreated() { super.afterSitesCreated(); for (int i = 0; i < defaultNumberOfSites(); ++i) { site(i).cacheManagers().forEach(cm -> replaceComponent(cm, TimeService.class, timeService, true)); } } private enum TestData { NON_TX, PESSIMISTIC, OPTIMISTIC } }
5,837
33.140351
107
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/Irac3SitesConflictTest.java
package org.infinispan.xsite.irac; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.util.TestOperation; import org.infinispan.util.concurrent.CompletionStages; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests if the simple conflict resolution works with 3 sites. * * @author Pedro Ruivo * @since 11.0 */ // TODO: unstable due to https://issues.redhat.com/browse/ISPN-13442 @Test(groups = "unstable", testName = "xsite.irac.Irac3SitesConflictTest") public class Irac3SitesConflictTest extends AbstractMultipleSitesTest { private static final int N_SITES = 3; private static final int CLUSTER_SIZE = 3; private final List<ManualIracManager> iracManagerList; private ConfigMode configMode; public Irac3SitesConflictTest configMode(ConfigMode configMode) { this.configMode = configMode; return this; } private enum ConfigMode { NON_TX, PESSIMISTIC_TX, OPTIMISTIC_TX_RC, OPTIMISTIC_TX_RR, } @Factory public Object[] factory() { List<Irac3SitesConflictTest> tests = new ArrayList<>(); for (ConfigMode configMode : ConfigMode.values()) { tests.add(new Irac3SitesConflictTest().configMode(configMode)); } return tests.toArray(); } @Override protected String[] parameterNames() { return new String[]{"configMode"}; } @Override protected Object[] parameterValues() { return new Object[]{configMode}; } protected Irac3SitesConflictTest() { this.iracManagerList = new ArrayList<>(N_SITES * CLUSTER_SIZE); } public void testPutIfAbsent(Method method) { doTest(method, new TestOperationInterop(TestOperation.PUT_IF_ABSENT)); } public void testPut(Method method) { doTest(method, new TestOperationInterop(TestOperation.PUT)); } public void testReplace(Method method) { doTest(method, new TestOperationInterop(TestOperation.REPLACE)); } public void testConditionalReplace(Method method) { doTest(method, new TestOperationInterop(TestOperation.REPLACE_CONDITIONAL)); } public void testRemove(Method method) { doTest(method, new TestOperationInterop(TestOperation.REMOVE)); } public void testConditionalRemove(Method method) { doTest(method, new TestOperationInterop(TestOperation.REMOVE_CONDITIONAL)); } // TODO: need to do this still? // public void testMaxIdleExpirationASync(Method method) { // doTest(method, TestOperation.REMOVE_MAX_IDLE_EXPIRED_ASYNC); // } // public void testMaxIdleExpirationSync(Method method) { doTest(method, new RemoveExpiredOperation(replaceTimeService())); } private ControlledTimeService replaceTimeService() { ControlledTimeService timeService = new ControlledTimeService(); for (int i = 0; i < N_SITES; i++) { String siteName = siteName(i); for (int j = 0; j < CLUSTER_SIZE; ++j) { Cache<?, ?> c = cache(siteName, j); // Max idle requires all caches to show it as expired to be removed. TestingUtil.replaceComponent(c.getCacheManager(), TimeService.class, timeService, true); } } return timeService; } interface IracTestOperation { <K, V> V execute(Cache<K, V> cache, K key, V prevValue, V newValue); boolean isRemove(); <K, V> V insertValueAndReturnIfRequired(Cache<K, V> cache, K key, V value); default <V> V getValueFromArray(V[] array) { return array[0]; } } static class RemoveExpiredOperation implements IracTestOperation { private final ControlledTimeService timeService; RemoveExpiredOperation(ControlledTimeService timeService) { this.timeService = timeService; } @Override public <K, V> V execute(Cache<K, V> cache, K key, V prevValue, V newValue) { timeService.advance(TimeUnit.SECONDS.toMillis(10)); CompletionStages.join(cache.getAdvancedCache().removeMaxIdleExpired(key, prevValue)); return null; } @Override public boolean isRemove() { return true; } @Override public <K, V> V insertValueAndReturnIfRequired(Cache<K, V> cache, K key, V value) { cache.put(key, value, -1, TimeUnit.SECONDS, 5, TimeUnit.SECONDS); return value; } @Override public <V> V getValueFromArray(V[] array) { // Our final value is a remove, however the put should win! return array[1]; } } static class TestOperationInterop implements IracTestOperation { private final TestOperation testOperation; TestOperationInterop(TestOperation testOperation) { this.testOperation = testOperation; } @Override public <K, V> V execute(Cache<K, V> cache, K key, V prevValue, V newValue) { return testOperation.execute(cache, key, prevValue, newValue); } @Override public boolean isRemove() { return TestOperation.REMOVE == testOperation || TestOperation.REMOVE_CONDITIONAL == testOperation; } @Override public <K, V> V insertValueAndReturnIfRequired(Cache<K, V> cache, K key, V value) { if (testOperation.requiresPreviousValue()) { cache.put(key, value); return value; } return null; } } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, configMode != ConfigMode.NON_TX); switch (configMode) { case OPTIMISTIC_TX_RC: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.READ_COMMITTED); break; case OPTIMISTIC_TX_RR: builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); break; case PESSIMISTIC_TX: builder.transaction().lockingMode(LockingMode.PESSIMISTIC); break; } for (int i = 0; i < N_SITES; ++i) { if (i == siteIndex) { //don't add our site as backup. continue; } builder.sites() .addBackup() .site(siteName(i)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { iracManagerList.forEach(iracManager -> iracManager.disable(ManualIracManager.DisableMode.DROP)); super.clearContent(); } @Override protected void afterSitesCreated() { for (int i = 0; i < N_SITES; ++i) { for (Cache<?, ?> cache : caches(siteName(i))) { iracManagerList.add(ManualIracManager.wrapCache(cache)); } } } private void doTest(Method method, IracTestOperation testConfig) { final String key = TestingUtil.k(method, 0); final String initialValue = testConfig.insertValueAndReturnIfRequired(cache(siteName(0), 0), key, TestingUtil.v(method, 0)); eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(initialValue, cache.get(key))); //disable xsite so each site won't send anything to the others iracManagerList.forEach(ManualIracManager::enable); //put a conflict value. each site has a different value for the same key String[] finalValues = new String[N_SITES]; for (int i = 0; i < N_SITES; ++i) { String newValue = TestingUtil.v(method, (i + 1) * 2); if (testConfig.isRemove() && i > 0) { //to make sure remove works, we remove from LON only since it is the winning site. //the other sites put other value. cache(siteName(i), 0).put(key, newValue); finalValues[i] = newValue; } else { finalValues[i] = testConfig.execute(cache(siteName(i), 0), key, initialValue, newValue); } } //check if everything is correct for (int i = 0; i < N_SITES; ++i) { String fValue = finalValues[i]; assertInSite(siteName(i), cache -> AssertJUnit.assertEquals(fValue, cache.get(key))); } //enable xsite. this will send the keys! iracManagerList.forEach(manualIracManager -> manualIracManager.disable(ManualIracManager.DisableMode.SEND)); String expectedFinalValue = testConfig.getValueFromArray(finalValues); eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(expectedFinalValue, cache.get(key))); assertNoDataLeak(null); } }
10,010
32.820946
122
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracExponentialBackOffTest.java
package org.infinispan.xsite.irac; import java.lang.reflect.Method; import java.util.Collections; import java.util.function.Supplier; import org.infinispan.commons.CacheException; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.ExponentialBackOff; import org.jgroups.UnreachableException; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Function test for exponential back-off with IRAC. * <p> * It tests if the {@link DefaultIracManager} respects the exception and invokes the proper {@link ExponentialBackOff} * methods. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.iract.IracExponentialBackOffTest") public class IracExponentialBackOffTest extends SingleCacheManagerTest { private static final String LON = "LON"; private static final String NYC = "NYC"; private static final String CACHE_NAME = "irac-exponential-backoff"; private static final Supplier<Throwable> NO_EXCEPTION = () -> null; private final ControlledExponentialBackOff backOff = new ControlledExponentialBackOff(); private volatile ControlledTransport transport; private volatile DefaultIracManager iracManager; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { //default cache manager EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createClusteredCacheManager(); this.transport = TestingUtil.wrapGlobalComponent(cacheManager, Transport.class, actual -> new ControlledTransport(actual, LON, Collections.singleton(NYC)), true); this.cache = cacheManager.administration() .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(CACHE_NAME, createCacheConfiguration().build()); iracManager = (DefaultIracManager) TestingUtil.extractComponent(cache, IracManager.class); iracManager.setBackOff(backup -> backOff); return cacheManager; } @AfterMethod(alwaysRun = true) public void resetStateAfterTest() { backOff.release(); eventually(iracManager::isEmpty); backOff.cleanupEvents(); backOff.assertNoEvents(); } private static ConfigurationBuilder createCacheConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.sites().addBackup() .site(NYC) .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder; } public void testSimulatedTimeout(Method method) throws InterruptedException { doTest(method, () -> log.requestTimedOut(1, NYC, "some time")); } public void testSimulatedUnreachableException(Method method) throws InterruptedException { doTest(method, () -> new UnreachableException(null)); } public void testSimulatedSiteUnreachableEvent(Method method) throws InterruptedException { doTest(method, () -> log.remoteNodeSuspected(null)); } public void testNoBackoffOnOtherException(Method method) throws InterruptedException { transport.throwableSupplier = CacheException::new; final String key = TestingUtil.k(method); final String value = TestingUtil.v(method); cache.put(key, value); backOff.eventually("Reset event with CacheException.", ControlledExponentialBackOff.Event.RESET); //with "normal" exception, the protocol will keep trying to send the request //we need to let it have a successful request otherwise it will fill queue with RESET events. transport.throwableSupplier = NO_EXCEPTION; eventually(iracManager::isEmpty); backOff.cleanupEvents(); backOff.assertNoEvents(); } private void doTest(Method method, Supplier<Throwable> throwableSupplier) throws InterruptedException { transport.throwableSupplier = throwableSupplier; final String key = TestingUtil.k(method); final String value = TestingUtil.v(method); cache.put(key, value); backOff.eventually("Backoff event on first try.", ControlledExponentialBackOff.Event.BACK_OFF); //the release should trigger another back off event backOff.release(); backOff.eventually("Backoff event on second try.", ControlledExponentialBackOff.Event.BACK_OFF); //no exception, request will be completed. transport.throwableSupplier = NO_EXCEPTION; backOff.release(); eventually(iracManager::isEmpty); //backOff.eventually("Reset event after successful try operations", ControlledExponentialBackOff.Event.RESET); backOff.eventually("Reset event after successful try", ControlledExponentialBackOff.Event.RESET); backOff.assertNoEvents(); } }
5,180
39.795276
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracTombstoneCleanupTest.java
package org.infinispan.xsite.irac; import static org.infinispan.test.TestingUtil.extractCacheTopology; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.wrapComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.function.Function; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.irac.IracTombstoneCleanupCommand; import org.infinispan.commands.irac.IracTombstonePrimaryCheckCommand; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.versioning.irac.DefaultIracTombstoneManager; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.IracTombstoneInfo; import org.infinispan.container.versioning.irac.IracTombstoneManager; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.rpc.RpcOptions; import org.infinispan.remoting.transport.Address; import org.infinispan.remoting.transport.ResponseCollector; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.util.AbstractDelegatingRpcManager; import org.infinispan.util.ByteString; import org.infinispan.xsite.status.TakeOfflineManager; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import net.jcip.annotations.GuardedBy; /** * Basic tests for IRAC tombstone cleanup * * @since 14.0 */ @Test(groups = "xsite", testName = "xsite.irac.IracTombstoneCleanupTest") public class IracTombstoneCleanupTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "xsite-tombstone"; private static final String SITE_NAME = "LON-1"; @Override protected void createCacheManagers() throws Throwable { TransportFlags flags = new TransportFlags().withSiteIndex(0).withSiteName(SITE_NAME).withFD(true); createClusteredCaches(3, CACHE_NAME, cacheConfiguration(), flags); for (Cache<?, ?> cache : caches(CACHE_NAME)) { // stop automatic cleanup to avoid adding random events to the tests tombstoneManager(cache).stopCleanupTask(); extractComponent(cache, TakeOfflineManager.class).takeSiteOffline("NYC"); } } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { for (Cache<String, String> cache : this.<String, String>caches(CACHE_NAME)) { recordingRpcManager(cache).stopRecording(); } super.clearContent(); } private static ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); builder.clustering().hash().numOwners(2).numSegments(16); builder.sites().addBackup().site("NYC").strategy(BackupConfiguration.BackupStrategy.ASYNC).stateTransfer().chunkSize(1); return builder; } public void testPrimaryOwnerRoundCleanupsBackup(Method method) { String key = k(method); int segment = getSegment(key); Cache<String, String> pCache = findPrimaryOwner(segment); Cache<String, String> bCache = findBackupOwner(segment); IracMetadata metadata = dummyMetadata(1); tombstoneManager(pCache).storeTombstone(segment, key, metadata); tombstoneManager(bCache).storeTombstone(segment, key, metadata); assertEquals(1, tombstoneManager(pCache).size()); assertEquals(1, tombstoneManager(bCache).size()); RecordingRpcManager pRpcManager = recordingRpcManager(pCache); pRpcManager.startRecording(); tombstoneManager(pCache).runCleanupAndWait(); eventuallyEquals(0, () -> tombstoneManager(pCache).size()); eventuallyEquals(0, () -> tombstoneManager(bCache).size()); IracTombstoneCleanupCommand cmd = pRpcManager.findSingleCommand(IracTombstoneCleanupCommand.class); assertNotNull(cmd); assertEquals(1, cmd.getTombstonesToRemove().size()); IracTombstoneInfo tombstone = cmd.getTombstonesToRemove().iterator().next(); assertEquals(segment, tombstone.getSegment()); assertEquals(key, tombstone.getKey()); assertEquals(metadata, tombstone.getMetadata()); } public void testBackupOwnerRoundCleanupDoNotCleanupPrimary(Method method) { String key = k(method); int segment = getSegment(key); Cache<String, String> pCache = findPrimaryOwner(segment); Cache<String, String> bCache = findBackupOwner(segment); IracMetadata metadata = dummyMetadata(2); tombstoneManager(pCache).storeTombstone(segment, key, metadata); tombstoneManager(bCache).storeTombstone(segment, key, metadata); assertEquals(1, tombstoneManager(pCache).size()); assertEquals(1, tombstoneManager(bCache).size()); RecordingRpcManager pRpcManager = recordingRpcManager(pCache); RecordingRpcManager bRpcManager = recordingRpcManager(bCache); pRpcManager.startRecording(); bRpcManager.startRecording(); tombstoneManager(bCache).runCleanupAndWait(); IracTombstonePrimaryCheckCommand cmd = bRpcManager.findSingleCommand(IracTombstonePrimaryCheckCommand.class); assertNotNull(cmd); assertEquals(1, cmd.getTombstoneToCheck().size()); IracTombstoneInfo tombstoneInfo = cmd.getTombstoneToCheck().iterator().next(); assertEquals(segment, tombstoneInfo.getSegment()); assertEquals(key, tombstoneInfo.getKey()); assertEquals(metadata, tombstoneInfo.getMetadata()); assertFalse(pRpcManager.isCommandSent(IracTombstoneCleanupCommand.class)); // check if nothing is removed... should we sleep here? assertEquals(1, tombstoneManager(pCache).size()); assertEquals(1, tombstoneManager(bCache).size()); // remove tombstone to avoid messing up with other tests tombstoneManager(pCache).removeTombstone(key); tombstoneManager(bCache).removeTombstone(key); } public void testNonOwnerRoundCleanupLocally(Method method) { String key = k(method); int segment = getSegment(key); Cache<String, String> pCache = findPrimaryOwner(segment); Cache<String, String> bCache = findBackupOwner(segment); Cache<String, String> nCache = findNonOwner(segment); IracMetadata metadata = dummyMetadata(3); tombstoneManager(pCache).storeTombstone(segment, key, metadata); tombstoneManager(bCache).storeTombstone(segment, key, metadata); tombstoneManager(nCache).storeTombstone(segment, key, metadata); assertEquals(1, tombstoneManager(pCache).size()); assertEquals(1, tombstoneManager(bCache).size()); assertEquals(1, tombstoneManager(nCache).size()); RecordingRpcManager pRpcManager = recordingRpcManager(pCache); RecordingRpcManager bRpcManager = recordingRpcManager(bCache); RecordingRpcManager nRpcManager = recordingRpcManager(nCache); pRpcManager.startRecording(); bRpcManager.startRecording(); nRpcManager.startRecording(); tombstoneManager(nCache).runCleanupAndWait(); // check if nothing is removed... should we sleep here? assertEquals(1, tombstoneManager(pCache).size()); assertEquals(1, tombstoneManager(bCache).size()); assertEquals(0, tombstoneManager(nCache).size()); assertFalse(nRpcManager.isCommandSent(IracTombstonePrimaryCheckCommand.class)); assertFalse(nRpcManager.isCommandSent(IracTombstoneCleanupCommand.class)); assertFalse(bRpcManager.isCommandSent(IracTombstonePrimaryCheckCommand.class)); assertFalse(bRpcManager.isCommandSent(IracTombstoneCleanupCommand.class)); assertFalse(pRpcManager.isCommandSent(IracTombstonePrimaryCheckCommand.class)); assertFalse(pRpcManager.isCommandSent(IracTombstoneCleanupCommand.class)); // remove tombstone to avoid messing up with other tests tombstoneManager(pCache).removeTombstone(key); tombstoneManager(bCache).removeTombstone(key); } public void testStateTransfer(Method method) { int numberOfKeys = 100; List<IracTombstoneInfo> keys = new ArrayList<>(numberOfKeys); for (int i = 0; i < numberOfKeys; ++i) { String key = k(method, i); int segment = getSegment(key); IracMetadata metadata = dummyMetadata(i * 2); keys.add(new IracTombstoneInfo(key, segment, metadata)); } Cache<String, String> cache0 = cache(0, CACHE_NAME); Cache<String, String> cache1 = cache(1, CACHE_NAME); for (IracTombstoneInfo tombstoneInfo : keys) { tombstoneManager(cache1).storeTombstone(tombstoneInfo.getSegment(), tombstoneInfo.getKey(), tombstoneInfo.getMetadata()); } assertEquals(0, tombstoneManager(cache0).size()); assertEquals(numberOfKeys, tombstoneManager(cache1).size()); // request singe segment int segment = keys.get(0).getSegment(); tombstoneManager(cache1).sendStateTo(address(cache0), IntSets.immutableSet(segment)); List<IracTombstoneInfo> segmentKeys = keys.stream() .filter(tombstoneInfo -> segment == tombstoneInfo.getSegment()) .collect(Collectors.toList()); // wait until it is transferred eventuallyEquals(segmentKeys.size(), () -> tombstoneManager(cache0).size()); for (IracTombstoneInfo tombstone : segmentKeys) { assertTrue(tombstoneManager(cache0).contains(tombstone)); } // send all segments tombstoneManager(cache1).sendStateTo(address(cache0), IntSets.immutableRangeSet(16)); eventuallyEquals(numberOfKeys, () -> tombstoneManager(cache0).size()); for (IracTombstoneInfo tombstone : keys) { assertTrue(tombstoneManager(cache0).contains(tombstone)); } } private Cache<String, String> findPrimaryOwner(int segment) { for (Cache<String, String> cache : this.<String, String>caches(CACHE_NAME)) { if (extractCacheTopology(cache).getSegmentDistribution(segment).isPrimary()) { return cache; } } throw new IllegalStateException("Find primary owner failed!"); } private Cache<String, String> findBackupOwner(int segment) { for (Cache<String, String> cache : this.<String, String>caches(CACHE_NAME)) { if (extractCacheTopology(cache).getSegmentDistribution(segment).isWriteBackup()) { return cache; } } throw new IllegalStateException("Find backup owner failed!"); } private Cache<String, String> findNonOwner(int segment) { for (Cache<String, String> cache : this.<String, String>caches(CACHE_NAME)) { if (!extractCacheTopology(cache).getSegmentDistribution(segment).isWriteOwner()) { return cache; } } throw new IllegalStateException("Find non owner failed!"); } private static IracMetadata dummyMetadata(long version) { TopologyIracVersion iracVersion = TopologyIracVersion.create(1, version); return new IracMetadata(SITE_NAME, IracEntryVersion.newVersion(ByteString.fromString(SITE_NAME), iracVersion)); } private int getSegment(String key) { return extractCacheTopology(cache(0, CACHE_NAME)).getSegment(key); } private static DefaultIracTombstoneManager tombstoneManager(Cache<?, ?> cache) { IracTombstoneManager tombstoneManager = extractComponent(cache, IracTombstoneManager.class); assert tombstoneManager instanceof DefaultIracTombstoneManager; return (DefaultIracTombstoneManager) tombstoneManager; } private static RecordingRpcManager recordingRpcManager(Cache<?, ?> cache) { RpcManager rpcManager = extractComponent(cache, RpcManager.class); if (rpcManager instanceof RecordingRpcManager) { return (RecordingRpcManager) rpcManager; } return wrapComponent(cache, RpcManager.class, RecordingRpcManager::new); } private static class RecordingRpcManager extends AbstractDelegatingRpcManager { @GuardedBy("this") private final List<CacheRpcCommand> commandList; private volatile boolean recording; RecordingRpcManager(RpcManager realOne) { super(realOne); commandList = new LinkedList<>(); } <T extends CacheRpcCommand> T findSingleCommand(Class<T> commandClass) { T found = null; synchronized (this) { for (CacheRpcCommand rpcCommand : commandList) { if (rpcCommand.getClass() == commandClass) { if (found != null) { fail("More than one " + commandClass + " found in list: " + commandList); } found = commandClass.cast(rpcCommand); } } } return found; } <T extends CacheRpcCommand> boolean isCommandSent(Class<T> commandClass) { boolean found = false; synchronized (this) { for (CacheRpcCommand rpcCommand : commandList) { if (rpcCommand.getClass() == commandClass) { if (found) { fail("More than one " + commandClass + " found in list: " + commandList); } found = true; } } } return found; } void startRecording() { synchronized (this) { commandList.clear(); } recording = true; } void stopRecording() { recording = false; synchronized (this) { commandList.clear(); } } @Override protected <T> CompletionStage<T> performRequest(Collection<Address> targets, ReplicableCommand command, ResponseCollector<T> collector, Function<ResponseCollector<T>, CompletionStage<T>> invoker, RpcOptions rpcOptions) { if (recording && command instanceof CacheRpcCommand) { synchronized (this) { commandList.add((CacheRpcCommand) command); } } return super.performRequest(targets, command, collector, invoker, rpcOptions); } @Override protected <T> void performSend(Collection<Address> targets, ReplicableCommand command, Function<ResponseCollector<T>, CompletionStage<T>> invoker) { if (recording && command instanceof CacheRpcCommand) { synchronized (this) { commandList.add((CacheRpcCommand) command); } } super.performSend(targets, command, invoker); } } }
15,356
39.413158
226
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/Irac3SitesExponentialBackOffTest.java
package org.infinispan.xsite.irac; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.jgroups.UnreachableException; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Functional test for exponential back-off with IRAC. * </p> * This test uses 3 sites with a cluster of size 1 for simplification. We issue all commands from site 1, * which has sites 2 and 3 as backups. The requests from 1 -> 2 will complete on the first try, * whereas 1 -> 3 will need the back-off to kick in. * </p> * We verify that the back-off only retries the failed operations. We have the same verifications as * {@link IracExponentialBackOffTest}. * * @author Jose Bolina * @since 15.0 */ @Test(groups = "functional", testName = "xsite.irac.Irac3SitesExponentialBackOffTest") public class Irac3SitesExponentialBackOffTest extends AbstractMultipleSitesTest { private static final int N_SITES = 3; private static final int CLUSTER_SIZE = 1; private static final Supplier<Throwable> NO_EXCEPTION = () -> null; private final Map<String, ControlledExponentialBackOff> backOffMap = new ConcurrentHashMap<>(); private volatile ControlledTransport transport; @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); for (int i = 0; i < N_SITES; ++i) { if (i == siteIndex) { //don't add our site as backup. continue; } builder.sites() .addBackup() .site(siteName(i)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected void afterSitesCreated() { Cache<String, String> c = cache(siteName(0), 0); Collection<String> connected = Arrays.asList(siteName(0), siteName(1)); Collection<String> disconnected = Collections.singletonList(siteName(2)); transport = TestingUtil.wrapGlobalComponent(manager(c), Transport.class, actual -> new ControlledTransport(actual, siteName(0), connected, disconnected), true); DefaultIracManager iracManager = (DefaultIracManager) TestingUtil.extractComponent(c, IracManager.class); iracManager.setBackOff(backup -> backOffMap.computeIfAbsent(backup.getSiteName(), ControlledExponentialBackOff::new)); } @AfterMethod(alwaysRun = true) public void resetStateAfterTest() { backOffMap.values().forEach(ControlledExponentialBackOff::release); Cache<String, String> c = cache(siteName(0), 0); DefaultIracManager iracManager = (DefaultIracManager) TestingUtil.extractComponent(c, IracManager.class); eventually(iracManager::isEmpty); backOffMap.values().forEach(ControlledExponentialBackOff::cleanupEvents); backOffMap.values().forEach(ControlledExponentialBackOff::assertNoEvents); } public void testSimulatedTimeout(Method method) { doTest(method, () -> log.requestTimedOut(1, siteName(2), "some time")); } public void testSimulatedUnreachableException(Method method) { doTest(method, () -> new UnreachableException(null)); } public void testSiteUnreachable(Method method) { doTest(method, () -> log.remoteNodeSuspected(null)); } public void testNoBackoffOnOtherException(Method method) { transport.throwableSupplier = CacheException::new; Cache<String, String> c = cache(siteName(0), 0); final String key = TestingUtil.k(method); final String value = TestingUtil.v(method); c.put(key, value); // Since no back off applied, both issues a reset. One backup succeeds and another fails. backOffMap.get(siteName(1)).eventually("Both reset with CacheException.", ControlledExponentialBackOff.Event.RESET); backOffMap.get(siteName(2)).eventually("Both reset with CacheException.", ControlledExponentialBackOff.Event.RESET); //with "normal" exception, the protocol will keep trying to send the request //we need to let it have a successful request otherwise it will fill the queue with RESET events. //it is possible that between the prev check and changing this, that already happened. transport.throwableSupplier = NO_EXCEPTION; DefaultIracManager iracManager = (DefaultIracManager) TestingUtil.extractComponent(c, IracManager.class); eventually(iracManager::isEmpty); // Only the backup that failed issued an event now, so only RESET event here (could be more than one). backOffMap.get(siteName(1)).assertNoEvents(); backOffMap.get(siteName(2)).containsOnly("Only one that failed reset.", ControlledExponentialBackOff.Event.RESET); // Back off not applied. backOffMap.values().forEach(ControlledExponentialBackOff::assertNoEvents); } private void doTest(Method method, Supplier<Throwable> throwableSupplier) { Cache<String, String> c = cache(siteName(0), 0); transport.throwableSupplier = throwableSupplier; final String key = TestingUtil.k(method); final String value = TestingUtil.v(method); c.put(key, value); // With 2 backups, one succeeds and another fails. backOffMap.get(siteName(1)).eventually("Backoff event on first try.", ControlledExponentialBackOff.Event.RESET); backOffMap.get(siteName(2)).eventually("Backoff event on first try.", ControlledExponentialBackOff.Event.BACK_OFF); // Release will trigger the backoff to the failed site. backOffMap.get(siteName(2)).release(); // Only one site sends the keys, so only a single event here. backOffMap.get(siteName(2)).eventually("Backoff event after release.", ControlledExponentialBackOff.Event.BACK_OFF); // Operation now should succeed. transport.throwableSupplier = NO_EXCEPTION; backOffMap.get(siteName(2)).release(); // The operation finally succeeds, since only one backup was failing we have only one event. backOffMap.get(siteName(2)).eventually("All operations should succeed.", ControlledExponentialBackOff.Event.RESET); // No other event was issued. backOffMap.values().forEach(ControlledExponentialBackOff::assertNoEvents); } }
6,997
41.412121
124
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracWriteSkewTest.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.fail; import java.util.Arrays; import java.util.Objects; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.versioning.IncrementableEntryVersion; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.distribution.DistributionInfo; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Make sure write-skew check isn't broken. * <p> * The remote sites updates are non-transactional (forced) so the write-skew version must changed with it. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.IracWriteSkewTest") public class IracWriteSkewTest extends AbstractMultipleSitesTest { private static final int N_SITES = 2; private static final int CLUSTER_SIZE = 2; private static final String CACHE_NAME = "ws-cache"; private static InternalDataContainer<String, String> dataContainer(Cache<String, String> cache) { //noinspection unchecked return TestingUtil.extractComponent(cache, InternalDataContainer.class); } private static DistributionInfo distributionInfo(Cache<String, String> cache, String key) { return TestingUtil.extractCacheTopology(cache).getDistribution(key); } @DataProvider(name = "default") public Object[][] dataProvider() { return Arrays.stream(TestMode.values()) .map(testMode -> new Object[]{testMode}) .toArray(Object[][]::new); } @Test(dataProvider = "default") public void testWriteSkewCheck(TestMode testMode) throws Exception { final Cache<String, String> lonCache = cache(siteName(0), CACHE_NAME, 0); final Cache<String, String> nycCache = cache(siteName(1), CACHE_NAME, 0); final TransactionManager tm = nycCache.getAdvancedCache().getTransactionManager(); final String key = testMode.toString(); if (!testMode.startEmpty) { lonCache.put(key, "before"); eventuallyAssertInAllSitesAndCaches(CACHE_NAME, C -> Objects.equals("before", C.get(key))); checkKey(key, "before"); } //start a tx and read the key //the transaction will keep the version read tm.begin(); String oldValue = nycCache.get(key); if (testMode.startEmpty) { assertNull(oldValue); } else { assertEquals("before", oldValue); } //suspend the transaction and write in LON to generate a WriteSkewException final Transaction tx = tm.suspend(); if (testMode.isRemove) { lonCache.remove(key); //Make sure the entry is replicated to NYC before attempting to commit NYC transaction //If the transaction is committed without IRAC finishes, it generates an IRAC conflict and the LON update wins //It makes the assertion on line 106 to fail. eventually(() -> iracManager(siteName(0), CACHE_NAME, 0).isEmpty()); eventuallyAssertInAllSitesAndCaches(CACHE_NAME, c -> Objects.isNull(c.get(key))); } else { lonCache.put(key, "write-skew-value"); eventuallyAssertInAllSitesAndCaches(CACHE_NAME, c -> Objects.equals("write-skew-value", c.get(key))); checkKey(key, "write-skew-value"); } tm.resume(tx); nycCache.put(key, "after"); if (testMode.startEmpty && testMode.isRemove) { //remove non-existing in LON doesn't trigger a WriteSkewException in NYC //because NYC reads non-existing and after the update from LON, the key still doesn't exist. tm.commit(); eventuallyAssertInAllSitesAndCaches(CACHE_NAME, c -> Objects.equals("after", c.get(key))); checkKey(key, "after"); } else { Exceptions.expectException(RollbackException.class, tm::commit); if (testMode.isRemove) { eventuallyAssertInAllSitesAndCaches(CACHE_NAME, c -> Objects.isNull(c.get(key))); } else { eventuallyAssertInAllSitesAndCaches(CACHE_NAME, c -> Objects.equals("write-skew-value", c.get(key))); checkKey(key, "write-skew-value"); } } assertNoDataLeak(CACHE_NAME); } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected void afterSitesCreated() { //LON is non-transactional ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.ASYNC); startCache(siteName(0), CACHE_NAME, builder); //NYC is transactional + write-skew builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); builder.sites().addBackup().site(siteName(0)).strategy(BackupConfiguration.BackupStrategy.ASYNC); startCache(siteName(1), CACHE_NAME, builder); } private void checkKey(String key, String value) { //irac version is the same in all nodes & sites. extract it from one site and check everywhere. IracEntryVersion iracVersion = extractIracEntryVersion(key); assertNotNull(iracVersion); assertIracEntryVersion(key, value, iracVersion); //NYC has the EntryVersion for write-skew check IncrementableEntryVersion entryVersion = extractEntryVersion(key); assertNotNull(entryVersion); assertIracEntryVersion(key, value, iracVersion, entryVersion); } private IracEntryVersion extractIracEntryVersion(String key) { return primaryOwner(0, key).getInternalMetadata().iracMetadata().getVersion(); } private IncrementableEntryVersion extractEntryVersion(String key) { return primaryOwner(1, key).getInternalMetadata().entryVersion(); } private InternalCacheEntry<String, String> primaryOwner(int siteIndex, String key) { for (Cache<String, String> c : this.<String, String>caches(siteName(siteIndex), CACHE_NAME)) { DistributionInfo distributionInfo = distributionInfo(c, key); if (distributionInfo.isPrimary()) { return dataContainer(c).peek(distributionInfo.segmentId(), key); } } fail("Unable to find primary owner for key: " + key); throw new IllegalStateException(); } private void assertIracEntryVersion(String key, String value, IracEntryVersion version) { for (Cache<String, String> c : this.<String, String>caches(siteName(0), CACHE_NAME)) { InternalDataContainer<String, String> dc = dataContainer(c); InternalCacheEntry<String, String> entry = dc.peek(key); assertEquals(value, entry.getValue()); assertEquals(version, entry.getInternalMetadata().iracMetadata().getVersion()); } } private void assertIracEntryVersion(String key, String value, IracEntryVersion iracVersion, IncrementableEntryVersion entryVersion) { for (Cache<String, String> c : this.<String, String>caches(siteName(1), CACHE_NAME)) { InternalDataContainer<String, String> dc = dataContainer(c); InternalCacheEntry<String, String> entry = dc.peek(key); assertEquals(value, entry.getValue()); assertEquals(iracVersion, entry.getInternalMetadata().iracMetadata().getVersion()); assertEquals(entryVersion, entry.getInternalMetadata().entryVersion()); } } private enum TestMode { EMPTY_AND_REMOVE(true, true), EMPTY_AND_PUT(true, false), NON_EMPTY_AND_REMOVE(false, true), NON_EMPTY_AND_PUT(false, false), ; private final boolean startEmpty; private final boolean isRemove; TestMode(boolean startEmpty, boolean isRemove) { this.startEmpty = startEmpty; this.isRemove = isRemove; } } }
8,792
40.672986
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracCustomConflictTest.java
package org.infinispan.xsite.irac; import static org.testng.AssertJUnit.assertEquals; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.TestOperation; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.spi.SiteEntry; import org.infinispan.xsite.spi.XSiteEntryMergePolicy; import org.testng.annotations.AfterMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.IracCustomConflictTest") public class IracCustomConflictTest extends AbstractMultipleSitesTest { private static final int N_SITES = 2; private static final int CLUSTER_SIZE = 3; private final List<ManualIracManager> iracManagerList; private final ConfigMode site1Config; private final ConfigMode site2Config; IracCustomConflictTest(ConfigMode site1Config, ConfigMode site2Config) { this.site1Config = site1Config; this.site2Config = site2Config; this.iracManagerList = new ArrayList<>(N_SITES * CLUSTER_SIZE); } @Factory public static Object[] defaultFactory() { ConfigMode[] values = ConfigMode.values(); Object[] tests = new Object[values.length * values.length]; int i = 0; for (ConfigMode s1 : values) { for (ConfigMode s2 : values) { tests[i++] = new IracCustomConflictTest(s1, s2); } } return tests; } public void testPutIfAbsent(Method method) { doTest(method, TestOperation.PUT_IF_ABSENT); } public void testPut(Method method) { doTest(method, TestOperation.PUT); } public void testReplace(Method method) { doTest(method, TestOperation.REPLACE); } public void testConditionalReplace(Method method) { doTest(method, TestOperation.REPLACE_CONDITIONAL); } public void testRemove(Method method) { doTest(method, TestOperation.REMOVE); } public void testConditionalRemove(Method method) { doTest(method, TestOperation.REMOVE_CONDITIONAL); } @Override protected String[] parameterNames() { return new String[]{null, null}; } @Override protected Object[] parameterValues() { return new Object[]{site1Config, site2Config}; } @Override protected int defaultNumberOfSites() { return N_SITES; } @Override protected int defaultNumberOfNodes() { return CLUSTER_SIZE; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigMode configMode = siteIndex == 0 ? site1Config : site2Config; ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); switch (configMode) { case P_TX: builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(LockingMode.PESSIMISTIC); break; case O_TX: builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(LockingMode.OPTIMISTIC); break; case NO_TX: default: //no-op } builder.sites().mergePolicy(new CustomEntryMergePolicy()); for (int i = 0; i < N_SITES; ++i) { if (i == siteIndex) { //don't add our site as backup. continue; } builder.sites() .addBackup() .site(siteName(i)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected GlobalConfigurationBuilder defaultGlobalConfigurationForSite(int siteIndex) { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { iracManagerList.forEach(iracManager -> iracManager.disable(ManualIracManager.DisableMode.DROP)); super.clearContent(); } @Override protected void afterSitesCreated() { for (int i = 0; i < N_SITES; ++i) { for (Cache<?, ?> cache : caches(siteName(i))) { iracManagerList.add(ManualIracManager.wrapCache(cache)); } } } private void doTest(Method method, TestOperation testConfig) { final String key = TestingUtil.k(method, 0); MySortedSet initialValue; if (testConfig != TestOperation.PUT_IF_ABSENT) { initialValue = new MySortedSet(new String[]{"a"}); cache(siteName(0), 0).put(key, initialValue); eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(initialValue, cache.get(key))); } else { initialValue = null; } //disable xsite so each site won't send anything to the others iracManagerList.forEach(ManualIracManager::enable); //put a conflict value. each site has a different value for the same key MySortedSet[] finalValues = new MySortedSet[N_SITES]; for (int i = 0; i < N_SITES; ++i) { MySortedSet newValue = initialValue == null ? new MySortedSet(new String[]{"a", "site_" + i}) : //putIfAbsent, add "a" element initialValue.add("site_" + i); if (i == 0) { finalValues[i] = testConfig.execute(cache(siteName(i), 0), key, initialValue, newValue); } else { cache(siteName(i), 0).put(key, newValue); finalValues[i] = newValue; } } //check if everything is correct for (int i = 0; i < N_SITES; ++i) { MySortedSet fValue = finalValues[i]; assertInSite(siteName(i), cache -> assertEquals(fValue, cache.get(key))); } //enable xsite. this will send the keys! iracManagerList.forEach(manualIracManager -> manualIracManager.disable(ManualIracManager.DisableMode.SEND)); MySortedSet finalValue = testConfig == TestOperation.REMOVE || testConfig == TestOperation.REMOVE_CONDITIONAL ? new MySortedSet(new String[]{"a", "site_1"}) : new MySortedSet(new String[]{"a", "site_0", "site_1"}); //the values should be merged. eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(finalValue, cache.get(key))); assertNoDataLeak(null); } private enum ConfigMode { NO_TX, P_TX, O_TX } public static class CustomEntryMergePolicy implements XSiteEntryMergePolicy<String, MySortedSet> { @Override public CompletionStage<SiteEntry<MySortedSet>> merge(String key, SiteEntry<MySortedSet> localEntry, SiteEntry<MySortedSet> remoteEntry) { MySortedSet local = localEntry.getValue(); MySortedSet remote = remoteEntry.getValue(); if (local == remote) { return CompletableFuture.completedFuture(compare(localEntry, remoteEntry) < 0 ? localEntry : remoteEntry); } else if (local == null) { return CompletableFuture.completedFuture(remoteEntry); } else if (remote == null) { return CompletableFuture.completedFuture(localEntry); } //both are not null MySortedSet result = local.addAll(remote); String site = compare(localEntry, remoteEntry) < 0 ? localEntry.getSiteName() : remoteEntry.getSiteName(); return CompletableFuture.completedFuture(new SiteEntry<>(site, result, null)); } private int compare(SiteEntry<MySortedSet> local, SiteEntry<MySortedSet> remote) { return local.getSiteName().compareTo(remote.getSiteName()); } } public static class MySortedSet { private final String[] data; @ProtoFactory public MySortedSet(String[] data) { this.data = Objects.requireNonNull(data); } public boolean contains(String element) { return Arrays.binarySearch(data, element) >= 0; } public MySortedSet add(String element) { if (contains(element)) { return this; } String[] newData = Arrays.copyOf(data, data.length + 1); newData[data.length] = element; Arrays.sort(newData); return new MySortedSet(newData); } public MySortedSet addAll(MySortedSet other) { List<String> newElements = new LinkedList<>(); for (String e : other.data) { if (contains(e)) { continue; } newElements.add(e); } if (newElements.isEmpty()) { return this; } String[] newData = Arrays.copyOf(data, data.length + newElements.size()); int i = data.length; for (String e : newElements) { newData[i++] = e; } Arrays.sort(newData); return new MySortedSet(newData); } @ProtoField(number = 1) public String[] getData() { return data; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MySortedSet that = (MySortedSet) o; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(data, that.data); } @Override public int hashCode() { return Arrays.hashCode(data); } } }
10,399
32.986928
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/ManualIracManager.java
package org.infinispan.xsite.irac; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import org.infinispan.Cache; import org.infinispan.commons.util.IntSet; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.statetransfer.XSiteState; /** * A manually trigger {@link IracManager} delegator. * <p> * The keys are only sent to the remote site if triggered. * * @author Pedro Ruivo * @since 11.0 */ public class ManualIracManager extends ControlledIracManager { private final Map<Object, PendingKeyRequest> pendingKeys = new ConcurrentHashMap<>(16); private volatile boolean enabled; private final List<StateTransferRequest> pendingStateTransfer = new ArrayList<>(2); private ManualIracManager(IracManager actual) { super(actual); } public static ManualIracManager wrapCache(Cache<?, ?> cache) { IracManager iracManager = TestingUtil.extractComponent(cache, IracManager.class); if (iracManager instanceof ManualIracManager) { return (ManualIracManager) iracManager; } return TestingUtil.wrapComponent(cache, IracManager.class, ManualIracManager::new); } @Override public void trackUpdatedKey(int segment, Object key, Object lockOwner) { if (enabled) { pendingKeys.put(key, new PendingKeyRequest(key, lockOwner, segment, false)); } else { super.trackUpdatedKey(segment, key, lockOwner); } } @Override public void trackExpiredKey(int segment, Object key, Object lockOwner) { if (enabled) { pendingKeys.put(key, new PendingKeyRequest(key, lockOwner, segment, true)); } else { super.trackExpiredKey(segment, key, lockOwner); } } @Override public CompletionStage<Void> trackForStateTransfer(Collection<XSiteState> stateList) { if (enabled) { StateTransferRequest request = new StateTransferRequest(stateList); pendingStateTransfer.add(request); return request; } else { return super.trackForStateTransfer(stateList); } } @Override public void requestState(Address requestor, IntSet segments) { //send the state for the keys we have pending in this instance! asDefaultIracManager().ifPresent(im -> im.transferStateTo(requestor, segments, pendingKeys.values())); super.requestState(requestor, segments); } public void sendKeys() { pendingKeys.values().forEach(this::send); pendingKeys.clear(); pendingStateTransfer.forEach(this::send); pendingStateTransfer.clear(); } public void enable() { enabled = true; } public void disable(DisableMode disableMode) { enabled = false; switch (disableMode) { case DROP: pendingKeys.clear(); pendingStateTransfer.clear(); break; case SEND: sendKeys(); break; } } public boolean isEmpty() { return asDefaultIracManager().map(DefaultIracManager::isEmpty).orElse(true); } boolean hasPendingKeys() { return !pendingKeys.isEmpty(); } private void send(PendingKeyRequest request) { if (request.isExpiration()) { super.trackExpiredKey(request.getSegment(), request.getKey(), request.getOwner()); return; } super.trackUpdatedKey(request.getSegment(), request.getKey(), request.getOwner()); } private void send(StateTransferRequest request) { CompletionStage<Void> rsp = super.trackForStateTransfer(request.getState()); rsp.whenComplete(request); } public enum DisableMode { SEND, DROP } private static class StateTransferRequest extends CompletableFuture<Void> implements BiConsumer<Void, Throwable> { private final Collection<XSiteState> state; private StateTransferRequest(Collection<XSiteState> state) { this.state = new ArrayList<>(state); } Collection<XSiteState> getState() { return state; } @Override public void accept(Void unused, Throwable throwable) { if (throwable != null) { completeExceptionally(throwable); } else { complete(null); } } } private static class PendingKeyRequest implements IracManagerKeyState { private final Object key; private final Object lockOwner; private final int segment; private final boolean expiration; private PendingKeyRequest(Object key, Object lockOwner, int segment, boolean expiration) { this.key = key; this.lockOwner = lockOwner; this.segment = segment; this.expiration = expiration; } @Override public Object getKey() { return key; } @Override public Object getOwner() { return lockOwner; } @Override public int getSegment() { return segment; } @Override public boolean isExpiration() { return expiration; } @Override public boolean isStateTransfer() { return false; } @Override public boolean canSend() { return false; } @Override public void retry() { } @Override public boolean isDone() { return false; } @Override public void discard() { } @Override public void successFor(IracXSiteBackup site) { } @Override public boolean wasSuccessful(IracXSiteBackup site) { return false; } } }
5,851
25.6
117
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/ControlledIracVersionGenerator.java
package org.infinispan.xsite.irac; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.IracVersionGenerator; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.topology.CacheTopology; /** * An {@link IracVersionGenerator} implementation that can be controlled for testing. * * @author Pedro Ruivo * @since 11.0 */ public class ControlledIracVersionGenerator implements IracVersionGenerator { private final IracVersionGenerator actual; public ControlledIracVersionGenerator(IracVersionGenerator actual) { this.actual = actual; } @Override public IracMetadata generateNewMetadata(int segment) { return actual.generateNewMetadata(segment); } @Override public IracMetadata generateMetadataWithCurrentVersion(int segment) { return actual.generateMetadataWithCurrentVersion(segment); } @Override public IracMetadata generateNewMetadata(int segment, IracEntryVersion versionSeen) { return actual.generateNewMetadata(segment, versionSeen); } @Override public void updateVersion(int segment, IracEntryVersion remoteVersion) { actual.updateVersion(segment, remoteVersion); } @Override public void onTopologyChange(CacheTopology newTopology) { actual.onTopologyChange(newTopology); } @Override public void start() { actual.start(); } @Override public void stop() { actual.stop(); } }
1,492
25.192982
87
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/IracRestartWithoutGlobalStateTest.java
package org.infinispan.xsite.irac; import static java.lang.String.format; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.container.versioning.InequalVersionComparisonResult.BEFORE; import static org.infinispan.container.versioning.InequalVersionComparisonResult.EQUAL; import static org.infinispan.test.TestingUtil.extractCacheTopology; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.infinispan.xsite.XSiteAdminOperations.SUCCESS; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.versioning.InequalVersionComparisonResult; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.XSiteAdminOperations; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Same as {@link IracRestartWithGlobalStateTest} but without global state. * <p> * The versions are supposed to survive if there is a cache store or, if volatile, the state transfer from remote site * must set the correct versions. * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.IracRestartWithoutGlobalStateTest") public class IracRestartWithoutGlobalStateTest extends AbstractMultipleSitesTest { private static final int NUM_KEYS = 100; private final boolean persistent; public IracRestartWithoutGlobalStateTest(boolean persistent) { this.persistent = persistent; } @Factory public static Object[] defaultFactory() { return new Object[]{ new IracRestartWithoutGlobalStateTest(false), new IracRestartWithoutGlobalStateTest(true) }; } private static void forEachKeyValue(Method method, String prefix, BiConsumer<String, String> keyValueConsumer) { for (int i = 0; i < NUM_KEYS; ++i) { keyValueConsumer.accept(k(method, i), v(method, prefix, i)); } } @BeforeClass(alwaysRun = true) @Override public void createBeforeClass() { Util.recursiveFileRemove(tmpDirectory(getClass())); super.createBeforeClass(); } public void testRestart(Method method) { doTest(method, false); } public void testRestartReverse(Method method) { doTest(method, true); } @Override protected String[] parameterNames() { return new String[]{null}; } @Override protected Object[] parameterValues() { return new String[]{persistent ? "PERSISTENT" : "VOLATILE"}; } @Override protected int defaultNumberOfNodes() { return 3; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); if (siteIndex == 0) { builder.sites().addBackup() .site(siteName(1)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } else { builder.sites().addBackup() .site(siteName(0)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); } return builder; } @Override protected void decorateCacheConfiguration(ConfigurationBuilder builder, int siteIndex, int nodeIndex) { if (siteIndex == 0 && persistent) { String data = tmpDirectory(getClass().getSimpleName(), "site_" + siteIndex, "node_" + nodeIndex); builder.persistence().addSingleFileStore().location(data).fetchPersistentState(true); } } private void doTest(Method method, boolean reverse) { forEachKeyValue(method, "initial", (k, v) -> cache(0, 0).put(k, v)); forEachKeyValue(method, "initial", this::eventuallyAssertData); Map<String, IracEntryVersion> entryVersionsBefore = snapshotKeyVersions(method, 0); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 1), EQUAL); log.debug("Stopping site_0"); stopSite(0); log.debug("Starting site_0"); restartSite(0); if (!persistent) { XSiteAdminOperations operations = adminOperations(); assertEquals(SUCCESS, operations.pushState(siteName(0))); eventually(() -> operations.getRunningStateTransfer().isEmpty()); forEachKeyValue(method, "initial", this::eventuallyAssertData); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 0), EQUAL); } forEachKeyValue(method, "final", (k, v) -> cache(reverse ? 1 : 0, 0).put(k, v)); forEachKeyValue(method, "final", this::eventuallyAssertData); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 0), BEFORE); assertVersions(entryVersionsBefore, snapshotKeyVersions(method, 1), BEFORE); } private Map<String, IracEntryVersion> snapshotKeyVersions(Method method, int siteIndex) { Map<String, IracEntryVersion> versions = new HashMap<>(); for (Cache<String, String> cache : this.<String, String>caches(siteIndex)) { LocalizedCacheTopology topology = extractCacheTopology(cache); //noinspection unchecked InternalDataContainer<String, String> dataContainer = extractComponent(cache, InternalDataContainer.class); for (int i = 0; i < NUM_KEYS; ++i) { String key = k(method, i); DistributionInfo distributionInfo = topology.getDistribution(key); if (distributionInfo.isPrimary()) { IracEntryVersion version = dataContainer.peek(distributionInfo.segmentId(), key).getInternalMetadata() .iracMetadata().getVersion(); AssertJUnit.assertNotNull(version); versions.put(key, version); } } } return versions; } private <K> void assertVersions(Map<K, IracEntryVersion> v1, Map<K, IracEntryVersion> v2, InequalVersionComparisonResult expected) { assertEquals(v1.size(), v2.size()); Iterator<K> iterator = Stream.concat(v1.keySet().stream(), v2.keySet().stream()) .distinct() .iterator(); while (iterator.hasNext()) { K key = iterator.next(); IracEntryVersion version1 = v1.get(key); IracEntryVersion version2 = v2.get(key); assertNotNull(format("'%s' version is null for Map 1", key), version1); assertNotNull(format("'%s' version is null for Map 2", key), version2); InequalVersionComparisonResult result = version1.compareTo(version2); assertEquals(format("'%s' version mismatch: %s and %s", key, version1, version2), expected, result); } } private void eventuallyAssertData(String key, String value) { eventuallyAssertInAllSitesAndCaches(cache -> Objects.equals(value, cache.get(key))); } protected XSiteAdminOperations adminOperations() { return extractComponent(cache(1, 0), XSiteAdminOperations.class); } }
7,746
37.929648
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/statetransfer/IracStateTransferTest.java
package org.infinispan.xsite.irac.statetransfer; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.v; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.XSiteAdminOperations; import org.infinispan.xsite.irac.ManualIracManager; import org.infinispan.xsite.statetransfer.XSiteStateTransferManager; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * State transfer test for IRAC * * @author Pedro Ruivo * @since 12.0 */ @Test(groups = "functional", testName = "xsite.irac.statetransfer.IracStateTransferTest") public class IracStateTransferTest extends AbstractMultipleSitesTest { private final IracManagerHolder[] iracManagers; public IracStateTransferTest() { iracManagers = new IracManagerHolder[defaultNumberOfSites()]; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); builder.sites().addBackup() .site(siteName(siteIndex == 0 ? 1 : 0)) .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder; } @Override protected void afterSitesCreated() { for (int i = 0; i < defaultNumberOfSites(); ++i) { List<ManualIracManager> list = new ArrayList<>(defaultNumberOfNodes()); for (Cache<?, ?> cache : caches(siteName(i))) { list.add(ManualIracManager.wrapCache(cache)); } iracManagers[i] = new IracManagerHolder(list); } } @BeforeMethod(alwaysRun = true) @Override public void createBeforeMethod() { super.createBeforeMethod(); for (IracManagerHolder holder : iracManagers) { holder.iracManagers.forEach(m -> m.disable(ManualIracManager.DisableMode.DROP)); } } public void testStateTransfer(Method method) { //simple state transfer from site1 -> site2 final int keys = 8; //disconnect site1 from site2 assertOk(0, op -> op.takeSiteOffline(siteName(1))); assertStatus(0, 1, XSiteAdminOperations.OFFLINE); //put some data in site1 for (int i = 0; i < keys; ++i) { cache(0, 0).put(k(method, i), v(method, i)); } //check keys assertKeys(method, 0, 0, keys); assertNoKeys(method, 1, 0, keys); //pause xsite requests iracManagers[0].iracManagers.forEach(ManualIracManager::enable); //state state transfer assertOk(0, op -> op.pushState(siteName(1))); assertStatus(0, 1, XSiteAdminOperations.ONLINE); assertEquals(XSiteStateTransferManager.STATUS_SENDING, getPushStatus(0, 1)); //with IRAC, the receiving site don't know the difference between an update or state transfer assertNull(getSendingSiteName(1)); //resume xsite requests iracManagers[0].iracManagers.forEach(m -> m.disable(ManualIracManager.DisableMode.SEND)); waitStateTransfer(0, 1); assertKeys(method, 0, 0, keys); assertKeys(method, 1, 0, keys); } public void testConflict(Method method) { //disconnect both sites assertOk(0, op -> op.takeSiteOffline(siteName(1))); assertOk(1, op -> op.takeSiteOffline(siteName(0))); assertStatus(0, 1, XSiteAdminOperations.OFFLINE); assertStatus(1, 0, XSiteAdminOperations.OFFLINE); //keys 0-3: only in site1 //keys 4-7: both sites //keys 8-11: only in site2 //trigger state transfer and we should have all keys in both site (with the same value, site1 wins in conflict resolution) for (int i = 0; i < 4; ++i) { cache(0, 0).put(k(method, i), v(method, "site1", i)); } assertKeys(method, 0, "site1", 0, 4); assertNoKeys(method, 1, 0, 4); for (int i = 4; i < 8; ++i) { cache(0, 0).put(k(method, i), v(method, "site1", i)); cache(1, 0).put(k(method, i), v(method, "site2", i)); } assertKeys(method, 0, "site1", 0, 8); assertNoKeys(method, 1, 0, 4); assertKeys(method, 1, "site2", 4, 8); for (int i = 8; i < 12; ++i) { cache(1, 0).put(k(method, i), v(method, "site2", i)); } assertKeys(method, 0, "site1", 0, 8); assertNoKeys(method, 0, 8, 12); assertNoKeys(method, 1, 0, 4); assertKeys(method, 1, "site2", 4, 12); //pause xsite requests iracManagers[0].iracManagers.forEach(ManualIracManager::enable); //state state transfer site1 => site2 assertOk(0, op -> op.pushState(siteName(1))); assertStatus(0, 1, XSiteAdminOperations.ONLINE); assertEquals(XSiteStateTransferManager.STATUS_SENDING, getPushStatus(0, 1)); //with IRAC, the receiving site don't know the difference between an update or state transfer assertNull(getSendingSiteName(1)); //resume xsite requests iracManagers[0].iracManagers.forEach(m -> m.disable(ManualIracManager.DisableMode.SEND)); waitStateTransfer(0, 1); //site1 keys should overwrite site2 keys assertKeys(method, 0, "site1", 0, 8); assertNoKeys(method, 0, 8, 12); assertKeys(method, 1, "site1", 0, 8); assertKeys(method, 1, "site2", 8, 12); //pause xsite requests iracManagers[1].iracManagers.forEach(ManualIracManager::enable); //state state transfer site2 => site1 assertOk(1, op -> op.pushState(siteName(0))); assertStatus(1, 0, XSiteAdminOperations.ONLINE); assertEquals(XSiteStateTransferManager.STATUS_SENDING, getPushStatus(1, 0)); //with IRAC, the receiving site don't know the difference between an update or state transfer assertNull(getSendingSiteName(0)); //resume xsite requests iracManagers[1].iracManagers.forEach(m -> m.disable(ManualIracManager.DisableMode.SEND)); waitStateTransfer(1, 0); assertKeys(method, 0, "site1", 0, 8); assertKeys(method, 0, "site2", 8, 12); assertKeys(method, 1, "site1", 0, 8); assertKeys(method, 1, "site2", 8, 12); } private void assertStatus(int srcSite, int dstSite, String status) { assertInSite(siteName(srcSite), c -> assertEquals(status, adminOperations(c).siteStatus(siteName(dstSite)))); } private void assertNoKeys(Method method, int srcSite, int startKey, int endKey) { assertInSite(siteName(srcSite), cache -> { for (int i = startKey; i < endKey; ++i) { assertNull(cache.get(k(method, i))); } }); } private void assertKeys(Method method, int srcSite, String prefix, int startKey, int endKey) { assertInSite(siteName(srcSite), cache -> { for (int i = startKey; i < endKey; ++i) { assertEquals(v(method, prefix, i), cache.get(k(method, i))); } }); } private void assertKeys(Method method, int srcSite, int startKey, int endKey) { assertInSite(siteName(srcSite), cache -> { for (int i = startKey; i < endKey; ++i) { assertEquals(v(method, i), cache.get(k(method, i))); } }); } private void assertOk(int siteIndex, Function<XSiteAdminOperations, String> f) { assertEquals(XSiteAdminOperations.SUCCESS, f.apply(adminOperations(siteIndex))); } private void waitStateTransfer(int srcSite, int dstSite) { eventually(() -> "Expected <ok> but was " + getPushStatus(srcSite, dstSite), () -> XSiteStateTransferManager.STATUS_OK.equals(getPushStatus(srcSite, dstSite))); } private String getPushStatus(int srcSite, int dstSite) { return adminOperations(srcSite).getPushStateStatus().get(siteName(dstSite)); } private String getSendingSiteName(int dstSite) { return adminOperations(dstSite).getSendingSiteName(); } private XSiteAdminOperations adminOperations(int siteIndex) { return adminOperations(cache(siteIndex, 0)); } private XSiteAdminOperations adminOperations(Cache<?, ?> cache) { return extractComponent(cache, XSiteAdminOperations.class); } private static class IracManagerHolder { private final List<ManualIracManager> iracManagers; private IracManagerHolder(List<ManualIracManager> iracManagers) { this.iracManagers = iracManagers; } } }
8,709
35.141079
128
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/statetransfer/IracLocalStateTransferTest.java
package org.infinispan.xsite.irac.statetransfer; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.xsite.AbstractXSiteTest; import org.infinispan.xsite.irac.IracManager; import org.infinispan.xsite.irac.ManualIracManager; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests the backup sending while topology change happens in the local cluster. * * @author Pedro Ruivo * @since 11.0 */ @Test(groups = "functional", testName = "irac.statetransfer.IracLocalStateTransferTest") public class IracLocalStateTransferTest extends AbstractXSiteTest { private static final String LON = "LON-1"; private static final String NYC = "NYC-2"; private static final int NUM_NODES = 3; private final ControlledConsistentHashFactory<?> lonCHF = new ControlledConsistentHashFactory.Default(0, 1); private final ControlledConsistentHashFactory<?> nycCHF = new ControlledConsistentHashFactory.Default(0, 1); private TxMode lonTxMode; @Factory public Object[] factory() { List<IracLocalStateTransferTest> tests = new LinkedList<>(); for (TxMode lon : TxMode.values()) { tests.add(new IracLocalStateTransferTest().setLonTxMode(lon)); } return tests.toArray(); } public void testStateTransfer(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); assertOwnership(key, 0); cache(LON, 0).put(key, value); IracMetadata metadata = extractMetadataFromPrimaryOwner(key); assertEventuallyInSite(NYC, cache -> value.equals(cache.get(key)), 30, TimeUnit.SECONDS); changeOwnership(LON, NUM_NODES); //primary owner changes from node-0 to node-3 addNewNode(site(LON)); site(LON).waitForClusterToForm(null); assertOwnership(key, 3); assertInDataContainer(LON, key, value, metadata); } public void testBackupSendAfterPrimaryFail(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); assertOwnership(key, 0); ManualIracManager iracManager = ManualIracManager.wrapCache(cache(LON, 0)); iracManager.enable(); cache(LON, 0).put(key, value); IracMetadata metadata = extractMetadataFromPrimaryOwner(key); assertInSite(NYC, cache -> assertNull(cache.get(key))); site(LON).kill(0); //kill the primary owner site(LON).waitForClusterToForm(null); assertEventuallyInSite(NYC, cache -> value.equals(cache.get(key)), 30, TimeUnit.SECONDS); assertInDataContainer(LON, key, value, metadata); assertInDataContainer(NYC, key, value, metadata); } public void testBackupRemovedKeySendAfterPrimaryFail(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); assertOwnership(key, 0); cache(LON, 0).put(key, value); assertEventuallyInSite(NYC, cache -> value.equals(cache.get(key)), 30, TimeUnit.SECONDS); ManualIracManager iracManager = ManualIracManager.wrapCache(cache(LON, 0)); iracManager.enable(); //disable sending cache(LON, 0).remove(key); assertInSite(NYC, cache -> assertEquals(value, cache.get(key))); site(LON).kill(0); //kill the primary owner site(LON).waitForClusterToForm(null); assertEventuallyInSite(NYC, cache -> cache.get(key) == null, 30, TimeUnit.SECONDS); assertNotInDataContainer(LON, key); assertNotInDataContainer(NYC, key); } public void testNewPrimarySend(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); assertOwnership(key, 0); //this is the old primary owner. //it won't send the data. the new primary owner (node-3) will send it. ManualIracManager iracManager = ManualIracManager.wrapCache(cache(LON, 0)); iracManager.enable(); cache(LON, 0).put(key, value); IracMetadata metadata = extractMetadataFromPrimaryOwner(key); assertInSite(NYC, cache -> assertNull(cache.get(key))); changeOwnership(LON, NUM_NODES); //primary owner changes from node-0 to node-3 addNewNode(site(LON)); site(LON).waitForClusterToForm(null); assertEventuallyInSite(NYC, cache -> value.equals(cache.get(key)), 30, TimeUnit.SECONDS); assertInDataContainer(LON, key, value, metadata); assertInDataContainer(NYC, key, value, metadata); } public void testNewPrimarySendRemovedKey(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); assertOwnership(key, 0); cache(LON, 0).put(key, value); assertEventuallyInSite(NYC, cache -> value.equals(cache.get(key)), 30, TimeUnit.SECONDS); //this is the old primary owner. //it won't send the data. the new primary owner (node-3) will send it. ManualIracManager iracManager = ManualIracManager.wrapCache(cache(LON, 0)); iracManager.enable(); cache(LON, 0).remove(key); assertInSite(NYC, cache -> assertEquals(value, cache.get(key))); changeOwnership(LON, NUM_NODES); //primary owner changes from node-0 to node-3 addNewNode(site(LON)); site(LON).waitForClusterToForm(null); assertEventuallyInSite(NYC, cache -> cache.get(key) == null, 30, TimeUnit.SECONDS); assertNotInDataContainer(LON, key); assertNotInDataContainer(NYC, key); } @BeforeMethod(alwaysRun = true) @Override public void createBeforeMethod() { super.createBeforeMethod(); //reset the consistent hash to default ownership changeOwnership(LON, 0); changeOwnership(NYC, 0); //reset the number of nodes for (TestSite site : sites) { int numNodes = site.cacheManagers().size(); if (numNodes > NUM_NODES) { removeExtraNodes(site); } else if (numNodes < NUM_NODES) { addMissingNodes(site); } } //reset IracManager resetIracManager(LON); resetIracManager(NYC); } @Override protected String[] parameterNames() { return new String[]{"LON"}; } @Override protected Object[] parameterValues() { return new Object[]{lonTxMode}; } @Override protected void createSites() { GlobalConfigurationBuilder lonGCB = globalConfigurationBuilderForSite(); TestSite lon = addSite(LON); for (int i = 0; i < NUM_NODES; ++i) { ConfigurationBuilder builder = getLonActiveConfig(); lon.addCache(lonGCB, builder); } GlobalConfigurationBuilder nycGCB = globalConfigurationBuilderForSite(); TestSite nyc = addSite(NYC); for (int i = 0; i < NUM_NODES; ++i) { ConfigurationBuilder builder = getNycActiveConfig(); nyc.addCache(nycGCB, builder); } lon.waitForClusterToForm(null); nyc.waitForClusterToForm(null); } private IracLocalStateTransferTest setLonTxMode(TxMode txMode) { this.lonTxMode = txMode; return this; } private void resetIracManager(String site) { for (Cache<String, String> cache : this.<String, String>caches(site)) { IracManager manager = TestingUtil.extractComponent(cache, IracManager.class); if (manager instanceof ManualIracManager) { ((ManualIracManager) manager).disable(ManualIracManager.DisableMode.DROP); } } } private void assertOwnership(String key, int primaryOwner) { assertTrue(getDistributionForKey(cache(LON, primaryOwner), key).isPrimary()); assertTrue(getDistributionForKey(cache(LON, 1), key).isWriteBackup()); } private void assertInDataContainer(String site, String key, String value, IracMetadata metadata) { for (Cache<String, String> cache : this.<String, String>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } InternalDataContainer<String, String> dc = getInternalDataContainer(cache); InternalCacheEntry<String, String> ice = dc.peek(key); log.debugf("Checking DataContainer in %s. entry=%s", DistributionTestHelper.addressOf(cache), ice); assertNotNull(String.format("Internal entry is null for key %s", key), ice); assertEquals("Internal entry wrong key", key, ice.getKey()); assertEquals("Internal entry wrong value", value, ice.getValue()); assertEquals("Internal entry wrong metadata", metadata, ice.getInternalMetadata().iracMetadata()); } } private void assertNotInDataContainer(String site, String key) { for (Cache<String, String> cache : this.<String, String>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } InternalDataContainer<String, String> dc = getInternalDataContainer(cache); InternalCacheEntry<String, String> ice = dc.peek(key); log.debugf("Checking DataContainer in %s. entry=%s", DistributionTestHelper.addressOf(cache), ice); assertNull(String.format("Internal entry found for key %s", key), ice); } } private boolean isNotWriteOwner(Cache<String, String> cache, String key) { return !getDistributionForKey(cache, key).isWriteOwner(); } private IracMetadata extractMetadataFromPrimaryOwner(String key) { Cache<String, String> cache = findPrimaryOwner(key); InternalDataContainer<String, String> dataContainer = getInternalDataContainer(cache); InternalCacheEntry<String, String> entry = dataContainer.peek(key); assertNotNull(entry); PrivateMetadata internalMetadata = entry.getInternalMetadata(); assertNotNull(internalMetadata); IracMetadata metadata = internalMetadata.iracMetadata(); assertNotNull(metadata); return metadata; } private InternalDataContainer<String, String> getInternalDataContainer(Cache<String, String> cache) { //noinspection unchecked return TestingUtil.extractComponent(cache, InternalDataContainer.class); } private Cache<String, String> findPrimaryOwner(String key) { for (Cache<String, String> c : this.<String, String>caches(LON)) { if (getDistributionForKey(c, key).isPrimary()) { return c; } } throw new IllegalStateException(String.format("Unable to find primary owner for key %s", key)); } private DistributionInfo getDistributionForKey(Cache<String, String> cache, String key) { return TestingUtil.extractComponent(cache, ClusteringDependentLogic.class) .getCacheTopology() .getDistribution(key); } private void removeExtraNodes(TestSite site) { int numNodes = site.cacheManagers().size(); while (numNodes > NUM_NODES) { site.kill(--numNodes); } site.waitForClusterToForm(null); } private void addMissingNodes(TestSite site) { int numNodes = site.cacheManagers().size(); while (numNodes < NUM_NODES) { addNewNode(site); ++numNodes; } site.waitForClusterToForm(null); } private void addNewNode(TestSite site) { String siteName = site.getSiteName(); GlobalConfigurationBuilder gBuilder = globalConfigurationBuilderForSite(); ConfigurationBuilder builder = LON.equals(siteName) ? getLonActiveConfig() : getNycActiveConfig(); site.addCache(gBuilder, builder); } private void changeOwnership(String site, int primaryOwner) { ControlledConsistentHashFactory<?> chf = LON.equals(site) ? lonCHF : nycCHF; chf.setOwnerIndexes(primaryOwner, 1); } private GlobalConfigurationBuilder globalConfigurationBuilderForSite() { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } private ConfigurationBuilder getNycActiveConfig() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.clustering().hash() .consistentHashFactory(nycCHF) .numSegments(1); return builder; } private ConfigurationBuilder getLonActiveConfig() { ConfigurationBuilder builder = lonTxMode.create(); BackupConfigurationBuilder lonBackupConfigurationBuilder = builder.sites().addBackup(); lonBackupConfigurationBuilder .site(NYC) .strategy(BackupConfiguration.BackupStrategy.ASYNC); builder.clustering().hash() .consistentHashFactory(lonCHF) .numSegments(1); return builder; } private enum TxMode { NON_TX { @Override ConfigurationBuilder create() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } }, OPT_TX {//2PC with Versions @Override ConfigurationBuilder create() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.transaction().lockingMode(LockingMode.OPTIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); return builder; } }, PES_TX { // 1PC @Override ConfigurationBuilder create() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.transaction().lockingMode(LockingMode.PESSIMISTIC); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); return builder; } }; abstract ConfigurationBuilder create(); } }
14,956
35.480488
111
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/persistence/IracMetadataStoreTest.java
package org.infinispan.xsite.irac.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.lang.reflect.Method; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.IracVersionGenerator; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.distribution.DistributionInfo; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.interceptors.locking.ClusteringDependentLogic; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.manager.PreloadManager; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.LockingMode; import org.infinispan.util.ByteString; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.xsite.AbstractXSiteTest; import org.infinispan.xsite.XSiteNamedCache; import org.infinispan.xsite.irac.ControlledIracVersionGenerator; import org.infinispan.xsite.irac.IracManager; import org.infinispan.xsite.irac.ManualIracManager; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Test for {@link IracManager} to check if can load and send the update even if the key is only in the cache store. * * @author Pedro Ruivo * @since 11.0 */ @Test(groups = "functional", testName = "xsite.irac.persistence.IracMetadataStoreTest") public class IracMetadataStoreTest extends AbstractXSiteTest { private static final String LON = "LON-1"; private static final String NYC = "NYC-2"; private static final int NUM_NODES = 3; private static final AtomicLong V_GENERATOR = new AtomicLong(0); private final List<Runnable> cleanupTask = Collections.synchronizedList(new LinkedList<>()); private TxMode lonTxMode; private TxMode nycTxMode; private boolean passivation; private static ConfigurationBuilder createConfigurationBuilder(TxMode txMode, boolean passivation) { ConfigurationBuilder builder; switch (txMode) { case NON_TX: builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); break; case OPT_TX: builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); builder.transaction().lockingMode(LockingMode.OPTIMISTIC); break; case PES_TX: builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); builder.transaction().lockingMode(LockingMode.PESSIMISTIC); break; default: throw new IllegalStateException(); } builder.persistence().passivation(passivation); builder.clustering().hash().numSegments(4); return builder; } private static IracMetadata generateNew() { long v = V_GENERATOR.incrementAndGet(); ByteString site = XSiteNamedCache.cachedByteString(LON); return new IracMetadata(site, IracEntryVersion.newVersion(site, TopologyIracVersion.create(1, v))); } private static ManualIracVersionGenerator createManualIracVerionGenerator(Cache<String, Object> cache) { return TestingUtil.wrapComponent(cache, IracVersionGenerator.class, ManualIracVersionGenerator::new); } @Factory public Object[] factory() { List<IracMetadataStoreTest> tests = new LinkedList<>(); for (TxMode lon : TxMode.values()) { for (TxMode nyc : TxMode.values()) { tests.add(new IracMetadataStoreTest().setLonTxMode(lon).setNycTxMode(nyc).setPassivation(true)); tests.add(new IracMetadataStoreTest().setLonTxMode(lon).setNycTxMode(nyc).setPassivation(false)); } } return tests.toArray(); } public void testSendEvictedKey(Method method) { final String key = TestingUtil.k(method, 1); final Cache<String, Object> pOwnerCache = findPrimaryOwner(key); final ManualIracVersionGenerator vGenerator = createManualIracVerionGenerator(pOwnerCache); final ManualIracManager iracManager = createManualIracManager(pOwnerCache); IracMetadata metadata = generateNew(); vGenerator.metadata = metadata; //next write will have this version pOwnerCache.put(key, "v1"); evictKey(LON, key); //key only exists in cache store assertNotInDataContainer(LON, key); assertInCacheStore(LON, key, "v1", metadata); assertInSite(NYC, cache -> assertNull(cache.get(key))); iracManager.sendKeys(); //test if send can fetch the key from persistence assertEventuallyInSite(NYC, cache -> cache.get(key) != null, 30, TimeUnit.SECONDS); assertInDataContainer(NYC, key, "v1", metadata); if (!passivation) { assertInCacheStore(NYC, key, "v1", metadata); } } public void testCorrectMetadataStored(Method method) { final String key = TestingUtil.k(method, 1); final Cache<String, Object> pOwnerCache = findPrimaryOwner(key); final ManualIracVersionGenerator vGenerator = createManualIracVerionGenerator(pOwnerCache); final ManualIracManager iracManager = createManualIracManager(pOwnerCache); IracMetadata metadata = generateNew(); vGenerator.metadata = metadata; //next write will have this version pOwnerCache.put(key, "v"); assertInDataContainer(LON, key, "v", metadata); if (!passivation) { assertInCacheStore(LON, key, "v", metadata); } assertInSite(NYC, cache -> assertNull(cache.get(key))); iracManager.sendKeys(); assertEventuallyInSite(NYC, cache -> cache.get(key) != null, 30, TimeUnit.SECONDS); assertInDataContainer(NYC, key, "v", metadata); if (!passivation) { assertInCacheStore(NYC, key, "v", metadata); } } public void testKeyEvictedOnReceive(Method method) { final String key = TestingUtil.k(method, 1); final Cache<String, Object> pOwnerCache = findPrimaryOwner(key); final ManualIracVersionGenerator vGenerator = createManualIracVerionGenerator(pOwnerCache); final ManualIracManager iracManager = createManualIracManager(pOwnerCache); IracMetadata metadata = generateNew(); vGenerator.metadata = metadata; //next write will have this version pOwnerCache.put(key, "v2"); iracManager.sendKeys(); assertInDataContainer(LON, key, "v2", metadata); if (!passivation) { assertInCacheStore(LON, key, "v2", metadata); } assertEventuallyInSite(NYC, cache -> cache.get(key) != null, 30, TimeUnit.SECONDS); assertInDataContainer(NYC, key, "v2", metadata); if (!passivation) { assertInCacheStore(NYC, key, "v2", metadata); } //in this test, NYC primary-owner should be able to fetch the IracMetadata from cache loader to perform validation evictKey(NYC, key); assertNotInDataContainer(NYC, key); assertInCacheStore(NYC, key, "v2", metadata); metadata = generateNew(); vGenerator.metadata = metadata; pOwnerCache.put(key, "v3"); iracManager.sendKeys(); assertEventuallyInSite(NYC, cache -> "v3".equals(cache.get(key)), 30, TimeUnit.SECONDS); assertInDataContainer(NYC, key, "v3", metadata); if (!passivation) { assertInCacheStore(NYC, key, "v3", metadata); } } public void testPreload(Method method) { final String key = TestingUtil.k(method, 1); final Cache<String, Object> pOwnerCache = findPrimaryOwner(key); final ManualIracVersionGenerator vGenerator = createManualIracVerionGenerator(pOwnerCache); final ManualIracManager iracManager = createManualIracManager(pOwnerCache); IracMetadata metadata = generateNew(); vGenerator.metadata = metadata; //next write will have this version //we evict the key and then invoke the preload() method //to avoid killing and starting a node. pOwnerCache.put(key, "v4"); iracManager.sendKeys(); assertEventuallyInSite(NYC, cache -> "v4".equals(cache.get(key)), 30, TimeUnit.SECONDS); evictKey(LON, key); assertNotInDataContainer(LON, key); assertInCacheStore(LON, key, "v4", metadata); preload(); assertInDataContainer(LON, key, "v4", metadata); if (!passivation) { assertInCacheStore(LON, key, "v4", metadata); } } @AfterClass(alwaysRun = true) @Override protected void destroy() { cleanupTask.forEach(Runnable::run); super.destroy(); } @Override protected void createSites() { GlobalConfigurationBuilder lonGCB = globalConfigurationBuilderForSite(); TestSite lon = addSite(LON); for (int i = 0; i < NUM_NODES; ++i) { ConfigurationBuilder builder = getLonActiveConfig(); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true); lon.addCache(lonGCB, builder); } GlobalConfigurationBuilder nycGCB = globalConfigurationBuilderForSite(); TestSite nyc = addSite(NYC); for (int i = 0; i < NUM_NODES; ++i) { ConfigurationBuilder builder = getNycActiveConfig(); builder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class).preload(true); nyc.addCache(nycGCB, builder); } lon.waitForClusterToForm(null); nyc.waitForClusterToForm(null); } @Override protected String[] parameterNames() { return new String[]{"LON", "NYC", "passivation"}; } @Override protected Object[] parameterValues() { return new Object[]{lonTxMode, nycTxMode, passivation}; } private void preload() { for (Cache<String, String> cache : this.<String, String>caches(LON)) { PreloadManager pm = TestingUtil.extractComponent(cache, PreloadManager.class); pm.start(); } } private GlobalConfigurationBuilder globalConfigurationBuilderForSite() { GlobalConfigurationBuilder builder = GlobalConfigurationBuilder.defaultClusteredBuilder(); builder.serialization().addContextInitializer(TestDataSCI.INSTANCE); return builder; } private ConfigurationBuilder getNycActiveConfig() { return createConfigurationBuilder(nycTxMode, passivation); } private ConfigurationBuilder getLonActiveConfig() { ConfigurationBuilder builder = createConfigurationBuilder(lonTxMode, passivation); BackupConfigurationBuilder lonBackupConfigurationBuilder = builder.sites().addBackup(); lonBackupConfigurationBuilder .site(NYC) .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder; } private ManualIracManager createManualIracManager(Cache<String, Object> cache) { ManualIracManager manager = ManualIracManager.wrapCache(cache); manager.enable(); return manager; } private void assertNotInDataContainer(String site, String key) { for (Cache<String, Object> cache : this.<String, Object>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } InternalDataContainer<String, Object> dc = getInternalDataContainer(cache); InternalCacheEntry<String, Object> ice = dc.peek(key); log.debugf("Checking DataContainer in %s. entry=%s", DistributionTestHelper.addressOf(cache), ice); assertNull(String.format("Internal entry found for key %s", key), ice); } } private void assertInDataContainer(String site, String key, String value, IracMetadata metadata) { for (Cache<String, Object> cache : this.<String, Object>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } InternalDataContainer<String, Object> dc = getInternalDataContainer(cache); InternalCacheEntry<String, Object> ice = dc.peek(key); log.debugf("Checking DataContainer in %s. entry=%s", DistributionTestHelper.addressOf(cache), ice); assertNotNull(String.format("Internal entry is null for key %s", key), ice); assertEquals("Internal entry wrong key", key, ice.getKey()); assertEquals("Internal entry wrong value", value, ice.getValue()); assertEquals("Internal entry wrong metadata", metadata, ice.getInternalMetadata().iracMetadata()); } } private void assertInCacheStore(String site, String key, String value, IracMetadata metadata) { for (Cache<String, Object> cache : this.<String, Object>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } WaitNonBlockingStore<String, Object> cl = TestingUtil.getFirstStoreWait(cache); MarshallableEntry<String, Object> mEntry = cl.loadEntry(key); log.debugf("Checking CacheLoader in %s. entry=%s", DistributionTestHelper.addressOf(cache), mEntry); assertNotNull(String.format("CacheLoader entry is null for key %s", key), mEntry); assertEquals("CacheLoader entry wrong key", key, mEntry.getKey()); assertEquals("CacheLoader entry wrong value", value, mEntry.getValue()); assertNotNull("CacheLoader entry wrong internal metadata", mEntry.getInternalMetadata()); assertEquals("CacheLoader entry wrong IRAC metadata", metadata, mEntry.getInternalMetadata().iracMetadata()); } } private InternalDataContainer<String, Object> getInternalDataContainer(Cache<String, Object> cache) { //noinspection unchecked return TestingUtil.extractComponent(cache, InternalDataContainer.class); } private void evictKey(String site, String key) { for (Cache<String, Object> cache : this.<String, Object>caches(site)) { if (isNotWriteOwner(cache, key)) { continue; } getInternalDataContainer(cache).evict(getSegmentForKey(cache, key), key).toCompletableFuture().join(); } } private IracMetadataStoreTest setLonTxMode(TxMode lonTxMode) { this.lonTxMode = lonTxMode; return this; } private IracMetadataStoreTest setNycTxMode(TxMode nycTxMode) { this.nycTxMode = nycTxMode; return this; } private IracMetadataStoreTest setPassivation(boolean passivation) { this.passivation = passivation; return this; } private DistributionInfo getDistributionForKey(Cache<String, Object> cache, String key) { return TestingUtil.extractComponent(cache, ClusteringDependentLogic.class) .getCacheTopology() .getDistribution(key); } private int getSegmentForKey(Cache<String, Object> cache, String key) { return getDistributionForKey(cache, key).segmentId(); } private Cache<String, Object> findPrimaryOwner(String key) { for (Cache<String, Object> c : this.<String, Object>caches(LON)) { if (getDistributionForKey(c, key).isPrimary()) { return c; } } throw new IllegalStateException(String.format("Unable to find primary owner for key %s", key)); } private boolean isNotWriteOwner(Cache<String, Object> cache, String key) { return !getDistributionForKey(cache, key).isWriteOwner(); } private enum TxMode { NON_TX, OPT_TX, //2PC with Versions PES_TX // 1PC } private static class ManualIracVersionGenerator extends ControlledIracVersionGenerator { private volatile IracMetadata metadata; public ManualIracVersionGenerator(IracVersionGenerator actual) { super(actual); } @Override public IracMetadata generateNewMetadata(int segment) { return metadata; } @Override public IracMetadata generateNewMetadata(int segment, IracEntryVersion versionSeen) { return metadata; } } }
16,752
37.960465
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/persistence/BaseIracPersistenceTest.java
package org.infinispan.xsite.irac.persistence; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicLong; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.IntSets; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.container.versioning.irac.IracEntryVersion; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.impl.IracMetadata; import org.infinispan.metadata.impl.PrivateMetadata; import org.infinispan.persistence.KeyValueWrapper; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.MarshallableEntryFactory; import org.infinispan.persistence.support.WaitNonBlockingStore; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.ByteString; import org.infinispan.xsite.XSiteNamedCache; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import net.jcip.annotations.GuardedBy; /** * An abstract IRAC test to make sure the {@link IracMetadata} is properly stored and retrieved from persistence. * * @author Pedro Ruivo * @since 11.0 */ @Test(groups = "functional") public abstract class BaseIracPersistenceTest<V> extends SingleCacheManagerTest { private static final AtomicLong V_GENERATOR = new AtomicLong(); private static final String SITE = "LON"; private final KeyValueWrapper<String, String, V> keyValueWrapper; protected String tmpDirectory; protected WaitNonBlockingStore<String, V> cacheStore; protected int segmentCount; protected MarshallableEntryFactory<String, V> entryFactory; protected BaseIracPersistenceTest( KeyValueWrapper<String, String, V> keyValueWrapper) { this.keyValueWrapper = keyValueWrapper; } public void testWriteAndPublisher(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); IracMetadata metadata = createMetadata(); cacheStore.write(createEntry(key, value, metadata)); MarshallableEntrySubscriber<V> subscriber = new MarshallableEntrySubscriber<>(); cacheStore.publishEntries(IntSets.immutableRangeSet(segmentCount), key::equals, true).subscribe(subscriber); List<MarshallableEntry<String, V>> entries = subscriber.cf.join(); assertEquals(1, entries.size()); assertCorrectEntry(entries.get(0), key, value, metadata); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder gBuilder = createGlobalConfigurationBuilder(); ConfigurationBuilder cBuilder = new ConfigurationBuilder(); configure(cBuilder); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(gBuilder, cBuilder); cacheStore = TestingUtil.getFirstStoreWait(cm.getCache()); segmentCount = cm.getCache().getCacheConfiguration().clustering().hash().numSegments(); //noinspection unchecked entryFactory = TestingUtil.extractComponent(cm.getCache(), MarshallableEntryFactory.class); return cm; } protected abstract void configure(ConfigurationBuilder builder); public void testWriteAndLoad(Method method) { String key = TestingUtil.k(method); String value = TestingUtil.v(method); IracMetadata metadata = createMetadata(); cacheStore.write(createEntry(key, value, metadata)); MarshallableEntry<String, V> loadedMEntry = cacheStore.loadEntry(key); assertCorrectEntry(loadedMEntry, key, value, metadata); } private GlobalConfigurationBuilder createGlobalConfigurationBuilder() { GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder().nonClusteredDefault(); builder.globalState().persistentLocation(tmpDirectory); builder.serialization().addContextInitializer(getSerializationContextInitializer()); return builder; } @BeforeClass(alwaysRun = true) @Override protected void createBeforeClass() throws Exception { tmpDirectory = CommonsTestingUtil.tmpDirectory(getClass()); Util.recursiveFileRemove(tmpDirectory); boolean created = new File(tmpDirectory).mkdirs(); log.debugf("Created temporary directory %s (exists? %s)", tmpDirectory, !created); super.createBeforeClass(); } @AfterClass(alwaysRun = true) @Override protected void destroyAfterClass() { super.destroyAfterClass(); Util.recursiveFileRemove(tmpDirectory); } protected SerializationContextInitializer getSerializationContextInitializer() { return TestDataSCI.INSTANCE; } private void assertCorrectEntry(MarshallableEntry<String, V> entry, String key, String value, IracMetadata metadata) { assertNotNull(entry); assertEquals(key, entry.getKey()); assertEquals(value, keyValueWrapper.unwrap(entry.getValue())); PrivateMetadata internalMetadata = entry.getInternalMetadata(); assertNotNull(internalMetadata); IracMetadata storedMetadata = entry.getInternalMetadata().iracMetadata(); assertEquals(metadata, storedMetadata); } private MarshallableEntry<String, V> createEntry(String key, String value, IracMetadata metadata) { return entryFactory.create(key, keyValueWrapper.wrap(key, value), null, wrapInternalMetadata(metadata), -1, -1); } private static IracMetadata createMetadata() { TopologyIracVersion version = TopologyIracVersion.create(1, V_GENERATOR.incrementAndGet()); ByteString site = XSiteNamedCache.cachedByteString(SITE); return new IracMetadata(site, IracEntryVersion.newVersion(site, version)); } private static PrivateMetadata wrapInternalMetadata(IracMetadata metadata) { return new PrivateMetadata.Builder() .iracMetadata(metadata) .build(); } private static class MarshallableEntrySubscriber<V> implements Subscriber<MarshallableEntry<String, V>> { @GuardedBy("this") private final List<MarshallableEntry<String, V>> entries = new ArrayList<>(1); private final CompletableFuture<List<MarshallableEntry<String, V>>> cf = new CompletableFuture<>(); @Override public void onSubscribe(Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public synchronized void onNext(MarshallableEntry<String, V> entry) { entries.add(entry); } @Override public void onError(Throwable throwable) { cf.completeExceptionally(throwable); } @Override public synchronized void onComplete() { cf.complete(entries); } } }
7,379
38.465241
118
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/irac/persistence/IracSingleFileStoreTest.java
package org.infinispan.xsite.irac.persistence; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.IdentityKeyValueWrapper; import org.infinispan.persistence.file.SingleFileStore; import org.testng.annotations.Test; /** * Tests if the IRAC metadata is properly stored and retrieved from a {@link SingleFileStore}. * * @author Pedro Ruivo * @since 10.1 */ @Test(groups = "functional", testName = "xsite.irac.persistence.IracSingleFileStoreTest") public class IracSingleFileStoreTest extends BaseIracPersistenceTest<String> { public IracSingleFileStoreTest() { super(IdentityKeyValueWrapper.instance()); } @Override protected void configure(ConfigurationBuilder builder) { builder.persistence().addSingleFileStore().location(tmpDirectory); } }
825
29.592593
94
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/InvalidConfigurationOfflineTest.java
package org.infinispan.xsite.offline; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.OfflineStatus; import org.infinispan.xsite.status.DefaultTakeOfflineManager; import org.infinispan.xsite.status.TakeOfflineManager; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests if the site is taken offline in case of incorrect cache configuration from the remote site. * * @author Pedro Ruivo * @since 12 */ @Test(groups = "xsite", testName = "xsite.offline.InvalidConfigurationOfflineTest") public class InvalidConfigurationOfflineTest extends AbstractMultipleSitesTest { @Override protected int defaultNumberOfSites() { return 2; } @Override protected int defaultNumberOfNodes() { return 1; } @Override protected void afterSitesCreated() { waitForSites(sites.stream().map(TestSite::getSiteName).toArray(String[]::new)); } @DataProvider(name = "data") public Object[][] collectionItemProvider() { return new Object[][]{ {"not-defined-true", true, RemoteSiteMode.NOT_DEFINED}, {"not-started-true", true, RemoteSiteMode.NOT_STARTED}, {"not-clustered-true", true, RemoteSiteMode.LOCAL_CACHE}, {"not-defined-false", false, RemoteSiteMode.NOT_DEFINED}, {"not-started-false", false, RemoteSiteMode.NOT_STARTED}, {"not-clustered-false", false, RemoteSiteMode.LOCAL_CACHE}, }; } @Test(dataProvider = "data") public void testTakeOffline(String cacheName, boolean takeOfflineEnabled, RemoteSiteMode remoteSiteMode) { configureSite1(cacheName, takeOfflineEnabled); configureSite2(cacheName, remoteSiteMode); final OfflineStatus offlineStatus = takeOfflineManager(cacheName).getOfflineStatus(siteName(1)); assertEquals(takeOfflineEnabled, offlineStatus.isEnabled()); assertFalse(offlineStatus.isOffline()); cache(0, cacheName, 0).put("key", "value"); eventually(() -> "Invalid configuration should take site offline.", offlineStatus::isOffline); } private DefaultTakeOfflineManager takeOfflineManager(String cacheName) { return (DefaultTakeOfflineManager) TestingUtil.extractComponent(cache(0, cacheName, 0), TakeOfflineManager.class); } private void configureSite2(String cacheName, RemoteSiteMode remoteSiteMode) { switch (remoteSiteMode) { case LOCAL_CACHE: ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.LOCAL); defineInSite(site(1), cacheName, builder.build()); site(1).waitForClusterToForm(cacheName); assertTrue(site(1).cacheManagers().get(0).isRunning(cacheName)); return; case NOT_DEFINED: assertFalse(site(1).cacheManagers().get(0).cacheExists(cacheName)); return; case NOT_STARTED: //it defines the cache but doesn't start it. defineInSite(site(1), cacheName, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC).build()); assertFalse(site(1).cacheManagers().get(0).isRunning(cacheName)); return; default: fail("Unexpected: " + remoteSiteMode); } } private void configureSite1(String cacheName, boolean takeOfflineEnabled) { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); BackupConfigurationBuilder backupBuilder = builder.sites().addBackup(); backupBuilder.site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.ASYNC); if (takeOfflineEnabled) { // we want the take-offline enabled but prevent it for messing with the test. backupBuilder.takeOffline().afterFailures(Integer.MAX_VALUE); } defineInSite(site(0), cacheName, builder.build()); site(0).waitForClusterToForm(cacheName); } private enum RemoteSiteMode { NOT_DEFINED, NOT_STARTED, LOCAL_CACHE } }
4,522
39.026549
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/DelegatingTransport.java
package org.infinispan.xsite.offline; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; import org.infinispan.remoting.transport.AbstractDelegatingTransport; import org.infinispan.remoting.transport.BackupResponse; import org.infinispan.remoting.transport.Transport; import org.infinispan.remoting.transport.XSiteResponse; import org.infinispan.util.logging.Log; import org.infinispan.xsite.XSiteBackup; import org.infinispan.xsite.XSiteReplicateCommand; public class DelegatingTransport extends AbstractDelegatingTransport { volatile boolean fail; DelegatingTransport(Transport actual) { super(actual); } @Override public void start() { //no-op; avoid re-start the transport again... } @Override public BackupResponse backupRemotely(final Collection<XSiteBackup> backups, XSiteReplicateCommand rpcCommand) { throw new UnsupportedOperationException(); } @Override public <O> XSiteResponse<O> backupRemotely(XSiteBackup backup, XSiteReplicateCommand<O> rpcCommand) { DummyXSiteResponse<O> response = new DummyXSiteResponse<>(backup, fail); response.complete(); return response; } @Override public Log getLog() { return actual.getLog(); } private static class DummyXSiteResponse<O> extends CompletableFuture<O> implements XSiteResponse<O> { private final XSiteBackup backup; private final boolean fail; private DummyXSiteResponse(XSiteBackup backup, boolean fail) { this.backup = backup; this.fail = fail; } @Override public void whenCompleted(XSiteResponseCompleted xSiteResponseCompleted) { xSiteResponseCompleted .onCompleted(backup, System.currentTimeMillis(), 0, fail ? new TimeoutException() : null); } void complete() { if (fail) { completeExceptionally(new TimeoutException()); } else { complete(null); } } } }
2,043
28.2
114
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/ResetOfflineStatusTest.java
package org.infinispan.xsite.offline; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.TestingUtil; import org.infinispan.xsite.BaseSiteUnreachableTest; import org.infinispan.xsite.OfflineStatus; import org.infinispan.xsite.status.BringSiteOnlineResponse; import org.infinispan.xsite.status.DefaultTakeOfflineManager; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.offline.ResetOfflineStatusTest") public class ResetOfflineStatusTest extends BaseSiteUnreachableTest { private static final int FAILURES = 8; private static final Object[] KEYS = new Object[FAILURES * 10]; public ResetOfflineStatusTest() { failures = FAILURES; lonBackupFailurePolicy = BackupFailurePolicy.FAIL; } public void testPutWithFailures() { populateKeys(cache(LON, 0)); EmbeddedCacheManager manager = cache(LON, 0).getCacheManager(); Transport transport = manager.getGlobalComponentRegistry().getComponent(Transport.class); DelegatingTransport delegatingTransport = new DelegatingTransport(transport); TestingUtil.replaceComponent(manager, Transport.class, delegatingTransport, true); DefaultTakeOfflineManager tom = takeOfflineManager(LON, 0); OfflineStatus offlineStatus = tom.getOfflineStatus(NYC); delegatingTransport.fail = true; for (int i = 0; i < FAILURES; i++) { try { cache(LON, 0).put(KEYS[i], "v" + i); fail("This should have failed"); } catch (Exception e) { //expected } } for (int i = 0; i < FAILURES; i++) { cache(LON, 0).put(KEYS[i], "v" + i); } for (int i = 0; i < FAILURES; i++) { assertEquals("v" + i, cache(LON, 0).get(KEYS[i])); } assertEquals(BringSiteOnlineResponse.BROUGHT_ONLINE, tom.bringSiteOnline(NYC)); for (int i = 0; i < FAILURES - 1; i++) { try { cache(LON, 0).put(KEYS[i], "v" + i); fail("This should have failed"); } catch (Exception e) { //expected } } delegatingTransport.fail = false; assertEquals(FAILURES - 1, offlineStatus.getFailureCount()); cache(LON, 0).put(KEYS[FAILURES], "vi"); //this should reset the offline status assertEquals(0, offlineStatus.getFailureCount()); for (int i = 0; i < FAILURES * 10; i++) { cache(LON, 0).put(KEYS[i], "v" + i); } for (int i = 0; i < FAILURES * 10; i++) { assertEquals("v" + i, cache(LON, 0).get(KEYS[i])); } } protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } private void populateKeys(Cache primaryOwner) { for (int i = 0; i < KEYS.length; ++i) { KEYS[i] = new MagicKey("k" + i, primaryOwner); } } }
3,338
32.39
95
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/TxOfflineTest.java
package org.infinispan.xsite.offline; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "xsite", testName = "xsite.offline.TxOfflineTest") public class TxOfflineTest extends NonTxOfflineTest { public TxOfflineTest() { this.nrRpcPerPut = 1; //It's only the commit that fails (no prepare as by default we only replicate during commit) } @Override protected ConfigurationBuilder getLonActiveConfig() { ConfigurationBuilder dccc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); dccc.transaction().useSynchronization(false).recovery().disable(); return dccc; } }
731
33.857143
120
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/AsyncTimeBasedOfflineTest.java
package org.infinispan.xsite.offline; import static org.infinispan.test.TestingUtil.extractCacheTopology; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import org.infinispan.Cache; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.util.ExponentialBackOff; import org.infinispan.xsite.AbstractXSiteTest; import org.infinispan.xsite.OfflineStatus; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests the async cross-site replication is working properly. * * @author Pedro Ruivo * @since 10.0 */ @Test(groups = "functional", testName = "xsite.offline.AsyncTimeBasedOfflineTest") public class AsyncTimeBasedOfflineTest extends AbstractXSiteTest { private static final int NUM_NODES = 3; private static final long MIN_WAIT_TIME_MILLIS = 1000; private static final String LON = "LON-1"; private static final String NYC = "NYC-2"; private static final String SFO = "SFO-3"; public void testSFOOffline(Method method) { String cacheName = method.getName(); defineCache(LON, cacheName, getLONConfiguration()); defineCache(NYC, cacheName, getNYCOrSFOConfiguration()); //disable exponential back-off to avoid messing the times for (int i = 0; i < NUM_NODES; ++i) { iracManager(LON, cacheName, i).setBackOff(ExponentialBackOff.NO_OP_BUILDER); } String key = method.getName() + "-key"; int primaryOwner = primaryOwnerIndex(cacheName, key); for (int i = 0; i < NUM_NODES; ++i) { //probably and overkill, but this will test on primary owner, backup owner, sitemaster and non-sitemaster doTestInNode(cacheName, i, primaryOwner, key); } } @AfterMethod(alwaysRun = true) public void killSFO() { killSite(SFO); } @Override protected void createSites() { //we have 3 sites: LON, NYC and SFO. SFO is offline. createTestSite(LON); createTestSite(NYC); waitForSites(LON, NYC); } private void doTestInNode(String cacheName, int index, int primaryOwnerIndex, String key) { Cache<String, String> cache = this.cache(LON, cacheName, index); assertOnline(cacheName, index, NYC); assertOnline(cacheName, index, SFO); if (index != primaryOwnerIndex) { assertOnline(cacheName, primaryOwnerIndex, NYC); assertOnline(cacheName, primaryOwnerIndex, SFO); } cache.put(key, "value"); if (index == primaryOwnerIndex) { assertOnline(cacheName, index, NYC); assertEventuallyOffline(cacheName, index); } else { assertOnline(cacheName, index, NYC); assertOnline(cacheName, index, SFO); assertOnline(cacheName, primaryOwnerIndex, NYC); assertEventuallyOffline(cacheName, primaryOwnerIndex); } assertBringSiteOnline(cacheName, primaryOwnerIndex); } private void assertOnline(String cacheName, int index, String targetSiteName) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(targetSiteName); assertTrue(status.isEnabled()); assertFalse("Site " + targetSiteName + " is offline. status=" + status, status.isOffline()); } private void assertEventuallyOffline(String cacheName, int index) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(SFO); assertTrue(status.isEnabled()); eventually(status::minTimeHasElapsed); cache(LON, cacheName, index).put("_key_", "_value_"); eventually(() -> "Site " + SFO + " is online. status=" + status, status::isOffline); } private void assertBringSiteOnline(String cacheName, int index) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(SFO); assertTrue("Unable to bring " + SFO + " online. status=" + status, status.bringOnline()); } private int primaryOwnerIndex(String cacheName, String key) { for (int i = 0; i < NUM_NODES; ++i) { boolean isPrimary = extractCacheTopology(cache(LON, cacheName, i)) .getDistribution(key) .isPrimary(); if (isPrimary) { return i; } } throw new IllegalStateException(); } private Configuration getLONConfiguration() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.clustering().hash().numSegments(4); builder.sites().addBackup() .site(NYC) .backupFailurePolicy(BackupFailurePolicy.FAIL) .replicationTimeout(1000) //keep it small so that the test doesn't take long to run .takeOffline() .afterFailures(-1) .minTimeToWait(MIN_WAIT_TIME_MILLIS) .backup() .strategy(BackupConfiguration.BackupStrategy.SYNC); builder.sites().addBackup() .site(SFO) .backupFailurePolicy(BackupFailurePolicy.IGNORE) .replicationTimeout(1000) //keep it small so that the test doesn't take long to run .takeOffline() .afterFailures(-1) .minTimeToWait(MIN_WAIT_TIME_MILLIS) .backup() .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder.build(); } private Configuration getNYCOrSFOConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC).build(); } private void defineCache(String siteName, String cacheName, Configuration configuration) { TestSite site = site(siteName); site.cacheManagers().get(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, configuration); site.waitForClusterToForm(cacheName); } private void createTestSite(String siteName) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); createSite(siteName, NUM_NODES, gcb, new ConfigurationBuilder()); } }
6,430
36.608187
139
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/AsyncOfflineTest.java
package org.infinispan.xsite.offline; import static org.infinispan.test.TestingUtil.extractCacheTopology; import static org.infinispan.test.TestingUtil.wrapGlobalComponent; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.inboundhandler.InboundInvocationHandler; import org.infinispan.remoting.inboundhandler.Reply; import org.infinispan.remoting.transport.Address; import org.infinispan.util.ExponentialBackOff; import org.infinispan.xsite.AbstractXSiteTest; import org.infinispan.xsite.OfflineStatus; import org.infinispan.xsite.XSiteReplicateCommand; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Tests the async cross-site replication is working properly. * * @author Pedro Ruivo * @since 10.0 */ @Test(groups = "functional", testName = "xsite.offline.AsyncOfflineTest") public class AsyncOfflineTest extends AbstractXSiteTest { private static final int NUM_NODES = 3; private static final int NUM_FAILURES = 6; private static final String LON = "LON-1"; private static final String NYC = "NYC-2"; private static final String SFO = "SFO-3"; public void testSFOOffline(Method method) { String cacheName = method.getName(); defineCache(LON, cacheName, getLONConfiguration()); defineCache(NYC, cacheName, getNYCOrSFOConfiguration()); for (int i = 0; i < NUM_NODES; ++i) { iracManager(LON, cacheName, i).setBackOff(ExponentialBackOff.NO_OP_BUILDER); } String key = method.getName() + "-key"; int primaryOwner = primaryOwnerIndex(cacheName, key); for (int i = 0; i < NUM_NODES; ++i) { //probably and overkill, but this will test on primary owner, backup owner, sitemaster and non-sitemaster doTestInNode(cacheName, i, primaryOwner, key); } } public void testSlowSFO(Method method) { createTestSite(SFO); String cacheName = method.getName(); defineCache(LON, cacheName, getLONConfiguration()); defineCache(NYC, cacheName, getNYCOrSFOConfiguration()); defineCache(SFO, cacheName, getNYCOrSFOConfiguration()); for (int i = 0; i < NUM_NODES; ++i) { iracManager(LON, cacheName, i).setBackOff(ExponentialBackOff.NO_OP_BUILDER); } String key = method.getName() + "-key"; int primaryOwner = primaryOwnerIndex(cacheName, key); cache(LON, cacheName, 0).put("key", "value"); eventuallyEquals("value", () -> cache(SFO, cacheName, 0).get("key")); assertEquals(0, takeOfflineManager(LON, cacheName, primaryOwner).getOfflineStatus(SFO).getFailureCount()); List<DiscardInboundHandler> handlers = replaceSFOInboundHandler(); handlers.forEach(h -> h.discard = true); //same as testSFOOffline but every command should fail with timeout for SFO. for (int i = 0; i < NUM_NODES; ++i) { //probably and overkill, but this will test on primary owner, backup owner, sitemaster and non-sitemaster doTestInNode(cacheName, i, primaryOwner, key); } } public void testReset(Method method) { createTestSite(SFO); String cacheName = method.getName(); defineCache(LON, cacheName, getLONConfiguration()); defineCache(NYC, cacheName, getNYCOrSFOConfiguration()); defineCache(SFO, cacheName, getNYCOrSFOConfiguration()); for (int i = 0; i < NUM_NODES; ++i) { iracManager(LON, cacheName, i).setBackOff(ExponentialBackOff.NO_OP_BUILDER); } String key = method.getName() + "-key"; int primaryOwner = primaryOwnerIndex(cacheName, key); Cache<String, String> lonCache = cache(LON, cacheName, 0); Cache<String, String> sfoCache = cache(SFO, cacheName, 0); OfflineStatus lonStatus = takeOfflineManager(LON, cacheName, primaryOwner).getOfflineStatus(SFO); lonCache.put(key, "value"); eventuallyEquals("value", () -> sfoCache.get(key)); assertEquals(0, lonStatus.getFailureCount()); List<DiscardInboundHandler> handlers = replaceSFOInboundHandler(); handlers.forEach(h -> h.discard = true); //SFO request should timeout (timeout=1 sec) and it retries (max retries = 6) lonCache.put(key, "value2"); eventuallyEquals(1, lonStatus::getFailureCount); assertEquals("value", sfoCache.get(key)); handlers.forEach(h -> h.discard = false); // make sure the key is flushed. we don't want to receive timeouts after this point eventually(() -> { for (int i = 0; i < NUM_NODES; ++i) { if (!iracManager(LON, cacheName, i).isEmpty()) { return false; } } return true; }); //SFO request will succeed and reset the take offline status lonCache.put(key, "value3"); eventuallyEquals("value3", () -> sfoCache.get(key)); eventuallyEquals(0, lonStatus::getFailureCount); } @AfterMethod(alwaysRun = true) public void killSFO() { killSite(SFO); } @Override protected void createSites() { //we have 3 sites: LON, NYC and SFO. SFO is offline. createTestSite(LON); createTestSite(NYC); waitForSites(LON, NYC); } private void doTestInNode(String cacheName, int index, int primaryOwnerIndex, String key) { Cache<String, String> cache = this.cache(LON, cacheName, index); assertOnline(cacheName, index, NYC); assertOnline(cacheName, index, SFO); if (index != primaryOwnerIndex) { assertOnline(cacheName, primaryOwnerIndex, NYC); assertOnline(cacheName, primaryOwnerIndex, SFO); } for (int i = 0; i < NUM_FAILURES; ++i) { cache.put(key, "value"); } if (index == primaryOwnerIndex) { assertOnline(cacheName, index, NYC); assertEventuallyOffline(cacheName, index); } else { assertOnline(cacheName, index, NYC); assertOnline(cacheName, index, SFO); assertOnline(cacheName, primaryOwnerIndex, NYC); assertEventuallyOffline(cacheName, primaryOwnerIndex); } assertBringSiteOnline(cacheName, primaryOwnerIndex); } private void assertOnline(String cacheName, int index, String targetSiteName) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(targetSiteName); assertTrue(status.isEnabled()); assertFalse("Site " + targetSiteName + " is offline. status=" + status, status.isOffline()); } private void assertEventuallyOffline(String cacheName, int index) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(SFO); assertTrue(status.isEnabled()); eventually(() -> "Site " + SFO + " is online. status=" + status, status::isOffline); } private void assertBringSiteOnline(String cacheName, int index) { OfflineStatus status = takeOfflineManager(LON, cacheName, index).getOfflineStatus(SFO); assertTrue("Unable to bring " + SFO + " online. status=" + status, status.bringOnline()); } private int primaryOwnerIndex(String cacheName, String key) { for (int i = 0; i < NUM_NODES; ++i) { boolean isPrimary = extractCacheTopology(cache(LON, cacheName, i)) .getDistribution(key) .isPrimary(); if (isPrimary) { return i; } } throw new IllegalStateException(); } private Configuration getLONConfiguration() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); builder.clustering().hash().numSegments(4); builder.sites().addBackup() .site(NYC) .backupFailurePolicy(BackupFailurePolicy.FAIL) .replicationTimeout(1000) //keep it small so that the test doesn't take long to run .takeOffline() .afterFailures(NUM_FAILURES) .backup() .strategy(BackupConfiguration.BackupStrategy.SYNC); builder.sites().addBackup() .site(SFO) .replicationTimeout(1000) //keep it small so that the test doesn't take long to run .takeOffline() .afterFailures(NUM_FAILURES) .backup() .strategy(BackupConfiguration.BackupStrategy.ASYNC); return builder.build(); } private Configuration getNYCOrSFOConfiguration() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC).build(); } private void defineCache(String siteName, String cacheName, Configuration configuration) { TestSite site = site(siteName); site.cacheManagers().get(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache(cacheName, configuration); site.waitForClusterToForm(cacheName); } private void createTestSite(String siteName) { GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder(); createSite(siteName, NUM_NODES, gcb, new ConfigurationBuilder()); } private List<DiscardInboundHandler> replaceSFOInboundHandler() { List<DiscardInboundHandler> handlers = new ArrayList<>(NUM_NODES); for (EmbeddedCacheManager manager : site(SFO).cacheManagers()) { handlers.add(wrapGlobalComponent(manager, InboundInvocationHandler.class, DiscardInboundHandler::new, true)); } return handlers; } private static class DiscardInboundHandler implements InboundInvocationHandler { private final InboundInvocationHandler handler; private volatile boolean discard; private DiscardInboundHandler(InboundInvocationHandler handler) { this.handler = handler; this.discard = false; } @Override public void handleFromCluster(Address origin, ReplicableCommand command, Reply reply, DeliverOrder order) { handler.handleFromCluster(origin, command, reply, order); } @Override public void handleFromRemoteSite(String origin, XSiteReplicateCommand<?> command, Reply reply, DeliverOrder order) { if (discard) { return; } handler.handleFromRemoteSite(origin, command, reply, order); } } }
10,953
37.167247
139
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/NonTxOfflineTest.java
package org.infinispan.xsite.offline; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import org.infinispan.Cache; import org.infinispan.configuration.cache.BackupFailurePolicy; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.xsite.BaseSiteUnreachableTest; import org.infinispan.xsite.OfflineStatus; import org.infinispan.xsite.status.BringSiteOnlineResponse; import org.infinispan.xsite.status.DefaultTakeOfflineManager; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test(groups = "xsite", testName = "xsite.offline.NonTxOfflineTest") public class NonTxOfflineTest extends BaseSiteUnreachableTest { private static final int FAILURES = 8; private final Object[] keys = new Object[FAILURES]; protected int nrRpcPerPut = 1; public NonTxOfflineTest() { failures = FAILURES; lonBackupFailurePolicy = BackupFailurePolicy.FAIL; } public void testPutWithFailures() { populateKeys(cache(LON, 0)); DefaultTakeOfflineManager tom = takeOfflineManager(LON, 0); OfflineStatus nycStatus = tom.getOfflineStatus(NYC); for (int i = 0; i < FAILURES / nrRpcPerPut; i++) { try { assertEquals(BringSiteOnlineResponse.ALREADY_ONLINE, tom.bringSiteOnline(NYC)); cache(LON, 0).put(keys[i], "v" + i); fail("This should have failed"); } catch (Exception e) { eventuallyEquals(i + 1, nycStatus::getFailureCount); } } assertTrue(nycStatus.isOffline()); for (int i = 0; i < FAILURES; i++) { cache(LON, 0).put(keys[i], "v" + i); } for (int i = 0; i < FAILURES; i++) { assertEquals("v" + i, cache(LON, 0).get(keys[i])); } assertEquals(BringSiteOnlineResponse.NO_SUCH_SITE, tom.bringSiteOnline("NO_SITE")); assertEquals(BringSiteOnlineResponse.BROUGHT_ONLINE, tom.bringSiteOnline(NYC)); for (int i = 0; i < FAILURES / nrRpcPerPut; i++) { try { cache(LON, 0).put(keys[i], "v" + i); fail("This should have failed"); } catch (Exception e) { //expected } } } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } private void populateKeys(Cache primaryOwner) { for (int i = 0; i < keys.length; ++i) { keys[i] = new MagicKey("k" + i, primaryOwner); } } }
2,696
31.107143
91
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/offline/OfflineStatusTest.java
package org.infinispan.xsite.offline; import static java.lang.String.format; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import org.infinispan.configuration.cache.TakeOfflineConfiguration; import org.infinispan.configuration.cache.TakeOfflineConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.util.ControlledTimeService; import org.infinispan.xsite.OfflineStatus; import org.infinispan.xsite.notification.SiteStatusListener; import org.testng.annotations.Test; /** * @author Mircea Markus * @since 5.2 */ @Test (groups = "xsite", testName = "xsite.offline.OfflineStatusTest") public class OfflineStatusTest extends AbstractInfinispanTest { public void timeBasedTakeOffline() { //Tests if the offline status changes when the minimum time has elapsed and after failure counter. final long minTimeWait = 3000; final int minFailures = 10; final TestContext context = createNew(minTimeWait, minFailures); //first part, we reached the min failures but not the min time. for (int i = 0; i < minFailures + 1; i++) { assertOffline(context, false); addCommunicationFailure(context); } assertMinFailureCount(context, minFailures + 1); assertMinTimeElapsed(context, false); assertOffline(context, false); context.timeService.advance(minTimeWait + 1); assertMinTimeElapsed(context, true); assertMinFailureCount(context, minFailures + 1); addCommunicationFailure(context); assertOffline(context, true); context.offlineStatus.reset(); //reset everything //second part, we reached the min time, but not the failures- for (int i = 0; i < minFailures -1; i++) { assertOffline(context, false); addCommunicationFailure(context); } assertMinFailureCount(context, minFailures -1); assertMinTimeElapsed(context, false); assertOffline(context, false); context.timeService.advance(minTimeWait + 1); assertMinFailureCount(context, minFailures -1); assertMinTimeElapsed(context, true); assertOffline(context, false); addCommunicationFailure(context); assertMinTimeElapsed(context, true); assertMinFailureCount(context, minFailures); assertOffline(context, true); context.listener.check(SiteStatus.OFFLINE, SiteStatus.ONLINE, SiteStatus.OFFLINE); } public void testFailureBasedOnly() { //note: can't check the min time since it throws an IllegalStateException when disabled final int minFailures = 10; final TestContext context = createNew(0, minFailures); for (int i = 0; i < minFailures - 1; i++) { assertOffline(context, false); addCommunicationFailure(context); } assertMinFailureCount(context, minFailures - 1); assertOffline(context, false); context.timeService.advance(1); assertMinFailureCount(context, minFailures - 1); assertOffline(context, false); addCommunicationFailure(context); assertMinFailureCount(context, minFailures); assertOffline(context, true); context.listener.check(SiteStatus.OFFLINE); } public void testTimeBasedOnly() { final long minWaitTime = 3000; final int minFailures = 10; final TestContext context = createNew(minWaitTime, -1); for (int i = 0; i < minFailures; i++) { assertOffline(context, false); addCommunicationFailure(context); } assertMinFailureCount(context, minFailures); assertMinTimeElapsed(context, false); assertOffline(context, false); context.timeService.advance(minWaitTime + 1); assertMinFailureCount(context, minFailures); assertMinTimeElapsed(context, true); addCommunicationFailure(context); assertOffline(context, true); context.listener.check(SiteStatus.OFFLINE); } public void testForceOffline() { //note: can't check the min time since it throws an IllegalStateException when disabled final TestContext context = createNew(-1, -1); addCommunicationFailure(context); context.timeService.advance(1); assertMinFailureCount(context, 1); assertOffline(context, false); context.offlineStatus.forceOffline(); assertMinFailureCount(context, 1); assertOffline(context, true); //test bring online context.offlineStatus.bringOnline(); assertMinFailureCount(context, 0); assertOffline(context, false); addCommunicationFailure(context); context.timeService.advance(1); assertMinFailureCount(context, 1); assertOffline(context, false); context.offlineStatus.forceOffline(); assertMinFailureCount(context, 1); assertOffline(context, true); //test reset context.offlineStatus.reset(); assertMinFailureCount(context, 0); assertOffline(context, false); context.listener.check(SiteStatus.OFFLINE, SiteStatus.ONLINE, SiteStatus.OFFLINE, SiteStatus.ONLINE); } private static void assertOffline(TestContext context, boolean expected) { assertEquals("Checking offline.", expected, context.offlineStatus.isOffline()); } private static void assertMinFailureCount(TestContext context, int expected) { assertEquals("Check failure count.", expected, context.offlineStatus.getFailureCount()); } private static void assertMinTimeElapsed(TestContext context, boolean expected) { assertEquals(format("Check min time has elapsed. Current time=%d. Time elapsed=%d", context.timeService.time(), context.offlineStatus.millisSinceFirstFailure()), expected, context.offlineStatus.minTimeHasElapsed()); } private static void addCommunicationFailure(TestContext context) { context.offlineStatus.updateOnCommunicationFailure(context.timeService.wallClockTime()); } private static TestContext createNew(long minWait, int afterFailures) { ControlledTimeService t = new ControlledTimeService(); ListenerImpl l = new ListenerImpl(); TakeOfflineConfiguration c = new TakeOfflineConfigurationBuilder(null, null) .afterFailures(afterFailures) .minTimeToWait(minWait) .create(); return new TestContext(new OfflineStatus(c, t, l), t, l); } private static class TestContext { private final OfflineStatus offlineStatus; private final ControlledTimeService timeService; private final ListenerImpl listener; private TestContext(OfflineStatus offlineStatus, ControlledTimeService timeService, ListenerImpl listener) { this.offlineStatus = offlineStatus; this.timeService = timeService; this.listener = listener; } } private static class ListenerImpl implements SiteStatusListener { private final Queue<SiteStatus> notifications; private ListenerImpl() { notifications = new ConcurrentLinkedDeque<>(); } @Override public void siteOnline() { notifications.add(SiteStatus.ONLINE); } @Override public void siteOffline() { notifications.add(SiteStatus.OFFLINE); } private void check(SiteStatus first) { assertEquals("Check first site status.", first, notifications.poll()); assertTrue("Check notifications is empty.", notifications.isEmpty()); } private void check(SiteStatus first, SiteStatus... remaining) { assertEquals("Check first site status.", first, notifications.poll()); int i = 2; for (SiteStatus status : remaining) { assertEquals(format("Check %d(\"th\") site status", i), status, notifications.poll()); i++; } assertTrue("Check notifications is empty.", notifications.isEmpty()); } } private enum SiteStatus { ONLINE, OFFLINE } }
8,142
32.236735
117
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/BaseStateTransferTest.java
package org.infinispan.xsite.statetransfer; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.infinispan.test.TestingUtil.wrapComponent; import static org.infinispan.xsite.XSiteAdminOperations.SUCCESS; import static org.infinispan.xsite.statetransfer.XSiteStateTransferManager.STATUS_CANCELED; import static org.infinispan.xsite.statetransfer.XSiteStateTransferManager.STATUS_SENDING; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.Cache; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.functional.WriteOnlyManyEntriesCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.commands.write.ClearCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commands.write.RemoveCommand; import org.infinispan.commands.write.WriteCommand; import org.infinispan.commons.test.ExceptionRunnable; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.container.entries.InternalCacheValue; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.remoting.transport.Address; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.util.ControlledTransport; import org.infinispan.xsite.BackupReceiver; import org.infinispan.xsite.BackupReceiverDelegator; import org.infinispan.xsite.XSiteAdminOperations; import org.infinispan.xsite.commands.XSiteBringOnlineCommand; import org.infinispan.xsite.commands.XSiteStateTransferCancelSendCommand; import org.infinispan.xsite.commands.XSiteStateTransferFinishReceiveCommand; import org.infinispan.xsite.commands.XSiteStateTransferStartReceiveCommand; import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand; import org.infinispan.xsite.commands.XSiteStateTransferStatusRequestCommand; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency. * * @author Pedro Ruivo * @since 7.0 */ public abstract class BaseStateTransferTest extends AbstractStateTransferTest { private static final String VALUE = "value"; BaseStateTransferTest() { this.cleanup = CleanupPhase.AFTER_METHOD; this.cacheMode = CacheMode.DIST_SYNC; } @Test(groups = "xsite") public void testStateTransferNonExistingSite() { XSiteAdminOperations operations = adminOperations(); assertEquals("Unable to pushState to 'NO_SITE'. Incorrect site name: NO_SITE", operations.pushState("NO_SITE")); assertTrue(operations.getRunningStateTransfer().isEmpty()); assertNoStateTransferInSendingSite(); } @Test(groups = "xsite") public void testCancelStateTransfer(Method method) throws InterruptedException { takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(null); assertNoStateTransferInSendingSite(); // NYC is offline... lets put some initial data in LON. // The primary owner is the one sending the state to the backup. // We add keys until we have more than one chunk on the LON coordinator. LocalizedCacheTopology topology = cache(LON, 0).getAdvancedCache().getDistributionManager().getCacheTopology(); Address coordLON = cache(LON, 0).getCacheManager().getAddress(); Set<Object> keysOnCoordinator = new HashSet<>(); int i = 0; while (keysOnCoordinator.size() < chunkSize()) { Object key = k(method, i); cache(LON, 0).put(key, VALUE); if (topology.getDistribution(key).primary().equals(coordLON)) { keysOnCoordinator.add(key); } ++i; } int numKeys = i; log.debugf("Coordinator %s is primary owner for %d keys: %s", coordLON, keysOnCoordinator.size(), keysOnCoordinator); //check if NYC is empty assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); ControlledTransport controlledTransport = ControlledTransport.replace(cache(LON, 0)); controlledTransport.excludeCommands(XSiteBringOnlineCommand.class, XSiteStateTransferStartReceiveCommand.class, XSiteStateTransferStartSendCommand.class, XSiteStateTransferCancelSendCommand.class, XSiteStateTransferFinishReceiveCommand.class, XSiteStateTransferStatusRequestCommand.class); startStateTransfer(); // Wait for a push command and block it ControlledTransport.BlockedRequest<XSiteStatePushCommand> pushRequest = controlledTransport.expectCommand(XSiteStatePushCommand.class); assertEquals(SUCCESS, adminOperations().cancelPushState(NYC)); // Unblock the push command pushRequest.send().receiveAll(); assertEventuallyStateTransferNotRunning(); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); assertEquals(STATUS_CANCELED, adminOperations().getPushStateStatus().get(NYC)); startStateTransfer(); // Wait for a push command and block it ControlledTransport.BlockedRequest<XSiteStatePushCommand> pushRequest2 = controlledTransport.expectCommand(XSiteStatePushCommand.class); assertEquals(STATUS_SENDING, adminOperations().getPushStateStatus().get(NYC)); // Unblock the push command pushRequest2.send().receiveAll(); assertEventuallyStateTransferNotRunning(); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); //check if all data is visible assertInSite(NYC, cache -> { for (int i1 = 0; i1 < numKeys; ++i1) { assertEquals(VALUE, cache.get(k(method, i1))); } }); controlledTransport.stopBlocking(); } @Test(groups = "xsite") public void testStateTransferWithClusterIdle(Method method) { takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(null); assertNoStateTransferInSendingSite(); //NYC is offline... lets put some initial data in //we have 2 nodes in each site and the primary owner sends the state. Lets try to have more key than the chunk //size in order to each site to send more than one chunk. final int amountOfData = chunkSize() * 4; for (int i = 0; i < amountOfData; ++i) { cache(LON, 0).put(k(method, i), VALUE); } //check if NYC is empty assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); startStateTransfer(); assertEventuallyStateTransferNotRunning(); assertOnline(LON, NYC); //check if all data is visible assertInSite(NYC, cache -> { for (int i = 0; i < amountOfData; ++i) { assertEquals(VALUE, cache.get(k(method, i))); } }); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); } @Test(groups = "xsite") public void testPutOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.PUT, true, method); } @Test(groups = "xsite") public void testPutOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.PUT, false, method); } @Test(groups = "xsite") public void testRemoveOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REMOVE, true, method); } @Test(groups = "xsite") public void testRemoveOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REMOVE, false, method); } @Test(groups = "xsite") public void testRemoveIfMatchOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REMOVE_IF_MATCH, true, method); } @Test(groups = "xsite") public void testRemoveIfMatchOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REMOVE_IF_MATCH, false, method); } @Test(groups = "xsite") public void testReplaceOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REPLACE, true, method); } @Test(groups = "xsite") public void testReplaceOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REPLACE, false, method); } @Test(groups = "xsite") public void testReplaceIfMatchOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REPLACE_IF_MATCH, true, method); } @Test(groups = "xsite") public void testReplaceIfMatchOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.REPLACE_IF_MATCH, false, method); } @Test(groups = "xsite") public void testClearOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.CLEAR, true, method); } @Test(groups = "xsite") public void testClearOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.CLEAR, false, method); } @Test(groups = "xsite") public void testPutMapOperationBeforeState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.PUT_MAP, true, method); } @Test(groups = "xsite") public void testPutMapOperationAfterState(Method method) throws Exception { testStateTransferWithConcurrentOperation(Operation.PUT_MAP, false, method); } @Test(groups = "xsite") public void testPutIfAbsentFail(Method method) throws Exception { testStateTransferWithNoReplicatedOperation(Operation.PUT_IF_ABSENT_FAIL, method); } @Test(groups = "xsite") public void testRemoveIfMatchFail(Method method) throws Exception { testStateTransferWithNoReplicatedOperation(Operation.REMOVE_IF_MATCH_FAIL, method); } @Test(groups = "xsite") public void testReplaceIfMatchFail(Method method) throws Exception { testStateTransferWithNoReplicatedOperation(Operation.REPLACE_IF_MATCH_FAIL, method); } @Test(groups = "xsite") public void testPutIfAbsent(Method method) throws Exception { testConcurrentOperation(Operation.PUT_IF_ABSENT, method); } @Test(groups = "xsite") public void testRemoveNonExisting(Method method) throws Exception { testConcurrentOperation(Operation.REMOVE_NON_EXISTING, method); } @Override protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000); } private void testStateTransferWithConcurrentOperation(final Operation operation, final boolean performBeforeState, final Method method) throws Exception { assertNotNull(operation); assertTrue(operation.replicates()); takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(null); assertNoStateTransferInSendingSite(); final Object key = k(method, 0); final CheckPoint checkPoint = new CheckPoint(); operation.init(cache(LON, 0), key); assertNotNull(operation.initialValue()); final BackupListener listener = new BackupListener() { @Override public void beforeCommand(VisitableCommand command) throws Exception { checkPoint.trigger("before-update"); if (!performBeforeState && isUpdatingKeyWithValue(command, key, operation.finalValue())) { //we need to wait for the state transfer before perform the command checkPoint.awaitStrict("update-key", 30, TimeUnit.SECONDS); } } @Override public void afterCommand(VisitableCommand command) { if (performBeforeState && isUpdatingKeyWithValue(command, key, operation.finalValue())) { //command was performed before state... let the state continue checkPoint.trigger("apply-state"); } } @Override public void beforeState(XSiteStatePushCommand command) throws Exception { checkPoint.trigger("before-state"); //wait until the command is received with the new value. so we make sure that the command saw the old value //and will commit a new value checkPoint.awaitStrict("before-update", 30, TimeUnit.SECONDS); if (performBeforeState && containsKey(command.getChunk(), key)) { //command before state... we need to wait checkPoint.awaitStrict("apply-state", 30, TimeUnit.SECONDS); } } @Override public void afterState(XSiteStatePushCommand command) { if (!performBeforeState && containsKey(command.getChunk(), key)) { //state before command... let the command go... checkPoint.trigger("update-key"); } } }; for (Cache<?, ?> cache : caches(NYC)) { wrapComponent(cache, BackupReceiver.class, current -> new ListenableBackupReceiver(current, listener)); } //safe (i.e. not blocking main thread), the state transfer is async startStateTransfer(); assertOnline(LON, NYC); //state transfer should send old value checkPoint.awaitStrict("before-state", 30, TimeUnit.SECONDS); //safe, perform is async operation.perform(cache(LON, 0), key).get(); assertEventuallyStateTransferNotRunning(); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); //check if all data is visible assertInSite(NYC, cache -> assertEquals(operation.finalValue(), cache.get(key))); assertInSite(LON, cache -> assertEquals(operation.finalValue(), cache.get(key))); } private void testConcurrentOperation(final Operation operation, final Method method) throws Exception { assertNotNull(operation); assertTrue(operation.replicates()); takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(null); assertNoStateTransferInSendingSite(); final Object key = k(method, 0); operation.init(cache(LON, 0), key); assertNull(operation.initialValue()); final XSiteStateProviderControl control = XSiteStateProviderControl.replaceInCache(cache(LON, 0)); //safe (i.e. not blocking main thread), the state transfer is async final Future<?> f = fork((ExceptionRunnable) this::startStateTransfer); //state transfer will be running (nothing to transfer however) while the operation is done. control.await(); assertOnline(LON, NYC); //safe, perform is async operation.perform(cache(LON, 0), key).get(); control.trigger(); f.get(30, TimeUnit.SECONDS); assertEventuallyStateTransferNotRunning(); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); //check if all data is visible assertInSite(NYC, cache -> assertEquals(operation.finalValue(), cache.get(key))); assertInSite(LON, cache -> assertEquals(operation.finalValue(), cache.get(key))); } private void testStateTransferWithNoReplicatedOperation(final Operation operation, final Method method) throws Exception { assertNotNull(operation); assertFalse(operation.replicates()); takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(null); assertNoStateTransferInSendingSite(); final Object key = k(method, 0); final CheckPoint checkPoint = new CheckPoint(); final AtomicBoolean commandReceived = new AtomicBoolean(false); operation.init(cache(LON, 0), key); assertNotNull(operation.initialValue()); final BackupListener listener = new BackupListener() { @Override public void beforeCommand(VisitableCommand command) { commandReceived.set(true); } @Override public void afterCommand(VisitableCommand command) { commandReceived.set(true); } @Override public void beforeState(XSiteStatePushCommand command) throws Exception { checkPoint.trigger("before-state"); checkPoint.awaitStrict("before-update", 30, TimeUnit.SECONDS); } }; for (Cache<?, ?> cache : caches(NYC)) { wrapComponent(cache, BackupReceiver.class, current -> new ListenableBackupReceiver(current, listener)); } //safe (i.e. not blocking main thread), the state transfer is async startStateTransfer(); assertOnline(LON, NYC); //state transfer should send old value checkPoint.awaitStrict("before-state", 30, TimeUnit.SECONDS); //safe, perform is async operation.perform(cache(LON, 0), key).get(); assertFalse(commandReceived.get()); checkPoint.trigger("before-update"); assertEventuallyStateTransferNotRunning(); assertEventuallyNoStateTransferInReceivingSite(null); assertEventuallyNoStateTransferInSendingSite(); //check if all data is visible assertInSite(NYC, cache -> assertEquals(operation.finalValue(), cache.get(key))); assertInSite(LON, cache -> assertEquals(operation.finalValue(), cache.get(key))); } private boolean isUpdatingKeyWithValue(VisitableCommand command, Object key, Object value) { if (command instanceof PutKeyValueCommand) { return key.equals(((PutKeyValueCommand) command).getKey()) && value.equals(((PutKeyValueCommand) command).getValue()); } else if (command instanceof RemoveCommand) { return key.equals(((RemoveCommand) command).getKey()); } else if (command instanceof ClearCommand) { return true; } else if (command instanceof WriteOnlyManyEntriesCommand) { InternalCacheValue<?> icv = (InternalCacheValue<?>) ((WriteOnlyManyEntriesCommand<?, ?, ?>) command).getArguments().get(key); return Objects.equals(icv.getValue(), value); } else if (command instanceof PrepareCommand) { for (WriteCommand writeCommand : ((PrepareCommand) command).getModifications()) { if (isUpdatingKeyWithValue(writeCommand, key, value)) { return true; } } } return false; } private boolean containsKey(XSiteState[] states, Object key) { if (states == null || states.length == 0 || key == null) { return false; } for (XSiteState state : states) { if (key.equals(state.key())) { return true; } } return false; } private enum Operation { PUT("v0", "v1") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.putAsync(key, finalValue()); } @Override public boolean replicates() { return true; } }, PUT_IF_ABSENT(null, "v1") { @Override public <K> void init(Cache<K, Object> cache, K key) { //no-op } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.putIfAbsentAsync(key, finalValue()); } @Override public boolean replicates() { return true; } }, PUT_IF_ABSENT_FAIL("v0", "v0") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.putIfAbsentAsync(key, "v1"); } @Override public boolean replicates() { return false; } }, REPLACE("v0", "v1") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.replaceAsync(key, finalValue()); } @Override public boolean replicates() { return true; } }, /** * not used: it has no state to transfer neither it is replicated! can be useful in the future. */ REPLACE_NON_EXISTING(null, null) { @Override public <K> void init(Cache<K, Object> cache, K key) { //no-op } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.replaceAsync(key, "v1"); } @Override public boolean replicates() { return false; } }, REPLACE_IF_MATCH("v0", "v1") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.replaceAsync(key, initialValue(), finalValue()); } @Override public boolean replicates() { return true; } }, REPLACE_IF_MATCH_FAIL("v0", "v0") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { //this works because value != initial value, so the match will fail. return cache.replaceAsync(key, "v1", "v1"); } @Override public boolean replicates() { return false; } }, REMOVE_NON_EXISTING(null, null) { @Override public <K> void init(Cache<K, Object> cache, K key) { //no-op } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.removeAsync(key); } @Override public boolean replicates() { return true; } }, REMOVE("v0", null) { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.removeAsync(key); } @Override public boolean replicates() { return true; } }, REMOVE_IF_MATCH("v0", null) { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.removeAsync(key, initialValue()); } @Override public boolean replicates() { return true; } }, REMOVE_IF_MATCH_FAIL("v0", "v0") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { //this works because value != initial value, so the match will fail. return cache.removeAsync(key, "v1"); } @Override public boolean replicates() { return false; } }, CLEAR("v0", null) { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { return cache.clearAsync(); } @Override public boolean replicates() { return true; } }, PUT_MAP("v0", "v1") { @Override public <K> void init(Cache<K, Object> cache, K key) { cache.put(key, initialValue()); } @Override public <K> Future<?> perform(Cache<K, Object> cache, K key) { Map<K, Object> map = new HashMap<>(); map.put(key, finalValue()); return cache.putAllAsync(map); } @Override public boolean replicates() { return true; } }; private final Object initialValue; private final Object finalValue; Operation(Object initialValue, Object finalValue) { this.initialValue = initialValue; this.finalValue = finalValue; } final Object initialValue() { return initialValue; } final Object finalValue() { return finalValue; } protected abstract <K> void init(Cache<K, Object> cache, K key); protected abstract <K> Future<?> perform(Cache<K, Object> cache, K key); protected abstract boolean replicates(); } private static class XSiteStateProviderControl extends XSiteProviderDelegator { private final CheckPoint checkPoint; private XSiteStateProviderControl(XSiteStateProvider xSiteStateProvider) { super(xSiteStateProvider); checkPoint = new CheckPoint(); } @Override public void startStateTransfer(String siteName, Address requestor, int minTopologyId) { checkPoint.trigger("before-start"); try { checkPoint.awaitStrict("await-start", 30, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (TimeoutException e) { throw new RuntimeException(e); } super.startStateTransfer(siteName, requestor, minTopologyId); } static XSiteStateProviderControl replaceInCache(Cache<?, ?> cache) { XSiteStateProvider current = extractComponent(cache, XSiteStateProvider.class); XSiteStateProviderControl control = new XSiteStateProviderControl(current); replaceComponent(cache, XSiteStateProvider.class, control, true); return control; } final void await() throws TimeoutException, InterruptedException { checkPoint.awaitStrict("before-start", 30, TimeUnit.SECONDS); } final void trigger() { checkPoint.trigger("await-start"); } } private static abstract class BackupListener { void beforeCommand(VisitableCommand command) throws Exception { //no-op by default } void afterCommand(VisitableCommand command) { //no-op by default } void beforeState(XSiteStatePushCommand command) throws Exception { //no-op by default } void afterState(XSiteStatePushCommand command) { //no-op by default } } private static class ListenableBackupReceiver extends BackupReceiverDelegator { private final BackupListener listener; ListenableBackupReceiver(BackupReceiver delegate, BackupListener listener) { super(delegate); this.listener = Objects.requireNonNull(listener, "Listener must not be null."); } @Override public <O> CompletionStage<O> handleRemoteCommand(VisitableCommand command, boolean preserveOrder) { try { listener.beforeCommand(command); } catch (Exception e) { return CompletableFuture.failedFuture(e); } return super.<O>handleRemoteCommand(command, preserveOrder).whenComplete((v, t) -> listener.afterCommand(command)); } @Override public CompletionStage<Void> handleStateTransferState(XSiteStatePushCommand cmd) { try { listener.beforeState(cmd); } catch (Exception e) { return CompletableFuture.failedFuture(e); } return super.handleStateTransferState(cmd).whenComplete((v, t) -> listener.afterState(cmd)); } } }
29,287
34.159664
134
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/BackupForStateTransferTest.java
package org.infinispan.xsite.statetransfer; import static org.infinispan.test.TestingUtil.k; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import org.infinispan.configuration.cache.BackupConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Simple test for the state transfer with different cache names. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.BackupForStateTransferTest") public class BackupForStateTransferTest extends AbstractStateTransferTest { private static final String VALUE = "value"; private static final String LON_BACKUP_CACHE_NAME = "lonBackup"; public BackupForStateTransferTest() { super(); this.implicitBackupCache = false; } public void testStateTransferWithClusterIdle(Method method) { takeSiteOffline(); assertOffline(); assertNoStateTransferInReceivingSite(LON_BACKUP_CACHE_NAME); assertNoStateTransferInSendingSite(); //NYC is offline... lets put some initial data in //we have 2 nodes in each site and the primary owner sends the state. Lets try to have more key than the chunk //size in order to each site to send more than one chunk. final int amountOfData = chunkSize() * 4; for (int i = 0; i < amountOfData; ++i) { cache(LON, 0).put(k(method, i), VALUE); } //check if NYC is empty (LON backup cache) assertInSite(NYC, LON_BACKUP_CACHE_NAME, cache -> assertTrue(cache.isEmpty())); //check if NYC is empty (default cache) assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); startStateTransfer(); assertEventuallyStateTransferNotRunning(); assertOnline(LON, NYC); //check if all data is visible (LON backup cache) assertInSite(NYC, LON_BACKUP_CACHE_NAME, cache -> { for (int i = 0; i < amountOfData; ++i) { assertEquals(VALUE, cache.get(k(method, i))); } }); //check if NYC is empty (default cache) assertInSite(NYC, cache -> assertTrue(cache.isEmpty())); assertEventuallyNoStateTransferInReceivingSite(LON_BACKUP_CACHE_NAME); assertNoStateTransferInSendingSite(); } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); } @Override protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.site(NYC).stateTransfer().chunkSize(10); } }
2,852
31.793103
116
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/DistSyncOnePhaseTxStateTransferTest.java
package org.infinispan.xsite.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency using a distributed synchronous * transaction cache with one-phase backup. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.DistSyncOnePhaseTxStateTransferTest") public class DistSyncOnePhaseTxStateTransferTest extends BaseStateTransferTest { public DistSyncOnePhaseTxStateTransferTest() { super(); use2Pc = false; implicitBackupCache = true; transactional = true; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } }
984
28.848485
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/DistSyncOnePhaseWriteSkewTxStateTransferTest.java
package org.infinispan.xsite.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency using a distributed synchronous * cache with one-phase backup and write skew with versioning. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.DistSyncOnePhaseWriteSkewTxStateTransferTest") public class DistSyncOnePhaseWriteSkewTxStateTransferTest extends DistSyncOnePhaseTxStateTransferTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return enableWriteSkew(super.getNycActiveConfig()); } @Override protected ConfigurationBuilder getLonActiveConfig() { return enableWriteSkew(super.getLonActiveConfig()); } private static ConfigurationBuilder enableWriteSkew(ConfigurationBuilder builder) { builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); return builder; } }
1,095
33.25
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/SiteUpEvent.java
package org.infinispan.xsite.statetransfer; import java.util.Collection; import org.testng.AssertJUnit; /** * Controls and intercept site up events. * * @author Pedro Ruivo * @since 12.1 */ public class SiteUpEvent { private static final long TIMEOUT_MILLIS = 30000; private Collection<String> sites; private Runnable runnable; public synchronized void receive(Collection<String> sites, Runnable runnable) { assert this.runnable == null; assert this.sites == null; this.sites = sites; this.runnable = runnable; this.notifyAll(); } public synchronized Collection<String> waitForEvent() throws InterruptedException { long endMillis = System.currentTimeMillis() + TIMEOUT_MILLIS; long waitMillis; while (sites == null && (waitMillis = timeLeft(endMillis)) > 0) { this.wait(waitMillis); } Collection<String> sites = this.sites; this.sites = null; AssertJUnit.assertNotNull(sites); return sites; } public void continueRunnable() { Runnable runnable; synchronized (this) { runnable = this.runnable; this.runnable = null; } if (runnable != null) { runnable.run(); } } private long timeLeft(long endMillis) { return endMillis - System.currentTimeMillis(); } }
1,349
23.545455
86
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/XSiteAutoStateTransferTest.java
package org.infinispan.xsite.statetransfer; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.commands.irac.IracCleanupKeysCommand; import org.infinispan.commands.irac.IracRequestStateCommand; import org.infinispan.commands.irac.IracStateResponseCommand; import org.infinispan.commands.irac.IracTombstoneStateResponseCommand; import org.infinispan.commands.irac.IracUpdateVersionCommand; import org.infinispan.commands.statetransfer.StateResponseCommand; import org.infinispan.commands.statetransfer.StateTransferCancelCommand; import org.infinispan.commands.statetransfer.StateTransferStartCommand; import org.infinispan.configuration.cache.BackupConfiguration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.TestingUtil; import org.infinispan.util.ControlledRpcManager; import org.infinispan.xsite.AbstractMultipleSitesTest; import org.infinispan.xsite.commands.XSiteAutoTransferStatusCommand; import org.infinispan.xsite.commands.XSiteBringOnlineCommand; import org.infinispan.xsite.commands.XSiteStateTransferStartSendCommand; import org.infinispan.xsite.status.SiteState; import org.infinispan.xsite.status.TakeOfflineManager; import org.infinispan.xsite.status.TakeSiteOfflineResponse; import org.jgroups.JChannel; import org.jgroups.protocols.relay.RELAY2; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Test for cross-site automatic state transfer. * * @author Pedro Ruivo * @since 12.1 */ @Test(groups = "functional", testName = "xsite.statetransfer.XSiteAutoStateTransferTest") public class XSiteAutoStateTransferTest extends AbstractMultipleSitesTest { public void testSyncStrategyDoNotTriggerStateTransfer() throws InterruptedException { String remoteSite = siteName(2); //site2 is the sync one //make the remote site offline. for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertNotSame(TakeSiteOfflineResponse.NO_SUCH_SITE, manager.takeSiteOffline(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); } SiteMasterController controller = findSiteMaster(); //block sites up event and wait until received SiteUpEvent event = controller.getStateTransferManager().blockSiteUpEvent(); triggerSiteUpEvent(controller, remoteSite); Collection<String> sitesUp = event.waitForEvent(); //check if it is the correct event assertEquals(1, sitesUp.size()); assertEquals(remoteSite, sitesUp.iterator().next()); //let the event continue, it will be handled in this thread, which is fine event.continueRunnable(); //coordinator don't even query other nodes state controller.getRpcManager().expectNoCommand(10, TimeUnit.SECONDS); //site status must not change for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); } } public void testManualModeDoNotTriggerStateTransfer() throws InterruptedException { String remoteSite = siteName(1); //site1 is the async one //make the remote site offline. for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertNotSame(TakeSiteOfflineResponse.NO_SUCH_SITE, manager.takeSiteOffline(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); stateTransferManager(i).setAutomaticStateTransfer(remoteSite, XSiteStateTransferMode.MANUAL); } SiteMasterController controller = findSiteMaster(); //block sites up event and wait until received SiteUpEvent event = controller.getStateTransferManager().blockSiteUpEvent(); triggerSiteUpEvent(controller, remoteSite); Collection<String> sitesUp = event.waitForEvent(); //check if it is the correct event assertEquals(1, sitesUp.size()); assertEquals(remoteSite, sitesUp.iterator().next()); //let the event continue, it will be handled in this thread, which is fine event.continueRunnable(); //coordinator don't even query other nodes state controller.getRpcManager().expectNoCommand(10, TimeUnit.SECONDS); //site status must not change for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); } } public void testSingleManualModeDoNotTriggerStateTransfer() throws InterruptedException, TimeoutException, ExecutionException { String remoteSite = siteName(1); //site1 is the async one //make the remote site offline. for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertNotSame(TakeSiteOfflineResponse.NO_SUCH_SITE, manager.takeSiteOffline(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); } SiteMasterController controller = findSiteMaster(); boolean manualModeSet = false; for (int i = 0; i < defaultNumberOfNodes(); ++i) { if (i == controller.managerIndex) { stateTransferManager(i).setAutomaticStateTransfer(remoteSite, XSiteStateTransferMode.AUTO); } else if (!manualModeSet) { stateTransferManager(i).setAutomaticStateTransfer(remoteSite, XSiteStateTransferMode.MANUAL); manualModeSet = true; } //else, does not mather if the 3rd node is MANUAL or AUTO since it shouldn't start any state transfer if at least one node is MANUAL } //block sites up event and wait until received SiteUpEvent event = controller.getStateTransferManager().blockSiteUpEvent(); triggerSiteUpEvent(controller, remoteSite); Collection<String> sitesUp = event.waitForEvent(); //check if it is the correct event assertEquals(1, sitesUp.size()); assertEquals(remoteSite, sitesUp.iterator().next()); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteAutoTransferStatusCommand>> req = controller .getRpcManager().expectCommandAsync(XSiteAutoTransferStatusCommand.class); //let the event continue, it will be handled in this thread, which is fine event.continueRunnable(); //we expect the coordinator to send a command ControlledRpcManager.BlockedRequest<XSiteAutoTransferStatusCommand> cmd = req.get(30, TimeUnit.SECONDS); cmd.send().receiveAll(); //site status must not change for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); } } public void testAutoStateTransfer(Method method) throws InterruptedException, TimeoutException, ExecutionException { String remoteSite = siteName(1); //site1 is the async one //we need at least one node with offline status //we make all of them to put some data for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertNotSame(TakeSiteOfflineResponse.NO_SUCH_SITE, manager.takeSiteOffline(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); //site2 is disabled as well just to avoid replicating there manager.takeSiteOffline(siteName(2)); assertTrue(stateTransferManager(i).setAutomaticStateTransfer(remoteSite, XSiteStateTransferMode.AUTO)); } //lets put some data for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { cache(0, 0).put(TestingUtil.k(method, i), TestingUtil.v(method, i)); } //make sure data didn't go through for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { assertNull(cache(1, 0).get(TestingUtil.k(method, i))); } SiteMasterController controller = findSiteMaster(); //let the state command go through controller.getRpcManager().excludeCommands(XSiteStatePushCommand.class, IracCleanupKeysCommand.class, IracTombstoneStateResponseCommand.class, StateTransferCancelCommand.class); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteAutoTransferStatusCommand>> req1 = controller.getRpcManager().expectCommandAsync(XSiteAutoTransferStatusCommand.class); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteBringOnlineCommand>> req2 = controller.getRpcManager().expectCommandAsync(XSiteBringOnlineCommand.class); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteStateTransferStartSendCommand>> req3 = controller.getRpcManager().expectCommandAsync(XSiteStateTransferStartSendCommand.class); //block sites up event and wait until received SiteUpEvent event = controller.getStateTransferManager().blockSiteUpEvent(); triggerSiteUpEvent(controller, remoteSite); Collection<String> sitesUp = event.waitForEvent(); //check if it is the correct event assertEquals(1, sitesUp.size()); assertEquals(remoteSite, sitesUp.iterator().next()); //let the event continue event.continueRunnable(); //make sure the commands are blocked req1.get(10, TimeUnit.SECONDS).send().receiveAll(); req2.get(10, TimeUnit.SECONDS).send().receiveAll(); req3.get(10, TimeUnit.SECONDS).send().receiveAll(); controller.getRpcManager().stopBlocking(); //site1 must be online now for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertSame(SiteState.ONLINE, manager.getSiteState(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(siteName(2))); } //wait for state transfer to finish eventuallyEquals(StateTransferStatus.SEND_OK, () -> controller.getStateTransferManager().getStatus().get(remoteSite)); //check data for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { String key = TestingUtil.k(method, i); String value = TestingUtil.v(method, i); assertEquals(value, cache(0, 0).get(key)); assertEquals(value, cache(1, 0).get(key)); } } public void testNewSiteMasterStartsStateTransfer(Method method) throws Exception { String remoteSite = siteName(1); //site1 is the async one //we need at least one node with offline status //we make all of them to put some data for (int i = 0; i < defaultNumberOfNodes(); ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertNotSame(TakeSiteOfflineResponse.NO_SUCH_SITE, manager.takeSiteOffline(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(remoteSite)); //site2 is disabled as well just to avoid replicating there manager.takeSiteOffline(siteName(2)); assertTrue(stateTransferManager(i).setAutomaticStateTransfer(remoteSite, XSiteStateTransferMode.AUTO)); } //lets put some data for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { cache(0, 0).put(TestingUtil.k(method, i), TestingUtil.v(method, i)); } //make sure data didn't go through for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { assertNull(cache(1, 0).get(TestingUtil.k(method, i))); } SiteMasterController oldSiteMaster = findSiteMaster(); SiteMasterController newSiteMaster = getSiteMasterController( oldSiteMaster.managerIndex + 1 % defaultNumberOfNodes()); //reset current site master oldSiteMaster.getRpcManager().stopBlocking(); //let the state command go through newSiteMaster.getRpcManager().excludeCommands(XSiteStatePushCommand.class, StateTransferStartCommand.class, StateResponseCommand.class, StateTransferCancelCommand.class, IracRequestStateCommand.class, IracStateResponseCommand.class, IracUpdateVersionCommand.class, IracCleanupKeysCommand.class, IracTombstoneStateResponseCommand.class); //the JGroups events triggers this command where NodeB checks if it needs to starts the transfer CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteAutoTransferStatusCommand>> req1 = newSiteMaster .getRpcManager().expectCommandAsync(XSiteAutoTransferStatusCommand.class); //and we have a second command coming from NodeC. NodeB broadcast the RELAY2 events to all nodes CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteAutoTransferStatusCommand>> req2 = newSiteMaster .getRpcManager().expectCommandAsync(XSiteAutoTransferStatusCommand.class); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteBringOnlineCommand>> req3 = newSiteMaster .getRpcManager().expectCommandAsync(XSiteBringOnlineCommand.class); CompletableFuture<ControlledRpcManager.BlockedRequest<XSiteStateTransferStartSendCommand>> req4 = newSiteMaster .getRpcManager().expectCommandAsync(XSiteStateTransferStartSendCommand.class); //block sites up event and wait until received SiteUpEvent event = newSiteMaster.getStateTransferManager().blockSiteUpEvent(); site(0).kill(0); site(0).waitForClusterToForm(null); //new view should be installed Collection<String> sitesUp = event.waitForEvent(); //check if it is the correct event, it creates a new connection so the event contains the 3 sites assertEquals(3, sitesUp.size()); assertTrue(sitesUp.contains(siteName(0))); assertTrue(sitesUp.contains(siteName(1))); assertTrue(sitesUp.contains(siteName(2))); //let the event continue event.continueRunnable(); //make sure the commands are blocked req1.get(10, TimeUnit.SECONDS).fail(); //we only need req1 or req2 to succeed,it does not matter which one req2.get(10, TimeUnit.SECONDS).send().receiveAll(); req3.get(10, TimeUnit.SECONDS).send().receiveAll(); req4.get(10, TimeUnit.SECONDS).send().receiveAll(); newSiteMaster.getRpcManager().stopBlocking(); //site1 must be online now for (int i = 0; i < defaultNumberOfNodes() - 1; ++i) { TakeOfflineManager manager = takeOfflineManager(i); assertSame(SiteState.ONLINE, manager.getSiteState(remoteSite)); assertSame(SiteState.OFFLINE, manager.getSiteState(siteName(2))); } //wait for state transfer to finish eventuallyEquals(StateTransferStatus.SEND_OK, () -> newSiteMaster.getStateTransferManager().getStatus().get(remoteSite)); //check data for (int i = 0; i < defaultNumberOfNodes() * 5; ++i) { String key = TestingUtil.k(method, i); String value = TestingUtil.v(method, i); assertEquals(value, cache(0, newSiteMaster.managerIndex).get(key)); assertEquals(value, cache(1, 0).get(key)); } } @Override protected int defaultNumberOfSites() { return 3; } @Override protected int defaultNumberOfNodes() { return 3; } @Override protected ConfigurationBuilder defaultConfigurationForSite(int siteIndex) { ConfigurationBuilder builder = super.defaultConfigurationForSite(siteIndex); builder.clustering().hash().numSegments(21); if (siteIndex == 0) { //for testing purpose, we only need site0 to backup to site1 & site2 builder.sites().addBackup().site(siteName(1)).strategy(BackupConfiguration.BackupStrategy.ASYNC) .sites().addBackup().site(siteName(2)).strategy(BackupConfiguration.BackupStrategy.SYNC); } return builder; } @AfterMethod(alwaysRun = true) @Override protected void clearContent() throws Throwable { for (EmbeddedCacheManager manager : site(0).cacheManagers()) { ControlledXSiteStateTransferManager.revertXsiteStateTransferManager(manager.getCache()); RpcManager rpcManager = TestingUtil.extractComponent(manager.getCache(), RpcManager.class); if (rpcManager instanceof ControlledRpcManager) { ((ControlledRpcManager) rpcManager).revertRpcManager(); } } while (site(0).cacheManagers().size() < defaultNumberOfNodes()) { site(0).addCacheManager(null, defaultGlobalConfigurationForSite(0), defaultConfigurationForSite(0), false); } site(0).waitForClusterToForm(null); super.clearContent(); } private TakeOfflineManager takeOfflineManager(int managerIndex) { return TestingUtil.extractComponent(cache(0, managerIndex), TakeOfflineManager.class); } private SiteMasterController findSiteMaster() { for (int i = 0; i < defaultNumberOfNodes(); ++i) { EmbeddedCacheManager manager = manager(0, i); Optional<RELAY2> relay2 = findRelay2(manager); if (relay2.isPresent() && relay2.get().isSiteMaster()) { //we have a single site master, this must be the coordinator as well. assertTrue(TestingUtil.extractGlobalComponent(manager, Transport.class).isCoordinator()); //we need to replace the RpcManager before XSiteStateTransferManager //so the XSiteStateTransferManager gets the new RpcManager ControlledRpcManager rpcManager = ControlledRpcManager.replaceRpcManager(manager.getCache()); ControlledXSiteStateTransferManager stateTransferManager = ControlledXSiteStateTransferManager .extract(manager.getCache()); return new SiteMasterController(relay2.get(), stateTransferManager, rpcManager, i); } } throw new IllegalStateException(); } private void triggerSiteUpEvent(SiteMasterController controller, String site) { controller.getRelay2().getRouteStatusListener().sitesUp(site); } private Optional<RELAY2> findRelay2(EmbeddedCacheManager manager) { JChannel channel = TestingUtil.extractJChannel(manager); RELAY2 relay2 = channel.getProtocolStack().findProtocol(RELAY2.class); return relay2 == null ? Optional.empty() : Optional.of(relay2); } private XSiteStateTransferManager stateTransferManager(int managerIndex) { return TestingUtil.extractComponent(cache(0, managerIndex), XSiteStateTransferManager.class); } private SiteMasterController getSiteMasterController(int index) { EmbeddedCacheManager manager = manager(0, index); Optional<RELAY2> relay2 = findRelay2(manager); if (relay2.isPresent()) { //we need to replace the RpcManager before XSiteStateTransferManager //so the XSiteStateTransferManager gets the new RpcManager ControlledRpcManager rpcManager = ControlledRpcManager.replaceRpcManager(manager.getCache()); ControlledXSiteStateTransferManager stateTransferManager = ControlledXSiteStateTransferManager .extract(manager.getCache()); return new SiteMasterController(relay2.get(), stateTransferManager, rpcManager, index); } throw new IllegalStateException(); } private static class SiteMasterController { private final RELAY2 relay2; private final ControlledXSiteStateTransferManager stateTransferManager; private final ControlledRpcManager rpcManager; private final int managerIndex; private SiteMasterController(RELAY2 relay2, ControlledXSiteStateTransferManager stateTransferManager, ControlledRpcManager rpcManager, int managerIndex) { this.relay2 = relay2; this.stateTransferManager = stateTransferManager; this.rpcManager = rpcManager; this.managerIndex = managerIndex; } public RELAY2 getRelay2() { return relay2; } public ControlledXSiteStateTransferManager getStateTransferManager() { return stateTransferManager; } public ControlledRpcManager getRpcManager() { return rpcManager; } } }
21,094
45.362637
141
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/AbstractStateTransferTest.java
package org.infinispan.xsite.statetransfer; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.xsite.XSiteAdminOperations.OFFLINE; import static org.infinispan.xsite.XSiteAdminOperations.ONLINE; import static org.infinispan.xsite.XSiteAdminOperations.SUCCESS; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.infinispan.statetransfer.CommitManager; import org.infinispan.xsite.AbstractTwoSitesTest; import org.infinispan.xsite.XSiteAdminOperations; /** * Base class for state transfer tests with some utility method. * * @author Pedro Ruivo * @since 9.2 */ public abstract class AbstractStateTransferTest extends AbstractTwoSitesTest { void assertNoStateTransferInReceivingSite(String cacheName) { assertInSite(NYC, cacheName, this::assertNotReceivingStateForCache); } void assertNoStateTransferInSendingSite() { assertInSite(LON, cache -> assertTrue(isNotSendingStateForCache(cache))); } void assertEventuallyNoStateTransferInSendingSite() { assertEventuallyInSite(LON, this::isNotSendingStateForCache, 30, TimeUnit.SECONDS); } protected void assertEventuallyStateTransferNotRunning() { assertEventuallyStateTransferNotRunning(cache(LON, 0)); } protected void assertEventuallyStateTransferNotRunning(Cache<?,?> cache) { eventually(() -> adminOperations(cache).getRunningStateTransfer().isEmpty(), 30, TimeUnit.SECONDS); } int chunkSize() { return cache(LON, 0).getCacheConfiguration().sites().allBackups().get(0).stateTransfer().chunkSize(); } protected void assertEventuallyNoStateTransferInReceivingSite(String cacheName) { assertEventuallyInSite(NYC, cacheName, this::isNotReceivingStateForCache, 30, TimeUnit.SECONDS); } protected void startStateTransfer() { startStateTransfer(cache(LON, 0), NYC); } protected void startStateTransfer(Cache<?, ?> cache, String toSite) { XSiteAdminOperations operations = extractComponent(cache, XSiteAdminOperations.class); assertEquals(SUCCESS, operations.pushState(toSite)); } protected void takeSiteOffline() { XSiteAdminOperations operations = extractComponent(cache(LON, 0), XSiteAdminOperations.class); assertEquals(SUCCESS, operations.takeSiteOffline(NYC)); } protected void assertOffline() { XSiteAdminOperations operations = extractComponent(cache(LON, 0), XSiteAdminOperations.class); assertEquals(OFFLINE, operations.siteStatus(NYC)); } protected void assertOnline(String localSite, String remoteSite) { XSiteAdminOperations operations = extractComponent(cache(localSite, 0), XSiteAdminOperations.class); assertEquals(ONLINE, operations.siteStatus(remoteSite)); } protected XSiteAdminOperations adminOperations() { return adminOperations(cache(LON, 0)); } protected XSiteAdminOperations adminOperations(Cache<?,?> cache) { return extractComponent(cache, XSiteAdminOperations.class); } private void assertNotReceivingStateForCache(Cache<?, ?> cache) { CommitManager commitManager = extractComponent(cache, CommitManager.class); assertFalse(commitManager.isTracking(Flag.PUT_FOR_STATE_TRANSFER)); assertFalse(commitManager.isTracking(Flag.PUT_FOR_X_SITE_STATE_TRANSFER)); assertTrue(commitManager.isEmpty()); } private boolean isNotReceivingStateForCache(Cache<?, ?> cache) { CommitManager commitManager = extractComponent(cache, CommitManager.class); return !commitManager.isTracking(Flag.PUT_FOR_STATE_TRANSFER) && !commitManager.isTracking(Flag.PUT_FOR_X_SITE_STATE_TRANSFER) && commitManager.isEmpty(); } private boolean isNotSendingStateForCache(Cache<?, ?> cache) { return extractComponent(cache, XSiteStateProvider.class).getCurrentStateSending().isEmpty(); } }
4,088
37.214953
107
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/DistSyncNonTxStateTransferTest.java
package org.infinispan.xsite.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency using a distributed synchronous * non-transactional cache * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.DistSyncNonTxStateTransferTest") public class DistSyncNonTxStateTransferTest extends BaseStateTransferTest { public DistSyncNonTxStateTransferTest() { super(); implicitBackupCache = true; transactional = false; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } }
931
28.125
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/DistSyncTwoPhasesTxStateTransferTest.java
package org.infinispan.xsite.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency using a distributed synchronous * cache with two-phases backup. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.DistSyncTwoPhasesTxStateTransferTest") public class DistSyncTwoPhasesTxStateTransferTest extends BaseStateTransferTest { public DistSyncTwoPhasesTxStateTransferTest() { super(); use2Pc = true; implicitBackupCache = true; transactional = true; } @Override protected ConfigurationBuilder getNycActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } @Override protected ConfigurationBuilder getLonActiveConfig() { return getDefaultClusteredCacheConfig(cacheMode, transactional); } }
975
28.575758
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/AbstractDelegatingXSiteStateTransferManager.java
package org.infinispan.xsite.statetransfer; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.configuration.cache.XSiteStateTransferMode; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.infinispan.topology.CacheTopology; /** * Decorator for {@link XSiteStateTransferManager}. * * @author Pedro Ruivo * @since 12.1 */ @Scope(Scopes.NAMED_CACHE) public class AbstractDelegatingXSiteStateTransferManager implements XSiteStateTransferManager { private final XSiteStateTransferManager delegate; public AbstractDelegatingXSiteStateTransferManager(XSiteStateTransferManager delegate) { this.delegate = delegate; } public static <T extends AbstractDelegatingXSiteStateTransferManager> T wrapCache(Cache<?, ?> cache, Function<XSiteStateTransferManager, T> ctor, Class<T> tClass) { XSiteStateTransferManager actual = TestingUtil.extractComponent(cache, XSiteStateTransferManager.class); if (actual.getClass().isAssignableFrom(tClass)) { return tClass.cast(actual); } return TestingUtil.wrapComponent(cache, XSiteStateTransferManager.class, ctor); } public static void revertXsiteStateTransferManager(Cache<?, ?> cache) { XSiteStateTransferManager manager = TestingUtil.extractComponent(cache, XSiteStateTransferManager.class); if (manager instanceof AbstractDelegatingXSiteStateTransferManager) { TestingUtil.replaceComponent(cache, XSiteStateTransferManager.class, ((AbstractDelegatingXSiteStateTransferManager) manager).delegate, true); } } @Override public void notifyStatePushFinished(String siteName, Address node, boolean statusOk) { delegate.notifyStatePushFinished(siteName, node, statusOk); } @Override public void startPushState(String siteName) throws Throwable { delegate.startPushState(siteName); } @Override public void cancelPushState(String siteName) throws Throwable { delegate.cancelPushState(siteName); } @Override public List<String> getRunningStateTransfers() { return delegate.getRunningStateTransfers(); } @Override public Map<String, StateTransferStatus> getStatus() { return delegate.getStatus(); } @Override public void clearStatus() { delegate.clearStatus(); } @Override public Map<String, StateTransferStatus> getClusterStatus() { return delegate.getClusterStatus(); } @Override public void clearClusterStatus() { delegate.clearClusterStatus(); } @Override public String getSendingSiteName() { return delegate.getSendingSiteName(); } @Override public void cancelReceive(String siteName) throws Exception { delegate.cancelReceive(siteName); } @Override public void becomeCoordinator(String siteName) { delegate.becomeCoordinator(siteName); } @Override public void onTopologyUpdated(CacheTopology cacheTopology, boolean stateTransferInProgress) { delegate.onTopologyUpdated(cacheTopology, stateTransferInProgress); } @Override public XSiteStateProvider getStateProvider() { return delegate.getStateProvider(); } @Override public XSiteStateConsumer getStateConsumer() { return delegate.getStateConsumer(); } @Override public void startAutomaticStateTransfer(Collection<String> sites) { delegate.startAutomaticStateTransfer(sites); } @Override public XSiteStateTransferMode stateTransferMode(String site) { return delegate.stateTransferMode(site); } @Override public boolean setAutomaticStateTransfer(String site, XSiteStateTransferMode mode) { return delegate.setAutomaticStateTransfer(site, mode); } }
3,970
28.857143
111
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/XSiteProviderDelegator.java
package org.infinispan.xsite.statetransfer; import java.util.Collection; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import org.infinispan.commands.CommandsFactory; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.xsite.irac.IracManager; /** * {@link org.infinispan.xsite.statetransfer.XSiteStateProvider} delegator. Mean to be overridden. For test purpose * only! * * @author Pedro Ruivo * @since 7.0 */ public class XSiteProviderDelegator implements XSiteStateProvider { protected final XSiteStateProvider xSiteStateProvider; protected XSiteProviderDelegator(XSiteStateProvider xSiteStateProvider) { this.xSiteStateProvider = xSiteStateProvider; } @Override public void startStateTransfer(String siteName, Address requestor, int minTopologyId) { xSiteStateProvider.startStateTransfer(siteName, requestor, minTopologyId); } @Override public void cancelStateTransfer(String siteName) { xSiteStateProvider.cancelStateTransfer(siteName); } @Override public Collection<String> getCurrentStateSending() { return xSiteStateProvider.getCurrentStateSending(); } @Override public Collection<String> getSitesMissingCoordinator(Collection<Address> currentMembers) { return xSiteStateProvider.getSitesMissingCoordinator(currentMembers); } @Override public void notifyStateTransferEnd(String siteName, Address origin, boolean statusOk) { xSiteStateProvider.notifyStateTransferEnd(siteName, origin, statusOk); } @Override public CommandsFactory getCommandsFactory() { return xSiteStateProvider.getCommandsFactory(); } @Override public RpcManager getRpcManager() { return xSiteStateProvider.getRpcManager(); } @Override public IracManager getIracManager() { return xSiteStateProvider.getIracManager(); } @Override public ScheduledExecutorService getScheduledExecutorService() { return xSiteStateProvider.getScheduledExecutorService(); } @Override public Executor getExecutor() { return xSiteStateProvider.getExecutor(); } }
2,214
27.766234
115
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/DistSyncTwoPhasesWriteSkewTxStateTransferTest.java
package org.infinispan.xsite.statetransfer; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * Tests the cross-site replication with concurrent operations checking for consistency using a distributed synchronous * cache with two-phases backup and write skew check with versioning. * * @author Pedro Ruivo * @since 7.0 */ @Test(groups = "xsite", testName = "xsite.statetransfer.DistSyncTwoPhasesWriteSkewTxStateTransferTest") public class DistSyncTwoPhasesWriteSkewTxStateTransferTest extends DistSyncTwoPhasesTxStateTransferTest { @Override protected ConfigurationBuilder getNycActiveConfig() { return enableWriteSkew(super.getNycActiveConfig()); } @Override protected ConfigurationBuilder getLonActiveConfig() { return enableWriteSkew(super.getLonActiveConfig()); } private static ConfigurationBuilder enableWriteSkew(ConfigurationBuilder builder) { builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); return builder; } }
1,105
33.5625
119
java
null
infinispan-main/core/src/test/java/org/infinispan/xsite/statetransfer/ControlledXSiteStateTransferManager.java
package org.infinispan.xsite.statetransfer; import java.util.Collection; import org.infinispan.Cache; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; /** * A {@link XSiteStateTransferManager} implementation that intercepts and controls the {@link * #startAutomaticStateTransfer(Collection)} method. * * @author Pedro Ruivo * @since 12.1 */ class ControlledXSiteStateTransferManager extends AbstractDelegatingXSiteStateTransferManager { private static final Log log = LogFactory.getLog(ControlledXSiteStateTransferManager.class); private SiteUpEvent event; private ControlledXSiteStateTransferManager(XSiteStateTransferManager delegate) { super(delegate); } public static ControlledXSiteStateTransferManager extract(Cache<?, ?> cache) { return AbstractDelegatingXSiteStateTransferManager .wrapCache(cache, ControlledXSiteStateTransferManager::new, ControlledXSiteStateTransferManager.class); } @Override public void startAutomaticStateTransfer(Collection<String> sites) { SiteUpEvent event = getEvent(); if (event != null) { log.tracef("Blocking automatic state transfer with sites %s", sites); event.receive(sites, () -> { log.tracef("Resuming automatic state transfer with sites %s", sites); super.startAutomaticStateTransfer(sites); }); } else { super.startAutomaticStateTransfer(sites); } } public synchronized SiteUpEvent blockSiteUpEvent() { assert event == null; event = new SiteUpEvent(); return event; } private synchronized SiteUpEvent getEvent() { SiteUpEvent event = this.event; this.event = null; return event; } }
1,764
30.517857
115
java