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/expiration/impl/ExpirationFileStoreListenerFunctionalTest.java
package org.infinispan.expiration.impl; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationFileStoreListenerFunctionalTest") public class ExpirationFileStoreListenerFunctionalTest extends ExpirationStoreListenerFunctionalTest { private final String location = CommonsTestingUtil.tmpDirectory(this.getClass()); private FileStoreToUse fileStoreToUse; ExpirationStoreFunctionalTest fileStoreToUse(FileStoreToUse fileStoreToUse) { this.fileStoreToUse = fileStoreToUse; return this; } enum FileStoreToUse { SINGLE, SOFT_INDEX } @Factory @Override public Object[] factory() { return new Object[]{ // Test is for single file store with a listener in a local cache and we don't care about memory storage types new ExpirationFileStoreListenerFunctionalTest().fileStoreToUse(FileStoreToUse.SINGLE).cacheMode(CacheMode.LOCAL), new ExpirationFileStoreListenerFunctionalTest().fileStoreToUse(FileStoreToUse.SOFT_INDEX).cacheMode(CacheMode.LOCAL), }; } @Override protected String parameters() { return "[ " + fileStoreToUse + "]"; } @Override protected void configure(GlobalConfigurationBuilder globalBuilder) { super.configure(globalBuilder); globalBuilder.globalState().enable().persistentLocation(location); } @Override protected void configure(ConfigurationBuilder config) { config // Prevent the reaper from running, reaperEnabled(false) doesn't work when a store is present .expiration().wakeUpInterval(Long.MAX_VALUE); switch (fileStoreToUse) { case SINGLE: config.persistence().addSingleFileStore().location(location); break; case SOFT_INDEX: config.persistence().addSoftIndexFileStore().dataLocation(location); break; } } @AfterClass(alwaysRun = true) protected void clearTempDir() { Util.recursiveFileRemove(CommonsTestingUtil.tmpDirectory(this.getClass())); } }
2,457
34.114286
129
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ClusterExpirationMaxIdleTest.java
package org.infinispan.expiration.impl; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; 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.invoke.MethodHandles; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.test.skip.SkipTestNG; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.commons.util.CloseableIterator; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.context.Flag; import org.infinispan.distribution.LocalizedCacheTopology; import org.infinispan.expiration.TouchMode; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.testng.annotations.Test; /** * Tests to make sure that when max-idle expiration occurs it occurs across the cluster * * @author William Burns * @since 8.0 */ @Test(groups = "functional", testName = "expiration.impl.ClusterExpirationMaxIdleTest") public class ClusterExpirationMaxIdleTest extends MultipleCacheManagersTest { protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); protected ControlledTimeService ts0; protected ControlledTimeService ts1; protected ControlledTimeService ts2; protected Cache<Object, String> cache0; protected Cache<Object, String> cache1; protected Cache<Object, String> cache2; private TouchMode touchMode = TouchMode.SYNC; protected ConfigurationBuilder configurationBuilder; @Override public Object[] factory() { return Arrays.stream(StorageType.values()) .flatMap(type -> Stream.builder() // .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) // .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(false)) // .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) // .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) // .add(new ClusterExpirationMaxIdleTest().storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(false)) // .add(new ClusterExpirationMaxIdleTest().touch(TouchMode.ASYNC).storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC)) // .add(new ClusterExpirationMaxIdleTest().touch(TouchMode.ASYNC).storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC)) // .add(new ClusterExpirationMaxIdleTest().touch(TouchMode.ASYNC).storageType(type).cacheMode(CacheMode.DIST_SYNC).transactional(false)) // .add(new ClusterExpirationMaxIdleTest().touch(TouchMode.ASYNC).storageType(type).cacheMode(CacheMode.REPL_SYNC).transactional(false)) .build() ).toArray(); } @Override protected void createCacheManagers() throws Throwable { configurationBuilder = new ConfigurationBuilder(); configurationBuilder.clustering().cacheMode(cacheMode); configurationBuilder.transaction().transactionMode(transactionMode()).lockingMode(lockingMode); configurationBuilder.expiration().disableReaper().touch(touchMode); if (storageType != null) { configurationBuilder.memory().storage(storageType); } createCluster(TestDataSCI.INSTANCE, configurationBuilder, 3); waitForClusterToForm(); injectTimeServices(); cache0 = cache(0); cache1 = cache(1); cache2 = cache(2); } protected void injectTimeServices() { ts0 = new ControlledTimeService(address(0)); TestingUtil.replaceComponent(manager(0), TimeService.class, ts0, true); ts1 = new ControlledTimeService(address(1)); TestingUtil.replaceComponent(manager(1), TimeService.class, ts1, true); ts2 = new ControlledTimeService(address(2)); TestingUtil.replaceComponent(manager(2), TimeService.class, ts2, true); } private Object createKey(Cache<Object, String> primaryOwner, Cache<Object, String> backupOwner) { if (storageType == StorageType.OBJECT) { return getKeyForCache(primaryOwner, backupOwner); } else { // BINARY and OFF heap can't use MagicKey as they are serialized LocalizedCacheTopology primaryLct = primaryOwner.getAdvancedCache().getDistributionManager().getCacheTopology(); LocalizedCacheTopology backupLct = backupOwner.getAdvancedCache().getDistributionManager().getCacheTopology(); ThreadLocalRandom tlr = ThreadLocalRandom.current(); int attempt = 0; while (true) { int key = tlr.nextInt(); // We test ownership based on the stored key instance Object wrappedKey = primaryOwner.getAdvancedCache().getKeyDataConversion().toStorage(key); if (primaryLct.getDistribution(wrappedKey).isPrimary() && backupLct.getDistribution(wrappedKey).isWriteBackup()) { log.tracef("Found key %s for primary owner %s and backup owner %s", wrappedKey, primaryOwner, backupOwner); // Return the actual key not the stored one, else it will be wrapped again :( return key; } if (++attempt == 1_000) { throw new AssertionError("Unable to find key that maps to primary " + primaryOwner + " and backup " + backupOwner); } } } } public void testMaxIdleExpiredOnBoth() throws Exception { Object key = createKey(cache0, cache1); cache1.put(key, key.toString(), -1, null, 10, MINUTES); incrementAllTimeServices(1, MINUTES); assertEquals(key.toString(), cache0.get(key)); assertLastUsedUpdate(key, ts0.wallClockTime(), cache0, cache1); // It should be expired on all incrementAllTimeServices(11, MINUTES); // Both should be null assertNull(cache0.get(key)); assertNull(cache1.get(key)); } public void testMaxIdleExpiredOnPrimaryOwner() throws Exception { testMaxIdleExpiredEntryRetrieval(true); } public void testMaxIdleExpiredOnBackupOwner() throws Exception { testMaxIdleExpiredEntryRetrieval(false); } private void incrementAllTimeServices(long time, TimeUnit unit) { for (ControlledTimeService cts : Arrays.asList(ts0, ts1, ts2)) { cts.advance(unit.toMillis(time)); } } private void testMaxIdleExpiredEntryRetrieval(boolean expireOnPrimary) throws Exception { AdvancedCache<Object, String> primaryOwner = cache0.getAdvancedCache(); AdvancedCache<Object, String> backupOwner = cache1.getAdvancedCache(); Object key = createKey(primaryOwner, backupOwner); backupOwner.put(key, key.toString(), -1, null, 10, MINUTES); assertEquals(key.toString(), primaryOwner.get(key)); assertEquals(key.toString(), backupOwner.get(key)); // Use flag CACHE_MODE_LOCAL, we don't want to go remote on accident AdvancedCache<Object, String> expiredCache; AdvancedCache<Object, String> otherCache; if (expireOnPrimary) { expiredCache = localModeCache(primaryOwner); otherCache = localModeCache(backupOwner); } else { expiredCache = localModeCache(backupOwner); otherCache = localModeCache(primaryOwner); } // Now we increment it a bit and force an access on the node that it doesn't expire on incrementAllTimeServices(5, MINUTES); assertNotNull(otherCache.get(key)); // TODO The comment above says "we don't want to go remote on accident", but the touch command does go remotely assertLastUsedUpdate(key, ts1.wallClockTime(), otherCache, expiredCache); // Now increment enough to cause it to be expired on the other node that didn't access it incrementAllTimeServices(6, MINUTES); long targetTime = ts0.wallClockTime(); // Now both nodes should return the value CacheEntry<Object, String> ce = otherCache.getCacheEntry(key); assertNotNull(ce); // Transactional cache doesn't report last access times to user if (transactional == Boolean.FALSE) { assertEquals(targetTime, ce.getLastUsed()); } ce = expiredCache.getCacheEntry(key); assertNotNull(ce); if (transactional == Boolean.FALSE) { assertEquals(targetTime, ce.getLastUsed()); } } private AdvancedCache<Object, String> localModeCache(AdvancedCache<Object, String> expiredCache) { return expiredCache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL, Flag.SKIP_OWNERSHIP_CHECK); } private void testMaxIdleExpireExpireIteration(boolean expireOnPrimary, boolean iterateOnPrimary) { // Cache0 is always the primary and cache1 is backup Object key = createKey(cache0, cache1); cache1.put(key, key.toString(), -1, null, 10, SECONDS); ControlledTimeService expiredTimeService; if (expireOnPrimary) { expiredTimeService = ts0; } else { expiredTimeService = ts1; } expiredTimeService.advance(11, SECONDS); Cache<Object, String> cacheToIterate; if (iterateOnPrimary) { cacheToIterate = cache0; } else { cacheToIterate = cache1; } try (CloseableIterator<Map.Entry<Object, String>> iterator = cacheToIterate.entrySet().iterator()) { if (expireOnPrimary == iterateOnPrimary) { // Iteration only checks for expiration on the local node, assertFalse(iterator.hasNext()); } else { assertTrue(iterator.hasNext()); Map.Entry<Object, String> entry = iterator.next(); assertEquals(key, entry.getKey()); assertEquals(key.toString(), entry.getValue()); } } finally { for (ControlledTimeService cts : Arrays.asList(ts0, ts1, ts2)) { if (cts != expiredTimeService) { cts.advance(SECONDS.toMillis(11)); } } } } public void testMaxIdleExpirePrimaryIteratePrimary() { testMaxIdleExpireExpireIteration(true, true); } public void testMaxIdleExpireBackupIteratePrimary() { testMaxIdleExpireExpireIteration(false, true); } public void testMaxIdleExpirePrimaryIterateBackup() { testMaxIdleExpireExpireIteration(true, false); } public void testMaxIdleExpireBackupIterateBackup() { testMaxIdleExpireExpireIteration(false, false); } /** * This test verifies that an entry is refreshed properly when the originator thinks the entry is expired * but another node accessed recently, but not same timestamp */ public void testMaxIdleAccessSuspectedExpiredEntryRefreshesProperly() { Object key = createKey(cache0, cache1); String value = key.toString(); cache1.put(key, value, -1, null, 10, SECONDS); // Now proceed half way in the max idle period before we access it on backup node incrementAllTimeServices(5, SECONDS); // Access it on the backup to update the last access time (primary still has old access time only) assertEquals(value, cache1.get(key)); // TODO The comment above says "primary still has old access time only", but the touch command does go remotely assertLastUsedUpdate(key, ts1.wallClockTime(), cache1, cache0); // Note now the entry would have been expired, if not for access above incrementAllTimeServices(5, SECONDS); assertEquals(value, cache0.get(key)); assertLastUsedUpdate(key, ts1.wallClockTime(), cache0, cache1); // Now we try to access just before it expires, but it still should be available incrementAllTimeServices(9, SECONDS); assertEquals(value, cache0.get(key)); } public void testPutAllExpiredEntries() { SkipTestNG.skipIf(cacheMode.isDistributed() && transactional, "Disabled in transactional caches because of ISPN-13618"); // Can reproduce ISPN-13549 with nKey=20_000 and no trace logs (and without the fix) int nKeys = 4; for (int i = 0; i < nKeys * 3 / 4; i++) { cache0.put("k" + i, "v1", -1, SECONDS, 10, SECONDS); } incrementAllTimeServices(11, SECONDS); Map<String, String> v2s = new HashMap<>(); for (int i = 0; i < nKeys; i++) { v2s.put("k" + i, "v2"); } cache0.putAll(v2s, -1, SECONDS, 10, SECONDS); } public void testGetAllExpiredEntries() { // Can reproduce ISPN-13549 with nKey=20_000 and no trace logs (and without the fix) int nKeys = 4; for (int i = 0; i < nKeys * 3 / 4; i++) { cache0.put("k" + i, "v1", -1, SECONDS, 10, SECONDS); } incrementAllTimeServices(11, SECONDS); Map<String, String> v1s = new HashMap<>(); for (int i = 0; i < nKeys; i++) { v1s.put("k" + i, "v1"); } assertEquals(Collections.emptyMap(), cache0.getAdvancedCache().getAll(v1s.keySet())); } private void assertLastUsedUpdate(Object key, long expectedLastUsed, Cache<Object, String> readCache, Cache<Object, String> otherCache) { Object storageKey = readCache.getAdvancedCache().getKeyDataConversion().toStorage(key); if (touchMode == TouchMode.SYNC) { assertEquals(expectedLastUsed, getLastUsed(readCache, storageKey)); assertEquals(expectedLastUsed, getLastUsed(otherCache, storageKey)); } else { // Normally the touch command is executed synchronously on the reader. eventuallyEquals(expectedLastUsed, () -> getLastUsed(readCache, storageKey)); eventuallyEquals(expectedLastUsed, () -> getLastUsed(otherCache, storageKey)); } } private long getLastUsed(Cache<Object, String> cache, Object storageKey) { InternalCacheEntry<Object, String> entry = cache.getAdvancedCache().getDataContainer().peek(storageKey); assertNotNull(entry); return entry.getLastUsed(); } public void testMaxIdleReadNodeDiesPrimary() { testMaxIdleNodeDies(true); } public void testMaxIdleReadNodeDiesBackup() { testMaxIdleNodeDies(false); } private void testMaxIdleNodeDies(boolean isPrimary) { addClusterEnabledCacheManager(TestDataSCI.INSTANCE, configurationBuilder); waitForClusterToForm(); Cache<Object, String> cache3 = cache(3); ControlledTimeService ts3 = new ControlledTimeService(address(3), ts2); TestingUtil.replaceComponent(manager(3), TimeService.class, ts3, true); Cache<Object, String> primary = isPrimary ? cache3 : cache0; Cache<Object, String> backup = isPrimary ? cache0 : cache3; Object key = createKey(primary, backup); backup.put(key, "max-idle", -1, SECONDS, 100, SECONDS); // Advance the clock so the entry is expired everywhere ("all time services" does not include ts3) incrementAllTimeServices(99, SECONDS); ts3.advance(99, SECONDS); assertNotNull(cache3.get(key)); assertLastUsedUpdate(key, ts3.wallClockTime(), cache3, cache0); killMember(3); incrementAllTimeServices(2, SECONDS); assertNotNull(cache1.get(key)); } protected MultipleCacheManagersTest touch(TouchMode touchMode) { this.touchMode = touchMode; return this; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "touch"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), touchMode); } }
16,932
40.400978
192
java
null
infinispan-main/core/src/test/java/org/infinispan/expiration/impl/ExpirationFunctionalTest.java
package org.infinispan.expiration.impl; 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.io.Serializable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.commons.time.ControlledTimeService; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.expiration.ExpirationManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "expiration.impl.ExpirationFunctionalTest") public class ExpirationFunctionalTest extends SingleCacheManagerTest { protected final int SIZE = 10; protected ControlledTimeService timeService = new ControlledTimeService(); protected StorageType storage; protected CacheMode cacheMode; protected ExpirationManager<?, ?> expirationManager; @Factory public Object[] factory() { return new Object[]{ new ExpirationFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.BINARY), new ExpirationFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.OBJECT), new ExpirationFunctionalTest().cacheMode(CacheMode.LOCAL).withStorage(StorageType.OFF_HEAP), new ExpirationFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.BINARY), new ExpirationFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.OBJECT), new ExpirationFunctionalTest().cacheMode(CacheMode.DIST_SYNC).withStorage(StorageType.OFF_HEAP) }; } protected ExpirationFunctionalTest cacheMode(CacheMode mode) { this.cacheMode = mode; return this; } @Override protected String parameters() { return "[" + cacheMode + ", " + storage + "]"; } protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(false); configure(builder); // Create the cache manager, but don't start it until we replace the time service EmbeddedCacheManager cm = createCacheManager(builder); TestingUtil.replaceComponent(cm, TimeService.class, timeService, true); cache = cm.getCache(); expirationManager = cache.getAdvancedCache().getExpirationManager(); afterCacheCreated(cm); return cm; } protected EmbeddedCacheManager createCacheManager(ConfigurationBuilder builder) { GlobalConfigurationBuilder globalBuilder; if (builder.clustering().cacheMode().isClustered()) { globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); configure(globalBuilder); return TestCacheManagerFactory.createClusteredCacheManager(false, globalBuilder, builder, new TransportFlags()); } else { globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); configure(globalBuilder); return TestCacheManagerFactory.createCacheManager(globalBuilder, builder, false); } } protected void configure(GlobalConfigurationBuilder globalBuilder) { globalBuilder.serialization().addContextInitializer(TestDataSCI.INSTANCE); } protected void configure(ConfigurationBuilder config) { config.clustering().cacheMode(cacheMode) .expiration().disableReaper() .memory().storage(storage); } protected void afterCacheCreated(EmbeddedCacheManager cm) { } protected void processExpiration() { expirationManager.processExpiration(); } public ExpirationFunctionalTest withStorage(StorageType storage) { this.storage = storage; return this; } public StorageType getStorageType() { return storage; } public void testSimpleExpirationLifespan() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); assertEquals(0, cache.size()); } protected int maxInMemory() { return SIZE; } public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i, -1, null, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); assertEquals(0, cache.size()); // Only processExpiration actually removes the entries assertEquals(maxInMemory(), cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); processExpiration(); assertEquals(0, cache.size()); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); } public void testSimpleExprationMaxIdleWithGet() { Object key = "max-idle-get-key"; Object value = "max-idle-value"; assertNull(cache.put(key, value,-1, null, 20, TimeUnit.MILLISECONDS)); // Just before it expires timeService.advance(19); assertEquals(value, cache.get(key)); timeService.advance(5); assertEquals(value, cache.get(key)); timeService.advance(25); assertNull(cache.get(key)); } public void testExpirationLifespanInOps() throws Exception { for (int i = 0; i < SIZE; i++) { long expirationTime = i % 2 == 0 ? 1 : 1000; cache.put("key-" + i, "value-" + i, expirationTime, TimeUnit.MILLISECONDS); } timeService.advance(2); checkOddExist(SIZE); } public void testExpirationMaxIdleInOps() throws Exception { for (int i = 0; i < SIZE; i++) { long expirationTime = i % 2 == 0 ? 1 : 1000; cache.put("key-" + i, "value-" + i, -1, null, expirationTime, TimeUnit.MILLISECONDS); } timeService.advance(2); checkOddExist(SIZE); } protected Object keyToUseWithExpiration() { return "key"; } public void testRemoveExpiredValueWithNoEquals() { Object keyToUseForExpiration = keyToUseWithExpiration(); cache.put(keyToUseForExpiration, new NoEquals("value"), 3, TimeUnit.MILLISECONDS); timeService.advance(5); expirationManager.processExpiration(); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); } protected void checkOddExist(int SIZE) { for (int i = 0; i < SIZE; i++) { if (i % 2 == 0) { assertFalse(cache.containsKey("key-" + i)); assertNull(cache.get("key-" + i)); assertNull(cache.remove("key-" + i)); } else { assertTrue(cache.containsKey("key-" + i)); assertNotNull(cache.get("key-" + i)); assertNotNull(cache.remove("key-" + i)); } } } public void testExpirationLifespanInExec() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); cache.getAdvancedCache().getDataContainer() .forEach(ice -> { throw new RuntimeException( "No task should be executed on expired entry"); }); } public void testExpirationMaxIdleDataContainerIterator() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i,-1, null, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); cache.getAdvancedCache().getDataContainer() .iterator().forEachRemaining(ice -> { throw new RuntimeException("No task should be executed on expired entry"); }); cache.getAdvancedCache().getDataContainer() .forEach(ice -> { throw new RuntimeException("No task should be executed on expired entry"); }); AtomicInteger invocationCount = new AtomicInteger(); cache.getAdvancedCache().getDataContainer().iteratorIncludingExpired().forEachRemaining(ice -> invocationCount.incrementAndGet()); assertEquals(maxInMemory(), invocationCount.get()); processExpiration(); cache.getAdvancedCache().getDataContainer() .iteratorIncludingExpired().forEachRemaining(ice -> { throw new RuntimeException("No task should be executed on expired entry"); }); } public void testExpiredEntriesCleared() { cache.put("key-" + 0, "value-" + 1, -1, null, 0, TimeUnit.MILLISECONDS); cache.put("key-" + 1, "value-" + 1, -1, null, 1, TimeUnit.MILLISECONDS); // This should expire 1 of the entries timeService.advance(1); cache.clear(); assertEquals(0, cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); } public static class NoEquals implements Serializable { private final String value; @ProtoFactory public NoEquals(String value) { this.value = value; } @ProtoField(number = 1) public String getValue() { return value; } } }
9,738
34.543796
136
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/GlobalStateRestartWithCacheTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.util.Arrays; import java.util.stream.IntStream; import org.infinispan.commons.util.Util; 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.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * ISPN-13740 A test to ensure that a NPE is not thrown when a cache is deleted after a graceful shutdown and restart. * * The {@link org.infinispan.globalstate.impl.GlobalConfigurationManagerImpl} uses events and the {@link org.infinispan.globalstate.impl.GlobalConfigurationStateListener} * to create Caches and templates cluster-wide after a local caches.xml and templates.xml have been loaded. Consequently, * there is a small window on a cluster restart where attempts to remove a cache/template will result in an event being * created with null state, as the state in the cache has not yet been created by the local listener. This test is to ensure * that the implementation never relies on this state during remove operations. * * @author Ryan Emerson * @since 14.0 */ @Test(groups = "functional", testName = "globalstate.GlobalStateRestartWithCacheTest") public class GlobalStateRestartWithCacheTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "testCache"; @AfterClass(alwaysRun = true) @Override protected void destroy() { super.destroy(); Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); } @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); createStatefulCacheManagers(); } private void createStatefulCacheManagers() { IntStream.range(0, 2).forEach(this::createStatefulCacheManager); } private void createStatefulCacheManager(int index) { String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), Integer.toString(index)); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory).configurationStorage(ConfigurationStorage.OVERLAY); addClusterEnabledCacheManager(global, null); } public void testCacheDeletionAfterRestart() { // Create cache via EmbeddedCacheManagerAdmin Configuration cacheConfig = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_SYNC).build(); manager(0).administration().createCache(CACHE_NAME, cacheConfig); waitForClusterToForm(CACHE_NAME); // Shutdown server in the same manner as the Server manager(0).shutdownAllCaches(); for (EmbeddedCacheManager manager : managers()) { manager.stop(); } // Restart the cluster // Verify that the cache state file exists for (int i = 0; i < 2; i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Recreate the cluster createStatefulCacheManagers(); // Delete cache manager(0).administration().removeCache(CACHE_NAME); } @Override public DefaultCacheManager manager(int i) { return (DefaultCacheManager) cacheManagers.get(i); } }
3,978
40.884211
170
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/ScopedPersistentStateTest.java
package org.infinispan.globalstate; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import org.infinispan.globalstate.impl.ScopedPersistentStateImpl; import org.testng.annotations.Test; @Test(testName = "globalstate.ScopedPersistentStateTest", groups = "functional") public class ScopedPersistentStateTest { public void testStateChecksum() { ScopedPersistentState state1 = new ScopedPersistentStateImpl("scope"); state1.setProperty("a", "a"); state1.setProperty("b", 1); state1.setProperty("c", 2.0f); state1.setProperty("@local", "state1"); ScopedPersistentState state2 = new ScopedPersistentStateImpl("scope"); state2.setProperty("a", "a"); state2.setProperty("b", 1); state2.setProperty("c", 2.0f); state2.setProperty("@local", "state2"); assertEquals(state1.getChecksum(), state2.getChecksum()); ScopedPersistentState state3 = new ScopedPersistentStateImpl("scope"); state3.setProperty("a", "x"); state3.setProperty("b", 1); state3.setProperty("c", 2.0f); state3.setProperty("@local", "state1"); assertFalse(state1.getChecksum() == state3.getChecksum()); } }
1,228
37.40625
80
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/NoOpGlobalConfigurationManager.java
package org.infinispan.globalstate; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.infinispan.Cache; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.PrincipalRoleMapper; import org.infinispan.security.Role; import org.infinispan.security.RolePermissionMapper; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.TestingUtil; /* * A no-op implementation for tests which mess up with initial state transfer and RPCs */ public class NoOpGlobalConfigurationManager implements GlobalConfigurationManager { @Override public Cache<ScopedState, Object> getStateCache() { return null; } @Override public CompletableFuture<Configuration> createCache(String cacheName, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Configuration> getOrCreateCache(String cacheName, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Configuration> createCache(String cacheName, String template, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Configuration> getOrCreateCache(String cacheName, String template, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Void> removeCache(String cacheName, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Void> createTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Configuration> getOrCreateTemplate(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } @Override public CompletableFuture<Void> removeTemplate(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) { return CompletableFutures.completedNull(); } public static void amendCacheManager(EmbeddedCacheManager cm) { TestingUtil.replaceComponent(cm, PrincipalRoleMapper.class, new IdentityRoleMapper(), true); TestingUtil.replaceComponent(cm, RolePermissionMapper.class, new RolePermissionMapper() { @Override public Role getRole(String name) { return null; } @Override public Map<String, Role> getAllRoles() { return Collections.emptyMap(); } @Override public boolean hasRole(String name) { return false; } }, true); TestingUtil.replaceComponent(cm, GlobalConfigurationManager.class, new NoOpGlobalConfigurationManager(), true); } }
3,309
36.191011
154
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/ThreeNodeGlobalStatePartialRestartTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertEquals; import java.io.File; import java.util.Arrays; import java.util.Map; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StoreConfigurationBuilder; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.test.TestingUtil; import org.infinispan.topology.MissingMembersException; import org.infinispan.topology.PersistentUUID; import org.infinispan.topology.PersistentUUIDManager; import org.testng.annotations.Test; @Test(testName = "globalstate.ThreeNodeGlobalStatePartialRestartTest", groups = "functional") public class ThreeNodeGlobalStatePartialRestartTest extends AbstractGlobalStateRestartTest { private PartitionHandling handling; private CacheMode cacheMode; private boolean purge; @Override protected int getClusterSize() { return 3; } @Override protected void applyCacheManagerClusteringConfiguration(ConfigurationBuilder config) { config.clustering().cacheMode(cacheMode).hash().numOwners(getClusterSize() - 1); config.clustering().partitionHandling().whenSplit(handling); } @Override protected void applyCacheManagerClusteringConfiguration(String id, ConfigurationBuilder config) { applyCacheManagerClusteringConfiguration(config); StoreConfigurationBuilder scb = config.persistence().addSoftIndexFileStore() .dataLocation(tmpDirectory(this.getClass().getSimpleName(), id, "data")) .indexLocation(tmpDirectory(this.getClass().getSimpleName(), id, "index")); scb.purgeOnStartup(purge); } public void testClusterDelayedJoiners() throws Exception { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); // Shutdown the cache cluster-wide cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Partially recreate the cluster for (int i = 0; i < getClusterSize() - 1; i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); } TestingUtil.blockUntilViewsReceived(30000, getCaches(CACHE_NAME)); assertOperationsFail(); // The last pending member joins. createStatefulCacheManager(Character.toString((char) ('A' + getClusterSize() - 1)), false); // Healthy cluster waitForClusterToForm(CACHE_NAME); checkClusterRestartedCorrectly(addressMappings); checkData(); ConsistentHash newConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); PersistentUUIDManager persistentUUIDManager = TestingUtil.extractGlobalComponent(manager(0), PersistentUUIDManager.class); assertEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager); } public void testConnectAndDisconnectDuringRestart() throws Exception { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); // Shutdown the cache cluster-wide cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for all participants. for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Partially recreate the cluster. for (int i = 0; i < getClusterSize() - 1; i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); } TestingUtil.blockUntilViewsReceived(30000, getCaches(CACHE_NAME)); assertOperationsFail(); // Stop one of the caches and assert the files are still here. EmbeddedCacheManager left = cacheManagers.remove(1); TestingUtil.killCacheManagers(left); String persistentLocation = left.getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); // Assert we are still unable to execute operations. assertOperationsFail(); // Create the missing member instead of the one that left. createStatefulCacheManager(Character.toString((char) ('A' + getClusterSize() - 1)), false); TestingUtil.blockUntilViewsReceived(30000, getCaches(CACHE_NAME)); // Assert we are still unable to execute operations. assertOperationsFail(); // The missing restart again. createStatefulCacheManager(Character.toString((char) ('A' + 1)), false); // Healthy cluster waitForClusterToForm(CACHE_NAME); checkClusterRestartedCorrectly(addressMappings); checkData(); ConsistentHash newConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); PersistentUUIDManager persistentUUIDManager = TestingUtil.extractGlobalComponent(manager(0), PersistentUUIDManager.class); assertEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager); } public void testClusterWithRestartsDuringPartitioning() throws Exception { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); // Shutdown the cache cluster-wide cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for all participants. for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Partially recreate the cluster. for (int i = 0; i < getClusterSize() - 1; i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); } TestingUtil.blockUntilViewsReceived(30000, getCaches(CACHE_NAME)); assertOperationsFail(); // Shutdown the malformed cluster. cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists. // Since the topology was never restored, the state files should be present. for (int i = 0; i < getClusterSize() - 1; i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals("Node " + i + " wrong files: " + Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Recreate the complete cluster now. for (int i = 0; i < getClusterSize(); i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); } // Healthy cluster waitForClusterToForm(CACHE_NAME); checkClusterRestartedCorrectly(addressMappings); checkData(); ConsistentHash newConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); PersistentUUIDManager persistentUUIDManager = TestingUtil.extractGlobalComponent(manager(0), PersistentUUIDManager.class); assertEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager); } private void assertOperationsFail() { for (int i = 0; i < cacheManagers.size(); i++) { for (int v = 0; v < DATA_SIZE; v++) { final Cache<Object, Object> cache = cache(i, CACHE_NAME); String key = String.valueOf(v); // Always returns null. Message about not stable yet is logged. Exceptions.expectException(MissingMembersException.class, "ISPN000689: Recovering cache 'testCache' but there are missing members, known members \\[.*\\] of a total of 3$", () -> cache.get(key)); } } } public ThreeNodeGlobalStatePartialRestartTest withPartitionHandling(PartitionHandling handling) { this.handling = handling; return this; } public ThreeNodeGlobalStatePartialRestartTest withCacheMode(CacheMode mode) { this.cacheMode = mode; return this; } public ThreeNodeGlobalStatePartialRestartTest purgeOnStartup(boolean purge) { this.purge = purge; return this; } @Override public Object[] factory() { return Arrays.stream(PartitionHandling.values()) .flatMap(ph -> Arrays.stream(new Object[] { new ThreeNodeGlobalStatePartialRestartTest().withCacheMode(CacheMode.DIST_SYNC).withPartitionHandling(ph), new ThreeNodeGlobalStatePartialRestartTest().withCacheMode(CacheMode.DIST_SYNC).withPartitionHandling(ph).purgeOnStartup(true), new ThreeNodeGlobalStatePartialRestartTest().withCacheMode(CacheMode.REPL_SYNC).withPartitionHandling(ph).purgeOnStartup(true), new ThreeNodeGlobalStatePartialRestartTest().withCacheMode(CacheMode.REPL_SYNC).withPartitionHandling(ph), })) .toArray(); } @Override protected String parameters() { return String.format("[cacheMode=%s, ph=%s, purge=%b]", cacheMode, handling, purge); } }
11,027
42.761905
145
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/ThreeNodeDistGlobalStateRestartTest.java
package org.infinispan.globalstate; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Map; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.test.TestingUtil; import org.infinispan.topology.PersistentUUID; import org.testng.annotations.Test; @Test(testName = "globalstate.ThreeNodeDistGlobalStateRestartTest", groups = "functional") public class ThreeNodeDistGlobalStateRestartTest extends AbstractGlobalStateRestartTest { @Override protected int getClusterSize() { return 3; } @Override protected void applyCacheManagerClusteringConfiguration(ConfigurationBuilder config) { config.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(2); } public void testGracefulShutdownAndRestart() throws Throwable { shutdownAndRestart(-1, false); } public void testGracefulShutdownAndRestartReverseOrder() throws Throwable { shutdownAndRestart(-1, true); } public void testFailedRestartWithExtraneousCoordinator() throws Throwable { shutdownAndRestart(0, false); } public void testFailedRestartWithExtraneousNode() throws Throwable { shutdownAndRestart(1, false); } public void testPersistentStateIsDeletedAfterRestart() throws Throwable { shutdownAndRestart(-1, false); restartWithoutGracefulShutdown(); } public void testDisableRebalanceRestartEnableRebalance() throws Throwable { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); manager(0).getGlobalComponentRegistry().getLocalTopologyManager().setRebalancingEnabled(false); for (int i = 0; i < getClusterSize(); i++) { ((DefaultCacheManager) manager(i)).shutdownAllCaches(); manager(i).stop(); } cacheManagers.clear(); createStatefulCacheManagers(false, -1, false); for (int i = 0; i < getClusterSize() - 1; i++) { cache(i, CACHE_NAME); } manager(0).getGlobalComponentRegistry().getLocalTopologyManager().setRebalancingEnabled(true); // Last missing. cache(getClusterSize() - 1, CACHE_NAME); assertHealthyCluster(addressMappings, oldConsistentHash); assertTrue(manager(0).getGlobalComponentRegistry().getLocalTopologyManager().isRebalancingEnabled()); } public void testClusterRecoveryAfterRestart() throws Throwable { shutdownAndRestart(-1, false); killMember(0, CACHE_NAME, false); assertEquals(DATA_SIZE, (long) cache(0, CACHE_NAME).size()); assertEquals(DATA_SIZE, (long) cache(1, CACHE_NAME).size()); TestingUtil.waitForNoRebalance(caches(CACHE_NAME)); } }
3,057
32.604396
120
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/GlobalStateBackwardsCompatibilityTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.topology.PersistentUUID; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * ISPN-12667 A test to ensure that global state properties from previous Infinispan majors are compatible. * * @author Ryan Emerson * @since 12.0 */ @Test(groups = "functional", testName = "globalstate.GlobalStateBackwardsCompatibilityTest") public class GlobalStateBackwardsCompatibilityTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "testCache"; private static final String MEMBER_0 = PersistentUUID.randomUUID().toString(); private static final String MEMBER_1 = PersistentUUID.randomUUID().toString(); @Override protected void createCacheManagers() throws Throwable { } @AfterClass(alwaysRun = true) @Override protected void destroy() { super.destroy(); Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); } public void testCreateClusterWithGlobalState11() throws Exception { createCacheManagerWithGlobalState(MEMBER_0, tmpDirectory(this.getClass().getSimpleName(), "0")); createCacheManagerWithGlobalState(MEMBER_1, tmpDirectory(this.getClass().getSimpleName(), "1")); waitForClusterToForm(CACHE_NAME); } private void createCacheManagerWithGlobalState(String uuid, String stateDirectory) throws Exception { new File(stateDirectory).mkdirs(); createCacheState(stateDirectory); Properties globalState = new Properties(); globalState.put("@version", "11.0.9.Final"); globalState.put("version-major", "11"); globalState.put("@timestamp", "2021-01-28T10\\:53\\:56.289272Z"); globalState.put("uuid", uuid); globalState.store(new FileOutputStream(new File(stateDirectory, "___global.state")), null); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory); ConfigurationBuilder config = new ConfigurationBuilder(); config.clustering().cacheMode(CacheMode.REPL_SYNC).stateTransfer().timeout(30, TimeUnit.SECONDS) .persistence().addSingleFileStore().location(stateDirectory); EmbeddedCacheManager manager = addClusterEnabledCacheManager(global, null); manager.defineConfiguration(CACHE_NAME, config.build()); } private void createCacheState(String stateDirectory) throws Exception { Properties cacheState = new Properties(); cacheState.put("@version", "11.0.9.Final"); cacheState.put("@timestamp", "2021-01-28T10\\:53\\:56.289272Z"); cacheState.put("version-major", "11"); cacheState.put("consistentHash", "org.infinispan.distribution.ch.impl.ReplicatedConsistentHash"); cacheState.put("members", "2"); cacheState.put("member.0", MEMBER_0); cacheState.put("member.1", MEMBER_1); cacheState.put("primaryOwners", "256"); IntStream.range(0, 256).forEach(i -> cacheState.put("primaryOwners." + i, Integer.toString(i % 2))); cacheState.store(new FileOutputStream(new File(stateDirectory, CACHE_NAME + ".state")), null); } }
3,758
43.223529
107
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/AbstractGlobalStateRestartTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.infinispan.commons.CacheException; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.topology.LocalTopologyManager; import org.infinispan.topology.PersistentUUID; import org.infinispan.topology.PersistentUUIDManager; public abstract class AbstractGlobalStateRestartTest extends MultipleCacheManagersTest { public static final int DATA_SIZE = 100; public static final String CACHE_NAME = "testCache"; protected abstract int getClusterSize(); @Override protected boolean cleanupAfterMethod() { return true; } @Override protected boolean cleanupAfterTest() { return false; } @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); createStatefulCacheManagers(true, -1, false); } protected void createStatefulCacheManagers(boolean clear, int extraneousNodePosition, boolean reverse) { int totalNodes = getClusterSize() + ((extraneousNodePosition < 0) ? 0 : 1); int node = reverse ? getClusterSize() - 1 : 0; int step = reverse ? -1 : 1; for (int i = 0; i < totalNodes; i++) { if (i == extraneousNodePosition) { // Create one more node if needed in the requested position createStatefulCacheManager(Character.toString('@'), true); } else { createStatefulCacheManager(Character.toString((char) ('A' + node)), clear); node += step; } } } void createStatefulCacheManager(String id, boolean clear) { String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), id); if (clear) Util.recursiveFileRemove(stateDirectory); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory); ConfigurationBuilder config = new ConfigurationBuilder(); applyCacheManagerClusteringConfiguration(id, config); config.persistence().addSingleFileStore().location(stateDirectory).fetchPersistentState(true); EmbeddedCacheManager manager = addClusterEnabledCacheManager(global, null); manager.defineConfiguration(CACHE_NAME, config.build()); } protected abstract void applyCacheManagerClusteringConfiguration(ConfigurationBuilder config); protected void applyCacheManagerClusteringConfiguration(String id, ConfigurationBuilder config) { applyCacheManagerClusteringConfiguration(config); } protected void shutdownAndRestart(int extraneousNodePosition, boolean reverse) throws Throwable { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); // Shutdown the cache cluster-wide cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Recreate the cluster createStatefulCacheManagers(false, extraneousNodePosition, reverse); if(reverse) { Map<JGroupsAddress, PersistentUUID> reversed = new LinkedHashMap<>(); reverseLinkedMap(addressMappings.entrySet().iterator(), reversed); addressMappings = reversed; } // Healthy cluster switch (extraneousNodePosition) { case -1: { assertHealthyCluster(addressMappings, oldConsistentHash); break; } case 0: { // Coordinator without state, all other nodes will break for(int i = 1; i < cacheManagers.size(); i++) { try { cache(i, CACHE_NAME); fail("Cache with state should not have joined coordinator without state"); } catch (CacheException e) { // Ignore log.debugf("Got expected exception: %s", e); } } break; } default: { // Other node without state try { cache(extraneousNodePosition, CACHE_NAME); fail("Cache without state should not have joined coordinator with state"); } catch (CacheException e) { // Ignore } } } } protected void assertHealthyCluster(Map<JGroupsAddress, PersistentUUID> addressMappings, ConsistentHash oldConsistentHash) throws Throwable { // Healthy cluster waitForClusterToForm(CACHE_NAME); checkClusterRestartedCorrectly(addressMappings); checkData(); ConsistentHash newConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); PersistentUUIDManager persistentUUIDManager = TestingUtil.extractGlobalComponent(manager(0), PersistentUUIDManager.class); assertEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager); } protected void restartWithoutGracefulShutdown() { // Verify that the state file was removed for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 0, listFiles.length); } // Stop the cluster without graceful shutdown for (int i = getClusterSize() - 1; i >= 0; i--) { killMember(i, CACHE_NAME, false); } // Start a coordinator without state and then make the nodes with state join createStatefulCacheManagers(false, 0, false); for (int i = 0; i <= getClusterSize(); i++) { cache(i, CACHE_NAME); } } void assertEquivalent(Map<JGroupsAddress, PersistentUUID> addressMappings, ConsistentHash oldConsistentHash, ConsistentHash newConsistentHash, PersistentUUIDManager persistentUUIDManager) { assertTrue(isEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager)); } void checkClusterRestartedCorrectly(Map<JGroupsAddress, PersistentUUID> addressMappings) throws Exception { Iterator<Map.Entry<JGroupsAddress, PersistentUUID>> addressIterator = addressMappings.entrySet().iterator(); Set<PersistentUUID> uuids = new HashSet<>(); for (int i = 0; i < cacheManagers.size(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); assertTrue(uuids.add(ltm.getPersistentUUID())); } for (int i = 0; i < cacheManagers.size(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); // Ensure that nodes have the old UUID Map.Entry<JGroupsAddress, PersistentUUID> entry = addressIterator.next(); assertTrue(entry.getKey() + " is mapping to the wrong UUID: " + "Expected: " + entry.getValue() + " not found in: " + uuids, uuids.contains(entry.getValue())); // Ensure that rebalancing is enabled for the cache assertTrue(ltm.isCacheRebalancingEnabled(CACHE_NAME)); } } void checkData() { // Ensure that the cache contains the right data assertEquals(DATA_SIZE, cache(0, CACHE_NAME).size()); for (int i = 0; i < DATA_SIZE; i++) { assertEquals(cache(0, CACHE_NAME).get(String.valueOf(i)), String.valueOf(i)); } } Map<JGroupsAddress, PersistentUUID> createInitialCluster() { waitForClusterToForm(CACHE_NAME); Map<JGroupsAddress, PersistentUUID> addressMappings = new LinkedHashMap<>(); for (int i = 0; i < getClusterSize(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); PersistentUUID uuid = ltm.getPersistentUUID(); assertNotNull(uuid); addressMappings.put((JGroupsAddress) manager(i).getAddress(), uuid); } fillData(); checkData(); return addressMappings; } private void fillData() { // Fill some data for (int i = 0; i < DATA_SIZE; i++) { cache(0, CACHE_NAME).put(String.valueOf(i), String.valueOf(i)); } } private boolean isEquivalent(Map<JGroupsAddress, PersistentUUID> addressMapping, ConsistentHash oldConsistentHash, ConsistentHash newConsistentHash, PersistentUUIDManager persistentUUIDManager) { if (oldConsistentHash.getNumSegments() != newConsistentHash.getNumSegments()) return false; for (int i = 0; i < oldConsistentHash.getMembers().size(); i++) { JGroupsAddress oldAddress = (JGroupsAddress) oldConsistentHash.getMembers().get(i); JGroupsAddress remappedOldAddress = (JGroupsAddress) persistentUUIDManager.getAddress(addressMapping.get(oldAddress)); JGroupsAddress newAddress = (JGroupsAddress) newConsistentHash.getMembers().get(i); if (!remappedOldAddress.equals(newAddress)) return false; Set<Integer> oldSegmentsForOwner = oldConsistentHash.getSegmentsForOwner(oldAddress); Set<Integer> newSegmentsForOwner = newConsistentHash.getSegmentsForOwner(newAddress); if (!oldSegmentsForOwner.equals(newSegmentsForOwner)) return false; } return true; } private void checkStateDirNotEmpty(String location) { File[] listFiles = new File(location).listFiles(); assertTrue(listFiles.length > 0); } private void reverseLinkedMap(Iterator<Map.Entry<JGroupsAddress, PersistentUUID>> iterator, Map<JGroupsAddress, PersistentUUID> reversed) { if (iterator.hasNext()) { Map.Entry<JGroupsAddress, PersistentUUID> entry = iterator.next(); reverseLinkedMap(iterator, reversed); reversed.put(entry.getKey(), entry.getValue()); } } }
11,281
41.734848
198
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/ThreeNodeTopologyReinstallTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.Arrays; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.test.TestingUtil; import org.infinispan.topology.MissingMembersException; import org.infinispan.topology.PersistentUUID; import org.infinispan.util.concurrent.AggregateCompletionStage; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.Test; @Test(testName = "globalstate.ThreeNodeTopologyReinstallTest", groups = "functional") public class ThreeNodeTopologyReinstallTest extends AbstractGlobalStateRestartTest { private CacheMode cacheMode; private int getNumOwners() { return getClusterSize() - 1; } @Override protected int getClusterSize() { return 3; } @Override protected void applyCacheManagerClusteringConfiguration(ConfigurationBuilder config) { config.clustering().cacheMode(cacheMode).hash().numOwners(getNumOwners()); } @Override protected void applyCacheManagerClusteringConfiguration(String id, ConfigurationBuilder config) { applyCacheManagerClusteringConfiguration(config); config.persistence().addSoftIndexFileStore() .dataLocation(tmpDirectory(this.getClass().getSimpleName(), id, "data")) .indexLocation(tmpDirectory(this.getClass().getSimpleName(), id, "index")); } public void testReinstallTopologyByForce() throws Exception { executeTestRestart(true); } public void testReinstallTopologySafely() throws Exception { executeTestRestart(false); } private void executeTestRestart(boolean force) throws Exception { boolean possibleDataLoss = !cacheMode.isReplicated() && force; Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); // Shutdown the cache cluster-wide cache(0, CACHE_NAME).shutdown(); TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for all participants. for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } this.cacheManagers.clear(); // Partially recreate the cluster while trying to reinstall topology. int i = 0; for (; i < (getClusterSize() - getNumOwners()); i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); TestingUtil.blockUntilViewsReceived(15000, getCaches(CACHE_NAME)); GlobalComponentRegistry gcr = TestingUtil.extractGlobalComponentRegistry(manager(i)); Exceptions.expectException(MissingMembersException.class, "ISPN000694: Cache 'testCache' has number of owners \\d but is missing too many members \\(\\d\\/3\\) to reinstall topology$", () -> gcr.getClusterTopologyManager().useCurrentTopologyAsStable(CACHE_NAME, false)); } // Since we didn't force the installation, operations still fail. assertOperationsFail(); if (!force) { createStatefulCacheManager(Character.toString((char) ('A' + i++)), false); TestingUtil.blockUntilViewsReceived(15000, getCaches(CACHE_NAME)); } // Now we install the topology. for (int j = 0; j < cacheManagers.size(); j++) { EmbeddedCacheManager ecm = manager(j); if (ecm.isCoordinator()) { TestingUtil.extractGlobalComponentRegistry(manager(0)) .getClusterTopologyManager() .useCurrentTopologyAsStable(CACHE_NAME, force); break; } } // Wait topology installation. AggregateCompletionStage<Void> topologyInstall = CompletionStages.aggregateCompletionStage(); for (int j = 0; j < cacheManagers.size(); j++) { GlobalComponentRegistry gcr = TestingUtil.extractGlobalComponentRegistry(manager(j)); topologyInstall.dependsOn(gcr.getLocalTopologyManager().stableTopologyCompletion(CACHE_NAME)); } CompletableFutures.uncheckedAwait(topologyInstall.freeze().toCompletableFuture(), 30, TimeUnit.SECONDS); if (possibleDataLoss) { // Varying the cache configuration and if forcing the topology, we can lose data. for (int j = 0; j < cacheManagers.size(); j++) { assertFalse(cache(j, CACHE_NAME).isEmpty()); assertTrue(cache(j, CACHE_NAME).size() < DATA_SIZE); } } else { // In some cases, it is possible to recover all the data. checkData(); } // Now we add the missing members back. for (; i < getClusterSize(); i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), false); } // This will create the cache, and trigger the join operation for the new managers. TestingUtil.blockUntilViewsReceived(30000, getCaches(CACHE_NAME)); // Wait topology again, just to make sure. topologyInstall = CompletionStages.aggregateCompletionStage(); for (int j = 0; j < cacheManagers.size(); j++) { GlobalComponentRegistry gcr = TestingUtil.extractGlobalComponentRegistry(manager(j)); topologyInstall.dependsOn(gcr.getLocalTopologyManager().stableTopologyCompletion(CACHE_NAME)); } CompletableFutures.uncheckedAwait(topologyInstall.freeze().toCompletableFuture(), 30, TimeUnit.SECONDS); checkClusterRestartedCorrectly(addressMappings); waitForClusterToForm(CACHE_NAME); if (possibleDataLoss) { for (int j = 0; j < getClusterSize(); j++) { assertFalse(cache(j, CACHE_NAME).isEmpty()); assertTrue(cache(j, CACHE_NAME).size() < DATA_SIZE); } } else { checkData(); } } private void assertOperationsFail() { for (int i = 0; i < cacheManagers.size(); i++) { for (int v = 0; v < DATA_SIZE; v++) { final Cache<Object, Object> cache = cache(i, CACHE_NAME); String key = String.valueOf(v); // Always returns null. Message about not stable yet is logged. Exceptions.expectException(MissingMembersException.class, "ISPN000689: Recovering cache 'testCache' but there are missing members, known members \\[.*\\] of a total of 3$", () -> cache.get(key)); } } } private ThreeNodeTopologyReinstallTest withCacheMode(CacheMode mode) { this.cacheMode = mode; return this; } @Override public Object[] factory() { return new Object[]{ new ThreeNodeTopologyReinstallTest().withCacheMode(CacheMode.DIST_SYNC), new ThreeNodeTopologyReinstallTest().withCacheMode(CacheMode.REPL_SYNC), }; } @Override protected String parameters() { return String.format("[cacheMode=%s]", cacheMode); } }
7,727
40.106383
141
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/GlobalStateRestartJoinWithZeroCapacityTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import org.infinispan.commons.util.Util; 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.test.MultipleCacheManagersTest; import org.infinispan.topology.PersistentUUID; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; /** * ISPN-13729 A test to ensure that zero-capacity REPL_SYNC caches can join a cluster which has restarted from persistent state. * * @author Ryan Emerson * @since 14.0 */ @Test(groups = "functional", testName = "globalstate.GlobalStateRestartJoinWithZeroCapacityTest") public class GlobalStateRestartJoinWithZeroCapacityTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "testCache"; private static final String MEMBER_0 = PersistentUUID.randomUUID().toString(); private static final String MEMBER_1 = PersistentUUID.randomUUID().toString(); @Override protected void createCacheManagers() throws Throwable { } @AfterClass(alwaysRun = true) @Override protected void destroy() { super.destroy(); Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); } public void testCreateClusterWithGlobalState11() throws Exception { createCacheManagerWithGlobalState(MEMBER_0, tmpDirectory(this.getClass().getSimpleName(), "0")); createCacheManagerWithGlobalState(MEMBER_1, tmpDirectory(this.getClass().getSimpleName(), "1")); waitForClusterToForm(CACHE_NAME); createZeroCapacityManager(tmpDirectory(this.getClass().getSimpleName(), "2")); waitForClusterToForm(CACHE_NAME); } private void createCacheManagerWithGlobalState(String uuid, String stateDirectory) throws Exception { new File(stateDirectory).mkdirs(); createCacheState(stateDirectory); Properties globalState = new Properties(); globalState.put("@version", "13.0.5.Final"); globalState.put("version-major", "13"); globalState.put("@timestamp", "2022-02-24T11\\:57\\:30.530659Z"); globalState.put("uuid", uuid); globalState.store(new FileOutputStream(new File(stateDirectory, "___global.state")), null); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory); EmbeddedCacheManager manager = addClusterEnabledCacheManager(global, null); manager.defineConfiguration(CACHE_NAME, cacheConfig()); } private void createZeroCapacityManager(String stateDirectory) { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.zeroCapacityNode(true) .globalState().enable().persistentLocation(stateDirectory); EmbeddedCacheManager manager = addClusterEnabledCacheManager(global, null); manager.defineConfiguration(CACHE_NAME, cacheConfig()); } private Configuration cacheConfig() { return new ConfigurationBuilder() .clustering().cacheMode(CacheMode.REPL_SYNC).stateTransfer().timeout(30, TimeUnit.SECONDS) .build(); } private void createCacheState(String stateDirectory) throws Exception { Properties cacheState = new Properties(); cacheState.put("@version", "13.0.5.Final"); cacheState.put("@timestamp", "2022-02-24T11\\:57\\:29.977881Z"); cacheState.put("version-major", "13"); cacheState.put("consistentHash", "org.infinispan.distribution.ch.impl.ReplicatedConsistentHash"); cacheState.put("members", "1"); cacheState.put("member.0", MEMBER_0); cacheState.put("primaryOwners", "256"); IntStream.range(0, 256).forEach(i -> cacheState.put("primaryOwners." + i, "0")); cacheState.store(new FileOutputStream(new File(stateDirectory, CACHE_NAME + ".state")), null); } }
4,299
42.434343
128
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/NodeRestartPartitionHandlingTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.infinispan.Cache; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.partitionhandling.BasePartitionHandlingTest; import org.infinispan.partitionhandling.PartitionHandling; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.test.TestingUtil; import org.infinispan.topology.LocalTopologyManager; import org.infinispan.topology.MissingMembersException; import org.infinispan.topology.PersistentUUID; import org.infinispan.topology.PersistentUUIDManager; import org.testng.annotations.Test; @Test(groups = "functional", testName = "globalstate.NodeRestartPartitionHandlingTest") public class NodeRestartPartitionHandlingTest extends BasePartitionHandlingTest { public static final int DATA_SIZE = 100; public static final String CACHE_NAME = "testCache"; { partitionHandling = PartitionHandling.ALLOW_READ_WRITES; numMembersInCluster = 2; } protected int getClusterSize() { return numMembersInCluster; } @Override protected String customCacheName() { return CACHE_NAME; } @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); createStatefulCacheManagers(true); } public void testRestartDuringNetworkPartition() throws Throwable { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); for (int i = 0; i < getClusterSize(); i++) { ((DefaultCacheManager) manager(i)).shutdownAllCaches(); } TestingUtil.killCacheManagers(this.cacheManagers); // Verify that the cache state file exists for (int i = 0; i < getClusterSize(); i++) { String persistentLocation = manager(i).getCacheManagerConfiguration().globalState().persistentLocation(); File[] listFiles = new File(persistentLocation).listFiles((dir, name) -> name.equals(CACHE_NAME + ".state")); assertEquals(Arrays.toString(listFiles), 1, listFiles.length); } cacheManagers.clear(); createStatefulCacheManagers(false); // We split the cluster. This should make the caches not be able to restore. splitCluster(new int[]{0}, new int[]{1}); partition(0).assertDegradedMode(); partition(1).assertDegradedMode(); // We restart the cluster, completely. Caches should issue join requests during partition. for (int i = 0; i < getClusterSize(); i++) { cache(i, CACHE_NAME); } // Assert we still partitioned. partition(0).assertDegradedMode(); partition(1).assertDegradedMode(); // Since the cluster is partitioned, the cache didn't recovered, operations should fail. assertOperationsFail(); // Merge the cluster. This should make the caches restore. partition(0).merge(partition(1), false); waitForClusterToForm(CACHE_NAME); assertHealthyCluster(addressMappings, oldConsistentHash); } protected void createStatefulCacheManagers(boolean clear) { for (int i = 0; i < getClusterSize(); i++) { createStatefulCacheManager(Character.toString((char) ('A' + i)), clear); } } void createStatefulCacheManager(String id, boolean clear) { String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), id); if (clear) Util.recursiveFileRemove(stateDirectory); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory); ConfigurationBuilder config = new ConfigurationBuilder(); partitionHandlingBuilder(config); config.persistence().addSingleFileStore().location(stateDirectory).fetchPersistentState(true); EmbeddedCacheManager manager = addClusterEnabledCacheManager(global, null); manager.defineConfiguration(CACHE_NAME, config.build()); } Map<JGroupsAddress, PersistentUUID> createInitialCluster() { waitForClusterToForm(CACHE_NAME); Map<JGroupsAddress, PersistentUUID> addressMappings = new LinkedHashMap<>(); for (int i = 0; i < getClusterSize(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); PersistentUUID uuid = ltm.getPersistentUUID(); assertNotNull(uuid); addressMappings.put((JGroupsAddress) manager(i).getAddress(), uuid); } fillData(); checkData(); return addressMappings; } private void assertOperationsFail() { for (int i = 0; i < cacheManagers.size(); i++) { for (int v = 0; v < DATA_SIZE; v++) { final Cache<Object, Object> cache = cache(i, CACHE_NAME); String key = String.valueOf(v); // Always returns null. Message about not stable yet is logged. Exceptions.expectException(MissingMembersException.class, "ISPN000689: Recovering cache 'testCache' but there are missing members, known members \\[.*\\] of a total of 2$", () -> cache.get(key)); } } } private void fillData() { // Fill some data for (int i = 0; i < DATA_SIZE; i++) { cache(0, CACHE_NAME).put(String.valueOf(i), String.valueOf(i)); } } void checkData() { // Ensure that the cache contains the right data assertEquals(DATA_SIZE, cache(0, CACHE_NAME).size()); for (int i = 0; i < DATA_SIZE; i++) { assertEquals(cache(0, CACHE_NAME).get(String.valueOf(i)), String.valueOf(i)); } } protected void assertHealthyCluster(Map<JGroupsAddress, PersistentUUID> addressMappings, ConsistentHash oldConsistentHash) throws Throwable { // Healthy cluster waitForClusterToForm(CACHE_NAME); checkClusterRestartedCorrectly(addressMappings); checkData(); ConsistentHash newConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); PersistentUUIDManager persistentUUIDManager = TestingUtil.extractGlobalComponent(manager(0), PersistentUUIDManager.class); assertEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager); } void checkClusterRestartedCorrectly(Map<JGroupsAddress, PersistentUUID> addressMappings) throws Exception { Iterator<Map.Entry<JGroupsAddress, PersistentUUID>> addressIterator = addressMappings.entrySet().iterator(); Set<PersistentUUID> uuids = new HashSet<>(); for (int i = 0; i < cacheManagers.size(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); assertTrue(uuids.add(ltm.getPersistentUUID())); } for (int i = 0; i < cacheManagers.size(); i++) { LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(i), LocalTopologyManager.class); // Ensure that nodes have the old UUID Map.Entry<JGroupsAddress, PersistentUUID> entry = addressIterator.next(); assertTrue(entry.getKey() + " is mapping to the wrong UUID: " + "Expected: " + entry.getValue() + " not found in: " + uuids, uuids.contains(entry.getValue())); // Ensure that rebalancing is enabled for the cache assertTrue(ltm.isCacheRebalancingEnabled(CACHE_NAME)); } } void assertEquivalent(Map<JGroupsAddress, PersistentUUID> addressMappings, ConsistentHash oldConsistentHash, ConsistentHash newConsistentHash, PersistentUUIDManager persistentUUIDManager) { assertTrue(isEquivalent(addressMappings, oldConsistentHash, newConsistentHash, persistentUUIDManager)); } private boolean isEquivalent(Map<JGroupsAddress, PersistentUUID> addressMapping, ConsistentHash oldConsistentHash, ConsistentHash newConsistentHash, PersistentUUIDManager persistentUUIDManager) { if (oldConsistentHash.getNumSegments() != newConsistentHash.getNumSegments()) return false; for (int i = 0; i < oldConsistentHash.getMembers().size(); i++) { JGroupsAddress oldAddress = (JGroupsAddress) oldConsistentHash.getMembers().get(i); JGroupsAddress remappedOldAddress = (JGroupsAddress) persistentUUIDManager.getAddress(addressMapping.get(oldAddress)); JGroupsAddress newAddress = (JGroupsAddress) newConsistentHash.getMembers().get(i); if (!remappedOldAddress.equals(newAddress)) return false; Set<Integer> oldSegmentsForOwner = oldConsistentHash.getSegmentsForOwner(oldAddress); Set<Integer> newSegmentsForOwner = newConsistentHash.getSegmentsForOwner(newAddress); if (!oldSegmentsForOwner.equals(newSegmentsForOwner)) return false; } return true; } }
9,666
42.940909
198
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/ThreeNodeReplGlobalStateRestartTest.java
package org.infinispan.globalstate; import static org.testng.AssertJUnit.assertTrue; import java.util.Map; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.remoting.transport.jgroups.JGroupsAddress; import org.infinispan.topology.PersistentUUID; import org.testng.annotations.Test; @Test(testName = "globalstate.ThreeNodeReplGlobalStateRestartTest", groups = "functional") public class ThreeNodeReplGlobalStateRestartTest extends AbstractGlobalStateRestartTest { @Override protected int getClusterSize() { return 3; } @Override protected void applyCacheManagerClusteringConfiguration(ConfigurationBuilder config) { config.clustering().cacheMode(CacheMode.REPL_SYNC); } public void testGracefulShutdownAndRestart() throws Throwable { shutdownAndRestart(-1, false); } public void testGracefulShutdownAndRestartReverseOrder() throws Throwable { shutdownAndRestart(-1, true); } public void testFailedRestartWithExtraneousCoordinator() throws Throwable { shutdownAndRestart(0, false); } public void testFailedRestartWithExtraneousNode() throws Throwable { shutdownAndRestart(1, false); } public void testDisableRebalanceRestartEnableRebalance() throws Throwable { Map<JGroupsAddress, PersistentUUID> addressMappings = createInitialCluster(); ConsistentHash oldConsistentHash = advancedCache(0, CACHE_NAME).getDistributionManager().getWriteConsistentHash(); manager(0).getGlobalComponentRegistry().getLocalTopologyManager().setRebalancingEnabled(false); for (int i = 0; i < getClusterSize(); i++) { ((DefaultCacheManager) manager(i)).shutdownAllCaches(); manager(i).stop(); } cacheManagers.clear(); createStatefulCacheManagers(false, -1, false); for (int i = 0; i < getClusterSize() - 1; i++) { cache(i, CACHE_NAME); } manager(0).getGlobalComponentRegistry().getLocalTopologyManager().setRebalancingEnabled(true); // Last missing. cache(getClusterSize() - 1, CACHE_NAME); assertHealthyCluster(addressMappings, oldConsistentHash); assertTrue(manager(0).getGlobalComponentRegistry().getLocalTopologyManager().isRebalancingEnabled()); } public void testPersistentStateIsDeletedAfterRestart() throws Throwable { shutdownAndRestart(-1, false); restartWithoutGracefulShutdown(); } }
2,601
31.936709
120
java
null
infinispan-main/core/src/test/java/org/infinispan/globalstate/GlobalStateTest.java
package org.infinispan.globalstate; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.commons.test.Exceptions.expectException; import static org.testng.Assert.assertNotEquals; 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.fail; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.util.Properties; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.jdkspecific.CallerId; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Util; 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.configuration.global.UncleanShutdownAction; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.manager.EmbeddedCacheManagerStartupException; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.ConfigurationChanged; import org.infinispan.notifications.cachemanagerlistener.event.ConfigurationChangedEvent; import org.infinispan.remoting.transport.jgroups.JGroupsTransport; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.testng.annotations.Test; /** * @since 9.2 */ @Test(testName = "globalstate.GlobalStateTest", groups = "functional") public class GlobalStateTest extends AbstractInfinispanTest { public void testReplicatedState(Method m) { String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "1"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(state1, true); String state2 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "2"); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(state2, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, null, new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, null, new TransportFlags()); try { Configuration cacheConfig = new ConfigurationBuilder().build(); Configuration template = new ConfigurationBuilder().template(true).build(); cm1.start(); cm2.start(); cm1.defineConfiguration("not-replicated-template", template); cm1.createCache("not-replicated-cache", cacheConfig); assertNull(cm2.getCacheConfiguration("not-replicated-template")); assertFalse(cm2.cacheExists("not-replicated-cache")); cm1.administration().getOrCreateCache("replicated-cache", cacheConfig); cm1.administration().getOrCreateTemplate("replicated-template", template); assertNotNull(cm2.getCache("replicated-cache")); assertNotNull(cm2.getCacheConfiguration("replicated-template")); assertEquals(2, cm1.getCacheNames().size()); assertEquals(1, cm2.getCacheNames().size()); cm1.stop(); cm2.stop(); global1 = statefulGlobalBuilder(state1, false); EmbeddedCacheManager newCm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); assertNotNull(newCm1.getCache("replicated-cache")); assertNotNull(newCm1.getCacheConfiguration("replicated-template")); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } public void testLockPersistentLocation() { String name = CallerId.getCallerMethodName(1); String stateDirectory = tmpDirectory(name, "COMMON"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(stateDirectory, true); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(stateDirectory, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, new ConfigurationBuilder(), new TransportFlags()); try { cm1.start(); expectException(EmbeddedCacheManagerStartupException.class, "ISPN000693:.*", cm2::start); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } public void testCorruptGlobalState(Method m) throws Exception { String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "1"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(state1, true); String state2 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "2"); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(state2, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, new ConfigurationBuilder(), new TransportFlags()); try { cm1.start(); cm2.start(); cm1.stop(); cm2.stop(); // corrupt one of the state files Writer w = new FileWriter(new File(state1, ScopedPersistentState.GLOBAL_SCOPE + ".state")); w.write("'Cause I want to be anarchy\nIt's the only way to be"); w.close(); global1 = statefulGlobalBuilder(state1, false); EmbeddedCacheManager newCm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); expectException(EmbeddedCacheManagerStartupException.class, "ISPN000516: The state file for '___global' is invalid.*", newCm1::start); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } public void testIncompatibleGlobalState(Method m) throws Exception { String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "1"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(state1, true); String state2 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "2"); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(state2, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, new ConfigurationBuilder(), new TransportFlags()); try { cm1.start(); cm2.start(); // Create two DIST caches ConfigurationBuilder distBuilder = new ConfigurationBuilder(); distBuilder.clustering().cacheMode(CacheMode.DIST_SYNC); cm1.administration().createCache("cache1", distBuilder.build()); cm1.administration().createCache("cache2", distBuilder.build()); cm2.stop(); // Remove the caches from the first node cm1.administration().removeCache("cache1"); cm1.administration().removeCache("cache2"); // Recreate the cache as REPL ConfigurationBuilder replBuilder = new ConfigurationBuilder(); replBuilder.clustering().cacheMode(CacheMode.REPL_SYNC); cm1.administration().createCache("cache1", replBuilder.build()); // Attempt to restart the second cache manager global2 = statefulGlobalBuilder(state2, false); EmbeddedCacheManager newCm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, new ConfigurationBuilder(), new TransportFlags()); expectException(EmbeddedCacheManagerStartupException.class, "(?s)ISPN000500: Cannot create clustered configuration for cache.*", newCm2::start); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } public void testConfigurationUpdate(Method m) { String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "1"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(state1, true); String state2 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "2"); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(state2, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, new ConfigurationBuilder(), new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, new ConfigurationBuilder(), new TransportFlags()); try { cm1.start(); cm2.start(); // Create two DIST caches ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC).memory().maxCount(1000); cm1.administration().getOrCreateCache("cache1", builder.build()); assertEquals(1000, cm1.getCache("cache1").getCacheConfiguration().memory().maxCount()); assertEquals(1000, cm2.getCache("cache1").getCacheConfiguration().memory().maxCount()); // Update the configuration builder.clustering().cacheMode(CacheMode.DIST_SYNC).memory().maxCount(2000); cm1.administration().withFlags(CacheContainerAdmin.AdminFlag.UPDATE).getOrCreateCache("cache1", builder.build()); assertEquals(2000, cm1.getCache("cache1").getCacheConfiguration().memory().maxCount()); assertEquals(2000, cm2.getCache("cache1").getCacheConfiguration().memory().maxCount()); // Verify that it is unchanged if we don't use the UPDATE flag builder.clustering().cacheMode(CacheMode.DIST_SYNC).memory().maxCount(3000); cm1.administration().getOrCreateCache("cache1", builder.build()); assertEquals(2000, cm1.getCache("cache1").getCacheConfiguration().memory().maxCount()); assertEquals(2000, cm2.getCache("cache1").getCacheConfiguration().memory().maxCount()); // Try to use an incompatible configuration builder.clustering().cacheMode(CacheMode.REPL_SYNC); Exceptions.expectRootCause(IllegalArgumentException.class, () -> cm1.administration().withFlags(CacheContainerAdmin.AdminFlag.UPDATE).getOrCreateCache("cache1", builder.build())); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } private GlobalConfigurationBuilder statefulGlobalBuilder(String stateDirectory, boolean clear) { if (clear) Util.recursiveFileRemove(stateDirectory); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory).sharedPersistentLocation(stateDirectory).configurationStorage(ConfigurationStorage.OVERLAY); return global; } public void testFailStartup(Method m) throws Exception { String state = tmpDirectory(this.getClass().getSimpleName(), m.getName()); GlobalConfigurationBuilder global = statefulGlobalBuilder(state, true); global.transport().transport(new FailingJGroupsTransport()); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(false, global, new ConfigurationBuilder(), new TransportFlags()); try { cm.start(); fail("Should not reach here"); } catch (Exception e) { // Ensure there is no global state file File globalStateFile = new File(state, ScopedPersistentState.GLOBAL_SCOPE + ".state"); assertFalse(globalStateFile.exists()); } finally { TestingUtil.killCacheManagers(cm); } } public void testUncleanShutdownAction() throws IOException { String state = tmpDirectory(this.getClass().getSimpleName(), CallerId.getCallerMethodName(1)); // Test the default FAIL action by creating a "dangling" lock file GlobalConfigurationBuilder global = statefulGlobalBuilder(state, true); global.globalState().uncleanShutdownAction(UncleanShutdownAction.FAIL); File globalLockFile = new File(state, ScopedPersistentState.GLOBAL_SCOPE + ".lck"); globalLockFile.getParentFile().mkdirs(); globalLockFile.createNewFile(); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(false, global, null, new TransportFlags()); Exceptions.expectException("ISPN000693:.*", cm::start, EmbeddedCacheManagerStartupException.class, CacheConfigurationException.class); // Remove the lock file, this should allow the cache manager to start globalLockFile.delete(); cm = TestCacheManagerFactory.createClusteredCacheManager(false, global, null, new TransportFlags()); try { cm.start(); } finally { TestingUtil.killCacheManagers(cm); } File globalScopeFile = new File(state, ScopedPersistentState.GLOBAL_SCOPE + ".state"); Properties properties = new Properties(); try (FileReader reader = new FileReader(globalScopeFile)) { properties.load(reader); } String uuid = properties.getProperty("uuid"); // Test the PURGE action by creating a dangling lock file globalLockFile.createNewFile(); global = statefulGlobalBuilder(state, false); global.globalState().uncleanShutdownAction(UncleanShutdownAction.PURGE); cm = TestCacheManagerFactory.createClusteredCacheManager(false, global, null, new TransportFlags()); try { cm.start(); } finally { TestingUtil.killCacheManagers(cm); } properties.clear(); try (FileReader reader = new FileReader(globalScopeFile)) { properties.load(reader); } assertNotEquals(uuid, properties.getProperty("uuid"), "uuids should be different"); uuid = properties.getProperty("uuid"); // Test the IGNORE action globalLockFile.createNewFile(); global = statefulGlobalBuilder(state, false); global.globalState().uncleanShutdownAction(UncleanShutdownAction.IGNORE); cm = TestCacheManagerFactory.createClusteredCacheManager(false, global, null, new TransportFlags()); try { cm.start(); } finally { TestingUtil.killCacheManagers(cm); } properties.clear(); try (FileReader reader = new FileReader(globalScopeFile)) { properties.load(reader); } assertEquals("uuids should be the same", uuid, properties.getProperty("uuid")); } public void testCacheManagerNotifications(Method m) { String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "1"); GlobalConfigurationBuilder global1 = statefulGlobalBuilder(state1, true); String state2 = tmpDirectory(this.getClass().getSimpleName(), m.getName() + "2"); GlobalConfigurationBuilder global2 = statefulGlobalBuilder(state2, true); EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(false, global1, null, new TransportFlags()); EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(false, global2, null, new TransportFlags()); try { Configuration cacheConfig = new ConfigurationBuilder().build(); Configuration template = new ConfigurationBuilder().template(true).build(); cm1.start(); cm2.start(); cm1.addListener(new StateListener()); cm2.addListener(new StateListener()); cm1.administration().getOrCreateCache("replicated-cache", cacheConfig); cm1.administration().getOrCreateTemplate("replicated-template", template); assertNotNull(cm2.getCache("replicated-cache")); assertNotNull(cm2.getCacheConfiguration("replicated-template")); assertEquals(1, cm1.getCacheNames().size()); assertEquals(1, cm2.getCacheNames().size()); cm1.stop(); cm2.stop(); } finally { TestingUtil.killCacheManagers(cm1, cm2); } } public void testNameSize(Method m) { final String cacheName = new String(new char[256]); final String exceptionMessage = String.format("ISPN000663: Name must be less than 256 bytes, current name '%s' exceeds the size.", cacheName); String state1 = tmpDirectory(this.getClass().getSimpleName(), m.getName()); GlobalConfigurationBuilder gcb = statefulGlobalBuilder(state1, true); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(false, gcb, null, new TransportFlags()); final Configuration configuration = new ConfigurationBuilder().build(); try { cm.start(); expectException(exceptionMessage, () -> cm.administration().getOrCreateCache(cacheName, configuration), CacheConfigurationException.class); expectException(exceptionMessage, () -> cm.administration().createTemplate(cacheName, configuration), CacheConfigurationException.class); expectException(exceptionMessage, () -> cm.administration().getOrCreateTemplate(cacheName, configuration), CacheConfigurationException.class); } finally { TestingUtil.killCacheManagers(cm); } } @Listener public static class StateListener { @ConfigurationChanged public void configurationChanged(ConfigurationChangedEvent event) { } } public static class FailingJGroupsTransport extends JGroupsTransport { @Override public void start() { throw new RuntimeException("fail"); } } }
18,072
50.34375
188
java
null
infinispan-main/core/src/test/java/org/infinispan/security/RolePermissionNoACLCacheTest.java
package org.infinispan.security; import java.util.concurrent.TimeUnit; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.RolePermissionNoACLCacheTest") public class RolePermissionNoACLCacheTest extends RolePermissionTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().securityCacheTimeout(0, TimeUnit.SECONDS).authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new IdentityRoleMapper()); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); globalRoles .role("role1").permission(AuthorizationPermission.EXEC) .role("role2").permission(AuthorizationPermission.EXEC) .role("role3").permission(AuthorizationPermission.EXEC) .role("role4").permission(AuthorizationPermission.EXEC) .role("role5").permission(AuthorizationPermission.EXEC) .role("role6").permission(AuthorizationPermission.EXEC) .role("admin").permission(AuthorizationPermission.ALL); authConfig.role("role1").role("role2").role("admin"); return TestCacheManagerFactory.createCacheManager(global, config); } }
1,959
50.578947
144
java
null
infinispan-main/core/src/test/java/org/infinispan/security/TestCachePermission.java
package org.infinispan.security; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface TestCachePermission { AuthorizationPermission value(); }
359
26.692308
48
java
null
infinispan-main/core/src/test/java/org/infinispan/security/CacheAuthorizationTest.java
package org.infinispan.security; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "security.CacheAuthorizationTest") public class CacheAuthorizationTest extends BaseAuthorizationTest { public void testAllCombinations() throws Exception { Method[] allMethods = SecureCache.class.getMethods(); Set<String> methodNames = new HashSet<>(); collectmethods: for (Method m : allMethods) { StringBuilder s = new StringBuilder("test"); String name = m.getName(); s.append(name.substring(0, 1).toUpperCase()); s.append(name.substring(1)); for (Class<?> p : m.getParameterTypes()) { Package pkg = p.getPackage(); if (pkg != null && pkg.getName().startsWith("java.util.function")) continue collectmethods; // Skip methods which use interfaces introduced in JDK8 s.append("_"); s.append(p.getSimpleName().replaceAll("\\[\\]", "Array")); } methodNames.add(s.toString()); } final SecureCacheTestDriver driver = new SecureCacheTestDriver(); final SecureCache<String, String> cache = (SecureCache<String, String>) Security.doAs(ADMIN, () -> { Cache<String, String> c = cacheManager.getCache(); return c; }); for (final String methodName : methodNames) { Class<? extends SecureCacheTestDriver> driverClass = driver.getClass(); try { final Method method = driverClass.getMethod(methodName, SecureCache.class); TestCachePermission annotation = method.getAnnotation(TestCachePermission.class); if (annotation == null) { throw new Exception(String.format("Method %s on class %s is missing the TestCachePermission annotation", methodName, driver.getClass().getName())); } final AuthorizationPermission expectedPerm = annotation.value(); for (final AuthorizationPermission perm : AuthorizationPermission.values()) { if (perm == AuthorizationPermission.NONE) continue;// Skip log.debugf("Method %s > %s", methodName, perm.toString()); if (expectedPerm == AuthorizationPermission.NONE) { try { method.invoke(driver, cache); } catch (SecurityException e) { throw new Exception(String.format("Unexpected SecurityException while invoking %s with permission %s", methodName, perm), e); } } else { Security.doAs(SUBJECTS.get(perm),() -> { try { invokeCacheMethod(driver, cache, methodName, method, expectedPerm, perm); } catch (Exception e) { throw new RuntimeException(e); } }); invokeCacheMethod(driver, cache.withSubject(SUBJECTS.get(perm)), methodName, method, expectedPerm, perm); } } } catch (NoSuchMethodException e) { throw new Exception( String.format( "Class %s needs to declare a method with the following signature: public void %s(SecureCache<String, String> cache) {}\n", driver.getClass().getName(), methodName), e); } } } private void invokeCacheMethod(SecureCacheTestDriver driver, AdvancedCache<String, String> cache, String methodName, Method method, AuthorizationPermission expectedPerm, AuthorizationPermission perm) throws Exception { try { method.invoke(driver, cache); if (!perm.implies(expectedPerm)) { throw new Exception(String.format("Expected SecurityException while invoking %s with permission %s", methodName, perm)); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof SecurityException) { if (perm.implies(expectedPerm)) { throw new Exception(String.format("Unexpected SecurityException while invoking %s with permission %s", methodName, perm), e); } else { // We were expecting a security exception } } else throw new Exception("Unexpected non-SecurityException", e); } } }
4,630
46.255102
221
java
null
infinispan-main/core/src/test/java/org/infinispan/security/SecurityXmlFileParsingTest.java
package org.infinispan.security; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "unit", testName = "security.SecurityXmlFileParsingTest") public class SecurityXmlFileParsingTest extends AbstractInfinispanTest { Subject ADMIN = TestingUtil.makeSubject("admin", "admin"); public void testParseAndConstructUnifiedXmlFile() { Security.doAs(ADMIN, () -> withCacheManager(new CacheManagerCallable(Exceptions.unchecked(() -> TestCacheManagerFactory.fromXml("configs/security.xml", true))) { @Override public void call() { GlobalConfiguration g = cm.getCacheManagerConfiguration(); assertTrue(g.security().authorization().enabled()); assertEquals(IdentityRoleMapper.class, g.security().authorization().principalRoleMapper().getClass()); Map<String, Role> globalRoles = g.security().authorization().roles(); assertTrue(globalRoles.containsKey("supervisor")); assertTrue(globalRoles.get("supervisor").getPermissions().containsAll(Arrays.asList(AuthorizationPermission.READ, AuthorizationPermission.WRITE, AuthorizationPermission.EXEC))); Configuration c = cm.getCache("secured").getCacheConfiguration(); assertTrue(c.security().authorization().enabled()); c.security().authorization().roles().containsAll(Arrays.asList("admin", "reader", "writer")); } })); } public void testClusterRoleMapperWithRewriter() { Security.doAs(ADMIN, () -> withCacheManager(new CacheManagerCallable(Exceptions.unchecked(() -> TestCacheManagerFactory.fromXml("configs/security-role-mapper-rewriter.xml", true))) { @Override public void call() { GlobalConfiguration g = cm.getCacheManagerConfiguration(); assertTrue(g.security().authorization().enabled()); assertEquals(ClusterRoleMapper.class, g.security().authorization().principalRoleMapper().getClass()); ClusterRoleMapper mapper = (ClusterRoleMapper) g.security().authorization().principalRoleMapper(); mapper.grant("supervisor", "tristan"); Set<String> roles = mapper.principalToRoles(new TestingUtil.TestPrincipal("cn=tristan,ou=developers,dc=infinispan,dc=org")); assertEquals(1, roles.size()); assertTrue(roles.contains("supervisor")); } })); } }
3,133
48.746032
189
java
null
infinispan-main/core/src/test/java/org/infinispan/security/RoleMapperTest.java
package org.infinispan.security; import static org.testng.AssertJUnit.assertEquals; import java.util.Collections; import org.infinispan.security.mappers.CommonNameRoleMapper; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups="functional", testName = "security.RoleMapperTest") public class RoleMapperTest { public void testCommonNameRoleMapper() { CommonNameRoleMapper mapper = new CommonNameRoleMapper(); assertEquals(Collections.singleton("MadHatter"), mapper.principalToRoles(new TestingUtil.TestPrincipal("CN=MadHatter,OU=Users,DC=infinispan,DC=org"))); assertEquals(Collections.singleton("MadHatter"), mapper.principalToRoles(new TestingUtil.TestPrincipal("cn=MadHatter,ou=Users,dc=infinispan,dc=org"))); } }
782
38.15
157
java
null
infinispan-main/core/src/test/java/org/infinispan/security/SecureListenerTest.java
package org.infinispan.security; import static org.testng.AssertJUnit.assertEquals; import javax.security.auth.Subject; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.SecureListenerTest") public class SecureListenerTest extends SingleCacheManagerTest { static final Subject ADMIN = TestingUtil.makeSubject("admin"); static final Subject SUBJECT_A = TestingUtil.makeSubject("A", "listener"); static final Subject SUBJECT_B = TestingUtil.makeSubject("B", "listener"); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new IdentityRoleMapper()); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); globalRoles .role("listener").permission(AuthorizationPermission.LISTEN) .role("admin").permission(AuthorizationPermission.ALL); authConfig.role("listener").role("admin"); return TestCacheManagerFactory.createCacheManager(global, config); } @Override protected void setup() throws Exception { Security.doAs(ADMIN, () -> { try { cacheManager = createCacheManager(); } catch (Exception e) { throw new RuntimeException(e); } if (cache == null) cache = cacheManager.getCache(); }); } public void testSecureListenerSubject() { registerListener(SUBJECT_A); registerListener(SUBJECT_B); Security.doAs(ADMIN, () -> cacheManager.getCache().put("key", "value")); } private void registerListener(final Subject subject) { Security.doAs(subject, () -> cacheManager.getCache().addListener(new SubjectVerifyingListener(subject))); } @Override protected void teardown() { Security.doAs(ADMIN, () -> SecureListenerTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } @Listener public static final class SubjectVerifyingListener { final Subject subject; public SubjectVerifyingListener(Subject subject) { this.subject = subject; } @CacheEntryCreated public void handleCreated(CacheEntryCreatedEvent<String, String> event) { assertEquals(subject, Security.getSubject()); } } }
3,436
37.188889
111
java
null
infinispan-main/core/src/test/java/org/infinispan/security/DynamicRBACRestartTest.java
package org.infinispan.security; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.AssertJUnit.assertEquals; import javax.security.auth.Subject; import org.infinispan.AdvancedCache; import org.infinispan.commons.util.Util; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.globalstate.ConfigurationStorage; import org.infinispan.security.mappers.ClusterPermissionMapper; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.DynamicRBACRestartTest") public class DynamicRBACRestartTest extends MultipleCacheManagersTest { static final Subject ADMIN = TestingUtil.makeSubject("admin"); private ClusterRoleMapper crm; private ClusterPermissionMapper cpm; @Override protected void createCacheManagers() throws Throwable { Security.doAs(ADMIN, () -> { addClusterEnabledCacheManager(getGlobalConfigurationBuilder("A", true), getConfigurationBuilder()); addClusterEnabledCacheManager(getGlobalConfigurationBuilder("B", true), getConfigurationBuilder()); waitForClusterToForm(); crm = (ClusterRoleMapper) cacheManagers.get(0).getCacheManagerConfiguration().security().authorization().principalRoleMapper(); crm.grant("admin", "admin"); cpm = (ClusterPermissionMapper) cacheManagers.get(0).getCacheManagerConfiguration().security().authorization().rolePermissionMapper(); await(cpm.addRole(Role.newRole("wizard", true, AuthorizationPermission.ALL_WRITE))); await(cpm.addRole(Role.newRole("cleric", true, AuthorizationPermission.ALL_READ))); return null; }); } private ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.clustering().cacheMode(CacheMode.DIST_SYNC); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); authConfig.role("reader").role("writer").role("admin"); return config; } private GlobalConfigurationBuilder getGlobalConfigurationBuilder(String id, boolean clear) { String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), id); if (clear) Util.recursiveFileRemove(stateDirectory); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory). configurationStorage(ConfigurationStorage.OVERLAY); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new ClusterRoleMapper()) .rolePermissionMapper(new ClusterPermissionMapper()); globalRoles .role("reader").permission(AuthorizationPermission.ALL_READ) .role("writer").permission(AuthorizationPermission.ALL_WRITE) .role("admin").permission(AuthorizationPermission.ALL); return global; } public void testPermissionsRestart() { ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.clustering().cacheMode(CacheMode.DIST_SYNC); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); authConfig.role("admin").role("wizard").role("cleric"); Security.doAs(ADMIN, () -> cacheManagers.get(0).administration().createCache("minastirith", config.build()) ); Security.doAs(ADMIN, () -> TestingUtil.killCacheManagers(cacheManagers)); cacheManagers.clear(); Security.doAs(ADMIN, () -> { addClusterEnabledCacheManager(getGlobalConfigurationBuilder("A", false), getConfigurationBuilder()); addClusterEnabledCacheManager(getGlobalConfigurationBuilder("B", false), getConfigurationBuilder()); waitForClusterToForm(); }); AdvancedCache<Object, Object> cache = manager(0).getCache("minastirith").getAdvancedCache(); cache.withSubject(TestingUtil.makeSubject("wizard")).put("k1", "v1"); assertEquals("v1", cache.withSubject(TestingUtil.makeSubject("cleric")).get("k1")); } @AfterClass(alwaysRun = true) @Override protected void destroy() { Security.doAs(ADMIN, () -> { DynamicRBACRestartTest.super.destroy(); return null; }); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> { cacheManagers.forEach(cm -> cm.getCache().clear()); return null; }); } }
5,241
46.225225
143
java
null
infinispan-main/core/src/test/java/org/infinispan/security/CustomAuditLoggerTest.java
package org.infinispan.security; import static org.testng.AssertJUnit.assertEquals; import javax.security.auth.Subject; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.CustomAuditLoggerTest") public class CustomAuditLoggerTest extends SingleCacheManagerTest { public static final String ADMIN_ROLE = "admin"; public static final String READER_ROLE = "reader"; public static final Subject ADMIN = TestingUtil.makeSubject(ADMIN_ROLE); public static final Subject READER = TestingUtil.makeSubject(READER_ROLE); private static final TestAuditLogger LOGGER = new TestAuditLogger(); @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new IdentityRoleMapper()).auditLogger(LOGGER); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); globalRoles.role(ADMIN_ROLE).permission(AuthorizationPermission.ALL).role(READER_ROLE) .permission(AuthorizationPermission.READ); authConfig.role(ADMIN_ROLE).role(READER_ROLE); return TestCacheManagerFactory.createCacheManager(global, config); } @Override protected void setup() throws Exception { Security.doAs(ADMIN, () -> { try { cacheManager = createCacheManager(); } catch (Exception e) { throw new RuntimeException(e); } cache = cacheManager.getCache(); }); } @Override protected void teardown() { Security.doAs(ADMIN, () -> CustomAuditLoggerTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } public void testAdminWriteAllow() { Security.doAs(ADMIN, () -> cacheManager.getCache().put("key", "value")); String actual = LOGGER.getLastRecord(); String expected = LOGGER.formatLogRecord(AuthorizationPermission.WRITE.toString(), AuditResponse.ALLOW.toString(), ADMIN.toString()); assertEquals(expected, actual); } public void testReaderReadAllow() { Security.doAs(READER, () -> cacheManager.getCache().get("key")); String actual = LOGGER.getLastRecord(); String expected = LOGGER.formatLogRecord(AuthorizationPermission.READ.toString(), AuditResponse.ALLOW.toString(), READER.toString()); assertEquals(expected, actual); } public void testReaderWriteDeny() { Exceptions.expectException(SecurityException.class, () -> Security.doAs(READER, () -> cacheManager.getCache().put("key", "value"))); String actual = LOGGER.getLastRecord(); String expected = LOGGER.formatLogRecord(AuthorizationPermission.WRITE.toString(), AuditResponse.DENY.toString(), READER.toString()); assertEquals(expected, actual); } public static class TestAuditLogger implements AuditLogger { public static final String logTemplate = "Permission to %s is %s for user %s"; private String lastLogRecord; @Override public void audit(Subject subject, AuditContext context, String contextName, AuthorizationPermission permission, AuditResponse response) { lastLogRecord = formatLogRecord(String.valueOf(permission), String.valueOf(response), String.valueOf(subject)); } public String getLastRecord() { return lastLogRecord; } public String formatLogRecord(String permission, String response, String subject) { return String.format(logTemplate, permission, response, subject); } } }
4,536
39.508929
138
java
null
infinispan-main/core/src/test/java/org/infinispan/security/RolePermissionTest.java
package org.infinispan.security; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Set; import javax.security.auth.Subject; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.RolePermissionTest") public class RolePermissionTest extends SingleCacheManagerTest { static final Subject ADMIN = TestingUtil.makeSubject("admin"); static final Subject SUBJECT_A = TestingUtil.makeSubject("A", "role1"); static final Subject SUBJECT_WITHOUT_PRINCIPAL = TestingUtil.makeSubject(); AuthorizationManager authzManager; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new IdentityRoleMapper()); ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); globalRoles .role("role1").permission(AuthorizationPermission.EXEC) .role("role2").permission(AuthorizationPermission.EXEC) .role("role3").permission(AuthorizationPermission.READ, AuthorizationPermission.WRITE) .role("role4").permission(AuthorizationPermission.READ, AuthorizationPermission.WRITE) .role("role5").permission(AuthorizationPermission.READ, AuthorizationPermission.WRITE) .role("admin").permission(AuthorizationPermission.ALL); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); authConfig.role("role1").role("role2").role("admin"); return TestCacheManagerFactory.createCacheManager(global, config); } @Override protected void setup() throws Exception { authzManager = Security.doAs(ADMIN, () -> { try { cacheManager = createCacheManager(); } catch (Exception e) { throw new RuntimeException(e); } if (cache == null) cache = cacheManager.getCache(); return cache.getAdvancedCache().getAuthorizationManager(); }); } public void testPermissionAndRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.EXEC, "role1"); return null; }); } public void testPermissionAndNoRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.EXEC); return null; }); } @Test(expectedExceptions = SecurityException.class) public void testWrongPermissionAndNoRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.LISTEN); return null; }); } @Test(expectedExceptions = SecurityException.class) public void testWrongPermissionAndRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.LISTEN, "role1"); return null; }); } @Test(expectedExceptions = SecurityException.class) public void testPermissionAndWrongRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.EXEC, "role2"); return null; }); } @Test(expectedExceptions = SecurityException.class) public void testWrongPermissionAndWrongRole() { Security.doAs(SUBJECT_A, () -> { authzManager.checkPermission(AuthorizationPermission.LISTEN, "role2"); return null; }); } public void testNoPrincipalInSubject() { Security.doAs(SUBJECT_WITHOUT_PRINCIPAL, () -> { authzManager.checkPermission(AuthorizationPermission.NONE); return null; }); } public void testAccessibleCaches() { Security.doAs(ADMIN, () -> { for (int i = 3; i < 6; i++) { ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.security().authorization().enable().role("role" + i).role("admin"); cacheManager.createCache("cache" + i, config.build()); } }); Set<String> names = Security.doAs(TestingUtil.makeSubject("Subject34", "role3", "role4"), () -> cacheManager.getAccessibleCacheNames()); assertEquals(2, names.size()); assertTrue(names.toString(), names.contains("cache3")); assertTrue(names.toString(), names.contains("cache4")); names = Security.doAs(TestingUtil.makeSubject("Subject35", "role3", "role5"), () -> cacheManager.getAccessibleCacheNames()); assertEquals(2, names.size()); assertTrue(names.toString(), names.contains("cache3")); assertTrue(names.toString(), names.contains("cache5")); names = Security.doAs(TestingUtil.makeSubject("Subject45", "role4", "role5"), () -> cacheManager.getAccessibleCacheNames()); assertEquals(2, names.size()); assertTrue(names.toString(), names.contains("cache4")); assertTrue(names.toString(), names.contains("cache5")); names = Security.doAs(TestingUtil.makeSubject("Subject0"), () -> cacheManager.getAccessibleCacheNames()); assertEquals(0, names.size()); } @Override protected void teardown() { Security.doAs(ADMIN, () -> { RolePermissionTest.super.teardown(); return null; }); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> { cacheManager.getCache().clear(); return null; }); } }
6,181
38.883871
142
java
null
infinispan-main/core/src/test/java/org/infinispan/security/CacheManagerAuthorizationTest.java
package org.infinispan.security; import static org.testng.Assert.assertTrue; import java.lang.reflect.Field; import java.util.function.Supplier; import javax.security.auth.Subject; import org.infinispan.commons.test.Exceptions; import org.testng.annotations.Test; @Test(groups = {"functional", "smoke"}, testName = "security.CacheManagerAuthorizationTest") public class CacheManagerAuthorizationTest extends BaseAuthorizationTest { @TestCachePermission(AuthorizationPermission.ADMIN) Runnable GET_GLOBAL_COMPONENT_REGISTRY = () -> cacheManager.getGlobalComponentRegistry(); @TestCachePermission(AuthorizationPermission.ADMIN) Runnable GET_CACHE_MANAGER_CONFIGURATION = () -> cacheManager.getCacheManagerConfiguration(); @TestCachePermission(AuthorizationPermission.MONITOR) Runnable GET_STATS = () -> cacheManager.getStats(); public void testCombinations() throws Exception { Field[] fields = this.getClass().getDeclaredFields(); for (Field f : fields) { if (f.getType().equals(Runnable.class)) { final Runnable fn = (Runnable) f.get(this); Supplier<Boolean> action = () -> { fn.run(); return true; }; TestCachePermission p = f.getAnnotation(TestCachePermission.class); for (final AuthorizationPermission perm : AuthorizationPermission.values()) { Subject subject = SUBJECTS.get(perm); if (perm.implies(p.value())) { assertTrue(Security.doAs(subject, action)); } else { Exceptions.expectException(SecurityException.class, () -> Security.doAs(subject, action)); } } } } } }
1,764
35.770833
96
java
null
infinispan-main/core/src/test/java/org/infinispan/security/CacheImplicitRolesAuthorizationTest.java
package org.infinispan.security; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.testng.annotations.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @Test(groups = {"functional", "smoke"}, testName = "security.CacheImplicitRolesAuthorizationTest") public class CacheImplicitRolesAuthorizationTest extends CacheAuthorizationTest { protected ConfigurationBuilder createCacheConfiguration(GlobalConfigurationBuilder global) { final ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.transaction().lockingMode(LockingMode.PESSIMISTIC); config.invocationBatching().enable(); config.security().authorization().enable(); return config; } }
958
38.958333
101
java
null
infinispan-main/core/src/test/java/org/infinispan/security/SecureCacheTestDriver.java
package org.infinispan.security; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_OBJECT_TYPE; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Function; import jakarta.transaction.NotSupportedException; import jakarta.transaction.SystemException; import org.infinispan.commons.dataconversion.ByteArrayWrapper; import org.infinispan.commons.dataconversion.IdentityEncoder; import org.infinispan.conflict.ConflictManagerFactory; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.context.Flag; import org.infinispan.interceptors.FooInterceptor; import org.infinispan.interceptors.impl.InvocationContextInterceptor; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.filter.CacheEventConverter; import org.infinispan.notifications.cachelistener.filter.CacheEventFilter; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.util.concurrent.CompletionStages; public class SecureCacheTestDriver { private Metadata metadata; private NullListener listener; private FooInterceptor interceptor; private CacheEventConverter<String, String, String> converter; private CacheEventFilter<String, String> keyValueFilter; public SecureCacheTestDriver() { interceptor = new FooInterceptor(); keyValueFilter = (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> true; converter = (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> null; listener = new NullListener(); metadata = new Metadata() { @Override public long lifespan() { return -1; } @Override public long maxIdle() { return -1; } @Override public EntryVersion version() { return null; } @Override public Builder builder() { return null; } }; } @TestCachePermission(AuthorizationPermission.READ) public void testIsEmpty(SecureCache<String, String> cache) { cache.isEmpty(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPut_Object_Object(SecureCache<String, String> cache) { cache.put("a", "a"); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetVersion(SecureCache<String, String> cache) { cache.getVersion(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsentAsync_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.putIfAbsent("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPut_Object_Object_Metadata(SecureCache<String, String> cache) { cache.put("a", "a", metadata); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testAddInterceptor_CommandInterceptor_int(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain().addInterceptor(interceptor, 0); cache.getAsyncInterceptorChain().removeInterceptor(0); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testRemoveListener_Object(SecureCache<String, String> cache) { cache.removeListener(listener); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testRemoveListenerAsync_Object(SecureCache<String, String> cache) { CompletionStages.join(cache.removeListenerAsync(listener)); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.replace("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testLock_Collection(SecureCache<String, String> cache) throws IllegalStateException, SystemException, NotSupportedException { try { cache.getTransactionManager().begin(); cache.lock(Collections.singleton("a")); } finally { cache.getTransactionManager().rollback(); } } @TestCachePermission(AuthorizationPermission.BULK_WRITE) public void testClear(SecureCache<String, String> cache) { cache.clear(); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetName(SecureCache<String, String> cache) { cache.getName(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testKeySet(SecureCache<String, String> cache) { cache.keySet(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetCacheConfiguration(SecureCache<String, String> cache) { cache.getCacheConfiguration(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAsync_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putAsync("a", "a", metadata); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAsyncEntry_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putAsyncEntry("a", "a", metadata); } @TestCachePermission(value = AuthorizationPermission.LIFECYCLE) public void testStop(SecureCache<String, String> cache) { cache.stop(); cache.start(); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddListener_Object_CacheEventFilter_CacheEventConverter(SecureCache<String, String> cache) { cache.addListener(listener, keyValueFilter, converter); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddListenerAsync_Object_CacheEventFilter_CacheEventConverter(SecureCache<String, String> cache) { CompletionStages.join(cache.addListenerAsync(listener, keyValueFilter, converter)); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddFilteredListenerAsync_Object_CacheEventFilter_CacheEventConverter_Set(SecureCache<String, String> cache) { CompletionStages.join(cache.addListenerAsync(listener, keyValueFilter, converter)); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testEntrySet(SecureCache<String, String> cache) { cache.entrySet(); } @TestCachePermission(AuthorizationPermission.READ) public void testContainsValue_Object(SecureCache<String, String> cache) { try { cache.containsValue("a"); } catch (UnsupportedOperationException e) { // We expect this } } @TestCachePermission(AuthorizationPermission.READ) public void testContainsKey_Object(SecureCache<String, String> cache) { cache.containsKey("a"); } @TestCachePermission(AuthorizationPermission.READ) public void testContainsKeyAsync_Object(SecureCache<String, String> cache) { cache.containsKeyAsync("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object(SecureCache<String, String> cache) { cache.replace("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_Object(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", "b"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_Object_Metadata(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", "b", new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsyncEntry_Object_Object_Metadata(SecureCache<String, String> cache) { cache.replaceAsyncEntry("a", "a", new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetStatus(SecureCache<String, String> cache) { cache.getStatus(); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetAvailability(SecureCache<String, String> cache) { cache.getAvailability(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testSetAvailability_AvailabilityMode(SecureCache<String, String> cache) { cache.setAvailability(AvailabilityMode.AVAILABLE); } @TestCachePermission(AuthorizationPermission.READ) public void testGetAsync_Object(SecureCache<String, String> cache) { cache.getAsync("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testStartBatch(SecureCache<String, String> cache) { cache.startBatch(); cache.endBatch(false); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", "b", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testAddInterceptorAfter_CommandInterceptor_Class(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain().addInterceptorAfter(interceptor, InvocationContextInterceptor.class); cache.getAsyncInterceptorChain().removeInterceptor(interceptor.getClass()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_Object(SecureCache<String, String> cache) { cache.replace("a", "a", "b"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemove_Object(SecureCache<String, String> cache) { cache.remove("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsentAsync_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putIfAbsentAsync("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.replace("a", "a", "b", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.replace("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAsync_Object_Object(SecureCache<String, String> cache) { cache.putAsync("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsent_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.putIfAbsent("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.NONE) public void testHashCode(SecureCache<String, String> cache) { cache.hashCode(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPut_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.put("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsent_Object_Object(SecureCache<String, String> cache) { cache.putIfAbsent("a", "a"); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testEvict_Object(SecureCache<String, String> cache) { cache.evict("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAsync_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putAsync("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testEndBatch_boolean(SecureCache<String, String> cache) { cache.startBatch(); cache.endBatch(false); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_Metadata(SecureCache<String, String> cache) { cache.replace("a", "a", metadata); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithFlags_FlagArray(SecureCache<String, String> cache) { cache.withFlags(Flag.IGNORE_RETURN_VALUES); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithFlags_Collection(SecureCache<String, String> cache) { cache.withFlags(Collections.singleton(Flag.IGNORE_RETURN_VALUES)); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithFlags_Flag(SecureCache<String, String> cache) { cache.withFlags(Flag.IGNORE_RETURN_VALUES); } @TestCachePermission(AuthorizationPermission.NONE) public void testNoFlags(SecureCache<String, String> cache) { cache.noFlags(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testTouch_Object_boolean(SecureCache<String, String> cache) { cache.touch(new Object(), true); } @TestCachePermission(AuthorizationPermission.WRITE) public void testTouch_Object_int_boolean(SecureCache<String, String> cache) { cache.touch(new Object(), 1, true); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testTransform_Function(SecureCache<String, String> cache) { cache.transform(Function.identity()); } @TestCachePermission(AuthorizationPermission.NONE) public void testWith_ClassLoader(SecureCache<String, String> cache) { cache.with(this.getClass().getClassLoader()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testGetBatchContainer(SecureCache<String, String> cache) { cache.getBatchContainer(); } @TestCachePermission(AuthorizationPermission.MONITOR) public void testGetStats(SecureCache<String, String> cache) { cache.getStats(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsentAsync_Object_Object(SecureCache<String, String> cache) { cache.putIfAbsentAsync("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsentAsync_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putIfAbsentAsync("a", "a", new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsentAsyncEntry_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putIfAbsentAsyncEntry("a", "a", new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAllAsync_Map(SecureCache<String, String> cache) { cache.putAllAsync(Collections.singletonMap("a", "a")); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testSize(SecureCache<String, String> cache) { cache.size(); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testSizeAsync(SecureCache<String, String> cache) { cache.sizeAsync(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetDataContainer(SecureCache<String, String> cache) { cache.getDataContainer(); } @TestCachePermission(AuthorizationPermission.READ) public void testGetCacheEntry_Object(SecureCache<String, String> cache) { cache.getCacheEntry("a"); } @TestCachePermission(AuthorizationPermission.READ) public void testGetCacheEntryAsync_Object(SecureCache<String, String> cache) { cache.getCacheEntryAsync("a"); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetTransactionManager(SecureCache<String, String> cache) { cache.getTransactionManager(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", "b", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAll_Map_long_TimeUnit(SecureCache<String, String> cache) { cache.putAll(Collections.singletonMap("a", "a"), 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutForExternalRead_Object_Object(SecureCache<String, String> cache) { cache.putForExternalRead("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutForExternalRead_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.putForExternalRead("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutForExternalRead_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putForExternalRead("a", "a", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutForExternalRead_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putForExternalRead("a", "a", new EmbeddedMetadata.Builder().lifespan(1, TimeUnit.SECONDS).build()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object(SecureCache<String, String> cache) { cache.replaceAsync("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_Metadata(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.BULK_WRITE) public void testClearAsync(SecureCache<String, String> cache) { cache.clearAsync(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testRemoveInterceptor_Class(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain().removeInterceptor(interceptor.getClass()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.replace("a", "a", "b", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAsync_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.putAsync("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAll_Map_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putAll(Collections.singletonMap("a", "a"), 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplace_Object_Object_Object_Metadata(SecureCache<String, String> cache) { cache.replace("a", "a", "b", metadata); } @TestCachePermission(AuthorizationPermission.LIFECYCLE) public void testStart(SecureCache<String, String> cache) { cache.start(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetDistributionManager(SecureCache<String, String> cache) { cache.getDistributionManager(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAll_Map(SecureCache<String, String> cache) { cache.putAll(Collections.singletonMap("a", "a")); } @TestCachePermission(AuthorizationPermission.NONE) public void testEquals_Object(SecureCache<String, String> cache) { cache.equals(cache); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemove_Object_Object(SecureCache<String, String> cache) { cache.remove("a", "a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testLock_ObjectArray(SecureCache<String, String> cache) throws NotSupportedException, SystemException { try { cache.getTransactionManager().begin(); cache.lock("a"); } finally { cache.getTransactionManager().rollback(); } } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsent_Object_Object_Metadata(SecureCache<String, String> cache) { cache.putIfAbsent("a", "a", metadata); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testRemoveInterceptor_int(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain().addInterceptor(interceptor, 0); cache.getAsyncInterceptorChain().removeInterceptor(0); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetComponentRegistry(SecureCache<String, String> cache) { cache.getComponentRegistry(); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddListener_Object(SecureCache<String, String> cache) { cache.addListener(listener); cache.removeListener(listener); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddListenerAsync_Object(SecureCache<String, String> cache) { CompletionStages.join(cache.addListenerAsync(listener)); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetXAResource(SecureCache<String, String> cache) { // requires setting up a xa transaction, but since we don't test permissions, let's not bother } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetAuthorizationManager(SecureCache<String, String> cache) { cache.getAuthorizationManager(); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testValues(SecureCache<String, String> cache) { cache.values(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemoveAsync_Object(SecureCache<String, String> cache) { cache.removeAsync("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemoveAsyncEntry_Object(SecureCache<String, String> cache) { cache.removeAsyncEntry("a"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPut_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.put("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutIfAbsent_Object_Object_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putIfAbsent("a", "a", 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetAdvancedCache(SecureCache<String, String> cache) { cache.getAdvancedCache(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testReplaceAsync_Object_Object_long_TimeUnit(SecureCache<String, String> cache) { cache.replaceAsync("a", "a", 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetCacheManager(SecureCache<String, String> cache) { cache.getCacheManager(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAllAsync_Map_long_TimeUnit(SecureCache<String, String> cache) { cache.putAllAsync(Collections.singletonMap("a", "a"), 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testGetLockManager(SecureCache<String, String> cache) { cache.getLockManager(); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testGetListeners(SecureCache<String, String> cache) { cache.getListeners(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAllAsync_Map_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.putAllAsync(Collections.singletonMap("a", "a"), 1000, TimeUnit.MILLISECONDS, 1000, TimeUnit.MILLISECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAllAsync_Map_Metadata(SecureCache<String, String> cache) { cache.putAllAsync(Collections.singletonMap("a", "a"), new EmbeddedMetadata.Builder().build()); } @TestCachePermission(AuthorizationPermission.READ) public void testGet_Object(SecureCache<String, String> cache) { cache.get("a"); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetClassLoader(SecureCache<String, String> cache) { cache.getClassLoader(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetRpcManager(SecureCache<String, String> cache) { cache.getRpcManager(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetConflictResolutionManager(SecureCache<String, String> cache) { ConflictManagerFactory.get(cache); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetAsyncInterceptorChain(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemoveAsync_Object_Object(SecureCache<String, String> cache) { cache.removeAsync("a", "a"); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetEvictionManager(SecureCache<String, String> cache) { cache.getEvictionManager(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testGetExpirationManager(SecureCache<String, String> cache) { cache.getExpirationManager(); } @TestCachePermission(AuthorizationPermission.ADMIN) public void testAddInterceptorBefore_CommandInterceptor_Class(SecureCache<String, String> cache) { cache.getAsyncInterceptorChain().addInterceptorBefore(interceptor, InvocationContextInterceptor.class); cache.getAsyncInterceptorChain().removeInterceptor(interceptor.getClass()); } @TestCachePermission(AuthorizationPermission.READ) public void testGetOrDefault_Object_Object(SecureCache<String, String> cache) { cache.get("a"); } @Listener public static class NullListener { } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testGetGroup_String(SecureCache<String, String> cache) { cache.getGroup("someGroup"); } @TestCachePermission(AuthorizationPermission.BULK_WRITE) public void testRemoveGroup_String(SecureCache<String, String> cache) { cache.removeGroup("someGroup"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testPutAll_Map_Metadata(SecureCache<String, String> cache) { cache.putAll(Collections.singletonMap("a", "a"), new EmbeddedMetadata.Builder(). lifespan(10, TimeUnit.SECONDS).maxIdle(5, TimeUnit.SECONDS).build()); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testGetAll_Set(SecureCache<String, String> cache) { cache.getAll(Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testGetAllAsync_Set(SecureCache<String, String> cache) { cache.getAllAsync(Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.BULK_WRITE) public void testGetAndPutAll_Map(SecureCache<String, String> cache) { cache.getAndPutAll(Collections.emptyMap()); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testGetAllCacheEntries_Set(SecureCache<String, String> cache) { cache.getAllCacheEntries(Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.BULK_READ) public void testCacheEntrySet(SecureCache<String, String> cache) { cache.getAdvancedCache().getAllCacheEntries(Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemoveLifespanExpired_Object_Object_Long(SecureCache<String, String> cache) { cache.getAdvancedCache().removeLifespanExpired("a", "a", null); } @TestCachePermission(AuthorizationPermission.WRITE) public void testRemoveMaxIdleExpired_Object_Object(SecureCache<String, String> cache) { cache.getAdvancedCache().removeMaxIdleExpired("a", "a"); } @TestCachePermission(value = AuthorizationPermission.LIFECYCLE) public void testShutdown(SecureCache<String, String> cache) { cache.shutdown(); cache.start(); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddFilteredListener_Object_CacheEventFilter_CacheEventConverter_Set(SecureCache<String, String> cache) { cache.addFilteredListener(listener, keyValueFilter, converter, Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithSubject_Subject(SecureCache<String, String> cache) { } @TestCachePermission(AuthorizationPermission.BULK_WRITE) public void testLockedStream(SecureCache<String, String> cache) { cache.lockedStream(); } @TestCachePermission(AuthorizationPermission.NONE) public void testLockAs_Object(SecureCache<String, String> cache) { cache.lockAs(new Object()); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithEncoding_Class(SecureCache<String, String> cache) { cache.withEncoding(IdentityEncoder.class); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetKeyDataConversion(SecureCache<String, String> cache) { cache.getKeyDataConversion(); } @TestCachePermission(AuthorizationPermission.NONE) public void testGetValueDataConversion(SecureCache<String, String> cache) { cache.getValueDataConversion(); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithEncoding_Class_Class(SecureCache<String, String> cache) { cache.withEncoding(IdentityEncoder.class, IdentityEncoder.class); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithWrapping_Class(SecureCache<String, String> cache) { cache.withWrapping(ByteArrayWrapper.class); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithWrapping_Class_Class(SecureCache<String, String> cache) { cache.withWrapping(ByteArrayWrapper.class, ByteArrayWrapper.class); } @TestCachePermission(AuthorizationPermission.WRITE) public void testCompute_Object_SerializableBiFunction(SecureCache<String, String> cache) { cache.compute("a", (k, v) -> "yes"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testCompute_Object_SerializableBiFunction_long_TimeUnit(SecureCache<String, String> cache) { cache.compute("a", (k, v) -> "yes", 1, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testCompute_Object_SerializableBiFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.compute("a", (k, v) -> "yes", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testCompute_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) { cache.compute("a", (k, v) -> "yes", metadata); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresent_Object_SerializableBiFunction(SecureCache<String, String> cache) { cache.computeIfPresent("a", (k, v) -> "yes"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresent_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) { cache.computeIfPresent("a", (k, v) -> "yes", metadata); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsent_Object_SerializableFunction_Metadata(SecureCache<String, String> cache) { cache.computeIfAbsent("b", k -> "no", metadata); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsent_Object_SerializableFunction(SecureCache<String, String> cache) { cache.computeIfAbsent("b", k -> "no"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsent_Object_SerializableFunction_long_TimeUnit(SecureCache<String, String> cache) { cache.computeIfAbsent("b", k -> "no", 10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsent_Object_SerializableFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.computeIfAbsent("b", k -> "no", 10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMerge_Object_Object_SerializableBiFunction(SecureCache<String, String> cache) { cache.merge("a", "b", (k, v) -> "no"); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMerge_Object_Object_SerializableBiFunction_long_TimeUnit(SecureCache<String, String> cache) { cache.merge("a", "b", (k, v) -> "no", 1, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMerge_Object_Object_SerializableBiFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) { cache.merge("a", "b", (k, v) -> "no", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMerge_Object_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) { cache.merge("a", "b", (k, v) -> "no", metadata); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithKeyEncoding_Class(SecureCache<String, String> cache) { cache.withKeyEncoding(IdentityEncoder.class); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithMediaType_String_String(SecureCache<String, String> cache) { cache.withMediaType(APPLICATION_OBJECT_TYPE, APPLICATION_OBJECT_TYPE); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithMediaType_MediaType_MediaType(SecureCache<String, String> cache) { cache.withMediaType(APPLICATION_OBJECT, APPLICATION_OBJECT); } @TestCachePermission(AuthorizationPermission.NONE) public void testWithStorageMediaType(SecureCache<String, String> cache) { cache.withStorageMediaType(); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddStorageFormatFilteredListener_Object_CacheEventFilter_CacheEventConverter_Set(SecureCache<String, String> cache) { cache.addStorageFormatFilteredListener(listener, keyValueFilter, converter, Collections.emptySet()); } @TestCachePermission(AuthorizationPermission.LISTEN) public void testAddStorageFormatFilteredListenerAsync_Object_CacheEventFilter_CacheEventConverter_Set(SecureCache<String, String> cache) { CompletionStages.join(cache.addStorageFormatFilteredListenerAsync(listener, keyValueFilter, converter, Collections.emptySet())); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsentAsync_Object_SerializableFunction(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfAbsentAsync("b", k -> "no").get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsentAsync_Object_SerializableFunction_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfAbsentAsync("b", k -> "no", 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsentAsync_Object_SerializableFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfAbsentAsync("b", k -> "no", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfAbsentAsync_Object_SerializableFunction_Metadata(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfAbsentAsync("b", k -> "no", metadata).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMergeAsync_Object_Object_SerializableBiFunction(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.mergeAsync("a", "b", (k, v) -> "no").get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMergeAsync_Object_Object_SerializableBiFunction_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.mergeAsync("a", "b", (k, v) -> "no", 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMergeAsync_Object_Object_SerializableBiFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.mergeAsync("a", "b", (k, v) -> "no", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testMergeAsync_Object_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.mergeAsync("a", "b", (k, v) -> "no", metadata).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresentAsync_Object_SerializableBiFunction(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfPresentAsync("a", (k, v) -> "yes").get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresentAsync_Object_SerializableBiFunction_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfPresentAsync("a", (k, v) -> "yes", 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresentAsync_Object_SerializableBiFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfPresentAsync("a", (k, v) -> "yes", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeIfPresentAsync_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeIfPresentAsync("a", (k, v) -> "yes", metadata).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeAsync_Object_SerializableBiFunction(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeAsync("a", (k, v) -> "yes").get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeAsync_Object_SerializableBiFunction_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeAsync("a", (k, v) -> "yes", 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeAsync_Object_SerializableBiFunction_long_TimeUnit_long_TimeUnit(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeAsync("a", (k, v) -> "yes", 1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS).get(); } @TestCachePermission(AuthorizationPermission.WRITE) public void testComputeAsync_Object_SerializableBiFunction_Metadata(SecureCache<String, String> cache) throws ExecutionException, InterruptedException { cache.computeAsync("a", (k, v) -> "yes", metadata).get(); } }
40,237
40.017329
183
java
null
infinispan-main/core/src/test/java/org/infinispan/security/BaseAuthorizationTest.java
package org.infinispan.security; import java.util.Map; import javax.security.auth.Subject; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; public abstract class BaseAuthorizationTest extends SingleCacheManagerTest { static final Log log = LogFactory.getLog(CacheAuthorizationTest.class); static final Subject ADMIN; static final Map<AuthorizationPermission, Subject> SUBJECTS; static { // Initialize one subject per permission SUBJECTS = TestingUtil.makeAllSubjects(); ADMIN = SUBJECTS.get(AuthorizationPermission.ALL); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { final GlobalConfigurationBuilder global = new GlobalConfigurationBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .principalRoleMapper(new IdentityRoleMapper()); for (AuthorizationPermission perm : AuthorizationPermission.values()) { globalRoles.role(perm.toString()).permission(perm); } ConfigurationBuilder config = createCacheConfiguration(global); return Security.doAs(ADMIN, () -> TestCacheManagerFactory.createCacheManager(global, config)); } protected ConfigurationBuilder createCacheConfiguration(GlobalConfigurationBuilder global) { final ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.transaction().lockingMode(LockingMode.PESSIMISTIC).invocationBatching().enable(); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); for (AuthorizationPermission perm : AuthorizationPermission.values()) { authConfig.role(perm.toString()); } return config; } @Override protected void setup() throws Exception { cacheManager = createCacheManager(); } @Override protected void teardown() { Security.doAs(ADMIN, () -> BaseAuthorizationTest.super.teardown()); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> cacheManager.getCache().clear()); } }
2,757
38.971014
102
java
null
infinispan-main/core/src/test/java/org/infinispan/security/SecurityConfigurationTest.java
package org.infinispan.security; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.CacheContainer; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; @Test(groups="functional", testName="security.SecurityConfigurationTest") public class SecurityConfigurationTest extends AbstractInfinispanTest { @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = ".*ISPN000414.*") public void testIncompleteConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.security().authorization().enable().role("reader"); withCacheManager(() -> createCacheManager(builder), CacheContainer::getCache); } }
982
39.958333
84
java
null
infinispan-main/core/src/test/java/org/infinispan/security/DynamicRBACTest.java
package org.infinispan.security; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.test.TestingUtil.extractField; 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.util.Map; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.ClusterPermissionMapper; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.topology.ClusterTopologyManager; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.DynamicRBACTest") public class DynamicRBACTest extends MultipleCacheManagersTest { static final Subject ADMIN = TestingUtil.makeSubject("admin"); static final Subject SUBJECT_A = TestingUtil.makeSubject("A"); static final Subject SUBJECT_B = TestingUtil.makeSubject("B"); private ClusterRoleMapper crm; private ClusterPermissionMapper cpm; @Override protected void createCacheManagers() throws Throwable { Security.doAs(ADMIN, () -> { addClusterEnabledCacheManager(getGlobalConfigurationBuilder(), getConfigurationBuilder()); addClusterEnabledCacheManager(getGlobalConfigurationBuilder(), getConfigurationBuilder()); waitForClusterToForm(); crm = (ClusterRoleMapper) cacheManagers.get(0).getCacheManagerConfiguration().security().authorization().principalRoleMapper(); crm.grant("admin", "admin"); cpm = (ClusterPermissionMapper) cacheManagers.get(0).getCacheManagerConfiguration().security().authorization().rolePermissionMapper(); await(cpm.addRole(Role.newRole("wizard", true, AuthorizationPermission.ALL_WRITE))); await(cpm.addRole(Role.newRole("cleric", true, AuthorizationPermission.ALL_READ))); return null; }); } private ConfigurationBuilder getConfigurationBuilder() { ConfigurationBuilder config = TestCacheManagerFactory.getDefaultCacheConfiguration(true); config.clustering().cacheMode(CacheMode.DIST_SYNC); AuthorizationConfigurationBuilder authConfig = config.security().authorization().enable(); authConfig.role("reader").role("writer").role("admin"); return config; } private GlobalConfigurationBuilder getGlobalConfigurationBuilder() { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .groupOnlyMapping(false) .principalRoleMapper(new ClusterRoleMapper()) .rolePermissionMapper(new ClusterPermissionMapper()); globalRoles .role("reader").permission(AuthorizationPermission.ALL_READ) .role("writer").permission(AuthorizationPermission.ALL_WRITE) .role("admin").permission(AuthorizationPermission.ALL); return global; } public void testClusterPrincipalMapper() { crm.grant("writer", "A"); Security.doAs(SUBJECT_A, () -> { cacheManagers.get(0).getCache().put("key", "value"); return null; }); crm.grant("reader", "B"); Security.doAs(SUBJECT_B, () -> { assertEquals("value", cacheManagers.get(0).getCache().get("key")); return null; }); } public void testClusterPermissionMapper() { Map<String, Role> roles = cpm.getAllRoles(); assertEquals(2, roles.size()); assertTrue(roles.containsKey("wizard")); assertTrue(roles.containsKey("cleric")); Cache<String, String> cpmCache = Security.doAs(ADMIN, () -> { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.security().authorization().enable().roles("admin", "wizard", "cleric"); return cacheManagers.get(0).createCache("cpm", builder.build(cacheManagers.get(0).getCacheManagerConfiguration())); }); Security.doAs(TestingUtil.makeSubject("wizard"), () -> { cpmCache.put("key", "value"); return null; }); Security.doAs(TestingUtil.makeSubject("cleric"), () -> { assertEquals("value", cpmCache.get("key")); return null; }); await(cpm.removeRole("cleric")); roles = cpm.getAllRoles(); assertEquals(1, roles.size()); } public void testJoiner() { crm.grant("wizard", "gandalf"); Cache<?, ?> crmCache = extractField(crm, "clusterRoleMap"); ClusterTopologyManager crmTM = TestingUtil.extractComponent(crmCache, ClusterTopologyManager.class); crmTM.setRebalancingEnabled(false); await(cpm.addRole(Role.newRole("rogue", true, AuthorizationPermission.LISTEN))); Cache<?, ?> cpmCache = extractField(cpm, "clusterPermissionMap"); ClusterTopologyManager cpmTM = TestingUtil.extractComponent(cpmCache, ClusterTopologyManager.class); cpmTM.setRebalancingEnabled(false); try { EmbeddedCacheManager joiner = Security.doAs(ADMIN, () -> addClusterEnabledCacheManager(getGlobalConfigurationBuilder(), getConfigurationBuilder(), new TransportFlags().withFD(true)) ); ClusterRoleMapper joinerCrm = Security.doAs(ADMIN, () -> (ClusterRoleMapper) joiner.getCacheManagerConfiguration().security().authorization().principalRoleMapper()); TestingUtil.TestPrincipal gandalf = new TestingUtil.TestPrincipal("gandalf"); assertTrue(crm.principalToRoles(gandalf).contains("wizard")); assertTrue(crm.list("gandalf").contains("wizard")); assertFalse(joinerCrm.principalToRoles(gandalf).contains("wizard")); assertFalse(joinerCrm.list("gandalf").contains("wizard")); ClusterPermissionMapper joinerCpm = Security.doAs(ADMIN, () -> (ClusterPermissionMapper) joiner.getCacheManagerConfiguration().security().authorization().rolePermissionMapper()); Role rogue0 = cpm.getRole("rogue"); assertNotNull(rogue0); Role rogue2 = joinerCpm.getRole("rogue"); assertNull(rogue2); } finally { crmTM.setRebalancingEnabled(true); cpmTM.setRebalancingEnabled(true); } } @AfterClass(alwaysRun = true) @Override protected void destroy() { Security.doAs(ADMIN, () -> { DynamicRBACTest.super.destroy(); return null; }); } @Override protected void clearContent() { Security.doAs(ADMIN, () -> { cacheManagers.forEach(cm -> cm.getCache().clear()); return null; }); } }
7,323
44.209877
187
java
null
infinispan-main/core/src/test/java/org/infinispan/security/ClusteredSecureCacheTest.java
package org.infinispan.security; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.security.Principal; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Function; import javax.security.auth.Subject; import org.infinispan.Cache; import org.infinispan.commons.marshall.AbstractExternalizer; import org.infinispan.configuration.cache.AuthorizationConfigurationBuilder; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalAuthorizationConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.ClusterExecutor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.security.mappers.IdentityRoleMapper; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; @Test(groups = "functional", testName = "security.ClusteredSecureCacheTest") public class ClusteredSecureCacheTest extends MultipleCacheManagersTest { static final Subject ADMIN; static final Map<AuthorizationPermission, Subject> SUBJECTS; static { // Initialize one subject per permission SUBJECTS = TestingUtil.makeAllSubjects(); ADMIN = SUBJECTS.get(AuthorizationPermission.ALL); } public CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } @Override protected void createCacheManagers() throws Throwable { final GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); final ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode()); GlobalAuthorizationConfigurationBuilder globalRoles = global.security().authorization().enable() .principalRoleMapper(new IdentityRoleMapper()); for (AuthorizationPermission perm : AuthorizationPermission.values()) { globalRoles.role(perm.toString()).permission(perm); } global.serialization().addAdvancedExternalizer(4321, new SecureConsumer.Externalizer()); AuthorizationConfigurationBuilder authConfig = builder.security().authorization().enable(); for (AuthorizationPermission perm : AuthorizationPermission.values()) { authConfig.role(perm.toString()); } Security.doAs(ADMIN,() -> { createCluster(global, builder, 2); waitForClusterToForm(); }); } @Override @AfterClass(alwaysRun = true) protected void destroy() { Security.doAs(ADMIN, () -> ClusteredSecureCacheTest.super.destroy()); } @Override @AfterMethod(alwaysRun = true) protected void clearContent() throws Throwable { Security.doAs(ADMIN, () -> { try { ClusteredSecureCacheTest.super.clearContent(); } catch (Throwable e) { throw new RuntimeException(e); } }); } public void testClusteredSecureCache() { Security.doAs(ADMIN, () -> { Cache<String, String> cache1 = cache(0); Cache<String, String> cache2 = cache(1); cache1.put("a", "a"); cache2.put("b", "b"); assertEquals("a", cache2.get("a")); assertEquals("b", cache1.get("b")); }); } public void testSecureClusteredExecutor() { ClusterExecutor executor = Security.doAs(SUBJECTS.get(AuthorizationPermission.EXEC), () -> manager(0).executor()); for (final AuthorizationPermission perm : AuthorizationPermission.values()) { Subject subject = SUBJECTS.get(perm); Security.doAs(subject, () -> { executor.allNodeSubmission().submitConsumer( new SecureConsumer(), (a, v, t) -> { if (t != null) { throw new RuntimeException(t); } else { // Ensure the Subject returned by the consumer matches the one it was invoked with for(Principal principal : v.getPrincipals()) { subject.getPrincipals().stream().filter(p -> p.getName().equals(principal.getName())).findFirst().orElseThrow(); } } } ); }); } } static class SecureConsumer implements Function<EmbeddedCacheManager, Subject>, Serializable { @Override public Subject apply(EmbeddedCacheManager m) { return Security.getSubject(); } public static class Externalizer extends AbstractExternalizer<SecureConsumer> { @Override public Set<Class<? extends SecureConsumer>> getTypeClasses() { return Collections.singleton(SecureConsumer.class); } @Override public void writeObject(ObjectOutput output, SecureConsumer task) throws IOException { } @Override public SecureConsumer readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new SecureConsumer(); } } } }
5,335
36.577465
139
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/RxJavaPublisherTest.java
package org.infinispan.reactive; import static org.testng.AssertJUnit.fail; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.schedulers.Schedulers; @Test(groups = "functional", testName = "reactive.RxJavaPublisherTest") public class RxJavaPublisherTest extends AbstractInfinispanTest { public void testExceptionHandling() { try { Flowable.just(new Object()) .subscribeOn(Schedulers.from(task -> { // Our undelivered handler ignores lifecycle exceptions - so piggy back on that throw new IllegalLifecycleStateException(); })) .subscribe(); fail("The error should have been thrown from subscribe!"); } catch (NullPointerException e) { Exceptions.assertException(IllegalLifecycleStateException.class, e.getCause()); } } }
1,073
36.034483
97
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/publisher/impl/RehashClusterPublisherManagerTest.java
package org.infinispan.reactive.publisher.impl; import static org.infinispan.context.Flag.STATE_TRANSFER_PROGRESS; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; import static org.testng.AssertJUnit.assertEquals; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.test.ExceptionRunnable; import org.infinispan.commons.util.EnumUtil; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.distribution.MagicKey; import org.infinispan.reactive.publisher.PublisherReducers; import org.infinispan.reactive.publisher.impl.commands.reduction.ReductionPublisherRequestCommand; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.Mocks; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.util.ControlledConsistentHashFactory; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Class that tests various rehash scenarios for ClusterPublisherManager to ensure it handles these cases properly * @author wburns * @since 10.0 */ @Test(groups = "functional", testName = "reactive.publisher.impl.RehashClusterPublisherManagerTest") public class RehashClusterPublisherManagerTest extends MultipleCacheManagersTest { private static final int[][] START_SEGMENT_OWNERS = new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}; protected ControlledConsistentHashFactory factory; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builderUsed = new ConfigurationBuilder(); factory = new ControlledConsistentHashFactory.Default(START_SEGMENT_OWNERS); builderUsed.clustering().cacheMode(CacheMode.DIST_SYNC).hash().consistentHashFactory(factory).numSegments(4); createClusteredCaches(4, TestDataSCI.INSTANCE, builderUsed); } @BeforeMethod protected void beforeMethod() throws Exception { // Make sure to reset the segments back to original factory.setOwnerIndexes(START_SEGMENT_OWNERS); factory.triggerRebalance(cache(0)); TestingUtil.waitForNoRebalance(caches()); Cache cache2 = cache(2); LocalPublisherManager lpm = TestingUtil.extractComponent(cache2, LocalPublisherManager.class); } @DataProvider(name = "GuaranteeParallelEntry") public Object[][] collectionAndVersionsProvider() { return Arrays.stream(DeliveryGuarantee.values()) .flatMap(dg -> Stream.of(Boolean.TRUE, Boolean.FALSE) .flatMap(parallel -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(entry -> new Object[]{dg, parallel, entry}))) .toArray(Object[][]::new); } private void triggerRebalanceSegment2MovesToNode0() throws Exception { // Notice that node2 lost the 2 segment and now node0 is the primary // {0, 1}, {1, 2}, {2, 3}, {3, 0} - before // {0, 1}, {1, 2}, {0, 3}, {3, 0} - after factory.setOwnerIndexes(new int[][]{{0, 1}, {1, 2}, {0, 3}, {3, 0}}); factory.triggerRebalance(cache(0)); TestingUtil.waitForNoRebalance(caches()); } Function<Map<MagicKey, Object>, Set<MagicKey>> toKeys(boolean useKeys) { if (useKeys) { return map -> { Set<MagicKey> set = new HashSet<>(); map.keySet().stream() // We purposely don't provide the key that maps to segment 1 to make sure it isn't returned .filter(key -> key.getSegment() != 1) .forEach(set::add); // We also add a key that isn't in the cache to make sure it doesn't break stuff set.add(new MagicKey(cache(3))); return set; }; } else { return map -> null; } } @Test(dataProvider = "GuaranteeParallelEntry") public void testSegmentMovesToOriginatorWhileRetrievingPublisher(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) throws Exception { Cache cache2 = cache(2); CheckPoint checkPoint = new CheckPoint(); // Block on the checkpoint when it is requesting segment 2 from node 2 (need both as different methods are invoked // if the invocation is parallel) Mocks.blockingMock(checkPoint, InternalDataContainer.class, cache2, (stub, m) -> stub.when(m).publisher(Mockito.eq(2))); Mocks.blockingMock(checkPoint, InternalDataContainer.class, cache2, (stub, m) -> stub.when(m).publisher(Mockito.eq(IntSets.immutableSet(2)))); int expectedAmount = caches().size(); runCommand(deliveryGuarantee, parallel, isEntry, expectedAmount, () -> { // Let it process the publisher checkPoint.triggerForever(Mocks.BEFORE_RELEASE); Future<?> rebalanceFuture = fork(this::triggerRebalanceSegment2MovesToNode0); // Now let the stream be processed checkPoint.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS); checkPoint.triggerForever(Mocks.AFTER_RELEASE); rebalanceFuture.get(10, TimeUnit.SECONDS); }); } @Test(dataProvider = "GuaranteeParallelEntry") public void testSegmentMovesToOriginatorJustBeforeSendingRemoteKey(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) throws Exception { testSegmentMovesToOriginatorJustBeforeSendingRemote(deliveryGuarantee, parallel, isEntry, true); } @Test(dataProvider = "GuaranteeParallelEntry") public void testSegmentMovesToOriginatorJustBeforeSendingRemoteNoKey(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) throws Exception { testSegmentMovesToOriginatorJustBeforeSendingRemote(deliveryGuarantee, parallel, isEntry, false); } private void testSegmentMovesToOriginatorJustBeforeSendingRemote(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry, boolean useKeys) throws Exception { Cache cache0 = cache(0); Address cache2Address = address(2); CheckPoint checkPoint = new CheckPoint(); // Always let it finish once released checkPoint.triggerForever(Mocks.AFTER_RELEASE); // Block on about to send the remote command to node2 RpcManager original = Mocks.blockingMock(checkPoint, RpcManager.class, cache0, (stub, m) -> stub.when(m).invokeCommand(eq(cache2Address), isA(ReductionPublisherRequestCommand.class), any(), any())); int expectedAmount = caches().size(); // If it is at most once, we don't retry the segment so the count will be off by 1 if (deliveryGuarantee == DeliveryGuarantee.AT_MOST_ONCE) { expectedAmount -= 1; } // When we are using keys, we explicitly don't pass one of them if (useKeys) { expectedAmount--; } try { runCommand(deliveryGuarantee, parallel, isEntry, expectedAmount, () -> { checkPoint.awaitStrict(Mocks.BEFORE_INVOCATION, 10, TimeUnit.SECONDS); triggerRebalanceSegment2MovesToNode0(); checkPoint.triggerForever(Mocks.BEFORE_RELEASE); }, toKeys(useKeys)); } finally { if (original != null) { TestingUtil.replaceComponent(cache0, RpcManager.class, original, true); } } } @Test(dataProvider = "GuaranteeParallelEntry") public void testSegmentMovesToOriginatorJustBeforePublisherCompletes(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) throws Exception { Cache cache2 = cache(2); CheckPoint checkPoint = new CheckPoint(); // Always let it process the publisher checkPoint.triggerForever(Mocks.BEFORE_RELEASE); // Block on the publisher LocalPublisherManager<?, ?> lpm = TestingUtil.extractComponent(cache2, LocalPublisherManager.class); LocalPublisherManager<?, ?> spy = spy(lpm); Answer<SegmentAwarePublisherSupplier<?>> blockingLpmAnswer = invocation -> { SegmentAwarePublisherSupplier<?> result = (SegmentAwarePublisherSupplier<?>) invocation.callRealMethod(); return Mocks.blockingPublisherAware(result, checkPoint); }; // Depending upon if it is parallel or not, it can invoke either method doAnswer(blockingLpmAnswer).when(spy) .entryPublisher(eq(IntSets.immutableSet(2)), any(), any(), eq(EnumUtil.bitSetOf(STATE_TRANSFER_PROGRESS)), any(), any()); TestingUtil.replaceComponent(cache2, LocalPublisherManager.class, spy, true); int expectedAmount = caches().size(); runCommand(deliveryGuarantee, parallel, isEntry, expectedAmount, () -> { Future<?> rebalanceFuture = fork(this::triggerRebalanceSegment2MovesToNode0); // Now let the stream be processed checkPoint.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS); checkPoint.triggerForever(Mocks.AFTER_RELEASE); rebalanceFuture.get(10, TimeUnit.SECONDS); }); } private void runCommand(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry, int expectedAmount, ExceptionRunnable performOperation) throws Exception { runCommand(deliveryGuarantee, parallel, isEntry, expectedAmount, performOperation, map -> null); } private void runCommand(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry, int expectedAmount, ExceptionRunnable performOperation, Function<Map<MagicKey, Object>, Set<MagicKey>> keysHandler) throws Exception { Map<MagicKey, Object> entries = new HashMap<>(); // Insert a key into each cache - so we always have values to find on each node - means we have 1 entry per segment as well for (Cache<MagicKey, Object> cache : this.<MagicKey, Object>caches()) { MagicKey key = new MagicKey(cache); Object value = key.toString(); cache.put(key, value); entries.put(key, value); } Set<MagicKey> keys = keysHandler.apply(entries); // We always fork, as some methods may block a resource that is invoked on the main thread Future<CompletionStage<Long>> future = fork(() -> { ClusterPublisherManager<MagicKey, String> cpm = TestingUtil.extractComponent(cache(0), ClusterPublisherManager.class); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, null, keys, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, null, keys, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } return stageCount; }); performOperation.run(); Long actualCount = future.get(10, TimeUnit.SECONDS) .toCompletableFuture().get(10, TimeUnit.SECONDS); // Should be 1 entry per node assertEquals(expectedAmount, actualCount.intValue()); } }
11,857
43.74717
131
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/publisher/impl/PersistenceLocalPublisherManagerTest.java
package org.infinispan.reactive.publisher.impl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; @Test(groups = "functional", testName = "reactive.publisher.impl.PersistenceLocalPublisherManagerTest") @InCacheMode({CacheMode.REPL_SYNC, CacheMode.DIST_SYNC}) public class PersistenceLocalPublisherManagerTest extends SimpleLocalPublisherManagerTest { @Override ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder configurationBuilder = super.cacheConfiguration(); configurationBuilder.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); configurationBuilder.memory().maxCount(10); return configurationBuilder; } }
908
42.285714
103
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/publisher/impl/SimpleClusterPublisherManagerTest.java
package org.infinispan.reactive.publisher.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.util.EnumUtil; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.NullCacheEntry; import org.infinispan.context.InvocationContext; import org.infinispan.context.impl.NonTxInvocationContext; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.marshall.core.MarshallableFunctions; import org.infinispan.reactive.RxJavaInterop; import org.infinispan.reactive.publisher.PublisherReducers; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.util.function.SerializableBinaryOperator; import org.infinispan.util.function.SerializableFunction; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.subscribers.TestSubscriber; /** * Test class for simple ClusterPublisherManager to ensure arguments are adhered to * @author wburns * @since 10.0 */ @Test(groups = "functional", testName = "reactive.publisher.impl.SimpleClusterPublisherManagerTest") @InCacheMode({CacheMode.REPL_SYNC, CacheMode.DIST_SYNC}) public class SimpleClusterPublisherManagerTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, false); // Reduce number of segments a bit builder.clustering().hash().numSegments(10); createCluster(builder, 4); waitForClusterToForm(); } private Map<Integer, String> insert(Cache<Integer, String> cache) { int amount = 12; Map<Integer, String> values = new HashMap<>(amount); Map<Integer, IntSet> keysBySegment = log.isTraceEnabled() ? new HashMap<>() : null; KeyPartitioner kp = TestingUtil.extractComponent(cache, KeyPartitioner.class); IntStream.range(0, amount).forEach(i -> { values.put(i, "value-" + i); if (keysBySegment != null) { int segment = kp.getSegment(i); IntSet keys = keysBySegment.computeIfAbsent(segment, IntSets::mutableEmptySet); keys.set(i); } }); if (keysBySegment != null) { log.tracef("Keys by segment are: " + keysBySegment); } cache.putAll(values); return values; } private ClusterPublisherManager<Integer, String> cpm(Cache<Integer, String> cache) { return TestingUtil.extractComponent(cache, ClusterPublisherManager.class); } @DataProvider(name = "GuaranteeParallelEntry") public Object[][] collectionAndVersionsProvider() { return Arrays.stream(DeliveryGuarantee.values()) .flatMap(dg -> Stream.of(Boolean.TRUE, Boolean.FALSE) .flatMap(parallel -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(entry -> new Object[]{dg, parallel, entry}))) .toArray(Object[][]::new); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCount(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); assertEquals(insertAmount, actualCount.intValue()); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCountSegments(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); IntSet targetSegments = IntSets.mutableEmptySet(); for (int i = 2; i <= 8; ++i) { targetSegments.set(i); } ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, targetSegments, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, targetSegments, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); int expected = findHowManyInSegments(insertAmount, targetSegments, TestingUtil.extractComponent(cache, KeyPartitioner.class)); assertEquals(expected, actualCount.intValue()); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCountSpecificKeys(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); Set<Integer> keysToInclude = new HashSet<>(); for (int i = 0; i < insertAmount; i += 2) { keysToInclude.add(i); } // This one won't work as it isn't in the cache keysToInclude.add(insertAmount + 1); ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); // We added all the even ones to the keysToInclude set int expected = insertAmount / 2; assertEquals(expected, actualCount.intValue()); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCountEmptyKeys(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); // This empty set filters everything, but the computation must still complete Set<Integer> keysToInclude = new HashSet<>(); ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); int expected = 0; assertEquals(expected, actualCount.intValue()); } @Test(dataProvider = "GuaranteeParallelEntry") public void testReduceTransformerOnlyIdentityEntriesFiltered(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); // The identity element must still be returned, even if only the transformer (but not the finalizer) function takes care of it ClusterPublisherManager<Integer, String> cpm = cpm(cache); int identity = 0; SerializableBinaryOperator<Integer> binOp = Integer::sum; CompletionStage<?> stage; if (isEntry) { stage = cpm.entryReduction(parallel, null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, (SerializableFunction<Publisher<CacheEntry<Integer, String>>, CompletionStage<Integer>>) iPublisher -> Flowable.fromPublisher(iPublisher) .filter(ce -> false) .map(RxJavaInterop.entryToKeyFunction()) .reduce(identity, binOp::apply) .toCompletionStage(), PublisherReducers.reduce(binOp)); } else { stage = cpm.keyReduction(parallel, null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, (SerializableFunction<Publisher<Integer>, CompletionStage<Integer>>) iPublisher -> Flowable.fromPublisher(iPublisher) .filter(ce -> false) .reduce(identity, binOp::apply) .toCompletionStage(), PublisherReducers.reduce(binOp)); } Object actual = stage.toCompletableFuture().join(); Object expected = identity; assertSame(expected, actual); } @Test(dataProvider = "GuaranteeParallelEntry") public void testReduceWithoutIdentityEmptyKeys(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); // This empty set filters everything, but the computation must still complete Set<Integer> keysToInclude = new HashSet<>(); // Using a reduce function without explicit identity tests the special case where completion-stages terminate with null ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<?> stage; if (isEntry) { Function<Publisher<CacheEntry<Integer, String>>, CompletionStage<CacheEntry<Integer, String>>> function = PublisherReducers.reduce((SerializableBinaryOperator<CacheEntry<Integer, String>>) (e1, e2) -> e1); // reduce without identity stage = cpm.entryReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, function, function); } else { Function<Publisher<Integer>, CompletionStage<Integer>> function = PublisherReducers.reduce((SerializableBinaryOperator<Integer>) (k1, k2) -> k1); // reduce without identity stage = cpm.keyReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, function, function); } Object result = stage.toCompletableFuture().join(); assertNull(result); } @Test(dataProvider = "GuaranteeParallelEntry") public void testReduceWithoutIdentityNonMatchingKeys(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); Set<Integer> keysToInclude = new HashSet<>(); keysToInclude.add(insertAmount + 1); // Not in the cache // Using a reduce function without explicit identity tests the special case where completion-stages terminate with null ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<?> stage; if (isEntry) { Function<Publisher<CacheEntry<Integer, String>>, CompletionStage<CacheEntry<Integer, String>>> function = PublisherReducers.reduce((SerializableBinaryOperator<CacheEntry<Integer, String>>)(e1, e2) -> e1); // reduce without identity stage = cpm.entryReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, function, function); } else { Function<Publisher<Integer>, CompletionStage<Integer>> function = PublisherReducers.reduce((SerializableBinaryOperator<Integer>)(k1, k2) -> k1); // reduce without identity stage = cpm.keyReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, function, function); } Object result = stage.toCompletableFuture().join(); assertNull(result); } @Test(dataProvider = "GuaranteeParallelEntry") public void testReduceTransformerOnlyIdentityEmptyKeys(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); // This empty set filters everything, but the computation must still complete Set<Integer> keysToInclude = Collections.emptySet(); // The identity element must still be returned, even if only the transformer (but not the finalizer) function takes care of it ClusterPublisherManager<Integer, String> cpm = cpm(cache); Object identity; CompletionStage<?> stage; if (isEntry) { SerializableBinaryOperator<CacheEntry<Integer, String>> binOp = (e1, e2) -> e1; identity = NullCacheEntry.getInstance(); stage = cpm.entryReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.reduce((CacheEntry<Integer, String>) identity, binOp), PublisherReducers.reduce(binOp)); } else { SerializableBinaryOperator<Integer> binOp = (k1, k2) -> k1; identity = 0; stage = cpm.keyReduction(parallel, null, keysToInclude, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.reduce((Integer) identity, binOp), PublisherReducers.reduce(binOp)); } Object actual = stage.toCompletableFuture().join(); Object expected = identity; assertSame(expected, actual); } @Test(dataProvider = "GuaranteeEntry") public void testPublisherEmptyKeys(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); performPublisherOperation(deliveryGuarantee, isEntry, null, Collections.emptySet(), null, Collections.emptyMap()); } @Test(dataProvider = "GuaranteeEntry") public void testPublisherWithReduce(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); assertTrue(insertAmount > 0); SegmentPublisherSupplier<Integer> publisher; if (isEntry) { publisher = cpm(cache).entryPublisher(null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, (SerializableFunction<Publisher<CacheEntry<Integer, String>>, Publisher<Integer>>) p -> Flowable.fromPublisher(p) .map(RxJavaInterop.entryToKeyFunction()) .reduce(0, Integer::sum).toFlowable()); } else { publisher = cpm(cache).keyPublisher(null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, (SerializableFunction<Publisher<Integer>, Publisher<Integer>>) p -> Flowable.fromPublisher(p) .reduce(0, Integer::sum).toFlowable()); } List<Integer> results = Flowable.fromPublisher(publisher.publisherWithoutSegments()) .toList(1) .blockingGet(); // We should have gotten a value at least... assertTrue(results.size() > 0); int total = 0; for (int value : results) { total += value; if (total < 0) { fail("Integer overflowed with: " + results); } } assertEquals(insertAmount * (insertAmount - 1) / 2, total); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCountWithContext(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); InvocationContext ctx = new NonTxInvocationContext(null); // These elements are removed or null - so aren't counted ctx.putLookedUpEntry(0, NullCacheEntry.getInstance()); ctx.putLookedUpEntry(insertAmount - 2, Mockito.when(Mockito.mock(CacheEntry.class).isRemoved()).thenReturn(true).getMock()); // This is an extra entry only in this context ctx.putLookedUpEntry(insertAmount + 1, new ImmortalCacheEntry(insertAmount + 1, insertAmount + 1)); ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, null, null, ctx, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, null, null, ctx, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); // We exclude 2 keys and add 1 int expected = insertAmount - 1; assertEquals(expected, actualCount.intValue()); } @Test(dataProvider = "GuaranteeParallelEntry") public void testCountWithContextSegments(DeliveryGuarantee deliveryGuarantee, boolean parallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); int insertAmount = insert(cache).size(); IntSet targetSegments = IntSets.mutableEmptySet(); for (int i = 2; i <= 8; ++i) { targetSegments.set(i); } KeyPartitioner keyPartitioner = TestingUtil.extractComponent(cache, KeyPartitioner.class); // We only expect a subset based on the provided segments int expected = findHowManyInSegments(insertAmount, targetSegments, keyPartitioner); AtomicInteger contextChange = new AtomicInteger(); InvocationContext ctx = new NonTxInvocationContext(null); // These elements are removed or null - so aren't counted ctx.putLookedUpEntry(0, NullCacheEntry.getInstance()); ctx.putLookedUpEntry(insertAmount - 2, Mockito.when(Mockito.mock(CacheEntry.class).isRemoved()).thenReturn(true).getMock()); // This is an extra entry only in this context ctx.putLookedUpEntry(insertAmount + 1, new ImmortalCacheEntry(insertAmount + 1, insertAmount + 1)); // For every entry that is in the context, we only count values that are in the segments that were provided ctx.forEachEntry((o, e) -> { if (targetSegments.contains(keyPartitioner.getSegment(o))) { contextChange.addAndGet((e.isRemoved() || e.isNull()) ? -1 : 1); } }); ClusterPublisherManager<Integer, String> cpm = cpm(cache); CompletionStage<Long> stageCount; if (isEntry) { stageCount = cpm.entryReduction(parallel, targetSegments, null, ctx, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } else { stageCount = cpm.keyReduction(parallel, targetSegments, null, ctx, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, PublisherReducers.count(), PublisherReducers.add()); } Long actualCount = stageCount.toCompletableFuture().join(); // Two keys are removed and another is new assertEquals(expected + contextChange.get(), actualCount.intValue()); } static int findHowManyInSegments(int insertAmount, IntSet targetSegments, KeyPartitioner kp) { int count = 0; for (int i = 0; i < insertAmount; ++i) { int segment = kp.getSegment(i); if (targetSegments.contains(segment)) { count++; } } return count; } @AfterMethod public void verifyNoDanglingRequests() { for (Cache cache : caches()) { // The publishers are closed asynchronously from processing of results eventuallyEquals(0, () -> TestingUtil.extractComponent(cache, PublisherHandler.class).openPublishers()); } } @DataProvider(name = "GuaranteeEntry") public Object[][] guaranteesEntryType() { return Arrays.stream(DeliveryGuarantee.values()) .flatMap(dg -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(entry -> new Object[]{dg, entry})) .toArray(Object[][]::new); } private <I> void performPublisherOperation(DeliveryGuarantee deliveryGuarantee, boolean isEntry, IntSet segments, Set<Integer> keys, InvocationContext context, Map<Integer, String> expectedValues) { ClusterPublisherManager<Integer, String> cpm = cpm(cache(0)); SegmentPublisherSupplier<?> publisher; Consumer<Object> assertConsumer; if (isEntry) { publisher = cpm.entryPublisher(segments, keys, context, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, MarshallableFunctions.identity()); assertConsumer = obj -> { Map.Entry<Object, Object> entry = (Map.Entry) obj; Object value = expectedValues.get(entry.getKey()); assertEquals(value, entry.getValue()); }; } else { publisher = cpm.keyPublisher(segments, keys, context, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, MarshallableFunctions.identity()); assertConsumer = obj -> assertTrue(expectedValues.containsKey(obj)); } int expectedSize = expectedValues.size(); List<?> results = Flowable.fromPublisher(publisher.publisherWithoutSegments()) .toList(Math.max(expectedSize, 1)) .blockingGet(); if (expectedSize != results.size()) { log.fatal("SIZE MISMATCH expected: " + expectedValues + " was: " + results); } assertEquals(expectedSize, results.size()); results.forEach(assertConsumer); } @Test(dataProvider = "GuaranteeEntry") public void testSimpleIteration(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> values = insert(cache); performPublisherOperation(deliveryGuarantee, isEntry, null, null, null, values); } @Test(dataProvider = "GuaranteeEntry") public void testIterationSegments(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> values = insert(cache); IntSet targetSegments = IntSets.mutableEmptySet(); for (int i = 2; i <= 7; ++i) { targetSegments.set(i); } removeEntriesNotInSegment(values, TestingUtil.extractComponent(cache, KeyPartitioner.class), targetSegments); performPublisherOperation(deliveryGuarantee, isEntry, targetSegments, null, null, values); } @Test(dataProvider = "GuaranteeEntry") public void testContextIteration(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> values = insert(cache); InvocationContext ctx = new NonTxInvocationContext(null); // These elements are removed or null - so aren't counted ctx.putLookedUpEntry(0, NullCacheEntry.getInstance()); values.remove(0); ctx.putLookedUpEntry(7, Mockito.when(Mockito.mock(CacheEntry.class).isRemoved()).thenReturn(true).getMock()); values.remove(7); // This is an extra entry only in this context ctx.putLookedUpEntry(156, new ImmortalCacheEntry(156, "value-" + 156)); values.put(156, "value-" + 156); performPublisherOperation(deliveryGuarantee, isEntry, null, null, ctx, values); } @Test(dataProvider = "GuaranteeEntry") public void testSpecificKeyIteration(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> values = insert(cache); Set<Integer> keysToUse = new HashSet<>(); keysToUse.add(1); keysToUse.add(4); keysToUse.add(7); keysToUse.add(123); values.entrySet().removeIf(e -> !keysToUse.contains(e.getKey())); performPublisherOperation(deliveryGuarantee, isEntry, null, keysToUse, null, values); } @Test(dataProvider = "GuaranteeEntry") public void testMapIteration(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); ClusterPublisherManager<Integer, String> cpm = cpm(cache(0)); Map<Integer, String> values = insert(cache); List<String> mappedValues; SegmentPublisherSupplier<String> publisher; if (isEntry) { mappedValues = values.entrySet().stream().map(Map.Entry::getValue).map(String::valueOf).collect(Collectors.toList()); publisher = cpm.entryPublisher(null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, (SerializableFunction<Publisher<CacheEntry<Integer, String>>, Publisher<String>>) entryPublisher -> Flowable.fromPublisher(entryPublisher).map(Map.Entry::getValue).map(String::valueOf)); } else { mappedValues = values.keySet().stream().map(String::valueOf).collect(Collectors.toList()); publisher = cpm.keyPublisher(null, null, null, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, (SerializableFunction<Publisher<Integer>, Publisher<String>>) entryPublisher -> Flowable.fromPublisher(entryPublisher).map(String::valueOf)); } performFunctionPublisherOperation(publisher.publisherWithoutSegments(), mappedValues); } @Test(dataProvider = "GuaranteeEntry") public void testEmptySegmentNotification(DeliveryGuarantee deliveryGuarantee, boolean isEntry) throws InterruptedException { performSegmentPublisherOperation(deliveryGuarantee, isEntry, null, null, null, null); } private <I, R> void performSegmentPublisherOperation(DeliveryGuarantee deliveryGuarantee, boolean isEntry, IntSet segments, Set<Integer> keys, InvocationContext context, Map<Integer, String> expectedValues) throws InterruptedException { ClusterPublisherManager<Integer, String> cpm = cpm(cache(0)); SegmentPublisherSupplier<R> publisher; if (isEntry) { publisher = (SegmentPublisherSupplier) cpm.entryPublisher(segments, keys, context, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, MarshallableFunctions.identity()); } else { publisher = (SegmentPublisherSupplier) cpm.keyPublisher(segments, keys, context, EnumUtil.EMPTY_BIT_SET, deliveryGuarantee, 10, MarshallableFunctions.identity()); } IntSet mutableIntSet = IntSets.concurrentSet(10); TestSubscriber<SegmentPublisherSupplier.Notification<R>> testSubscriber = TestSubscriber.create(); publisher.publisherWithSegments().subscribe(testSubscriber); testSubscriber.await(10, TimeUnit.SECONDS); for (SegmentPublisherSupplier.Notification<R> notification : testSubscriber.values()) { if (notification.isSegmentComplete()) { mutableIntSet.set(notification.completedSegment()); } } assertEquals(IntSets.immutableRangeSet(10), mutableIntSet); } private <I, R> void performFunctionPublisherOperation(Publisher<R> publisher, Collection<R> expectedValues) { int expectedSize = expectedValues.size(); List<R> results = Flowable.fromPublisher(publisher).toList(expectedSize).blockingGet(); if (expectedSize != results.size()) { log.fatal("SIZE MISMATCH was: " + results.size()); } assertEquals(expectedSize, results.size()); results.forEach(result -> assertTrue(expectedValues.contains(result))); } private void removeEntriesNotInSegment(Map<?, ?> map, KeyPartitioner kp, IntSet segments) { for (Iterator<?> keyIter = map.keySet().iterator(); keyIter.hasNext(); ) { Object key = keyIter.next(); int segment = kp.getSegment(key); if (!segments.contains(segment)) { keyIter.remove(); } } } }
29,219
44.372671
152
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/publisher/impl/PublisherManagerGetKeyStressTest.java
package org.infinispan.reactive.publisher.impl; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commands.GetAllCommandStressTest; import org.infinispan.commons.marshall.Externalizer; import org.infinispan.commons.marshall.SerializeWith; import org.infinispan.commons.util.EnumUtil; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.fwk.InCacheMode; import org.reactivestreams.Publisher; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; @Test(groups = "stress", testName = "PublisherManagerGetKeyStressTest", timeOut = 15*60*1000) @InCacheMode(CacheMode.DIST_SYNC) public class PublisherManagerGetKeyStressTest extends GetAllCommandStressTest { @Override protected void workerLogic(Cache<Integer, Integer> cache, Set<Integer> threadKeys, int iteration) { ClusterPublisherManager<Integer, Integer> cpm = cache.getAdvancedCache().getComponentRegistry().getComponent(ClusterPublisherManager.class); CompletionStage<Map<Integer, Integer>> stage = cpm.entryReduction(false, null, threadKeys, null, EnumUtil.EMPTY_BIT_SET, DeliveryGuarantee.EXACTLY_ONCE, MapReducer.getInstance(), FINALZER); Map<Integer, Integer> results = stage.toCompletableFuture().join(); assertEquals(threadKeys.size(), results.size()); for (Integer key : threadKeys) { assertEquals(key, results.get(key)); } } private static final Function<Publisher<Map<Integer, Integer>>, CompletionStage<Map<Integer, Integer>>> FINALZER = p -> Flowable.fromPublisher(p) .reduce((map1, map2) -> { map1.putAll(map2); return map1; }).toCompletionStage(); @SerializeWith(value = MapReducer.MapReducerExternalizer.class) private static class MapReducer<K, V> implements Function<Publisher<Map.Entry<K, V>>, CompletionStage<Map<K, V>>> { private static final MapReducer INSTANCE = new MapReducer(); public static <K, V> Function<Publisher<? extends Map.Entry<K, V>>, CompletionStage<Map<K, V>>> getInstance() { return INSTANCE; } @Override public CompletionStage<Map<K, V>> apply(Publisher<Map.Entry<K, V>> entryPublisher) { Map<K, V> startingMap = new HashMap<>(); return Flowable.fromPublisher(entryPublisher) .collectInto(startingMap, (map, e) -> map.put(e.getKey(), e.getValue())).toCompletionStage(); } static final class MapReducerExternalizer implements Externalizer<MapReducer> { @Override public void writeObject(ObjectOutput output, MapReducer object) throws IOException { } @Override public MapReducer readObject(ObjectInput input) throws IOException, ClassNotFoundException { return MapReducer.INSTANCE; } } } }
3,213
41.289474
158
java
null
infinispan-main/core/src/test/java/org/infinispan/reactive/publisher/impl/SimpleLocalPublisherManagerTest.java
package org.infinispan.reactive.publisher.impl; 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.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.CompletionStage; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.commons.util.IntSet; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.DistributionManager; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.reactive.publisher.impl.commands.reduction.PublisherResult; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.concurrent.CompletionStages; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.functions.BiFunction; @Test(groups = "functional", testName = "reactive.publisher.impl.SimpleLocalPublisherManagerTest") @InCacheMode({CacheMode.REPL_SYNC, CacheMode.DIST_SYNC}) public class SimpleLocalPublisherManagerTest extends MultipleCacheManagersTest { private static final int SEGMENT_COUNT = 128; ConfigurationBuilder cacheConfiguration() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, false); builder.clustering().hash().numSegments(SEGMENT_COUNT); return builder; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = cacheConfiguration(); createCluster(builder, 3); waitForClusterToForm(); } private Map<Integer, String> insert(Cache<Integer, String> cache) { int amount = 100; Map<Integer, String> values = new HashMap<>(amount); IntStream.range(0, amount).forEach(i -> values.put(i, "value-" + i)); cache.putAll(values); return values; } private LocalPublisherManager<Integer, String> lpm(Cache<Integer, String> cache) { return TestingUtil.extractComponent(cache, LocalPublisherManager.class); } @DataProvider(name = "GuaranteeEntry") public Object[][] deliveryGuaranteeAndEntryProvider() { return Arrays.stream(DeliveryGuarantee.values()) .flatMap(dg -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(entry -> new Object[]{dg, entry})) .toArray(Object[][]::new); } @Test(dataProvider = "GuaranteeEntry") public void testNoIntermediateOps(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> inserted = insert(cache); LocalPublisherManager<Integer, String> lpm = lpm(cache); IntSet allSegments = IntSets.immutableRangeSet(SEGMENT_COUNT); SegmentAwarePublisherSupplier<?> publisher; Consumer<Object> assertConsumer; if (isEntry) { publisher = lpm.keyPublisher(allSegments, null, null, 0L, deliveryGuarantee, Function.identity()); assertConsumer = obj -> assertTrue(inserted.containsKey(obj)); } else { publisher = lpm.entryPublisher(allSegments, null, null, 0L, deliveryGuarantee, Function.identity()); assertConsumer = obj -> { Map.Entry<Object, Object> entry = (Map.Entry) obj; Object value = inserted.get(entry.getKey()); assertEquals(value, entry.getValue()); }; } DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); IntSet localSegments = dm.getCacheTopology().getLocalReadSegments(); int expected = SimpleClusterPublisherManagerTest.findHowManyInSegments(inserted.size(), localSegments, TestingUtil.extractComponent(cache, KeyPartitioner.class)); Set<Object> results = Flowable.fromPublisher(publisher.publisherWithoutSegments()) .collectInto(new HashSet<>(), HashSet::add) .blockingGet(); assertEquals(expected, results.size()); results.forEach(assertConsumer); } @Test(dataProvider = "GuaranteeEntry") public void testProperOrderingGuarantees(DeliveryGuarantee deliveryGuarantee, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> inserted = insert(cache); LocalPublisherManager<Integer, String> lpm = lpm(cache); IntSet allSegments = IntSets.immutableRangeSet(SEGMENT_COUNT); SegmentAwarePublisherSupplier<?> publisher; if (isEntry) { publisher = lpm.keyPublisher(allSegments, null, null, 0L, deliveryGuarantee, Function.identity()); } else { publisher = lpm.entryPublisher(allSegments, null, null, 0L, deliveryGuarantee, Function.identity()); } DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); IntSet localSegments = dm.getCacheTopology().getLocalReadSegments(); int expected = SimpleClusterPublisherManagerTest.findHowManyInSegments(inserted.size(), localSegments, TestingUtil.extractComponent(cache, KeyPartitioner.class)); List<?> list = Flowable.fromPublisher(publisher.publisherWithLostSegments()) .collect(Collectors.toList()) .blockingGet(); assertEquals(expected + SEGMENT_COUNT, list.size()); int currentSegment = -1; for (Object obj : list) { SegmentAwarePublisherSupplier.NotificationWithLost<Object> notification = (SegmentAwarePublisherSupplier.NotificationWithLost<Object>) obj; if (notification.isValue()) { if (currentSegment == -1) { currentSegment = notification.valueSegment(); } else { assertEquals(currentSegment, notification.valueSegment()); } } else { int segment; if (notification.isSegmentComplete()) { segment = notification.completedSegment(); if (!localSegments.contains(segment)) { assertEquals("Only at most once can say the segment is complete without having it", deliveryGuarantee, DeliveryGuarantee.AT_MOST_ONCE); } } else { segment = notification.lostSegment(); assertFalse(localSegments.contains(segment)); } if (currentSegment != -1) { assertEquals(currentSegment, notification.completedSegment()); currentSegment = -1; } } } } @DataProvider(name = "GuaranteeParallelEntry") public Object[][] deliveryGuaranteeParallelEntryProvider() { return Arrays.stream(DeliveryGuarantee.values()) .flatMap(dg -> Stream.of(Boolean.TRUE, Boolean.FALSE) .flatMap(parallel -> Stream.of(Boolean.TRUE, Boolean.FALSE) .map(entry -> new Object[]{dg, parallel, entry})) ) .toArray(Object[][]::new); } @Test(dataProvider = "GuaranteeParallelEntry") public void testWithAsyncOperation(DeliveryGuarantee deliveryGuarantee, boolean isParallel, boolean isEntry) { Cache<Integer, String> cache = cache(0); Map<Integer, String> inserted = insert(cache); BlockingManager blockingManager = TestingUtil.extractComponent(cache, BlockingManager.class); LocalPublisherManager<Integer, String> lpm = lpm(cache); IntSet allSegments = IntSets.immutableRangeSet(SEGMENT_COUNT); CompletionStage<PublisherResult<Set<Object>>> stage; Consumer<Object> assertConsumer; Collector<Object, ?, Set<Object>> collector = Collectors.toSet(); BiFunction<Set<Object>, Set<Object>, Set<Object>> reduceBiFunction = (left, right) -> { left.addAll(right); return left; }; io.reactivex.rxjava3.functions.Function<Object, Single<Object>> sleepOnBlockingPoolFunction = value -> Single.fromCompletionStage(blockingManager.supplyBlocking(() -> value, "test-blocking-thread")); if (isEntry) { stage = lpm.keyReduction(isParallel, allSegments, null, null, 0L, deliveryGuarantee, publisher -> Flowable.fromPublisher(publisher) .concatMapSingle(sleepOnBlockingPoolFunction) .collect(collector) .toCompletionStage(), publisher -> Flowable.fromPublisher(publisher) .reduce(reduceBiFunction) .toCompletionStage(Collections.emptySet())); assertConsumer = obj -> assertTrue(inserted.containsKey(obj)); } else { stage = lpm.entryReduction(isParallel, allSegments, null, null, 0L, deliveryGuarantee, publisher -> Flowable.fromPublisher(publisher) .concatMapSingle(sleepOnBlockingPoolFunction).collect(collector).toCompletionStage() , publisher -> Flowable.fromPublisher(publisher) .reduce(reduceBiFunction).toCompletionStage(Collections.emptySet())); assertConsumer = obj -> { Map.Entry<Object, Object> entry = (Map.Entry) obj; Object value = inserted.get(entry.getKey()); assertEquals(value, entry.getValue()); }; } DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); IntSet localSegments = dm.getCacheTopology().getLocalReadSegments(); int expected = SimpleClusterPublisherManagerTest.findHowManyInSegments(inserted.size(), localSegments, TestingUtil.extractComponent(cache, KeyPartitioner.class)); Set<Object> results = CompletionStages.join(stage).getResult(); assertEquals(expected, results.size()); results.forEach(assertConsumer); } }
10,370
42.393305
168
java
null
infinispan-main/core/src/test/java/org/infinispan/health/impl/HostInfoImplTest.java
package org.infinispan.health.impl; import static org.testng.Assert.assertTrue; import org.infinispan.health.HostInfo; import org.testng.annotations.Test; @Test(testName = "health.impl.HostInfoImplTest", groups = "functional") public class HostInfoImplTest { @Test public void testReturningValuesFromHostInfo() { //given HostInfo hostInfo = new HostInfoImpl(); //when int numberOfCpus = hostInfo.getNumberOfCpus(); long freeMemoryInKb = hostInfo.getFreeMemoryInKb(); long totalMemoryKb = hostInfo.getTotalMemoryKb(); //then assertTrue(numberOfCpus > 0); assertTrue(freeMemoryInKb > 0); assertTrue(totalMemoryKb > 0); } }
719
25.666667
71
java
null
infinispan-main/core/src/test/java/org/infinispan/health/impl/ClusterHealthImplTest.java
package org.infinispan.health.impl; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.EnumSet; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.DistributionManager; import org.infinispan.health.ClusterHealth; import org.infinispan.health.HealthStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.registry.InternalCacheRegistry; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(testName = "health.impl.ClusterHealthImplTest", groups = "functional") public class ClusterHealthImplTest extends AbstractInfinispanTest { private static final String INTERNAL_CACHE_NAME = "internal_cache"; private static final String CACHE_NAME = "test_cache"; private EmbeddedCacheManager localCacheManager; private EmbeddedCacheManager cacheManager; private ClusterHealth clusterHealth; private InternalCacheRegistry internalCacheRegistry; @BeforeClass private void init() { localCacheManager = TestCacheManagerFactory.createCacheManager(); cacheManager = TestCacheManagerFactory.createClusteredCacheManager(); internalCacheRegistry = TestingUtil.extractGlobalComponent(cacheManager, InternalCacheRegistry.class); clusterHealth = new ClusterHealthImpl(cacheManager, internalCacheRegistry); } @BeforeMethod private void configureBeforeMethod() { internalCacheRegistry.registerInternalCache(INTERNAL_CACHE_NAME, new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_ASYNC).build(), EnumSet.of(InternalCacheRegistry.Flag.EXCLUSIVE)); cacheManager.defineConfiguration(CACHE_NAME, new ConfigurationBuilder().build()); } @AfterMethod(alwaysRun = true) private void cleanAfterMethod() { if (cacheManager != null) { cacheManager.administration().removeCache(CACHE_NAME); cacheManager.undefineConfiguration(CACHE_NAME); cacheManager.administration().removeCache(INTERNAL_CACHE_NAME); } if (internalCacheRegistry != null) { internalCacheRegistry.unregisterInternalCache(INTERNAL_CACHE_NAME); } } @AfterClass(alwaysRun = true) private void cleanUp() { if (cacheManager != null) { cacheManager.stop(); cacheManager = null; } } public void testGetClusterName() { assertEquals(cacheManager.getClusterName(), clusterHealth.getClusterName()); } public void testCallingGetHealthStatusDoesNotCreateAnyCache() { clusterHealth.getHealthStatus(); assertFalse(cacheManager.cacheExists(CACHE_NAME)); assertFalse(cacheManager.cacheExists(INTERNAL_CACHE_NAME)); } public void testHealthyStatusWithoutAnyUserCreatedCache() { assertEquals(HealthStatus.HEALTHY, clusterHealth.getHealthStatus()); } public void testHealthyStatusWhenUserCacheIsHealthy() { cacheManager.getCache(CACHE_NAME, true); HealthStatus healthStatus = clusterHealth.getHealthStatus(); assertEquals(HealthStatus.HEALTHY, healthStatus); } public void testUnhealthyStatusWhenUserCacheIsStopped() { Cache<Object, Object> testCache = cacheManager.getCache(CACHE_NAME, true); testCache.stop(); HealthStatus healthStatus = clusterHealth.getHealthStatus(); assertEquals(HealthStatus.FAILED, healthStatus); cacheManager.administration().removeCache(CACHE_NAME); healthStatus = clusterHealth.getHealthStatus(); assertEquals(HealthStatus.HEALTHY, healthStatus); } public void testRebalancingStatusWhenUserCacheIsRebalancing() { mockRehashInProgress(CACHE_NAME); ClusterHealth clusterHealth = new ClusterHealthImpl(cacheManager, internalCacheRegistry); assertEquals(HealthStatus.HEALTHY_REBALANCING, clusterHealth.getHealthStatus()); } public void testHealthyStatusForInternalCaches() { cacheManager.getCache(INTERNAL_CACHE_NAME, true); assertEquals(HealthStatus.HEALTHY, clusterHealth.getHealthStatus()); } public void testUnhealthyStatusWhenInternalCacheIsStopped() { Cache<Object, Object> internalCache = cacheManager.getCache(INTERNAL_CACHE_NAME, true); internalCache.stop(); assertEquals(HealthStatus.FAILED, clusterHealth.getHealthStatus()); } public void testRebalancingStatusWhenInternalCacheIsRebalancing() { mockRehashInProgress(INTERNAL_CACHE_NAME); ClusterHealth clusterHealth = new ClusterHealthImpl(cacheManager, internalCacheRegistry); assertEquals(HealthStatus.HEALTHY_REBALANCING, clusterHealth.getHealthStatus()); } public void testGetNodeNames() { assertEquals(cacheManager.getAddress().toString(), clusterHealth.getNodeNames().get(0)); } public void testGetNumberOfNodes() { assertEquals(1, clusterHealth.getNumberOfNodes()); } public void testGetNumberOfNodesWithNullTransport() { ClusterHealth clusterHealth = new ClusterHealthImpl(localCacheManager, internalCacheRegistry); assertEquals(0, clusterHealth.getNumberOfNodes()); } public void testGetNodeNamesWithNullTransport() { ClusterHealth clusterHealth = new ClusterHealthImpl(localCacheManager, internalCacheRegistry); assertTrue(clusterHealth.getNodeNames().isEmpty()); } private void mockRehashInProgress(String cacheName) { DistributionManager mockDistributionManager = mock(DistributionManager.class); when(mockDistributionManager.isRehashInProgress()).thenReturn(true); TestingUtil.replaceComponent(cacheManager.getCache(cacheName), DistributionManager.class, mockDistributionManager, false); } }
6,197
36.113772
151
java
null
infinispan-main/core/src/test/java/org/infinispan/health/impl/CacheHealthImplTest.java
package org.infinispan.health.impl; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import org.infinispan.distribution.DistributionManager; import org.infinispan.factories.ComponentRegistry; import org.infinispan.health.CacheHealth; import org.infinispan.health.HealthStatus; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.partitionhandling.AvailabilityMode; import org.infinispan.partitionhandling.impl.PartitionHandlingManager; import org.testng.annotations.Test; @Test(testName = "health.impl.CacheHealthImplTest", groups = "functional") public class CacheHealthImplTest { @Test public void testHealthyStatus() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); DistributionManager distributionManagerMock = mock(DistributionManager.class); doReturn(false).when(distributionManagerMock).isRehashInProgress(); doReturn(distributionManagerMock).when(componentRegistryMock).getDistributionManager(); doReturn(ComponentStatus.RUNNING).when(componentRegistryMock).getStatus(); PartitionHandlingManager partitionHandlingManagerMock = mock(PartitionHandlingManager.class); doReturn(AvailabilityMode.AVAILABLE).when(partitionHandlingManagerMock).getAvailabilityMode(); doReturn(partitionHandlingManagerMock).when(componentRegistryMock).getComponent(eq(PartitionHandlingManager.class)); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.HEALTHY); } @Test public void testUnhealthyStatusWithFailedComponent() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.FAILED).when(componentRegistryMock).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.DEGRADED); } @Test public void testUnhealthyStatusWithTerminatedComponent() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.TERMINATED).when(componentRegistryMock).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.DEGRADED); } @Test public void testUnhealthyStatusWithStoppingComponent() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.STOPPING).when(componentRegistryMock).getStatus(); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.DEGRADED); } @Test public void testUnhealthyStatusWithDegradedPartition() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.RUNNING).when(componentRegistryMock).getStatus(); PartitionHandlingManager partitionHandlingManagerMock = mock(PartitionHandlingManager.class); doReturn(AvailabilityMode.DEGRADED_MODE).when(partitionHandlingManagerMock).getAvailabilityMode(); doReturn(partitionHandlingManagerMock).when(componentRegistryMock).getComponent(eq(PartitionHandlingManager.class)); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.DEGRADED); } @Test public void testRebalancingStatusOnRebalance() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); DistributionManager distributionManagerMock = mock(DistributionManager.class); doReturn(true).when(distributionManagerMock).isRehashInProgress(); doReturn(distributionManagerMock).when(componentRegistryMock).getDistributionManager(); doReturn(ComponentStatus.RUNNING).when(componentRegistryMock).getStatus(); PartitionHandlingManager partitionHandlingManagerMock = mock(PartitionHandlingManager.class); doReturn(AvailabilityMode.AVAILABLE).when(partitionHandlingManagerMock).getAvailabilityMode(); doReturn(partitionHandlingManagerMock).when(componentRegistryMock).getComponent(eq(PartitionHandlingManager.class)); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when HealthStatus status = cacheHealth.getStatus(); //then assertEquals(status, HealthStatus.HEALTHY_REBALANCING); } @Test public void testReturningName() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn("test").when(componentRegistryMock).getCacheName(); CacheHealth cacheHealth = new CacheHealthImpl(componentRegistryMock); //when String name = cacheHealth.getCacheName(); //then assertEquals(name, "test"); } }
5,517
35.786667
124
java
null
infinispan-main/core/src/test/java/org/infinispan/container/SimpleDataContainerTest.java
package org.infinispan.container; import static org.mockito.Mockito.mock; 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.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.entries.MortalCacheEntry; import org.infinispan.container.entries.TransientCacheEntry; import org.infinispan.container.entries.TransientMortalCacheEntry; import org.infinispan.container.impl.DefaultDataContainer; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.infinispan.eviction.impl.ActivationManager; import org.infinispan.expiration.impl.InternalExpirationManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.ControlledTimeService; import org.infinispan.util.CoreImmutables; import org.infinispan.commons.util.concurrent.CompletableFutures; import org.mockito.Mockito; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "unit", testName = "container.SimpleDataContainerTest") public class SimpleDataContainerTest extends AbstractInfinispanTest { private InternalDataContainer<String, String> dc; private ControlledTimeService timeService; @BeforeMethod public void setUp() { dc = createContainer(); } @AfterMethod public void tearDown() { dc = null; } protected InternalDataContainer<String, String> createContainer() { DefaultDataContainer<String, String> dc = new DefaultDataContainer<>(16); InternalEntryFactoryImpl internalEntryFactory = new InternalEntryFactoryImpl(); timeService = new ControlledTimeService(); TestingUtil.inject(internalEntryFactory, timeService); ActivationManager activationManager = mock(ActivationManager.class); InternalExpirationManager expirationManager = mock(InternalExpirationManager.class); Mockito.when(expirationManager.entryExpiredInMemory(Mockito.any(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(CompletableFutures.completedTrue()); TestingUtil.inject(dc, internalEntryFactory, timeService, expirationManager); return dc; } public void testExpiredData() throws InterruptedException { dc.put("k", "v", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); timeService.advance(100); InternalCacheEntry entry = dc.get("k"); assertNotNull(entry); assertEquals(transienttype(), entry.getClass()); assertEquals(timeService.wallClockTime(), entry.getLastUsed()); long entryLastUsed = entry.getLastUsed(); timeService.advance(100); entry = dc.get("k"); assertEquals(entryLastUsed + 100, entry.getLastUsed()); dc.put("k", "v", new EmbeddedMetadata.Builder().maxIdle(1, TimeUnit.MILLISECONDS).build()); long oldTime = timeService.wallClockTime(); dc.put("k", "v", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); timeService.advance(100); assertEquals(1, dc.size()); entry = dc.get("k"); assertNotNull(entry); assertEquals(mortaltype(), entry.getClass()); assertEquals(oldTime, entry.getCreated()); assertEquals(-1, entry.getMaxIdle()); dc.put("k", "v", new EmbeddedMetadata.Builder().lifespan(1, TimeUnit.MILLISECONDS).build()); timeService.advance(10); assertNull(dc.get("k")); assertEquals(0, dc.size()); dc.put("k", "v", new EmbeddedMetadata.Builder().lifespan(1, TimeUnit.MILLISECONDS).build()); timeService.advance(100); assertEquals(0, dc.size()); } public void testResetOfCreationTime() throws Exception { long now = timeService.wallClockTime(); timeService.advance(1); dc.put("k", "v", new EmbeddedMetadata.Builder().lifespan(1000, TimeUnit.SECONDS).build()); long created1 = dc.get("k").getCreated(); assertEquals(now + 1, created1); timeService.advance(100); dc.put("k", "v", new EmbeddedMetadata.Builder().lifespan(1000, TimeUnit.SECONDS).build()); long created2 = dc.get("k").getCreated(); assertEquals(now + 101, created2); } public void testUpdatingLastUsed() throws Exception { long idle = 600000; dc.put("k", "v", new EmbeddedMetadata.Builder().build()); InternalCacheEntry ice = dc.get("k"); assertEquals(immortaltype(), ice.getClass()); assertEquals(-1, ice.toInternalCacheValue().getExpiryTime()); assertEquals(-1, ice.getMaxIdle()); assertEquals(-1, ice.getLifespan()); assertFalse(dc.hasExpirable()); dc.put("k", "v", new EmbeddedMetadata.Builder().maxIdle(idle, TimeUnit.MILLISECONDS).build()); timeService.advance(100); // for time calc granularity ice = dc.get("k"); assertEquals(transienttype(), ice.getClass()); assertEquals(idle + timeService.wallClockTime(), ice.toInternalCacheValue().getExpiryTime()); assertEquals(timeService.wallClockTime(), ice.getLastUsed()); assertEquals(idle, ice.getMaxIdle()); assertEquals(-1, ice.getLifespan()); assertTrue(dc.hasExpirable()); timeService.advance(100); // for time calc granularity assertNotNull(dc.get("k")); long oldTime = timeService.wallClockTime(); // check that the last used stamp has been updated on a get assertEquals(oldTime, ice.getLastUsed()); timeService.advance(100); // for time calc granularity assertEquals(oldTime, ice.getLastUsed()); } protected Class<? extends InternalCacheEntry> mortaltype() { return MortalCacheEntry.class; } protected Class<? extends InternalCacheEntry> immortaltype() { return ImmortalCacheEntry.class; } protected Class<? extends InternalCacheEntry> transienttype() { return TransientCacheEntry.class; } protected Class<? extends InternalCacheEntry> transientmortaltype() { return TransientMortalCacheEntry.class; } public void testExpirableToImmortalAndBack() { String value = "v"; dc.put("k", value, new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); assertContainerEntry(mortaltype(), value); assertTrue(dc.hasExpirable()); value = "v2"; dc.put("k", value, new EmbeddedMetadata.Builder().build()); assertContainerEntry(immortaltype(), value); assertFalse(dc.hasExpirable()); value = "v3"; dc.put("k", value, new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); assertContainerEntry(transienttype(), value); assertTrue(dc.hasExpirable()); value = "v4"; dc.put("k", value, new EmbeddedMetadata.Builder() .lifespan(100, TimeUnit.MINUTES).maxIdle(100, TimeUnit.MINUTES).build()); assertContainerEntry(transientmortaltype(), value); assertTrue(dc.hasExpirable()); value = "v41"; dc.put("k", value, new EmbeddedMetadata.Builder() .lifespan(100, TimeUnit.MINUTES).maxIdle(100, TimeUnit.MINUTES).build()); assertContainerEntry(transientmortaltype(), value); assertTrue(dc.hasExpirable()); value = "v5"; dc.put("k", value, new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); assertContainerEntry(mortaltype(), value); assertTrue(dc.hasExpirable()); } private void assertContainerEntry(Class<? extends InternalCacheEntry> type, String expectedValue) { assertTrue(dc.containsKey("k")); InternalCacheEntry entry = dc.get("k"); assertEquals(type, entry.getClass()); assertEquals(expectedValue, entry.getValue()); } public void testKeySet() { dc.put("k1", "v", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); dc.put("k2", "v", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); dc.put("k4", "v", new EmbeddedMetadata.Builder() .maxIdle(100, TimeUnit.MINUTES).lifespan(100, TimeUnit.MINUTES).build()); Set<String> expected = new HashSet<>(); expected.add("k1"); expected.add("k2"); expected.add("k3"); expected.add("k4"); for (InternalCacheEntry<String, String> entry : dc) { String o = entry.getKey(); assertTrue(expected.remove(o)); } assertTrue("Did not see keys " + expected + " in iterator!", expected.isEmpty()); } public void testContainerIteration() { dc.put("k1", "v", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); dc.put("k2", "v", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); dc.put("k4", "v", new EmbeddedMetadata.Builder() .maxIdle(100, TimeUnit.MINUTES).lifespan(100, TimeUnit.MINUTES).build()); Set<String> expected = new HashSet<>(); expected.add("k1"); expected.add("k2"); expected.add("k3"); expected.add("k4"); for (InternalCacheEntry<String, String> ice : dc) { assertTrue(expected.remove(ice.getKey())); } assertTrue("Did not see keys " + expected + " in iterator!", expected.isEmpty()); } public void testKeys() { dc.put("k1", "v1", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); dc.put("k2", "v2", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v3", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); dc.put("k4", "v4", new EmbeddedMetadata.Builder() .maxIdle(100, TimeUnit.MINUTES).lifespan(100, TimeUnit.MINUTES).build()); Set<String> expected = new HashSet<>(); expected.add("k1"); expected.add("k2"); expected.add("k3"); expected.add("k4"); for (InternalCacheEntry<String, String> entry : dc) { String o = entry.getKey(); assertTrue(expected.remove(o)); } assertTrue("Did not see keys " + expected + " in iterator!", expected.isEmpty()); } public void testValues() { dc.put("k1", "v1", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); dc.put("k2", "v2", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v3", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); dc.put("k4", "v4", new EmbeddedMetadata.Builder() .maxIdle(100, TimeUnit.MINUTES).lifespan(100, TimeUnit.MINUTES).build()); Set<String> expected = new HashSet<>(); expected.add("v1"); expected.add("v2"); expected.add("v3"); expected.add("v4"); for (InternalCacheEntry<String, String> entry : dc) { String o = entry.getValue(); assertTrue(expected.remove(o)); } assertTrue("Did not see keys " + expected + " in iterator!", expected.isEmpty()); } public void testEntrySet() { dc.put("k1", "v1", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MINUTES).build()); dc.put("k2", "v2", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v3", new EmbeddedMetadata.Builder().maxIdle(100, TimeUnit.MINUTES).build()); dc.put("k4", "v4", new EmbeddedMetadata.Builder() .maxIdle(100, TimeUnit.MINUTES).lifespan(100, TimeUnit.MINUTES).build()); Set<Map.Entry> expected = new HashSet<>(); expected.add(CoreImmutables.immutableInternalCacheEntry(dc.get("k1"))); expected.add(CoreImmutables.immutableInternalCacheEntry(dc.get("k2"))); expected.add(CoreImmutables.immutableInternalCacheEntry(dc.get("k3"))); expected.add(CoreImmutables.immutableInternalCacheEntry(dc.get("k4"))); Set<Map.Entry> actual = new HashSet<>(); for (Map.Entry<String, String> o : dc) { assertTrue(actual.add(o)); } assertEquals("Expected to see keys " + expected + " but only saw " + actual, expected, actual); } public void testGetDuringKeySetLoop() { for (int i = 0; i < 10; i++) dc.put(String.valueOf(i), "value", new EmbeddedMetadata.Builder().build()); int i = 0; for (InternalCacheEntry<String, String> entry : dc) { Object key = entry.getKey(); dc.peek(key); // calling get in this situations will result on corruption the iteration. i++; } assertEquals(10, i); } public void testEntrySetStreamWithExpiredEntries() { dc.put("k1", "v1", new EmbeddedMetadata.Builder().lifespan(100, TimeUnit.MILLISECONDS).build()); dc.put("k2", "v2", new EmbeddedMetadata.Builder().build()); dc.put("k3", "v3", new EmbeddedMetadata.Builder().maxIdle(200, TimeUnit.MILLISECONDS).build()); Set<Map.Entry<String, String>> expected = new HashSet<>(); Map.Entry<String, String> k1 = CoreImmutables.immutableInternalCacheEntry(dc.get("k1")); expected.add(k1); expected.add(CoreImmutables.immutableInternalCacheEntry(dc.get("k2"))); Map.Entry<String, String> k3 = CoreImmutables.immutableInternalCacheEntry(dc.get("k3")); expected.add(k3); List<Map.Entry<String, String>> results = StreamSupport.stream(dc.spliterator(), false).collect(Collectors.toList()); assertEquals(3, results.size()); assertArrayAndSetContainSame(expected, results); timeService.advance(101); results = StreamSupport.stream(dc.spliterator(), false).collect(Collectors.toList()); assertEquals(2, results.size()); expected.remove(k1); assertArrayAndSetContainSame(expected, results); timeService.advance(100); results = StreamSupport.stream(dc.spliterator(), false).collect(Collectors.toList()); assertEquals(1, results.size()); expected.remove(k3); assertArrayAndSetContainSame(expected, results); } private <E> void assertArrayAndSetContainSame(Set<E> expected, List<E> results) { for (E result : results) { assertTrue("Set didn't contain " + result, expected.contains(result)); } } }
14,632
39.988796
162
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/LocalWriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.commons.test.Exceptions; 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.IsolationLevel; import org.testng.annotations.Test; /** * Tests local-mode versioning * * @author Manik Surtani * @since 5.1 */ @Test(testName = "container.versioning.LocalWriteSkewTest", groups = "functional") @CleanupAfterMethod public class LocalWriteSkewTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .transaction().lockingMode(LockingMode.OPTIMISTIC); return TestCacheManagerFactory.createCacheManager(builder); } public void testWriteSkewEnabled() throws Exception { // Auto-commit is true cache.put("hello", "world 1"); tm().begin(); assertEquals("Wrong value read by transaction for key hello", "world 1", cache.get("hello")); Transaction t = tm().suspend(); // Create a write skew cache.put("hello", "world 3"); tm().resume(t); cache.put("hello", "world 2"); Exceptions.expectException(RollbackException.class, tm()::commit); assertEquals("Wrong final value for key hello", "world 3", cache.get("hello")); } public void testWriteSkewMultiEntries() throws Exception { tm().begin(); cache.put("k1", "v1"); cache.put("k2", "v2"); tm().commit(); tm().begin(); cache.put("k2", "v2000"); assertEquals("Wrong value read by transaction for key k1", "v1", cache.get("k1")); assertEquals("Wrong value read by transaction for key k2", "v2000", cache.get("k2")); Transaction t = tm().suspend(); // Create a write skew // Auto-commit is true cache.put("k1", "v3"); tm().resume(t); cache.put("k1", "v5000"); Exceptions.expectException(RollbackException.class, tm()::commit); assertEquals("Wrong final value for key k1", "v3", cache.get("k1")); assertEquals("Wrong final value for key k2", "v2", cache.get("k2")); } public void testNullEntries() throws Exception { // Auto-commit is true cache.put("hello", "world"); tm().begin(); assertEquals("Wrong value read by transaction for key hello", "world", cache.get("hello")); Transaction t = tm().suspend(); cache.remove("hello"); assertEquals("Wrong value after remove for key hello", null, cache.get("hello")); tm().resume(t); cache.put("hello", "world2"); Exceptions.expectException(RollbackException.class, tm()::commit); assertEquals("Wrong final value for key hello", null, cache.get("hello")); } public void testSameNodeKeyCreation() throws Exception { tm().begin(); assertEquals("Wrong value read by transaction 1 for key NewKey", null, cache.get("NewKey")); cache.put("NewKey", "v1"); Transaction tx0 = tm().suspend(); //other transaction do the same thing tm().begin(); assertEquals("Wrong value read by transaction 2 for key NewKey", null, cache.get("NewKey")); cache.put("NewKey", "v2"); tm().commit(); tm().resume(tx0); Exceptions.expectException(RollbackException.class, tm()::commit); assertEquals("Wrong final value for key NewKey", "v2", cache.get("NewKey")); } }
3,940
32.398305
99
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/VersionedConditionalOperationsTest.java
package org.infinispan.container.versioning; import static org.testng.Assert.assertNull; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** * This test checks behaivour of versioned caches * when executing conditional operations. * * @author Pedro Ruivo * @since 5.2 */ @Test(testName = "container.versioning.VersionedConditionalOperationsTest", groups = "functional") public class VersionedConditionalOperationsTest extends MultipleCacheManagersTest { protected static final String KEY_1 = "key_1"; protected static final String KEY_2 = "key_2"; protected static final String VALUE_1 = "value_1"; protected static final String VALUE_2 = "value_2"; protected static final String VALUE_3 = "value_3"; protected static final String VALUE_4 = "value_4"; protected final int clusterSize; protected final CacheMode mode; protected final boolean syncCommit; public VersionedConditionalOperationsTest() { this(2, CacheMode.REPL_SYNC, true); } protected VersionedConditionalOperationsTest( int clusterSize, CacheMode mode, boolean syncCommit) { this.clusterSize = clusterSize; this.mode = mode; this.syncCommit = syncCommit; } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(mode, true); dcc.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); createCluster(dcc, clusterSize); waitForClusterToForm(); } public void testPutIfAbsent() { assertEmpty(KEY_1, KEY_2); cache(1).put(KEY_1, VALUE_1); assertCacheValue(1, KEY_1, VALUE_1); cache(0).putIfAbsent(KEY_1, VALUE_2); assertCacheValue(0, KEY_1, VALUE_1); cache(1).put(KEY_1, VALUE_3); assertCacheValue(1, KEY_1, VALUE_3); cache(0).putIfAbsent(KEY_1, VALUE_4); assertCacheValue(0, KEY_1, VALUE_3); cache(0).putIfAbsent(KEY_2, VALUE_1); assertCacheValue(0, KEY_2, VALUE_1); assertNoTransactions(); } public void testRemoveIfPresent() { assertEmpty(KEY_1); cache(0).put(KEY_1, VALUE_1); cache(1).put(KEY_1, VALUE_2); assertCacheValue(1, KEY_1, VALUE_2); cache(0).remove(KEY_1, VALUE_1); assertCacheValue(0, KEY_1, VALUE_2); cache(0).remove(KEY_1, VALUE_2); assertCacheValue(0, KEY_1, null); assertNoTransactions(); } public void testReplaceWithOldVal() { assertEmpty(KEY_1); cache(1).put(KEY_1, VALUE_1); assertCacheValue(1, KEY_1, VALUE_1); cache(0).put(KEY_1, VALUE_2); assertCacheValue(0, KEY_1, VALUE_2); cache(0).replace(KEY_1, VALUE_3, VALUE_4); assertCacheValue(0, KEY_1, VALUE_2); cache(0).replace(KEY_1, VALUE_2, VALUE_4); assertCacheValue(0, KEY_1, VALUE_4); assertNoTransactions(); } protected void assertEmpty(Object... keys) { for (Cache cache : caches()) { for (Object key : keys) { assertNull(cache.get(key)); } } } //originatorIndex == cache which executed the transaction protected void assertCacheValue(int originatorIndex, Object key, Object value) { for (int index = 0; index < caches().size(); ++index) { if ((index == originatorIndex && mode.isSynchronous()) || (index != originatorIndex && syncCommit)) { assertEquals(index, key, value); } else { assertEventuallyEquals(index, key, value); } } } private void assertEquals(int index, Object key, Object value) { assert value == null ? value == cache(index).get(key) : value.equals(cache(index).get(key)); } }
3,960
28.559701
98
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/TopologyIracVersionUnitTest.java
package org.infinispan.container.versioning; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertSame; import java.util.stream.IntStream; import org.infinispan.container.versioning.irac.TopologyIracVersion; import org.infinispan.test.AbstractInfinispanTest; import org.testng.annotations.Test; /** * Unit test for {@link TopologyIracVersion} * * @since 14.0 */ @Test(groups = "unit", testName = "container.versioning.TopologyIracVersionUnitTest") public class TopologyIracVersionUnitTest extends AbstractInfinispanTest { public void testNoVersionInstance() { assertSame(TopologyIracVersion.NO_VERSION, TopologyIracVersion.create(0, 0)); } public void testIncrement() { TopologyIracVersion vBase = TopologyIracVersion.create(10, 1); // < topology assertEquals(vBase.increment(5), TopologyIracVersion.create(10, 2)); // == topology assertEquals(vBase.increment(10), TopologyIracVersion.create(10, 2)); // > topology assertEquals(vBase.increment(15), TopologyIracVersion.create(15, 1)); } public void testNoVersionIncrement() { assertEquals(TopologyIracVersion.NO_VERSION.increment(2), TopologyIracVersion.create(2, 1)); } public void testCompare() { TopologyIracVersion vBase = TopologyIracVersion.create(5, 5); // < topology and < version ; == version ; > version IntStream.range(4, 7).forEach(value -> assertCompare(vBase, TopologyIracVersion.create(4, value), 1)); // == topology ; < version assertCompare(vBase, TopologyIracVersion.create(5, 4), 1); // == topology ; == version assertCompareEquals(vBase, TopologyIracVersion.create(5, 5)); // == topology ; > version assertCompare(vBase, TopologyIracVersion.create(5, 6), -1); // > topology and < version ; == version ; > version IntStream.range(4, 7).forEach(value -> assertCompare(vBase, TopologyIracVersion.create(6, value), -1)); } public void testMax() { TopologyIracVersion vBase = TopologyIracVersion.create(5, 5); // < topology and < version ; == version ; > version IntStream.range(4, 7).forEach(value -> assertMax(vBase, TopologyIracVersion.create(4, value), true)); // == topology ; < version assertMax(vBase, TopologyIracVersion.create(5, 4), true); // == topology ; == version assertMax(vBase, TopologyIracVersion.create(5, 5), true); // == topology ; > version assertMax(vBase, TopologyIracVersion.create(5, 6), false); // > topology and < version ; == version ; > version IntStream.range(4, 7).forEach(value -> assertMax(vBase, TopologyIracVersion.create(6, value), false)); } private static void assertCompare(TopologyIracVersion v1, TopologyIracVersion v2, int result) { assertEquals(result, Integer.signum(v1.compareTo(v2))); assertEquals(result * -1, Integer.signum(v2.compareTo(v1))); assertNotEquals(v1, v2); assertNotEquals(v2, v1); } private static void assertCompareEquals(TopologyIracVersion v1, TopologyIracVersion v2) { assertEquals(0, v1.compareTo(v2)); assertEquals(0, v2.compareTo(v1)); assertEquals(v1, v2); assertEquals(v2, v1); } private static void assertMax(TopologyIracVersion v1, TopologyIracVersion v2, boolean expectsV1) { assertEquals(expectsV1 ? v1 : v2, TopologyIracVersion.max(v1, v2)); assertEquals(expectsV1 ? v1 : v2, TopologyIracVersion.max(v2, v1)); } }
3,562
37.311828
109
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/VersionedReplStateTransferTest.java
package org.infinispan.container.versioning; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import static org.testng.AssertJUnit.assertEquals; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.Cache; 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.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(testName = "container.versioning.VersionedReplStateTransferTest", groups = "functional") public class VersionedReplStateTransferTest extends MultipleCacheManagersTest { private ConfigurationBuilder builder; @Override protected void createCacheManagers() throws Throwable { builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.clustering().cacheMode(CacheMode.REPL_SYNC) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .transaction().lockingMode(LockingMode.OPTIMISTIC) .recovery().disable(); createCluster(TestDataSCI.INSTANCE, builder, 2); waitForClusterToForm(); } public void testStateTransfer() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); cache0.put("hello", "world"); assertEquals("world", cache0.get("hello")); assertEquals("world", cache1.get("hello")); tm(1).begin(); assertEquals("world", cache1.get("hello")); Transaction t = tm(1).suspend(); // create a cache2 addClusterEnabledCacheManager(builder); Cache<Object, Object> cache2 = cache(2); assertEquals("world", cache2.get("hello")); cacheManagers.get(0).stop(); cacheManagers.remove(0); waitForNoRebalance(caches()); // Cause a write skew cache2.put("hello", "new world"); tm(1).resume(t); cache1.put("hello", "world2"); //write skew should abort the transaction expectException(RollbackException.class, tm(1)::commit); assertEquals("new world", cache1.get("hello")); assertEquals("new world", cache2.get("hello")); } }
2,468
32.364865
94
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/AbstractClusteredWriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.fail; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; 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.distribution.MagicKey; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(testName = "container.versioning.AbstractClusteredWriteSkewTest", groups = "functional") public abstract class AbstractClusteredWriteSkewTest extends MultipleCacheManagersTest { private static final String PASSIVATION_CACHE = "passivation-cache"; private static final int MAX_ENTRIES = 2; public final void testPutIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.PUT, false); } public final void testPutIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.PUT, false); } public final void testPutIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.PUT, true); } public final void testPutIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.PUT, true); } public final void testRemoveIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.REMOVE, false); } public final void testRemoveIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.REMOVE, false); } public final void testRemoveIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.REMOVE, true); } public final void testRemoveIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.REMOVE, true); } public final void testReplaceIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.REPLACE, false); } public final void testReplaceIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.REPLACE, false); } public final void testReplaceIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.REPLACE, true); } public final void testReplaceIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.REPLACE, true); } public final void testPutIfAbsentIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_PUT, false); } public final void testPutIfAbsentIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_PUT, false); } public final void testPutIfAbsentIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_PUT, true); } public final void testPutIfAbsentIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_PUT, true); } public final void testConditionalRemoveIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_REMOVE, false); } public final void testConditionalRemoveIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_REMOVE, false); } public final void testConditionalRemoveIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_REMOVE, true); } public final void testConditionalRemoveIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_REMOVE, true); } public final void testConditionalReplaceIgnoreReturnValueOnNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_REPLACE, false); } public final void testConditionalReplaceIgnoreReturnValueOnNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_REPLACE, false); } public final void testConditionalReplaceIgnoreReturnValueNonExistingKey() throws Exception { doIgnoreReturnValueTest(true, Operation.CONDITIONAL_REPLACE, true); } public final void testConditionalReplaceIgnoreReturnValueNonExistingKeyOnNonOwner() throws Exception { doIgnoreReturnValueTest(false, Operation.CONDITIONAL_REPLACE, true); } public final void testPutWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.PUT, false); } public final void testPutFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.PUT, true); } public final void testPutWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.PUT, false); } public final void testPutFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.PUT, true); } public final void testRemoveWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.REMOVE, false); } public final void testRemoveFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.REMOVE, true); } public final void testRemoveWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.REMOVE, false); } public final void testRemoveFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.REMOVE, true); } public final void testReplaceWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.REPLACE, false); } public final void testReplaceFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.REPLACE, true); } public final void testReplaceWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.REPLACE, false); } public final void testReplaceFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.REPLACE, true); } public final void testConditionalPutWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_PUT, false); } public final void testConditionalPutFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_PUT, true); } public final void testConditionalPutWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_PUT, false); } public final void testConditionalPutFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_PUT, true); } public final void testConditionalRemoveWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_REMOVE, false); } public final void testConditionalRemoveFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_REMOVE, true); } public final void testConditionalRemoveWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_REMOVE, false); } public final void testConditionalRemoveFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_REMOVE, true); } public final void testConditionalReplaceWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_REPLACE, false); } public final void testConditionalReplaceFailWriteSkewWithPassivation() throws Exception { doTestWriteSkewWithPassivation(true, Operation.CONDITIONAL_REPLACE, true); } public final void testConditionalReplaceWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_REPLACE, false); } public final void testConditionalReplaceFailWriteSkewWithPassivationOnNonOwner() throws Exception { doTestWriteSkewWithPassivation(false, Operation.CONDITIONAL_REPLACE, true); } public final void testIgnorePreviousValueAndReadOnPrimary() throws Exception { doTestIgnoreReturnValueAndRead(false); } public final void testIgnorePreviousValueAndReadOnNonOwner() throws Exception { doTestIgnoreReturnValueAndRead(true); } protected void doTestIgnoreReturnValueAndRead(boolean executeOnPrimaryOwner) throws Exception { final Object key = new MagicKey("ignore-previous-value", cache(0)); final AdvancedCache<Object, Object> c = executeOnPrimaryOwner ? advancedCache(0) : advancedCache(1); final TransactionManager tm = executeOnPrimaryOwner ? tm(0) : tm(1); for (Cache cache : caches()) { assertNull("wrong initial value for " + address(cache) + ".", cache.get(key)); } c.put("k", "init"); tm.begin(); c.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES).put("k", "v1"); assertEquals("v1", c.put("k", "v2")); Transaction tx = tm.suspend(); assertEquals("init", c.put("k", "other")); tm.resume(tx); tm.commit(); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = defaultConfigurationBuilder(); decorate(builder); createCluster(TestDataSCI.INSTANCE, builder, clusterSize()); waitForClusterToForm(); builder = defaultConfigurationBuilder(); builder.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class); builder.memory().size(MAX_ENTRIES); decorate(builder); defineConfigurationOnAllManagers(PASSIVATION_CACHE, builder); waitForClusterToForm(PASSIVATION_CACHE); } protected void decorate(ConfigurationBuilder builder) { // No-op } protected abstract CacheMode getCacheMode(); protected abstract int clusterSize(); private void doTestWriteSkewWithPassivation(boolean executeOnPrimaryOwner, Operation operation, boolean fail) throws Exception { final AdvancedCache<Object, Object> primaryOwner = advancedCache(0, PASSIVATION_CACHE); final Object key = new MagicKey("ignore-return-value", primaryOwner); final AdvancedCache<Object, Object> executeOnCache = executeOnPrimaryOwner ? advancedCache(0, PASSIVATION_CACHE) : advancedCache(1, PASSIVATION_CACHE); final TransactionManager tm = executeOnPrimaryOwner ? tm(0, PASSIVATION_CACHE) : tm(1, PASSIVATION_CACHE); for (Cache cache : caches(PASSIVATION_CACHE)) { assertNull("wrong initial value for " + address(cache) + ".", cache.get(key)); } switch (operation) { case CONDITIONAL_REMOVE: case CONDITIONAL_REPLACE: case REPLACE: log.debug("Initialize key"); primaryOwner.put(key, "init"); } log.debugf("Start the transaction and perform a %s operation", operation); tm.begin(); switch (operation) { case PUT: executeOnCache.put(key, "v1"); break; case REMOVE: executeOnCache.remove(key); break; case REPLACE: executeOnCache.replace(key, "v1"); break; case CONDITIONAL_PUT: executeOnCache.putIfAbsent(key, "v1"); break; case CONDITIONAL_REMOVE: assertTrue(executeOnCache.remove(key, "init")); break; case CONDITIONAL_REPLACE: assertTrue(executeOnCache.replace(key, "init", "v1")); break; default: tm.rollback(); fail("Unknown operation " + operation); } final Transaction tx = tm.suspend(); if (fail) { primaryOwner.put(key, "v2"); } primaryOwner.evict(key); log.debugf("It is going to try to commit the suspended transaction"); try { tm.resume(tx); tm.commit(); if (fail) { fail("Rollback expected!"); } } catch (RollbackException | HeuristicRollbackException e) { if (!fail) { fail("Rollback *not* expected!"); } //no-op } Object finalValue; switch (operation) { case REMOVE: case CONDITIONAL_REMOVE: finalValue = fail ? "v2" : null; break; default: finalValue = fail ? "v2" : "v1"; } log.debugf("So far so good. Check the key final value"); assertNoTransactions(); for (Cache cache : caches(PASSIVATION_CACHE)) { assertEquals("wrong final value for " + address(cache) + ".", finalValue, cache.get(key)); } } private ConfigurationBuilder defaultConfigurationBuilder() { ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.clustering().cacheMode(getCacheMode()) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .transaction().lockingMode(LockingMode.OPTIMISTIC); return builder; } private void doIgnoreReturnValueTest(boolean executeOnPrimaryOwner, Operation operation, boolean initKey) throws Exception { final Object key = new MagicKey("ignore-return-value", cache(0)); final AdvancedCache<Object, Object> c = executeOnPrimaryOwner ? advancedCache(0) : advancedCache(1); final TransactionManager tm = executeOnPrimaryOwner ? tm(0) : tm(1); for (Cache cache : caches()) { assertNull("wrong initial value for " + address(cache) + ".", cache.get(key)); } log.debugf("Initialize the key? %s", initKey); if (initKey) { cache(0).put(key, "init"); } Object finalValue = null; boolean rollbackExpected = false; log.debugf("Start the transaction and perform a %s operation", operation); tm.begin(); switch (operation) { case PUT: finalValue = "v1"; rollbackExpected = false; c.withFlags(Flag.IGNORE_RETURN_VALUES).put(key, "v1"); break; case REMOVE: finalValue = null; rollbackExpected = false; c.withFlags(Flag.IGNORE_RETURN_VALUES).remove(key); break; case REPLACE: finalValue = "v2"; rollbackExpected = initKey; c.withFlags(Flag.IGNORE_RETURN_VALUES).replace(key, "v1"); break; case CONDITIONAL_PUT: finalValue = "v2"; rollbackExpected = !initKey; c.withFlags(Flag.IGNORE_RETURN_VALUES).putIfAbsent(key, "v1"); break; case CONDITIONAL_REMOVE: finalValue = "v2"; rollbackExpected = initKey; c.withFlags(Flag.IGNORE_RETURN_VALUES).remove(key, "init"); break; case CONDITIONAL_REPLACE: finalValue = "v2"; rollbackExpected = initKey; c.withFlags(Flag.IGNORE_RETURN_VALUES).replace(key, "init", "v1"); break; default: tm.rollback(); fail("Unknown operation " + operation); } Transaction tx = tm.suspend(); log.debugf("Suspend the transaction and update the key"); c.put(key, "v2"); log.debugf("Checking if all the keys has the same value"); for (Cache cache : caches()) { assertEquals("wrong intermediate value for " + address(cache) + ".", "v2", cache.get(key)); } log.debugf("It is going to try to commit the suspended transaction"); try { tm.resume(tx); tm.commit(); if (rollbackExpected) { fail("Rollback expected!"); } } catch (RollbackException | HeuristicRollbackException e) { if (!rollbackExpected) { fail("Rollback *not* expected!"); } //no-op } log.debugf("So far so good. Check the key final value"); assertNoTransactions(); for (Cache cache : caches()) { assertEquals("wrong final value for " + address(cache) + ".", finalValue, cache.get(key)); } } private enum Operation { PUT, REMOVE, REPLACE, CONDITIONAL_PUT, CONDITIONAL_REMOVE, CONDITIONAL_REPLACE } }
17,647
37.034483
127
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/TransactionalLocalWriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.Future; import jakarta.transaction.Status; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.commons.test.ExceptionRunnable; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(groups = "functional", testName = "container.versioning.TransactionalLocalWriteSkewTest") public class TransactionalLocalWriteSkewTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder .transaction() .transactionManagerLookup(new EmbeddedTransactionManagerLookup()) .transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(LockingMode.OPTIMISTIC) .locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()) .isolationLevel(IsolationLevel.REPEATABLE_READ); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(builder); cacheManager.defineConfiguration("cache", builder.build()); return cacheManager; } public void testSharedCounter() throws Exception { final int counterMaxValue = 1000; Cache<String, Integer> c1 = cacheManager.getCache("cache"); // initialize the counter c1.put("counter", 0); // check if the counter is initialized in all caches assertEquals(Integer.valueOf(0), c1.get("counter")); // this will keep the values put by both threads. any duplicate value // will be detected because of the // return value of add() method ConcurrentSkipListSet<Integer> uniqueValuesIncremented = new ConcurrentSkipListSet<>(); // create both threads (simulate a node) Future<Void> ict1 = fork(new IncrementCounterTask(c1, uniqueValuesIncremented, counterMaxValue)); Future<Void> ict2 = fork(new IncrementCounterTask(c1, uniqueValuesIncremented, counterMaxValue)); try { // wait to finish ict1.get(); ict2.get(); // check if all caches obtains the counter_max_values assertTrue(c1.get("counter") >= counterMaxValue); } finally { ict1.cancel(true); ict2.cancel(true); } } private class IncrementCounterTask implements ExceptionRunnable { private Cache<String, Integer> cache; private ConcurrentSkipListSet<Integer> uniqueValuesSet; private TransactionManager transactionManager; private int lastValue; private int counterMaxValue; public IncrementCounterTask(Cache<String, Integer> cache, ConcurrentSkipListSet<Integer> uniqueValuesSet, int counterMaxValue) { this.cache = cache; this.transactionManager = cache.getAdvancedCache().getTransactionManager(); this.uniqueValuesSet = uniqueValuesSet; this.lastValue = 0; this.counterMaxValue = counterMaxValue; } @Override public void run() { int failuresCounter = 0; while (lastValue < counterMaxValue && !Thread.interrupted()) { boolean success = false; try { //start transaction, get the counter value, increment and put it again //check for duplicates in case of success transactionManager.begin(); Integer value = cache.get("counter"); value = value + 1; lastValue = value; cache.put("counter", value); transactionManager.commit(); success = true; boolean unique = uniqueValuesSet.add(value); assertTrue("Duplicate value found (value=" + lastValue + ")", unique); } catch (Exception e) { // expected exception failuresCounter++; assertTrue("Too many failures incrementing the counter", failuresCounter < 10 * counterMaxValue); } finally { if (!success) { try { //lets rollback if (transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) transactionManager.rollback(); } catch (Throwable t) { //the only possible exception is thrown by the rollback. just ignore it log.trace("Exception during rollback", t); } } } } } } }
5,171
38.181818
134
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/SimpleConditionalOperationsWriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; 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.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(groups = "functional", testName = "container.versioning.SimpleConditionalOperationsWriteSkewTest") public class SimpleConditionalOperationsWriteSkewTest extends MultipleCacheManagersTest { protected ConfigurationBuilder getConfig() { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true); dcc.transaction().locking().isolationLevel(IsolationLevel.REPEATABLE_READ); return dcc; } @Override protected void createCacheManagers() throws Throwable { createCluster(TestDataSCI.INSTANCE, getConfig(), 2); waitForClusterToForm(); } public void testReplaceFromMainOwner() throws Throwable { Object k = getKeyForCache(0); cache(0).put(k, "0"); tm(0).begin(); cache(0).put("kkk", "vvv"); cache(0).replace(k, "v1", "v2"); tm(0).commit(); assertEquals(advancedCache(0).getDataContainer().get(k).getValue(), "0"); assertEquals(advancedCache(1).getDataContainer().get(k).getValue(), "0"); log.trace("here is the interesting replace."); cache(0).replace(k, "0", "1"); assertEquals(advancedCache(0).getDataContainer().get(k).getValue(), "1"); assertEquals(advancedCache(1).getDataContainer().get(k).getValue(), "1"); } public void testRemoveFromMainOwner() { Object k = getKeyForCache(0); cache(0).put(k, "0"); cache(0).remove(k, "1"); assertEquals(advancedCache(0).getDataContainer().get(k).getValue(), "0"); assertEquals(advancedCache(1).getDataContainer().get(k).getValue(), "0"); cache(0).remove(k, "0"); assertNull(advancedCache(0).getDataContainer().get(k)); assertNull(advancedCache(1).getDataContainer().get(k)); } public void testPutIfAbsentFromMainOwner() { Object k = getKeyForCache(0); cache(0).put(k, "0"); cache(0).putIfAbsent(k, "1"); assertEquals(advancedCache(0).getDataContainer().get(k).getValue(), "0"); assertEquals(advancedCache(1).getDataContainer().get(k).getValue(), "0"); cache(0).remove(k); cache(0).putIfAbsent(k, "1"); assertEquals(advancedCache(0).getDataContainer().get(k).getValue(), "1"); assertEquals(advancedCache(1).getDataContainer().get(k).getValue(), "1"); } }
2,708
36.109589
104
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/NumericVersionGeneratorTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import java.util.Arrays; import java.util.List; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.notifications.cachemanagerlistener.event.Event; import org.infinispan.notifications.cachemanagerlistener.event.impl.EventImpl; import org.infinispan.remoting.transport.Address; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * Test numeric version generator logic */ @Test(groups = "functional", testName = "container.versioning.NumericVersionGeneratorTest") public class NumericVersionGeneratorTest { public void testGenerateVersion() { RankCalculator rankCalculator = new RankCalculator(); Configuration config = new ConfigurationBuilder().clustering().cacheMode(CacheMode.DIST_SYNC).build(); NumericVersionGenerator vg = new NumericVersionGenerator(); TestingUtil.inject(vg, rankCalculator, config); vg.start(); vg.resetCounter(); TestAddress addr1 = new TestAddress(1); TestAddress addr2 = new TestAddress(2); TestAddress addr3 = new TestAddress(1); List<Address> members = Arrays.asList(addr1, addr2, addr3); rankCalculator.updateRank(new EventImpl(null, null, Event.Type.VIEW_CHANGED, members, members, addr2, 1)); assertEquals(0x1000200000000L, rankCalculator.getVersionPrefix()); assertEquals(new NumericVersion(0x1000200000001L), vg.generateNew()); assertEquals(new NumericVersion(0x1000200000002L), vg.generateNew()); members = Arrays.asList(addr2, addr3); rankCalculator.updateRank(new EventImpl(null, null, Event.Type.VIEW_CHANGED, members, members, addr2, 2)); assertEquals(0x2000100000000L, rankCalculator.getVersionPrefix()); assertEquals(new NumericVersion(0x2000100000003L), vg.generateNew()); } class TestAddress implements Address { int addressNum; TestAddress(int addressNum) { this.addressNum = addressNum; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; TestAddress that = (TestAddress) o; if (addressNum != that.addressNum) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + addressNum; return result; } @Override public int compareTo(Address o) { TestAddress oa = (TestAddress) o; return addressNum - oa.addressNum; } } }
2,825
33.048193
112
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/DistWriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.fail; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.context.Flag; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.distribution.MagicKey; import org.testng.Assert; import org.testng.annotations.Test; @Test(testName = "container.versioning.DistWriteSkewTest", groups = "functional") public class DistWriteSkewTest extends AbstractClusteredWriteSkewTest { @Override protected CacheMode getCacheMode() { return CacheMode.DIST_SYNC; } @Override protected int clusterSize() { return 4; } public void testWriteSkew() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); Cache<Object, Object> cache3 = cache(3); MagicKey hello = new MagicKey("hello", cache(2)); // Auto-commit is true cache1.put(hello, "world 1"); tm(1).begin(); assertEquals("world 1", cache1.get(hello)); Transaction t = tm(1).suspend(); // Induce a write skew cache3.put(hello, "world 3"); assertEquals("world 3", cache0.get(hello)); assertEquals("world 3", cache1.get(hello)); assertEquals("world 3", cache2.get(hello)); assertEquals("world 3", cache3.get(hello)); tm(1).resume(t); cache1.put(hello, "world 2"); try { tm(1).commit(); fail("Transaction should roll back"); } catch (RollbackException re) { // expected } assertEquals("world 3", cache0.get(hello)); assertEquals("world 3", cache1.get(hello)); assertEquals("world 3", cache2.get(hello)); assertEquals("world 3", cache3.get(hello)); } public void testWriteSkewOnNonOwner() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); Cache<Object, Object> cache3 = cache(3); MagicKey hello = new MagicKey("hello", cache(0)); // Owned by cache0 and cache1 int owners[] = {0, 0}; int nonOwners[] = {0, 0}; int j=0, k = 0; for (int i=0; i<4; i++) { if (DistributionTestHelper.isOwner(cache(i), hello)) owners[j++] = i; else nonOwners[k++] = i; } // Auto-commit is true cache(owners[1]).put(hello, "world 1"); tm(nonOwners[0]).begin(); assert "world 1".equals(cache(nonOwners[0]).get(hello)); Transaction t = tm(nonOwners[0]).suspend(); // Induce a write skew cache(nonOwners[1]).put(hello, "world 3"); assertEquals("world 3", cache0.get(hello)); assertEquals("world 3", cache1.get(hello)); assertEquals("world 3", cache2.get(hello)); assertEquals("world 3", cache3.get(hello)); tm(nonOwners[0]).resume(t); cache(nonOwners[0]).put(hello, "world 2"); try { tm(nonOwners[0]).commit(); fail("Transaction should roll back"); } catch (RollbackException re) { // expected } assertEquals("world 3", cache0.get(hello)); assertEquals("world 3", cache1.get(hello)); assertEquals("world 3", cache2.get(hello)); assertEquals("world 3", cache3.get(hello)); } public void testWriteSkewMultiEntries() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); Cache<Object, Object> cache3 = cache(3); MagicKey hello = new MagicKey("hello", cache(2)); MagicKey hello2 = new MagicKey("hello2", cache(3)); MagicKey hello3 = new MagicKey("hello3", cache(0)); tm(1).begin(); cache1.put(hello, "world 1"); cache1.put(hello2, "world 1"); cache1.put(hello3, "world 1"); tm(1).commit(); tm(1).begin(); cache1.put(hello2, "world 2"); cache1.put(hello3, "world 2"); assertEquals("world 1", cache1.get(hello)); assertEquals("world 2", cache1.get(hello2)); assertEquals("world 2", cache1.get(hello3)); Transaction t = tm(1).suspend(); // Induce a write skew // Auto-commit is true cache3.put(hello, "world 3"); for (Cache<Object, Object> c : caches()) { assertEquals("world 3", c.get(hello)); assertEquals("world 1", c.get(hello2)); assertEquals("world 1", c.get(hello3)); } tm(1).resume(t); cache1.put(hello, "world 2"); try { tm(1).commit(); fail("Transaction should roll back"); } catch (RollbackException re) { // expected } for (Cache<Object, Object> c : caches()) { assertEquals("world 3", c.get(hello)); assertEquals("world 1", c.get(hello2)); assertEquals("world 1", c.get(hello3)); } } public void testNullEntries() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); Cache<Object, Object> cache3 = cache(3); MagicKey hello = new MagicKey("hello", cache2, cache1); // Auto-commit is true cache0.put(hello, "world"); tm(0).begin(); assertEquals("world", cache0.get(hello)); Transaction t = tm(0).suspend(); cache1.remove(hello); assertNull(cache0.get(hello)); assertNull(cache1.get(hello)); assertNull(cache2.get(hello)); assertNull(cache3.get(hello)); tm(0).resume(t); cache0.put(hello, "world2"); try { tm(0).commit(); fail("This transaction should roll back"); } catch (RollbackException expected) { // expected } assertNull(cache0.get(hello)); assertNull(cache1.get(hello)); assertNull(cache2.get(hello)); assertNull(cache3.get(hello)); } public void testResendPrepare() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); Cache<Object, Object> cache3 = cache(3); MagicKey hello = new MagicKey("hello", cache(2)); // Auto-commit is true cache0.put(hello, "world"); // create a write skew tm(2).begin(); assertEquals("world", cache2.get(hello)); Transaction t = tm(2).suspend(); // Implicit tx. Prepare should be retried. cache(0).put(hello, "world 2"); assertEquals("world 2", cache0.get(hello)); assertEquals("world 2", cache1.get(hello)); assertEquals("world 2", cache2.get(hello)); assertEquals("world 2", cache3.get(hello)); tm(2).resume(t); cache2.put(hello, "world 3"); try { tm(2).commit(); fail("This transaction should roll back"); } catch (RollbackException expected) { // expected } assertEquals("world 2", cache0.get(hello)); assertEquals("world 2", cache1.get(hello)); assertEquals("world 2", cache2.get(hello)); assertEquals("world 2", cache3.get(hello)); } public void testLocalOnlyPut() { localOnlyPut(this.<Integer, String>cache(0), 1, "v1"); localOnlyPut(this.<Integer, String>cache(1), 2, "v2"); localOnlyPut(this.<Integer, String>cache(2), 3, "v3"); localOnlyPut(this.<Integer, String>cache(3), 4, "v4"); } public void testSameNodeKeyCreation() throws Exception { tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v1"); Transaction tx0 = tm(0).suspend(); //other transaction do the same thing tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v2"); tm(0).commit(); tm(0).resume(tx0); try { tm(0).commit(); Assert.fail("The transaction should rollback"); } catch (RollbackException expected) { //expected } Assert.assertEquals(cache(0).get("NewKey"), "v2"); Assert.assertEquals(cache(1).get("NewKey"), "v2"); } public void testDifferentNodeKeyCreation() throws Exception { tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v1"); Transaction tx0 = tm(0).suspend(); //other transaction, in other node, do the same thing tm(1).begin(); Assert.assertEquals(cache(1).get("NewKey"), null); cache(1).put("NewKey", "v2"); tm(1).commit(); tm(0).resume(tx0); try { tm(0).commit(); Assert.fail("The transaction should rollback"); } catch (RollbackException expected) { //expected } Assert.assertEquals(cache(0).get("NewKey"), "v2"); Assert.assertEquals(cache(1).get("NewKey"), "v2"); } private void localOnlyPut(Cache<Integer, String> cache, Integer k, String v) { cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).put(k, v); } }
9,323
29.272727
85
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/RecoveryEnabledWriteSkewTest.java
package org.infinispan.container.versioning; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; /** * It tests the write skew with recovery. * * @author Pedro Ruivo * @since 7.2 */ @Test(groups = "functional", testName = "container.versioning.RecoveryEnabledWriteSkewTest") public class RecoveryEnabledWriteSkewTest extends AbstractClusteredWriteSkewTest { @Override protected CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } @Override protected int clusterSize() { return 2; } @Override protected void decorate(ConfigurationBuilder builder) { builder.transaction().useSynchronization(false); builder.transaction().recovery().enabled(true); } }
815
25.322581
92
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/WriteSkewConsistencyTest.java
package org.infinispan.container.versioning; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.extractInterceptorChain; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.infinispan.test.TestingUtil.wrapInboundInvocationHandler; import static org.infinispan.transaction.impl.WriteSkewHelper.versionFromEntry; import static org.testng.AssertJUnit.assertEquals; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.commands.ReplicableCommand; import org.infinispan.commands.remote.CacheRpcCommand; import org.infinispan.commands.remote.ClusteredGetCommand; 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.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.context.impl.TxInvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.remoting.inboundhandler.AbstractDelegatingHandler; import org.infinispan.remoting.inboundhandler.DeliverOrder; import org.infinispan.remoting.inboundhandler.PerCacheInboundInvocationHandler; import org.infinispan.remoting.inboundhandler.Reply; import org.infinispan.remoting.responses.Response; 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.TestDataSCI; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.util.AbstractDelegatingRpcManager; import org.infinispan.util.ControlledConsistentHashFactory; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * @author Pedro Ruivo * @since 6.0 */ @Test(groups = "functional", testName = "container.versioning.WriteSkewConsistencyTest") @CleanupAfterMethod @InCacheMode({CacheMode.DIST_SYNC, CacheMode.REPL_SYNC}) public class WriteSkewConsistencyTest extends MultipleCacheManagersTest { public void testValidationOnlyInPrimaryOwner() throws Exception { // ControlledConsistentHashFactory sets cache(1) as the primary owner and cache(0) as the backup for all keys final Object key = "key"; final DataContainer<?, ?> primaryOwnerDataContainer = extractComponent(cache(1), InternalDataContainer.class); final DataContainer<?, ?> backupOwnerDataContainer = extractComponent(cache(0), InternalDataContainer.class); final VersionGenerator versionGenerator = extractComponent(cache(1), VersionGenerator.class); injectReorderResponseRpcManager(cache(3), cache(0)); cache(1).put(key, 1); for (Cache<?, ?> cache : caches()) { assertEquals("Wrong initial value for cache " + address(cache), 1, cache.get(key)); } InternalCacheEntry<? ,?> ice0 = primaryOwnerDataContainer.peek(key); InternalCacheEntry<?, ?> ice1 = backupOwnerDataContainer.peek(key); assertSameVersion("Wrong version for the same key", versionFromEntry(ice0), versionFromEntry(ice1)); final IncrementableEntryVersion version0 = versionFromEntry(ice0); //version1 is put by tx1 final IncrementableEntryVersion version1 = versionGenerator.increment(version0); //version2 is put by tx2 final IncrementableEntryVersion version2 = versionGenerator.increment(version1); ControllerInboundInvocationHandler handler = wrapInboundInvocationHandler(cache(0), ControllerInboundInvocationHandler::new); BackupOwnerInterceptor backupOwnerInterceptor = injectBackupOwnerInterceptor(cache(0)); backupOwnerInterceptor.blockCommit(true); handler.discardRemoteGet = true; Future<Boolean> tx1 = fork(() -> { tm(2).begin(); assertEquals("Wrong value for tx1.", 1, cache(2).get(key)); cache(2).put(key, 2); tm(2).commit(); return Boolean.TRUE; }); //after this, the primary owner has committed the new value but still have the locks acquired. //in the backup owner, it still has the old value eventually(() -> { Integer value = (Integer) cache(3).get(key); return value != null && value == 2; }); assertSameVersion("Wrong version in the primary owner", versionFromEntry(primaryOwnerDataContainer.peek(key)), version1); assertSameVersion("Wrong version in the backup owner", versionFromEntry(backupOwnerDataContainer.peek(key)), version0); backupOwnerInterceptor.resetPrepare(); //tx2 will read from the primary owner (i.e., the most recent value) and will commit. Future<Boolean> tx2 = fork(() -> { tm(3).begin(); assertEquals("Wrong value for tx2.", 2, cache(3).get(key)); cache(3).put(key, 3); tm(3).commit(); return Boolean.TRUE; }); //if everything works fine, it should ignore the value from the backup owner and only use the version returned by //the primary owner. AssertJUnit.assertTrue("Prepare of tx2 was never received.", backupOwnerInterceptor.awaitPrepare(10000)); backupOwnerInterceptor.blockCommit(false); handler.discardRemoteGet = false; //both transaction should commit AssertJUnit.assertTrue("Error in tx1.", tx1.get(15, SECONDS)); AssertJUnit.assertTrue("Error in tx2.", tx2.get(15, SECONDS)); //both txs has committed assertSameVersion("Wrong version in the primary owner", versionFromEntry(primaryOwnerDataContainer.peek(key)), version2); assertSameVersion("Wrong version in the backup owner", versionFromEntry(backupOwnerDataContainer.peek(key)), version2); assertNoTransactions(); assertNotLocked(key); } @Override protected final void createCacheManagers() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(cacheMode, true); builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ); ControlledConsistentHashFactory consistentHashFactory = cacheMode.isReplicated() ? new ControlledConsistentHashFactory.Replicated(1) : new ControlledConsistentHashFactory.Default(1, 0); builder.clustering().hash().numSegments(1).consistentHashFactory(consistentHashFactory); createClusteredCaches(4, TestDataSCI.INSTANCE, builder); } private BackupOwnerInterceptor injectBackupOwnerInterceptor(Cache<?, ?> cache) { BackupOwnerInterceptor ownerInterceptor = new BackupOwnerInterceptor(); extractInterceptorChain(cache).addInterceptor(ownerInterceptor, 1); return ownerInterceptor; } private void injectReorderResponseRpcManager(Cache<?, ?> toInject, Cache<?, ?> lastResponse) { RpcManager rpcManager = extractComponent(toInject, RpcManager.class); ReorderResponsesRpcManager newRpcManager = new ReorderResponsesRpcManager(address(lastResponse), rpcManager); replaceComponent(toInject, RpcManager.class, newRpcManager, true); } private void assertSameVersion(String message, EntryVersion v0, EntryVersion v1) { assertEquals(message, InequalVersionComparisonResult.EQUAL, v0.compareTo(v1)); } @SuppressWarnings("rawtypes") static class BackupOwnerInterceptor extends DDAsyncInterceptor { private final Object blockCommitLock = new Object(); private final Object prepareProcessedLock = new Object(); private boolean blockCommit; private boolean prepareProcessed; @Override public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { blockIfNeeded(); return invokeNext(ctx, command); } @Override public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { return invokeNextAndFinally(ctx, command, (rCtx, rCommand, rv, throwable) -> notifyPrepareProcessed()); } public void blockCommit(boolean blockCommit) { synchronized (blockCommitLock) { this.blockCommit = blockCommit; if (!blockCommit) { blockCommitLock.notifyAll(); } } } public boolean awaitPrepare(long milliseconds) throws InterruptedException { synchronized (prepareProcessedLock) { long endTime = System.nanoTime() + MILLISECONDS.toNanos(milliseconds); long sleepTime = NANOSECONDS.toMillis(endTime - System.nanoTime()); while (!prepareProcessed && sleepTime > 0) { prepareProcessedLock.wait(sleepTime); sleepTime = NANOSECONDS.toMillis(endTime - System.nanoTime()); } return prepareProcessed; } } public void resetPrepare() { synchronized (prepareProcessedLock) { prepareProcessed = false; } } private void notifyPrepareProcessed() { synchronized (prepareProcessedLock) { prepareProcessed = true; prepareProcessedLock.notifyAll(); } } private void blockIfNeeded() throws InterruptedException { synchronized (blockCommitLock) { while (blockCommit) { blockCommitLock.wait(); } } } } private class ReorderResponsesRpcManager extends AbstractDelegatingRpcManager { private final Address lastResponse; public ReorderResponsesRpcManager(Address lastResponse, RpcManager realOne) { super(realOne); this.lastResponse = lastResponse; } @SuppressWarnings("unchecked") @Override protected <T> CompletionStage<T> performRequest(Collection<Address> targets, ReplicableCommand command, ResponseCollector<T> collector, Function<ResponseCollector<T>, CompletionStage<T>> invoker, RpcOptions rpcOptions) { return super.performRequest(targets, command, collector, invoker, rpcOptions) .thenApply(responseObject -> { if (!(responseObject instanceof Map)) { log.debugf("Single response for command %s: %s", command, responseObject); return responseObject; } Map<Address, Response> newResponseMap = new LinkedHashMap<>(); boolean containsLastResponseAddress = false; for (Map.Entry<Address, Response> entry : ((Map<Address, Response>) responseObject) .entrySet()) { if (lastResponse.equals(entry.getKey())) { containsLastResponseAddress = true; continue; } newResponseMap.put(entry.getKey(), entry.getValue()); } if (containsLastResponseAddress) { newResponseMap.put(lastResponse, ((Map<Address, Response>) responseObject).get(lastResponse)); } log.debugf("Responses for command %s are %s", command, newResponseMap.values()); return (T) newResponseMap; }); } } private static class ControllerInboundInvocationHandler extends AbstractDelegatingHandler { private volatile boolean discardRemoteGet; private ControllerInboundInvocationHandler(PerCacheInboundInvocationHandler delegate) { super(delegate); } @Override public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) { if (discardRemoteGet && command.getCommandId() == ClusteredGetCommand.COMMAND_ID) { return; } delegate.handle(command, reply, order); } } }
12,831
42.945205
131
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/ReplWriteSkewTest.java
package org.infinispan.container.versioning; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.context.Flag; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.Assert; import org.testng.annotations.Test; @Test(testName = "container.versioning.ReplWriteSkewTest", groups = "functional") @CleanupAfterMethod public class ReplWriteSkewTest extends AbstractClusteredWriteSkewTest { @Override protected CacheMode getCacheMode() { return CacheMode.REPL_SYNC; } @Override protected int clusterSize() { return 2; } public void testWriteSkew() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); // Auto-commit is true cache0.put("hello", "world 1"); tm(0).begin(); assert "world 1".equals(cache0.get("hello")); Transaction t = tm(0).suspend(); // Induce a write skew cache1.put("hello", "world 3"); assert cache0.get("hello").equals("world 3"); assert cache1.get("hello").equals("world 3"); tm(0).resume(t); cache0.put("hello", "world 2"); try { tm(0).commit(); assert false : "Transaction should roll back"; } catch (RollbackException | HeuristicRollbackException re) { // expected } assert "world 3".equals(cache0.get("hello")); assert "world 3".equals(cache1.get("hello")); } public void testWriteSkewMultiEntries() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); tm(0).begin(); cache0.put("hello", "world 1"); cache0.put("hello2", "world 1"); tm(0).commit(); tm(0).begin(); cache0.put("hello2", "world 2"); assert "world 2".equals(cache0.get("hello2")); assert "world 1".equals(cache0.get("hello")); Transaction t = tm(0).suspend(); // Induce a write skew // Auto-commit is true cache1.put("hello", "world 3"); assert cache0.get("hello").equals("world 3"); assert cache0.get("hello2").equals("world 1"); assert cache1.get("hello").equals("world 3"); assert cache1.get("hello2").equals("world 1"); tm(0).resume(t); cache0.put("hello", "world 2"); try { tm(0).commit(); assert false : "Transaction should roll back"; } catch (RollbackException|HeuristicRollbackException re) { // expected } assert cache0.get("hello").equals("world 3"); assert cache0.get("hello2").equals("world 1"); assert cache1.get("hello").equals("world 3"); assert cache1.get("hello2").equals("world 1"); } public void testNullEntries() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); // Auto-commit is true cache0.put("hello", "world"); tm(0).begin(); assert "world".equals(cache0.get("hello")); Transaction t = tm(0).suspend(); cache1.remove("hello"); assert null == cache0.get("hello"); assert null == cache1.get("hello"); tm(0).resume(t); cache0.put("hello", "world2"); try { tm(0).commit(); assert false : "This transaction should roll back"; } catch (RollbackException|HeuristicRollbackException expected) { // expected } assert null == cache0.get("hello"); assert null == cache1.get("hello"); } public void testResendPrepare() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); // Auto-commit is true cache0.put("hello", "world"); // create a write skew tm(0).begin(); assert "world".equals(cache0.get("hello")); Transaction t = tm(0).suspend(); // Implicit tx. Prepare should be retried. cache(0).put("hello", "world2"); assert "world2".equals(cache0.get("hello")); assert "world2".equals(cache1.get("hello")); tm(0).resume(t); cache0.put("hello", "world3"); try { log.warn("----- Now committing ---- "); tm(0).commit(); assert false : "This transaction should roll back"; } catch (RollbackException|HeuristicRollbackException expected) { // expected } assert "world2".equals(cache0.get("hello")); assert "world2".equals(cache1.get("hello")); } public void testLocalOnlyPut() { localOnlyPut(this.<Integer, String>cache(0), 1, "v1"); localOnlyPut(this.<Integer, String>cache(1), 2, "v2"); } public void testSameNodeKeyCreation() throws Exception { tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v1"); Transaction tx0 = tm(0).suspend(); //other transaction do the same thing tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v2"); tm(0).commit(); tm(0).resume(tx0); try { tm(0).commit(); Assert.fail("The transaction should rollback"); } catch (RollbackException|HeuristicRollbackException expected) { //expected } Assert.assertEquals(cache(0).get("NewKey"), "v2"); Assert.assertEquals(cache(1).get("NewKey"), "v2"); } public void testDifferentNodeKeyCreation() throws Exception { tm(0).begin(); Assert.assertEquals(cache(0).get("NewKey"), null); cache(0).put("NewKey", "v1"); Transaction tx0 = tm(0).suspend(); //other transaction, in other node, do the same thing tm(1).begin(); Assert.assertEquals(cache(1).get("NewKey"), null); cache(1).put("NewKey", "v2"); tm(1).commit(); tm(0).resume(tx0); try { tm(0).commit(); Assert.fail("The transaction should rollback"); } catch (RollbackException|HeuristicRollbackException expected) { //expected } Assert.assertEquals(cache(0).get("NewKey"), "v2"); Assert.assertEquals(cache(1).get("NewKey"), "v2"); } private void localOnlyPut(Cache<Integer, String> cache, Integer k, String v) { cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).put(k, v); } }
6,458
28.359091
81
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/DistL1WriteSkewTest.java
package org.infinispan.container.versioning; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.distribution.MagicKey; import org.testng.AssertJUnit; import org.testng.annotations.Test; @Test(testName = "container.versioning.DistL1WriteSkewTest", groups = "functional") public class DistL1WriteSkewTest extends DistWriteSkewTest { @Override protected void decorate(ConfigurationBuilder builder) { // Enable L1 builder.clustering().l1().enable(); builder.clustering().remoteTimeout(4, TimeUnit.MINUTES); } @Test public void testL1ValuePutCanExpire() { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); MagicKey hello = new MagicKey("hello", cache0, cache1); DistributionTestHelper.assertIsNotInL1(cache2, hello); // Auto-commit is true cache2.put(hello, "world 1"); DistributionTestHelper.assertIsInL1(cache2, hello); } @Test public void testL1ValueGetCanExpire() { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache1 = cache(1); Cache<Object, Object> cache2 = cache(2); MagicKey hello = new MagicKey("hello", cache0, cache1); DistributionTestHelper.assertIsNotInL1(cache2, hello); // Auto-commit is true cache0.put(hello, "world 1"); assertEquals("world 1", cache2.get(hello)); DistributionTestHelper.assertIsInL1(cache2, hello); } public void testL1Enabled() { for (Cache cache : caches()) { AssertJUnit.assertTrue("L1 not enabled for " + address(cache), cache.getCacheConfiguration().clustering().l1().enabled()); } } }
1,947
29.4375
91
java
null
infinispan-main/core/src/test/java/org/infinispan/container/versioning/VersionedDistStateTransferTest.java
package org.infinispan.container.versioning; import static org.infinispan.transaction.impl.WriteSkewHelper.versionFromEntry; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.fail; import jakarta.transaction.RollbackException; import jakarta.transaction.Transaction; import org.infinispan.Cache; 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.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.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(testName = "container.versioning.VersionedDistStateTransferTest", groups = "functional") @CleanupAfterMethod public class VersionedDistStateTransferTest extends MultipleCacheManagersTest { ConfigurationBuilder builder; @Override protected void createCacheManagers() throws Throwable { builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true); builder.clustering().cacheMode(CacheMode.DIST_SYNC).l1().disable() .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) .transaction().lockingMode(LockingMode.OPTIMISTIC); createCluster(TestDataSCI.INSTANCE, builder, 4); waitForClusterToForm(); } public void testStateTransfer() throws Exception { Cache<Object, Object> cache0 = cache(0); Cache<Object, Object> cache3 = cache(3); int NUM_KEYS = 20; MagicKey[] keys = new MagicKey[NUM_KEYS]; String[] values = new String[NUM_KEYS]; for (int i = 0; i < NUM_KEYS; i++) { // Put the entries on the cache that will be killed keys[i] = new MagicKey("key" + i, cache3); values[i] = "v" + i; cache0.put(keys[i], values[i]); } // no state transfer per se, but we check that the initial data is ok checkStateTransfer(keys, values); Transaction[] txs = new Transaction[NUM_KEYS]; for (int i = 0; i < NUM_KEYS; i++) { int cacheIndex = i % 3; tm(cacheIndex).begin(); { assertEquals(values[i], cache(cacheIndex).get(keys[i])); } txs[i] = tm(cacheIndex).suspend(); } log.debugf("Starting joiner"); addClusterEnabledCacheManager(TestDataSCI.INSTANCE, builder); Cache<Object, Object> cache4 = cache(4); log.debugf("Joiner started, checking transferred data"); checkStateTransfer(keys, values); log.debugf("Stopping cache %s", cache3); manager(3).stop(); // Eliminate the dead cache from the caches collection, cache4 now becomes cache(3) cacheManagers.remove(3); TestingUtil.waitForNoRebalance(caches()); log.debugf("Leaver stopped, checking transferred data"); checkStateTransfer(keys, values); // Cause a write skew for (int i = 0; i < NUM_KEYS; i++) { cache4.put(keys[i], "new " + values[i]); } for (int i = 0; i < NUM_KEYS; i++) { int cacheIndex = i % 3; log.tracef("Expecting a write skew failure for key %s on cache %s", keys[i], cache(cacheIndex)); tm(cacheIndex).resume(txs[i]); cache(cacheIndex).put(keys[i], "new new " + values[i]); try { tm(cacheIndex).commit(); fail("The write skew check should have failed!"); } catch (RollbackException expected) { // Expected } } for (int cacheIndex = 0; cacheIndex < 4; cacheIndex++) { for (int i = 0; i < NUM_KEYS; i++) { assertEquals("Wrong value found on cache " + cache(cacheIndex), "new " + values[i], cache(cacheIndex).get(keys[i])); } } } private void checkStateTransfer(MagicKey[] keys, String[] values) { for (Cache<Object, Object> c: caches()) { for (int i = 0; i < keys.length; i++) { assertEquals("Wrong value found on cache " + c, values[i], c.get(keys[i])); checkVersion(c, keys[i]); } } } private void checkVersion(Cache<Object, Object> c, MagicKey key) { LocalizedCacheTopology topology = c.getAdvancedCache().getDistributionManager().getCacheTopology(); if (topology.isReadOwner(key)) { InternalCacheEntry<Object, Object> ice = c.getAdvancedCache().getDataContainer().peek(key); assertNotNull("Entry not found on owner cache " + c, ice); assertNotNull("Version is null on owner cache " + c, versionFromEntry(ice)); } } }
4,956
37.130769
105
java
null
infinispan-main/core/src/test/java/org/infinispan/container/impl/DefaultSegmentedDataContainerTest.java
package org.infinispan.container.impl; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Set; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.DataContainer; import org.infinispan.distribution.DistributionManager; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * @author wburns * @since 9.3 */ @Test(groups = "functional", testName = "container.impl.DefaultSegmentedDataContainerTest") public class DefaultSegmentedDataContainerTest extends MultipleCacheManagersTest { private static final String CACHE_NAME = "dist"; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(CacheMode.DIST_SYNC); createClusteredCaches(3, CACHE_NAME, builderUsed); } public void ensureOldMapsRemoved() { for (Cache<Object, Object> cache : caches(CACHE_NAME)) { DataContainer dc = TestingUtil.extractComponent(cache, InternalDataContainer.class); assertEquals(DefaultSegmentedDataContainer.class, dc.getClass()); DefaultSegmentedDataContainer segmentedDataContainer = (DefaultSegmentedDataContainer) dc; DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); Address address = cache.getCacheManager().getAddress(); Set<Integer> segments = dm.getReadConsistentHash().getSegmentsForOwner(address); int mapCount = 0; for (int i = 0; i < segmentedDataContainer.maps.length(); ++i) { if (segmentedDataContainer.maps.get(i) != null) { assertTrue("Segment " + i + " has non null map, but wasn't owned by node: " + address + "!", segments.contains(i)); mapCount++; } } assertEquals(mapCount, segments.size()); } } }
2,192
36.169492
107
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapSingleNodeTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.Cache; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.time.TimeService; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.encoding.DataConversion; import org.infinispan.test.TestingUtil; import org.infinispan.util.ControlledTimeService; import org.testng.annotations.Test; /** */ @Test(groups = "functional", testName = "container.offheap.OffHeapSingleNodeTest") public class OffHeapSingleNodeTest extends OffHeapMultiNodeTest { protected ControlledTimeService timeService; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false); dcc.memory().storageType(StorageType.OFF_HEAP); // Only start up the 1 cache addClusterEnabledCacheManager(dcc); configureTimeService(); } protected void configureTimeService() { timeService = new ControlledTimeService(); TestingUtil.replaceComponent(cacheManagers.get(0), TimeService.class, timeService, true); } public void testLotsOfWrites() { Cache<String, String> cache = cache(0); for (int i = 0; i < 5_000; ++i) { cache.put("key" + i, "value" + i); } } public void testExpiredEntryCompute() throws IOException, InterruptedException { Cache<Object, Object> cache = cache(0); String key = "key"; cache.put(key, "value", 10, TimeUnit.MILLISECONDS); timeService.advance(20); DataConversion keyDataConversion = cache.getAdvancedCache().getKeyDataConversion(); WrappedBytes keyWB = (WrappedBytes) keyDataConversion.toStorage(key); AtomicBoolean invoked = new AtomicBoolean(false); DataContainer container = cache.getAdvancedCache().getDataContainer(); container.compute(keyWB, (k, e, f) -> { invoked.set(true); // Just leave it in there return e; }); // Should not have invoked, due to expiration assertTrue(invoked.get()); assertNotNull(container.peek(keyWB)); // Actually reading it shouldn't return though and actually remove assertNull(cache.get(key)); // Now that we did a get, the peek shouldn't return anything assertNull(container.peek(keyWB)); } }
2,788
31.430233
95
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapConcurrentMapTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.container.impl.InternalEntryFactoryImpl; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(groups = "stress", testName = "container.offheap.OffHeapConcurrentMapTest") public class OffHeapConcurrentMapTest { private OffHeapConcurrentMap map; private WrappedByteArray valueByteArray = new WrappedByteArray(new byte[] { 0, 1, 2, 3, 4, 5 }); private static final int RESIZE_LIMITATION = OffHeapConcurrentMap.computeThreshold(OffHeapConcurrentMap.INITIAL_SIZE); @BeforeMethod void initializeMap() { OffHeapMemoryAllocator allocator = new UnpooledOffHeapMemoryAllocator(); OffHeapEntryFactoryImpl offHeapEntryFactory = new OffHeapEntryFactoryImpl(); offHeapEntryFactory.allocator = allocator; offHeapEntryFactory.internalEntryFactory = new InternalEntryFactoryImpl(); offHeapEntryFactory.configuration = new ConfigurationBuilder().build(); offHeapEntryFactory.start(); map = new OffHeapConcurrentMap(allocator, offHeapEntryFactory, null); } @AfterMethod void afterMethod() { if (map != null) { map.close(); } } private Set<WrappedBytes> insertUpToResizeLimitation() { Set<WrappedBytes> keys = new HashSet<>(); for (int i = 0; i < RESIZE_LIMITATION - 1; ++i) { assertTrue(keys.add(putInMap(map, valueByteArray))); } return keys; } public void testIterationStartedWithResize1() { Set<WrappedBytes> expectedKeys = insertUpToResizeLimitation(); Set<WrappedBytes> results = new HashSet<>(); Iterator<InternalCacheEntry<WrappedBytes, WrappedBytes>> iterator = map.values().iterator(); assertTrue(iterator.hasNext()); assertTrue(results.add(iterator.next().getKey())); // We can't guarantee this value will be in results as we don't know which bucket it mapped to putInMap(map, valueByteArray); while (iterator.hasNext()) { assertTrue(results.add(iterator.next().getKey())); } for (WrappedBytes expected : expectedKeys) { assertTrue("Results didn't contain: " + expected, results.contains(expected)); } } public void testIterationStartedWithTwoResizes() { Set<WrappedBytes> expectedKeys = insertUpToResizeLimitation(); Set<Object> results = new HashSet<>(); Iterator<InternalCacheEntry<WrappedBytes, WrappedBytes>> iterator = map.values().iterator(); assertTrue(iterator.hasNext()); assertTrue(results.add(iterator.next().getKey())); // Now cause a first and second for (int i = 0; i < RESIZE_LIMITATION + 2; ++i) { putInMap(map, valueByteArray); } while (iterator.hasNext()) { assertTrue(results.add(iterator.next().getKey())); } for (WrappedBytes expected : expectedKeys) { assertTrue("Results didn't contain: " + expected, results.contains(expected)); } } public void testIterationAfterAResize() { insertUpToResizeLimitation(); // Forces resize before iteration putInMap(map, valueByteArray); int entriesFound = 0; for (InternalCacheEntry<WrappedBytes, WrappedBytes> value : map.values()) { entriesFound++; } assertEquals(RESIZE_LIMITATION, entriesFound); } public void testIterationCreatedButNotUsedUntilAfterAResize() { insertUpToResizeLimitation(); Iterator<InternalCacheEntry<WrappedBytes, WrappedBytes>> iter = map.values().iterator(); // Forces resize before iteration putInMap(map, valueByteArray); int entriesFound = 0; while (iter.hasNext()) { InternalCacheEntry<WrappedBytes, WrappedBytes> ice = iter.next(); assertNotNull(ice); entriesFound++; } assertEquals(RESIZE_LIMITATION, entriesFound); } WrappedBytes putInMap(OffHeapConcurrentMap map, WrappedBytes value) { InternalCacheEntry<WrappedBytes, WrappedBytes> ice; WrappedBytes key; do { key = randomBytes(); ice = map.put(key, new ImmortalCacheEntry(key, value)); } while (ice != null); return key; } WrappedBytes randomBytes() { byte[] randomBytes = new byte[16]; ThreadLocalRandom.current().nextBytes(randomBytes); return new WrappedByteArray(randomBytes); } }
5,003
32.139073
121
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapSingleNodeExpirationEvictionTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.encoding.DataConversion; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.testng.annotations.Test; /** * Tests to make sure that off heap generates entry data properly when expiration and eviction are present * @author wburns * @since 9.0 */ @Test(groups = "functional", testName = "container.offheap.OffHeapSingleNodeExpirationEvictionTest") public class OffHeapSingleNodeExpirationEvictionTest extends OffHeapSingleNodeTest { private enum EXPIRE_TYPE { MORTAL, TRANSIENT, TRANSIENT_MORTAL } private EXPIRE_TYPE expirationType; private boolean eviction; private OffHeapSingleNodeExpirationEvictionTest expirationTest(EXPIRE_TYPE expirationType) { this.expirationType = expirationType; return this; } private OffHeapSingleNodeExpirationEvictionTest eviction(boolean enable) { eviction = enable; return this; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "EXPIRE_TYPE", "eviction"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), expirationType, eviction); } @Override public Object[] factory() { return new Object[] { new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.MORTAL).eviction(true), new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.MORTAL).eviction(false), new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.TRANSIENT).eviction(true), new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.TRANSIENT).eviction(false), new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.TRANSIENT_MORTAL).eviction(true), new OffHeapSingleNodeExpirationEvictionTest().expirationTest(EXPIRE_TYPE.TRANSIENT_MORTAL).eviction(false), }; } protected EmbeddedCacheManager addClusterEnabledCacheManager(ConfigurationBuilder defaultConfig) { // We don't want anything to expire or evict in the base test - just making sure the generation of metadata // for entries doesn't cause issues switch (expirationType) { case MORTAL: defaultConfig.expiration().lifespan(10, TimeUnit.MINUTES); break; case TRANSIENT: defaultConfig.expiration().maxIdle(10, TimeUnit.MINUTES); break; case TRANSIENT_MORTAL: defaultConfig.expiration().lifespan(10, TimeUnit.MINUTES).maxIdle(10, TimeUnit.MINUTES); break; } if (eviction) { defaultConfig.memory().evictionType(EvictionType.COUNT).size(1000); } return super.addClusterEnabledCacheManager(defaultConfig); } public void testEnsureCorrectStorage() { Cache<String, String> cache = cache(0); long beforeInsert = timeService.wallClockTime(); cache.put("k", "v"); timeService.advance(10); DataConversion dataConversion = cache.getAdvancedCache().getKeyDataConversion(); Object convertedKey = dataConversion.toStorage("k"); assertNotNull(cache.getAdvancedCache().getDataContainer().get(convertedKey)); CacheEntry<String, String> entry = cache.getAdvancedCache().getDataContainer().peek(convertedKey); assertNotNull(entry); long storedTime = TimeUnit.MINUTES.toMillis(10); switch (expirationType) { case MORTAL: assertEquals(storedTime, entry.getLifespan()); assertEquals(-1, entry.getMaxIdle()); assertEquals(beforeInsert, entry.getCreated()); assertEquals(-1, entry.getLastUsed()); break; case TRANSIENT: assertEquals(-1, entry.getLifespan()); assertEquals(storedTime, entry.getMaxIdle()); assertEquals(-1, entry.getCreated()); assertEquals(beforeInsert, entry.getLastUsed()); break; case TRANSIENT_MORTAL: assertEquals(storedTime, entry.getLifespan()); assertEquals(storedTime, entry.getMaxIdle()); assertEquals(beforeInsert, entry.getCreated()); assertEquals(beforeInsert, entry.getLastUsed()); break; } } }
4,673
37.311475
119
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapSingleNodeStressTest.java
package org.infinispan.container.offheap; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** */ @Test(groups = "stress", testName = "container.offheap.OffHeapSingleNodeStressTest", timeOut = 15*60*1000) public class OffHeapSingleNodeStressTest extends OffHeapMultiNodeStressTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false); dcc.memory().storageType(StorageType.OFF_HEAP); // Only start up the 1 cache addClusterEnabledCacheManager(dcc); } }
745
34.52381
106
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedMultiNodeTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.fail; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; @Test(groups = "functional", testName = "container.offheap.OffHeapBoundedMultiNodeTest") public class OffHeapBoundedMultiNodeTest extends OffHeapMultiNodeTest { static final int EVICTION_SIZE = NUMBER_OF_KEYS + 1; private TransactionMode transactionMode; OffHeapBoundedMultiNodeTest transactionMode(TransactionMode mode) { this.transactionMode = mode; return this; } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), transactionMode); } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "transactionMode"); } @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); dcc.memory().storageType(StorageType.OFF_HEAP).size(EVICTION_SIZE); dcc.transaction().transactionMode(transactionMode); createCluster(dcc, 4); waitForClusterToForm(); } @Override public Object[] factory() { return new Object[] { new OffHeapBoundedMultiNodeTest().transactionMode(TransactionMode.TRANSACTIONAL), new OffHeapBoundedMultiNodeTest().transactionMode(TransactionMode.NON_TRANSACTIONAL) }; } public void testEviction() { for (int i = 0; i < EVICTION_SIZE * 4; ++i) { cache(0).put("key" + i, "value" + i); } for (Cache cache : caches()) { int size = cache.getAdvancedCache().getDataContainer().size(); if (size > EVICTION_SIZE) { fail("Container size was: " + size + ", it is supposed to be less than or equal to " + EVICTION_SIZE); } } } }
2,085
32.111111
114
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/UnpooledOffHeapMemoryAllocatorTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author wburns * @since 9.0 */ @Test(groups = "functional", testName = "container.offheap.UnpooledOffHeapMemoryAllocatorTest") public class UnpooledOffHeapMemoryAllocatorTest { @DataProvider(name = "roundings") Object[][] roundings() { return new Object[][] { { 2, 16 }, { 14, 32 }, { 23, 32 }, { 32, 48 }, { 123, 144 }, { 43, 64 }, { 73, 96 }, }; } @Test(dataProvider = "roundings") public void testRoundings(long original, long expected) { // The estimate adds 8 and rounds up to 16 assertEquals(expected, UnpooledOffHeapMemoryAllocator.estimateSizeOverhead(original)); } }
889
25.176471
95
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapMultiNodeStressTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.Test; @Test(groups = "stress", testName = "container.offheap.OffHeapMultiNodeStressTest", timeOut = 15 * 60 * 1000) public class OffHeapMultiNodeStressTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); dcc.memory().storageType(StorageType.OFF_HEAP); createCluster(dcc, 4); waitForClusterToForm(); } static DataContainer<WrappedByteArray, WrappedByteArray> castDC(Object obj) { return (DataContainer<WrappedByteArray, WrappedByteArray>) obj; } public void testLotsOfWritesAndFewRemoves() throws Exception { final int WRITE_THREADS = 5; final int REMOVE_THREADS = 2; final int INSERTIONCOUNT = 2048; final int REMOVECOUNT = 1; ExecutorService execService = Executors.newFixedThreadPool(WRITE_THREADS + REMOVE_THREADS, getTestThreadFactory("Worker")); ExecutorCompletionService<Void> service = new ExecutorCompletionService<>(execService); try { final Map<byte[], byte[]> map = cache(0); for (int i = 0; i < WRITE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < INSERTIONCOUNT; ++j) { byte[] hcc = randomBytes(KEY_SIZE); map.put(hcc, hcc); } return null; }); } for (int i = 0; i < REMOVE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < REMOVECOUNT; ++j) { Iterator<Map.Entry<byte[], byte[]>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { map.remove(iterator.next().getKey()); } } return null; }); } for (int i = 0; i < WRITE_THREADS + REMOVE_THREADS; ++i) { Future<Void> future = service.poll(10, TimeUnit.SECONDS); if (future == null) { throw new TimeoutException(); } future.get(); } } finally { execService.shutdown(); execService.awaitTermination(1000, TimeUnit.SECONDS); } } public void testWritesAndRemovesWithExecutes() throws Exception { final int WRITE_THREADS = 5; final int REMOVE_THREADS = 2; final int EXECUTE_THREADS = 2; final int INSERTIONCOUNT = 2048; final int REMOVECOUNT = 1; final int EXECUTECOUNT = 2; ExecutorService execService = Executors.newFixedThreadPool(WRITE_THREADS + REMOVE_THREADS + EXECUTE_THREADS, getTestThreadFactory("Worker")); ExecutorCompletionService<Void> service = new ExecutorCompletionService<>(execService); try { final Cache<byte[], byte[]> bchm = cache(0); for (int i = 0; i < WRITE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < INSERTIONCOUNT; ++j) { byte[] hcc = randomBytes(KEY_SIZE); bchm.put(hcc, hcc); } return null; }); } for (int i = 0; i < REMOVE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < REMOVECOUNT; ++j) { Iterator<Map.Entry<byte[], byte[]>> iterator = bchm.entrySet().iterator(); while (iterator.hasNext()) { bchm.remove(iterator.next().getKey()); } } return null; }); } for (int i = 0; i < EXECUTE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < EXECUTECOUNT; ++j) { DataContainer<WrappedByteArray, WrappedByteArray> container = castDC(bchm.getAdvancedCache().getDataContainer()); container.forEach(ice -> assertEquals(ice, container.get(ice.getKey()))); } return null; }); } for (int i = 0; i < WRITE_THREADS + REMOVE_THREADS + EXECUTE_THREADS; ++i) { Future<Void> future = service.poll(10, TimeUnit.SECONDS); if (future == null) { throw new TimeoutException(); } future.get(); } } finally { execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); } } final static int KEY_SIZE = 20; byte[] randomBytes(int size) { byte[] bytes = new byte[size]; ThreadLocalRandom.current().nextBytes(bytes); return bytes; } }
5,641
35.4
114
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapSizeTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.ThreadLocalRandom; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.commons.util.MemoryUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.impl.KeyValueMetadataSizeCalculator; import org.infinispan.container.versioning.EntryVersion; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author wburns * @since 9.0 */ @Test(groups = "functional", testName = "container.offheap.OffHeapSizeTest") public class OffHeapSizeTest extends SingleCacheManagerTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder .memory() .storageType(StorageType.OFF_HEAP) .size(MemoryUnit.MEGABYTES.toBytes(10)) .evictionType(EvictionType.MEMORY) .evictionStrategy(EvictionStrategy.EXCEPTION) .transaction() .transactionMode(TransactionMode.TRANSACTIONAL); return TestCacheManagerFactory.createCacheManager(builder); } @DataProvider(name = "sizeMatchData") public Object[][] sizeMatchData() { return new Object[][] { { 10, 100, -1, -1, null }, { 20, 313, -1, -1, null }, { 10, 100, 4000, -1, null }, { 20, 313, -1, 10000, null }, { 10, 100, 4000, -1, new NumericVersion(1003)}, { 20, 313, -1, 10000, new NumericVersion(81418) }, { 10, 100, 4000, 738141, null}, { 20, 313, 14141, 10000, new NumericVersion(8417) }, }; } @Test(dataProvider = "sizeMatchData") public void testSizeMatch(int keyLength, int valueLength, long maxIdle, long lifespan, EntryVersion version) { OffHeapMemoryAllocator allocator = TestingUtil.extractComponent(cache, OffHeapMemoryAllocator.class); long beginningSize = allocator.getAllocatedAmount(); // We write directly to data container to avoid transformations ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current(); byte[] keyBytes = new byte[keyLength]; byte[] valueBytes = new byte[valueLength]; threadLocalRandom.nextBytes(keyBytes); threadLocalRandom.nextBytes(valueBytes); WrappedBytes key = new WrappedByteArray(keyBytes); WrappedBytes value = new WrappedByteArray(valueBytes); EmbeddedMetadata.Builder metadataBuilder = new EmbeddedMetadata.Builder(); if (maxIdle >= 0) { metadataBuilder.maxIdle(maxIdle); } if (lifespan >= 0) { metadataBuilder.lifespan(lifespan); } if (version != null) { metadataBuilder.version(version); } Metadata metadata = metadataBuilder.build(); KeyValueMetadataSizeCalculator<WrappedBytes, WrappedBytes> calculator = TestingUtil.extractComponent(cache, KeyValueMetadataSizeCalculator.class); long estimateSize = calculator.calculateSize(key, value, metadata); cache.getAdvancedCache().getDataContainer().put(key, value, metadata); long endingSize = allocator.getAllocatedAmount(); assertEquals(endingSize - beginningSize, estimateSize); } }
3,972
37.95098
113
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/KeyGenerator.java
package org.infinispan.container.offheap; import java.util.Random; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.metadata.Metadata; /** * Generates keys and values to be used during the container and cache operations. Currently these are limited to * {@link WrappedByteArray} instances primarily for use with off heap testing. * These instances are pre-created to minimize impact during measurements. */ public class KeyGenerator { private static final int randomSeed = 17; private static final int keySpaceSize = 1000; private static final int keyObjectSize = 10; private static final int valueSpaceSize = 100; private static final int valueObjectSize = 1000; private RandomSequence keySequence; private RandomSequence valueSequence; private Metadata metadata; public KeyGenerator() { Random random = new Random(randomSeed); keySequence = new RandomSequence( random, keySpaceSize, keyObjectSize); valueSequence = new RandomSequence( random, valueSpaceSize, valueObjectSize); metadata = new EmbeddedMetadata.Builder().build(); } public WrappedByteArray getNextKey() { return keySequence.nextValue(); } public WrappedByteArray getNextValue() { return valueSequence.nextValue(); } public Metadata getMetadata() { return metadata; } private class RandomSequence { private final WrappedByteArray[] list; private final int spaceSize; private int idx = -1; RandomSequence(Random random, int spaceSize, int objectSize) { this.list = new WrappedByteArray[spaceSize]; this.spaceSize = spaceSize; for (int i=0; i<spaceSize; i++) { byte[] bytes = new byte[objectSize]; random.nextBytes(bytes); list[i] = toUserObject(bytes); } } WrappedByteArray nextValue() { idx++; if (idx==spaceSize) { idx = 0; } return list[idx]; } } private WrappedByteArray toUserObject(byte[] bytes) { return new WrappedByteArray(bytes); } }
2,178
27.298701
113
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedSingleNodeTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.eviction.EvictionType; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; /** */ @Test(groups = "functional", testName = "container.offheap.OffHeapBoundedSingleNodeTest") public class OffHeapBoundedSingleNodeTest extends OffHeapSingleNodeTest { private static final int COUNT = 51; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false); dcc.memory().storageType(StorageType.OFF_HEAP).size(COUNT).evictionType(EvictionType.COUNT); dcc.locking().isolationLevel(IsolationLevel.READ_COMMITTED); // Only start up the 1 cache addClusterEnabledCacheManager(dcc); configureTimeService(); } public void testMoreWriteThanSize() { Cache<String, String> cache = cache(0); for (int i = 0; i < COUNT + 5; ++i) { cache.put("key" + i, "value" + i); } assertEquals(COUNT, cache.size()); } public void testMultiThreaded() throws ExecutionException, InterruptedException, TimeoutException { Cache<String, String> cache = cache(0); AtomicInteger offset = new AtomicInteger(); AtomicBoolean collision = new AtomicBoolean(); int threadCount = 5; List<Future> futures = new ArrayList<>(threadCount); for (int i = 0; i < threadCount; ++i) { futures.add(fork(() -> { boolean collide = collision.get(); // We could have overrides, that is fine collision.set(!collide); int value = collide ? offset.get() : offset.incrementAndGet(); for (int j = 0; j < COUNT + 5; ++j) { if (Thread.interrupted()) { log.tracef("Test was ordered to stop!"); return; } String key = "key" + value + "-" + j; cache.put(key, "value" + value + "-" + j); } })); } for (Future future : futures) { try { future.get(10, TimeUnit.SECONDS); } catch (Exception e) { // If we have an exception we need to stop all the others futures.forEach(f -> f.cancel(true)); throw e; } } int cacheSize = cache.size(); if (cacheSize > COUNT) { log.fatal("Entries were: " + cache.entrySet().stream().map(Object::toString).collect(Collectors.joining(","))); } assertTrue("Cache size was " + cacheSize, cacheSize <= COUNT); } }
3,264
33.734043
120
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedMemoryTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.TimeUnit; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.commons.util.MemoryUnit; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.container.versioning.NumericVersion; import org.infinispan.eviction.EvictionType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author wburns * @since 9.0 */ @Test(groups = "functional", testName = "container.offheap.OffHeapBoundedMemoryTest") public class OffHeapBoundedMemoryTest extends AbstractInfinispanTest { public void testTooSmallToInsert() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory() // Only allocate enough for address count and 1 byte .size(UnpooledOffHeapMemoryAllocator.estimateSizeOverhead((OffHeapConcurrentMap.INITIAL_SIZE << 3)) + 1) .evictionType(EvictionType.MEMORY) .storageType(StorageType.OFF_HEAP); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(builder); Cache<Object, Object> smallHeapCache = manager.getCache(); assertEquals(0, smallHeapCache.size()); // Put something larger than size assertNull(smallHeapCache.put(1, 3)); assertEquals(0, smallHeapCache.size()); } private static DataContainer getContainer(AdvancedCache cache) { return cache.getDataContainer(); } /** * Test to ensure that off heap allocated amount equals the total size used by the container */ public void testAllocatedAmountEqual() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory() .size(MemoryUnit.MEGABYTES.toBytes(20)) .evictionType(EvictionType.MEMORY) .storageType(StorageType.OFF_HEAP); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(builder); AdvancedCache<Object, Object> cache = manager.getCache().getAdvancedCache(); OffHeapMemoryAllocator allocator = cache.getComponentRegistry().getComponent( OffHeapMemoryAllocator.class); BoundedOffHeapDataContainer container = (BoundedOffHeapDataContainer) getContainer(cache); assertEquals(allocator.getAllocatedAmount(), container.currentSize); cache.put(1, 2); assertEquals(allocator.getAllocatedAmount(), container.currentSize); cache.clear(); assertEquals(allocator.getAllocatedAmount(), container.currentSize); } public void testAllocatedAmountEqualWithVersion() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory() .size(MemoryUnit.MEGABYTES.toBytes(20)) .evictionType(EvictionType.MEMORY) .storageType(StorageType.OFF_HEAP); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(builder); AdvancedCache<Object, Object> cache = manager.getCache().getAdvancedCache(); cache.put(1, 2, new EmbeddedMetadata.Builder().version(new NumericVersion(23)).build()); OffHeapMemoryAllocator allocator = cache.getComponentRegistry().getComponent( OffHeapMemoryAllocator.class); BoundedOffHeapDataContainer container = (BoundedOffHeapDataContainer) getContainer(cache); assertEquals(allocator.getAllocatedAmount(), container.currentSize); cache.clear(); assertEquals(allocator.getAllocatedAmount(), container.currentSize); } public void testAllocatedAmountEqualWithExpiration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory() .size(MemoryUnit.MEGABYTES.toBytes(20)) .evictionType(EvictionType.MEMORY) .storageType(StorageType.OFF_HEAP); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(builder); AdvancedCache<Object, Object> cache = manager.getCache().getAdvancedCache(); cache.put("lifespan", "value", 1, TimeUnit.MINUTES); cache.put("both", "value", 1, TimeUnit.MINUTES, 1, TimeUnit.MINUTES); cache.put("maxidle", "value", -1, TimeUnit.MINUTES, 1, TimeUnit.MINUTES); OffHeapMemoryAllocator allocator = cache.getComponentRegistry().getComponent( OffHeapMemoryAllocator.class); BoundedOffHeapDataContainer container = (BoundedOffHeapDataContainer) getContainer(cache); assertEquals(allocator.getAllocatedAmount(), container.currentSize); cache.clear(); assertEquals(allocator.getAllocatedAmount(), container.currentSize); } public void testAllocatedAmountEqualWithVersionAndExpiration() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.memory() .size(MemoryUnit.MEGABYTES.toBytes(20)) .evictionType(EvictionType.MEMORY) .storageType(StorageType.OFF_HEAP); EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(builder); AdvancedCache<Object, Object> cache = manager.getCache().getAdvancedCache(); cache.put("lifespan", 2, new EmbeddedMetadata.Builder() .lifespan(1, TimeUnit.MINUTES) .version(new NumericVersion(23)).build()); cache.put("both", 2, new EmbeddedMetadata.Builder() .lifespan(1, TimeUnit.MINUTES) .maxIdle(1, TimeUnit.MINUTES) .version(new NumericVersion(23)).build()); cache.put("maxidle", 2, new EmbeddedMetadata.Builder() .maxIdle(1, TimeUnit.MINUTES) .version(new NumericVersion(23)).build()); OffHeapMemoryAllocator allocator = cache.getComponentRegistry().getComponent( OffHeapMemoryAllocator.class); BoundedOffHeapDataContainer container = (BoundedOffHeapDataContainer) getContainer(cache); assertEquals(allocator.getAllocatedAmount(), container.currentSize); cache.clear(); assertEquals(allocator.getAllocatedAmount(), container.currentSize); } }
6,376
42.380952
116
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapBoundedSingleNodeStressTest.java
package org.infinispan.container.offheap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.marshall.WrappedBytes; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.eviction.EvictionType; import org.testng.annotations.Test; /** * Test for native memory fragmentation when the values have different size. * * @author Dan Berindei * @author William Burns */ @Test(groups = "stress", testName = "container.offheap.OffHeapBoundedSingleNodeStressTest") public class OffHeapBoundedSingleNodeStressTest extends OffHeapMultiNodeStressTest { @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false); dcc.memory().storageType(StorageType.OFF_HEAP).evictionType(EvictionType.COUNT) .size(500); // Only start up the 1 cache addClusterEnabledCacheManager(dcc); } public void testLotsOfWrites() throws Exception { final int WRITE_THREADS = 5; final int INSERTIONCOUNT = 1_000_000; final int KEY_SIZE = 30; ExecutorService execService = Executors.newFixedThreadPool(WRITE_THREADS, getTestThreadFactory("Worker")); ExecutorCompletionService<Void> service = new ExecutorCompletionService<>(execService); try { final Map<byte[], byte[]> map = cache(0); for (int i = 0; i < WRITE_THREADS; ++i) { service.submit(() -> { for (int j = 0; j < INSERTIONCOUNT; ++j) { byte[] key = randomBytes(KEY_SIZE); byte[] value = randomBytes(j / 100); map.put(key, value); if (j % 1000 == 0) { log.debugf("%d entries written", j); } } return null; }); } for (int i = 0; i < WRITE_THREADS; ++i) { Future<Void> future = service.poll(1000, TimeUnit.SECONDS); if (future == null) { throw new TimeoutException(); } future.get(); } } finally { execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); } } public void testLotsOfPutsAndReadsIntoDataContainer() throws InterruptedException, ExecutionException { int WRITE_THREADS = 4; int READ_THREADS = 16; ExecutorService execService = Executors.newFixedThreadPool(WRITE_THREADS + READ_THREADS, getTestThreadFactory("Worker")); ExecutorCompletionService<Void> service = new ExecutorCompletionService<>(execService); try { Cache<WrappedBytes, WrappedBytes> cache = cache(0); final DataContainer<WrappedBytes, WrappedBytes> map = cache.getAdvancedCache().getDataContainer(); for (int i = 0; i < WRITE_THREADS; ++i) { service.submit(() -> { KeyGenerator generator = new KeyGenerator(); while (!Thread.interrupted()) { WrappedByteArray key = generator.getNextKey(); WrappedByteArray value = generator.getNextValue(); map.put(key, value, generator.getMetadata()); } return null; }); } for (int i = 0; i < READ_THREADS; ++i) { service.submit(() -> { KeyGenerator generator = new KeyGenerator(); while (!Thread.interrupted()) { WrappedByteArray key = generator.getNextKey(); InternalCacheEntry<WrappedBytes, WrappedBytes> innerV = map.get(key); // Here just to make sure get doesn't get optimized away if (innerV != null && innerV.equals(cache)) { System.out.println(System.currentTimeMillis()); } } return null; }); } // This is how long this test will run for Future<Void> future = service.poll(30, TimeUnit.SECONDS); if (future != null) { future.get(); } } finally { execService.shutdownNow(); execService.awaitTermination(10, TimeUnit.SECONDS); } } }
4,847
36.581395
112
java
null
infinispan-main/core/src/test/java/org/infinispan/container/offheap/OffHeapMultiNodeTest.java
package org.infinispan.container.offheap; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.Cache; import org.infinispan.commons.marshall.WrappedByteArray; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.DataContainer; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.distribution.DistributionTestHelper; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.encoding.DataConversion; import org.infinispan.metadata.EmbeddedMetadata; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; @Test(groups = "functional", testName = "commands.OffHeapMultiNodeTest") public class OffHeapMultiNodeTest extends MultipleCacheManagersTest { protected static final int NUMBER_OF_KEYS = 10; @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); dcc.memory().storageType(StorageType.OFF_HEAP); dcc.clustering().stateTransfer().timeout(30, TimeUnit.SECONDS); createCluster(dcc, 4); waitForClusterToForm(); } public void testPutMapCommand() { Map<String, String> map = new HashMap<>(); for (int i = 0; i < NUMBER_OF_KEYS; ++i) { map.put("key" + i, "value" + i); } cache(0).putAll(map); for (int i = 0; i < NUMBER_OF_KEYS; ++i) { assertEquals("value" + i, cache(0).get("key" + i)); } } public void testPutRemovePut() { Map<byte[], byte[]> map = cache(0); byte[] key = randomBytes(KEY_SIZE); byte[] value = randomBytes(VALUE_SIZE); byte[] value2 = randomBytes(VALUE_SIZE); assertNull(map.put(key, value)); for (int i = 0; i < NUMBER_OF_KEYS; ++i) { map.put(randomBytes(KEY_SIZE), value); } assertEquals(value, map.remove(key)); assertNull(map.put(key, value)); assertEquals(value, map.remove(key)); assertNull(map.put(key, value2)); } public void testOverwriteSameKey() { Map<byte[], byte[]> map = cache(0); byte[] key = randomBytes(KEY_SIZE); byte[] value = randomBytes(VALUE_SIZE); byte[] value2 = randomBytes(VALUE_SIZE); byte[] value3 = randomBytes(VALUE_SIZE); assertNull(map.put(key, value)); byte[] prev = map.put(key, value2); assertTrue(Arrays.equals(prev, value)); assertTrue(Arrays.equals(value2, map.put(key, value3))); assertTrue(Arrays.equals(value3, map.get(key))); } public void testClear() { Map<String, String> map = cache(0); int size = 10; for (int i = 0; i < 10; ++i) { map.put("key-" + i, "value-" + i); } assertEquals(size, map.size()); for (int i = 0; i < 10; ++i) { assertEquals("value-" + i, map.get("key-" + i)); } map.clear(); assertEquals(0, map.size()); for (int i = 0; i < 10; ++i) { map.put("key-" + i, "value-" + i); } assertEquals(size, map.size()); } public void testIterate() { int cacheSize = NUMBER_OF_KEYS; Map<byte[], byte[]> original = new HashMap<>(); for (int i = 0; i < cacheSize; ++i) { byte[] key = randomBytes(KEY_SIZE); original.put(key, randomBytes(VALUE_SIZE)); } Map<byte[], byte[]> map = cache(0); map.putAll(original); Iterator<Map.Entry<byte[], byte[]>> iterator = map.entrySet().iterator(); AtomicInteger count = new AtomicInteger(); iterator.forEachRemaining(e -> { count.incrementAndGet(); assertEquals(e.getValue(), map.get(e.getKey())); }); assertEquals(cacheSize, count.get()); } public void testRemoveSegments() { Cache<String, String> cache = cache(0); if (cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.LOCAL) { // Local caches don't support removing segments return; } String key = "some-key"; String value = "some-value"; DataConversion keyDataConversion = cache.getAdvancedCache().getKeyDataConversion(); DataConversion valueDataConversion = cache.getAdvancedCache().getValueDataConversion(); Object storedKey = keyDataConversion.toStorage(key); Object storedValue = valueDataConversion.toStorage(value); Cache<String, String> primaryOwnerCache; int segmentWrittenTo; List<Cache<String, String>> caches = caches(); if (caches.size() == 1) { primaryOwnerCache = cache; segmentWrittenTo = 0; } else { primaryOwnerCache = DistributionTestHelper.getFirstOwner(storedKey, caches()); KeyPartitioner keyPartitioner = TestingUtil.extractComponent(primaryOwnerCache, KeyPartitioner.class); segmentWrittenTo = keyPartitioner.getSegment(storedKey); } InternalDataContainer container = TestingUtil.extractComponent(primaryOwnerCache, InternalDataContainer.class); assertEquals(0, container.size()); container.put(storedKey, storedValue, new EmbeddedMetadata.Builder().build()); assertEquals(1, container.size()); container.removeSegments(IntSets.immutableSet(segmentWrittenTo)); assertEquals(0, container.size()); } static DataContainer<WrappedByteArray, WrappedByteArray> castDC(Object obj) { return (DataContainer<WrappedByteArray, WrappedByteArray>) obj; } final static int KEY_SIZE = 20; final static int VALUE_SIZE = 1024; byte[] randomBytes(int size) { byte[] bytes = new byte[size]; ThreadLocalRandom.current().nextBytes(bytes); return bytes; } }
6,253
32.98913
117
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/SingleClusterExecutorTest.java
package org.infinispan.manager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Factory; import org.testng.annotations.Test; /** * Tests for a single cluster executor * @author Will Burns * @since 9.1 */ @Test(groups = {"functional", "smoke"}, testName = "manager.SingleClusterExecutorTest") public class SingleClusterExecutorTest extends AllClusterExecutorTest { static final AtomicInteger atomicInteger = new AtomicInteger(); private boolean local; public SingleClusterExecutorTest() { atomicIntegerSupplier = () -> atomicInteger; } SingleClusterExecutorTest executeLocal(boolean local) { this.local = local; return this; } @Override protected String parameters() { return "[" + local + "]"; } @Factory public Object[] factory() { return new Object[] { new SingleClusterExecutorTest().executeLocal(true), new SingleClusterExecutorTest().executeLocal(false) }; } ClusterExecutor executor(EmbeddedCacheManager cm) { return cm.executor().singleNodeSubmission().filterTargets(a -> local == a.equals(cm.getAddress())); } void assertSize(EmbeddedCacheManager[] cms, int receivedSize) { assertEquals(1, receivedSize); } void eventuallyAssertSize(EmbeddedCacheManager[] cms, Supplier<Integer> supplier) { eventuallyEquals(1, supplier); } void assertContains(EmbeddedCacheManager[] managers, Collection<Address> results) { boolean contains = false; for (EmbeddedCacheManager manager : managers) { if (results.contains(manager.getAddress())) { contains = true; break; } } assertTrue("At least 1 manager from " + Arrays.toString(managers) + " should be in " + results, contains); } }
2,068
28.140845
112
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerAdminSharedPermanentTest.java
package org.infinispan.manager; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; /** * @author Tristan Tarrant * @since 9.2 */ @Test(testName = "manager.CacheManagerAdminSharedPermanentTest", groups = "functional") @CleanupAfterMethod public class CacheManagerAdminSharedPermanentTest extends CacheManagerAdminPermanentTest { @Override protected boolean isShared() { return true; } public void testSharedClusterCache() { waitForClusterToForm(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration configuration = builder.build(); // Create a permanent cache manager(0).administration().createCache("a", configuration); waitForClusterToForm("a"); checkConsistencyAcrossCluster("a", configuration); // shutdown TestingUtil.killCacheManagers(this.cacheManagers); cacheManagers.clear(); // recreate the cache manager createStatefulCacheManager("A", true); createStatefulCacheManager("B", true); checkConsistencyAcrossCluster("a", configuration); } }
1,397
28.125
90
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/FailOverClusterExecutorTest.java
package org.infinispan.manager; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.testng.annotations.Test; /** * @author wburns * @since 9.0 */ @Test(groups = {"functional", "smoke"}, testName = "manager.FailOverClusterExecutorTest") public class FailOverClusterExecutorTest extends MultipleCacheManagersTest { private static AtomicInteger failureCount = new AtomicInteger(); @Override protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); addClusterEnabledCacheManager(builder); addClusterEnabledCacheManager(builder); addClusterEnabledCacheManager(builder); waitForClusterToForm(); } @Test public void testSimpleFailover() throws InterruptedException, ExecutionException, TimeoutException { int failOverAllowed = 2; failureCount.set(failOverAllowed); CompletableFuture<Void> fut = cacheManagers.get(0).executor().singleNodeSubmission(failOverAllowed).submit(() -> { if (failureCount.decrementAndGet() != 0) { throw new IllegalArgumentException(); } }); fut.get(10, TimeUnit.SECONDS); assertEquals(0, failureCount.get()); } @Test public void testTimeoutOccursWithRetry() { CompletableFuture<Void> fut = cacheManagers.get(0).executor().timeout(10, TimeUnit.MILLISECONDS) .singleNodeSubmission(2).submit(() -> TestingUtil.sleepThread(TimeUnit.SECONDS.toMillis(2))); Exceptions.expectExecutionException(org.infinispan.util.concurrent.TimeoutException.class, fut); } }
2,120
36.210526
120
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerXmlConfigurationTest.java
package org.infinispan.manager; 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 java.io.ByteArrayInputStream; import java.io.IOException; import javax.security.auth.Subject; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.security.Security; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TransportFlags; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author Manik Surtani * @since 4.0 */ @Test(groups = "functional", testName = "manager.CacheManagerXmlConfigurationTest") public class CacheManagerXmlConfigurationTest extends AbstractInfinispanTest { EmbeddedCacheManager cm; private Subject KING = TestingUtil.makeSubject("king-arthur", "king"); @AfterMethod public void tearDown() { if (cm != null) Security.doAs(KING, () -> cm.stop()); cm = null; } public void testNamedCacheXML() throws IOException { cm = TestCacheManagerFactory.fromXml("configs/named-cache-test.xml", false, false, new TransportFlags()); GlobalConfiguration globalConfiguration = TestingUtil.extractGlobalConfiguration(cm); assertEquals("s1", globalConfiguration.transport().siteId()); assertEquals("r1", globalConfiguration.transport().rackId()); assertEquals("m1", globalConfiguration.transport().machineId()); assertNotNull(globalConfiguration.transport().transport()); // test default cache Configuration c = getDefaultCacheConfiguration(); assertEquals(100, c.locking().concurrencyLevel()); assertEquals(1000, c.locking().lockAcquisitionTimeout()); assertFalse(c.transaction().transactionMode().isTransactional()); assertEquals(TransactionMode.NON_TRANSACTIONAL, c.transaction().transactionMode()); // test the "transactional" cache c = getCacheConfiguration(cm, "transactional"); assertTrue(c.transaction().transactionMode().isTransactional()); assertEquals(32, c.locking().concurrencyLevel()); assertEquals(10000, c.locking().lockAcquisitionTimeout()); assertTrue(c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup); // test the "replicated" cache c = getCacheConfiguration(cm, "syncRepl"); assertEquals(32, c.locking().concurrencyLevel()); assertEquals(10000, c.locking().lockAcquisitionTimeout()); assertEquals(TransactionMode.NON_TRANSACTIONAL, c.transaction().transactionMode()); // test the "txSyncRepl" cache c = getCacheConfiguration(cm, "txSyncRepl"); assertEquals(32, c.locking().concurrencyLevel()); assertEquals(10000, c.locking().lockAcquisitionTimeout()); assertTrue(c.transaction().transactionManagerLookup() instanceof GenericTransactionManagerLookup); } private Configuration getCacheConfiguration(EmbeddedCacheManager cm, String cacheName) { return Security.doAs(KING, () -> cm.getCacheConfiguration(cacheName)); } private Configuration getDefaultCacheConfiguration() { return Security.doAs(KING, () -> cm.getDefaultCacheConfiguration()); } public void testNamedCacheXMLClashingNames() { String xml = TestingUtil.wrapXMLWithSchema( "<cache-container default-cache=\"default\">" + "\n" + " <local-cache name=\"default\">\n" + " <locking concurrencyLevel=\"100\" lockAcquisitionTimeout=\"1000\" />\n" + " </local-cache>\n" + "\n" + " <local-cache name=\"c1\">\n" + " <transaction transaction-manager-lookup=\"org.infinispan.transaction.lookup.GenericTransactionManagerLookup\"/>\n" + " </local-cache>\n" + "\n" + " <replicated-cache name=\"c1\" mode=\"SYNC\" remote-timeout=\"15000\">\n" + " </replicated-cache>\n" + "</cache-container>"); ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); try { cm = TestCacheManagerFactory.fromStream(bais); assert false : "Should fail"; } catch (Throwable expected) { } } public void testBatchingIsEnabled() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.fromXml("configs/batching.xml"); try { Configuration c = cm.getCacheConfiguration("default"); assertTrue(c.invocationBatching().enabled()); assertTrue(c.transaction().transactionMode().isTransactional()); c = cm.getDefaultCacheConfiguration(); assertTrue(c.invocationBatching().enabled()); Configuration c2 = cm.getCacheConfiguration("tml"); assertTrue(c2.transaction().transactionMode().isTransactional()); } finally { cm.stop(); } } public void testXInclude() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.fromXml("configs/include.xml"); try { assertEquals("included", cm.getCacheManagerConfiguration().defaultCacheName().get()); assertNotNull(cm.getCacheConfiguration("included")); assertEquals(CacheMode.LOCAL, cm.getCacheConfiguration("included").clustering().cacheMode()); assertEquals(CacheMode.LOCAL, cm.getCacheConfiguration("another-included").clustering().cacheMode()); } finally { cm.stop(); } } }
5,871
41.244604
137
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/AllClusterExecutorExecutionPolicyTest.java
package org.infinispan.manager; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.global.TransportConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.test.MultipleCacheManagersTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests to verify that execution policy is applied properly when using a cluster executor * @author wburns * @since 9.1 */ @Test(groups = {"functional", "smoke"}, testName = "manager.AllClusterExecutorExecutionPolicyTest") public class AllClusterExecutorExecutionPolicyTest extends MultipleCacheManagersTest { @Override public String toString() { return super.toString(); } private static final AtomicInteger actualInvocations = new AtomicInteger(); @DataProvider(name="params") public Object[][] dataProvider() { return new Object[][] { // Policy, Site #, Rack #, Machine #, Expected invocation Count { ClusterExecutionPolicy.ALL, 0, 0, 0, 25 }, { ClusterExecutionPolicy.ALL, 2, 1, 1, 25 }, { ClusterExecutionPolicy.DIFFERENT_MACHINE, 1, 0, 1, 24 }, { ClusterExecutionPolicy.DIFFERENT_MACHINE, 0, 1, 4, 24 }, { ClusterExecutionPolicy.SAME_MACHINE, 2, 1, 1, 1 }, { ClusterExecutionPolicy.SAME_MACHINE, 0, 0, 1, 1 }, { ClusterExecutionPolicy.DIFFERENT_RACK, 2, 2, 3, 21 }, { ClusterExecutionPolicy.DIFFERENT_RACK, 1, 0, 1, 21 }, { ClusterExecutionPolicy.DIFFERENT_RACK, 0, 1, 4, 18 }, { ClusterExecutionPolicy.SAME_RACK, 2, 1, 1, 2 }, { ClusterExecutionPolicy.SAME_RACK, 1, 0, 1, 4 }, { ClusterExecutionPolicy.SAME_RACK, 0, 2, 0, 1 }, { ClusterExecutionPolicy.DIFFERENT_SITE, 2, 0, 4, 14 }, { ClusterExecutionPolicy.DIFFERENT_SITE, 1, 0, 3, 21 }, { ClusterExecutionPolicy.DIFFERENT_SITE, 0, 1, 6, 15 }, { ClusterExecutionPolicy.SAME_SITE, 2, 0, 2, 11 }, { ClusterExecutionPolicy.SAME_SITE, 1, 0, 0, 4 }, { ClusterExecutionPolicy.SAME_SITE, 0, 1, 4, 10 }, }; } @Override protected void createCacheManagers() throws Throwable { // Array where top level divides by site // Second array divide by rack // and the number within is how many machines are in each rack int[][] topology = { // Site 1 { // Rack 1 machine count 2, // Rack 2 machine count 7, // Rack 3 machine count 1 }, // Site 2 { // Only 1 rack with this many machines 4 }, // Site 3 { // Rack 1 machine count 5, // Rack 2 machine count 2, // Rack 3 machine count 4 }, }; for (int siteNumber = 0; siteNumber < topology.length; ++siteNumber) { int[] racksForSite = topology[siteNumber]; for (int rackNumber = 0; rackNumber < racksForSite.length; ++rackNumber) { int machines = racksForSite[rackNumber]; for (int machineNumber = 0; machineNumber < machines; ++machineNumber) { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); GlobalConfigurationBuilder globalConfigurationBuilder = holder.getGlobalConfigurationBuilder().clusteredDefault(); globalConfigurationBuilder.transport() .machineId(String.valueOf(machineNumber)) .rackId(String.valueOf(rackNumber)) .siteId(String.valueOf(siteNumber)); addClusterEnabledCacheManager(holder); } } } } @Test(dataProvider = "params") public void runTest(ClusterExecutionPolicy policy, int site, int rack, int machine, int invocationCount) throws InterruptedException, ExecutionException, TimeoutException { actualInvocations.set(0); EmbeddedCacheManager cacheManager = cacheManagers.stream().filter(cm -> { TransportConfiguration tc = cm.getCacheManagerConfiguration().transport(); return Integer.valueOf(tc.siteId()) == site && Integer.valueOf(tc.rackId()) == rack && Integer.valueOf(tc.machineId()) == machine; }).findFirst().orElseThrow(() -> new AssertionError("No cache manager matches site: " + site + " rack: " + rack + " machine: " + machine)); cacheManager.executor().filterTargets(policy).submit(() -> actualInvocations.incrementAndGet()).get(10, TimeUnit.SECONDS); assertEquals(invocationCount, actualInvocations.get()); } }
5,103
41.890756
175
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/DefaultCacheManagerHelper.java
package org.infinispan.manager; /** * Let tests access package-protected methods in DefaultCacheManager */ public class DefaultCacheManagerHelper { public static void enableManagerGetCacheBlockingCheck() { // Require isRunning(cache) before getCache(name) on non-blocking threads DefaultCacheManager.enableGetCacheBlockingCheck(); } }
356
28.75
79
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerAdminPermanentTest.java
package org.infinispan.manager; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.util.Util; 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.globalstate.ConfigurationStorage; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; @Test(testName = "manager.CacheManagerAdminPermanentTest", groups = "functional") @CleanupAfterMethod public class CacheManagerAdminPermanentTest extends CacheManagerAdminTest { @Override protected void createCacheManagers() throws Throwable { Util.recursiveFileRemove(tmpDirectory(this.getClass().getSimpleName())); createStatefulCacheManager("A", false); createStatefulCacheManager("B", false); } protected boolean isShared() { return false; } protected void createStatefulCacheManager(String id, boolean clear) { String stateDirectory = tmpDirectory(this.getClass().getSimpleName(), id); if (clear) Util.recursiveFileRemove(stateDirectory); GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().enable().persistentLocation(stateDirectory). configurationStorage(ConfigurationStorage.OVERLAY); if (isShared()) { String sharedDirectory = tmpDirectory(this.getClass().getSimpleName(), "COMMON"); global.globalState().sharedPersistentLocation(sharedDirectory); } else { global.globalState().sharedPersistentLocation(stateDirectory); } ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); addClusterEnabledCacheManager(global, builder); } public void testClusterCacheTest() { waitForClusterToForm(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration configuration = builder.build(); // Create a permanent cache manager(0).administration().createCache("a", configuration); waitForClusterToForm("a"); checkConsistencyAcrossCluster("a", configuration); manager(1).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache("b", configuration); TestingUtil.killCacheManagers(this.cacheManagers); cacheManagers.clear(); createStatefulCacheManager("A", false); checkConsistencyAcrossCluster("a", configuration); createStatefulCacheManager("B", true); checkConsistencyAcrossCluster("a", configuration); checkCacheExistenceAcrossCluster("b", false); manager(0).administration().createCache("c", configuration); checkConsistencyAcrossCluster("c", configuration); createStatefulCacheManager("C", false); checkConsistencyAcrossCluster("a", configuration); } }
3,190
35.678161
116
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheDependencyTest.java
package org.infinispan.manager; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.globalstate.GlobalConfigurationManager; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.security.mappers.ClusterPermissionMapper; import org.infinispan.security.mappers.ClusterRoleMapper; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author gustavonalle * @since 7.0 */ @Test(groups = "functional", testName = "manager.CacheDependencyTest") @CleanupAfterMethod public class CacheDependencyTest extends SingleCacheManagerTest { @Test public void testExplicitStop() { cacheManager.defineConfiguration("A", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("B", new ConfigurationBuilder().build()); Cache<?, ?> cacheA = cacheManager.getCache("A"); Cache<?, ?> cacheB = cacheManager.getCache("B"); cacheManager.addCacheDependency("A", "B"); cacheB.stop(); cacheA.stop(); assertAllTerminated(cacheA, cacheB); } @Test public void testDependencyOnStoppedCaches() { cacheManager.defineConfiguration("A", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("B", new ConfigurationBuilder().build()); Cache<?, ?> cacheA = cacheManager.getCache("A"); Cache<?, ?> cacheB = cacheManager.getCache("B"); cacheA.stop(); cacheManager.addCacheDependency("A", "B"); CacheEventListener listener = new CacheEventListener(); cacheManager.addListener(listener); cacheManager.stop(); assertAllTerminated(cacheA, cacheB); assertEquals(Arrays.asList("B", ClusterRoleMapper.CLUSTER_ROLE_MAPPER_CACHE, GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME, getDefaultCacheName(), ClusterPermissionMapper.CLUSTER_PERMISSION_MAPPER_CACHE), listener.stopOrder); } @Test public void testCyclicDependencies() { cacheManager.defineConfiguration("A", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("B", new ConfigurationBuilder().build()); Cache<?, ?> cacheA = cacheManager.getCache("A"); Cache<?, ?> cacheB = cacheManager.getCache("B"); cacheManager.addCacheDependency("A", "B"); cacheManager.addCacheDependency("B", "A"); // Order will not be enforced cacheManager.stop(); assertAllTerminated(cacheA, cacheB); } @Test public void testStopCacheManager() { CacheEventListener listener = new CacheEventListener(); cacheManager.addListener(listener); cacheManager.defineConfiguration("A", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("B", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("C", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("D", new ConfigurationBuilder().build()); Cache<?, ?> cacheA = cacheManager.getCache("A"); Cache<?, ?> cacheB = cacheManager.getCache("B"); Cache<?, ?> cacheC = cacheManager.getCache("C"); Cache<?, ?> cacheD = cacheManager.getCache("D"); cacheManager.addCacheDependency("A", "B"); cacheManager.addCacheDependency("A", "C"); cacheManager.addCacheDependency("A", "D"); cacheManager.addCacheDependency("B", "C"); cacheManager.addCacheDependency("B", "D"); cacheManager.addCacheDependency("D", "C"); cacheManager.stop(); assertAllTerminated(cacheA, cacheB, cacheC, cacheD); assertEquals(Arrays.asList("A", "B", "D", "C", ClusterRoleMapper.CLUSTER_ROLE_MAPPER_CACHE, GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME, getDefaultCacheName(), ClusterPermissionMapper.CLUSTER_PERMISSION_MAPPER_CACHE), listener.stopOrder); } @Test public void testRemoveCache() { cacheManager.defineConfiguration("A", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("B", new ConfigurationBuilder().build()); cacheManager.defineConfiguration("C", new ConfigurationBuilder().build()); Cache<?, ?> cacheA = cacheManager.getCache("A"); Cache<?, ?> cacheB = cacheManager.getCache("B"); Cache<?, ?> cacheC = cacheManager.getCache("C"); cacheManager.addCacheDependency("A", "B"); cacheManager.addCacheDependency("A", "C"); cacheManager.addCacheDependency("B", "C"); cacheManager.administration().removeCache("B"); CacheEventListener listener = new CacheEventListener(); cacheManager.addListener(listener); cacheManager.stop(); assertAllTerminated(cacheA, cacheB, cacheC); assertEquals(Arrays.asList("A", "C", ClusterRoleMapper.CLUSTER_ROLE_MAPPER_CACHE, GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME, getDefaultCacheName(), ClusterPermissionMapper.CLUSTER_PERMISSION_MAPPER_CACHE), listener.stopOrder); } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { return TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); } @Listener private static final class CacheEventListener { private final List<String> stopOrder = new ArrayList<>(); @CacheStopped public void cacheStopped(CacheStoppedEvent cse) { stopOrder.add(cse.getCacheName()); } } private void assertAllTerminated(Cache<?, ?>... caches) { for (Cache<?, ?> cache : caches) { assert cache.getStatus() == ComponentStatus.TERMINATED; } } }
5,967
37.25641
251
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/ImmutableCacheManagerAdminTest.java
package org.infinispan.manager; import org.infinispan.Cache; import org.infinispan.commons.api.CacheContainerAdmin; 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.globalstate.ConfigurationStorage; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; @Test(testName = "manager.ImmutableCacheManagerAdminTest", groups = "functional") @CleanupAfterMethod public class ImmutableCacheManagerAdminTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().configurationStorage(ConfigurationStorage.IMMUTABLE); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); addClusterEnabledCacheManager(builder); addClusterEnabledCacheManager(builder); } public void testClusterCacheTest() { waitForClusterToForm(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration configuration = builder.build(); Cache<Object, Object> cache = manager(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache("a", configuration); } }
1,616
42.702703
146
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/TestModuleRepository.java
package org.infinispan.manager; import org.infinispan.configuration.global.GlobalConfigurationBuilder; /** * Provide a default {@link ModuleRepository} for tests. */ public final class TestModuleRepository { private static final ModuleRepository MODULE_REPOSITORY = ModuleRepository.newModuleRepository( TestModuleRepository.class.getClassLoader(), new GlobalConfigurationBuilder().build()); public static ModuleRepository defaultModuleRepository() { return MODULE_REPOSITORY; } }
511
29.117647
98
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/AllClusterExecutorTest.java
package org.infinispan.manager; import static org.infinispan.test.TestingUtil.withCacheManagers; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.factories.KnownComponentNames; import org.infinispan.remoting.transport.Address; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.MultiCacheManagerCallable; import org.infinispan.test.TestBlocking; import org.infinispan.test.TestException; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.test.fwk.TestClassLocal; import org.infinispan.util.function.SerializableFunction; import org.infinispan.util.function.SerializableSupplier; import org.testng.annotations.Test; /** * @author Will Burns * @since 8.2 */ @Test(groups = {"functional", "smoke"}, testName = "manager.AllClusterExecutorTest") public class AllClusterExecutorTest extends AbstractInfinispanTest { static AtomicInteger atomicInteger = new AtomicInteger(); private TestClassLocal<CheckPoint> checkPoint = new TestClassLocal<>("checkpoint", this, CheckPoint::new, c -> {}); ClusterExecutor executor(EmbeddedCacheManager cm) { return cm.executor(); } void assertSize(EmbeddedCacheManager[] cms, int receivedSize) { assertEquals(cms.length, receivedSize); } void eventuallyAssertSize(EmbeddedCacheManager[] cms, Supplier<Integer> supplier) { eventuallyEquals(cms.length, supplier); } void assertContains(EmbeddedCacheManager[] managers, Collection<Address> results) { for (EmbeddedCacheManager manager : managers) { assertTrue(results.contains(manager.getAddress())); } } SerializableSupplier<AtomicInteger> atomicIntegerSupplier = () -> atomicInteger; public void testExecutorRunnable() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).submit(() -> supplier.get().getAndIncrement()).get(10, TimeUnit.SECONDS); assertSize(cms, atomicIntegerSupplier.get().get()); } }); } public void testExecutorLocalRunnable() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.LOCAL, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).submit(() -> supplier.get().getAndIncrement()).get(10, TimeUnit.SECONDS); assertSize(cms, atomicIntegerSupplier.get().get()); } }); } public void testExecutor3NodesRunnable() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).submit(() -> supplier.get().getAndIncrement()).get(10, TimeUnit.SECONDS); assertSize(cms, atomicIntegerSupplier.get().get()); } }); } public void testExecutorRunnablePredicateFilter() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).filterTargets(a -> a.equals(cm1.getAddress())) .submit(() -> supplier.get().getAndIncrement()).get(10, TimeUnit.SECONDS); assertEquals(1, atomicIntegerSupplier.get().get()); } }); } public void testExecutorRunnableCollectionFilter() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; EmbeddedCacheManager cm2 = cms[1]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).filterTargets(Collections.singleton(cm2.getAddress())) .submit(() -> supplier.get().getAndIncrement()).get(10, TimeUnit.SECONDS); assertEquals(1, atomicIntegerSupplier.get().get()); } }); } public void testExecutorRunnableException() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).submit(() -> { throw new TestException(); }); Exceptions.expectExecutionException(TestException.class, future); } }); } public void testExecutorRunnableExceptionWhenComplete() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).submit(() -> { throw new TestException(); }); Exchanger<Throwable> exchanger = new Exchanger<>(); future.whenCompleteAsync((v, t) -> { try { exchanger.exchange(t, 10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } }, TestingUtil.extractGlobalComponent(cm1, ExecutorService.class, KnownComponentNames.BLOCKING_EXECUTOR)); Throwable t = exchanger.exchange(null, 10, TimeUnit.SECONDS); assertNotNull(t); assertEquals(TestException.class, t.getClass()); } }); } public void testExecutorRunnable3NodesException() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).submit(() -> { throw new TestException(); }); Exceptions.expectExecutionException(TestException.class, future); } }); } public void testExecutorRunnable3NodesExceptionExcludeLocal() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).filterTargets(a -> !a.equals(cm1.getAddress())).submit(() -> { throw new TestException(); }); Exceptions.expectExecutionException(TestException.class, future); } }); } public void testExecutorTimeoutException() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; TestClassLocal<CheckPoint> checkPoint = AllClusterExecutorTest.this.checkPoint; CompletableFuture<Void> future = executor(cm1).timeout(1, TimeUnit.MILLISECONDS).submit(() -> { try { checkPoint.get().awaitStrict("resume_remote_execution", 10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { throw new TestException(e); } }); // This fails when local node is invoked since timeout is not adhered to Exceptions.expectExecutionException(org.infinispan.util.concurrent.TimeoutException.class, future); checkPoint.get().trigger("resume_remote_execution"); } }); } public void testExecutorExecuteRunnable() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); SerializableSupplier<AtomicInteger> supplier = atomicIntegerSupplier; executor(cm1).execute(() -> supplier.get().getAndIncrement()); eventuallyAssertSize(cms, () -> atomicIntegerSupplier.get().get()); } }); } public void testExecutorLocalExecuteRunnable() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.LOCAL, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; atomicIntegerSupplier.get().set(0); executor(cm1).execute(() -> atomicIntegerSupplier.get().getAndIncrement()); eventuallyEquals(1, () -> atomicIntegerSupplier.get().get()); } }); } public void testExecutorTriConsumer() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; EmbeddedCacheManager cm2 = cms[1]; AtomicReference<Throwable> throwable = new AtomicReference<>(); List<Address> addresses = Collections.synchronizedList(new ArrayList<>(2)); executor(cm1).submitConsumer(EmbeddedCacheManager::getAddress, (a, i, t) -> { if (t != null) { throwable.set(t); } else { addresses.add(i); } }).get(10, TimeUnit.SECONDS); Throwable t = throwable.get(); if (t != null) { throw new RuntimeException(t); } assertContains(cms, addresses); } }); } public void testExecutorLocalTriConsumer() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.LOCAL, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; AtomicReference<Throwable> throwable = new AtomicReference<>(); List<Address> addresses = Collections.synchronizedList(new ArrayList<>(2)); executor(cm1).submitConsumer(m -> m.getAddress(), (a, i, t) -> { if (t != null) { throwable.set(t); } else { addresses.add(i); } }).get(10, TimeUnit.SECONDS); Throwable t = throwable.get(); if (t != null) { throw new RuntimeException(t); } assertEquals(1, addresses.size()); assertTrue(addresses.contains(cm1.getAddress())); } }); } public void testExecutor3NodeTriConsumer() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; AtomicReference<Throwable> throwable = new AtomicReference<>(); List<Address> addresses = Collections.synchronizedList(new ArrayList<>(2)); executor(cm1).submitConsumer(m -> m.getAddress(), (a, i, t) -> { if (t != null) { throwable.set(t); } else { addresses.add(i); } }).get(10, TimeUnit.SECONDS); Throwable t = throwable.get(); if (t != null) { throw new RuntimeException(t); } assertContains(cms, addresses); } }); } public void testExecutorTriConsumerException() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; AtomicInteger exceptionCount = new AtomicInteger(); CompletableFuture<Void> future = executor(cm1).submitConsumer(m -> { throw new TestException(); }, (a, i, t) -> { Exceptions.assertException(TestException.class, t); exceptionCount.incrementAndGet(); }); future.get(10, TimeUnit.SECONDS); assertSize(cms, exceptionCount.get()); } }); } public void testExecutorTriConsumerTimeoutException() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.DIST_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; TestClassLocal<CheckPoint> checkPoint = AllClusterExecutorTest.this.checkPoint; SerializableFunction<EmbeddedCacheManager, Object> blockingFunction = m -> { try { checkPoint.get().trigger("block_execution"); checkPoint.get().awaitStrict("resume_execution", 10, TimeUnit.SECONDS); checkPoint.get().trigger("complete"); } catch (InterruptedException | TimeoutException e) { throw new TestException(e); } return null; }; CompletableFuture<Void> futureRemote = executor(cm1).filterTargets(a -> !a.equals(cm1.getAddress())) .timeout(1, TimeUnit.MILLISECONDS) .submitConsumer(blockingFunction, (a, i, t) -> { log.tracef("Consumer invoked with %s, %s, %s", a, i, t); }); Exceptions.expectExecutionException(org.infinispan.util.concurrent.TimeoutException.class, futureRemote); checkPoint.get().awaitStrict("block_execution", 10, TimeUnit.SECONDS); checkPoint.get().trigger("resume_execution"); // Have to wait for callback to complete - otherwise a different thread could find the "resume_execution" // checkpoint reached incorrectly checkPoint.get().awaitStrict("complete", 10, TimeUnit.SECONDS); CompletableFuture<Void> futureLocal = executor(cm1).filterTargets(a -> a.equals(cm1.getAddress())) .timeout(1, TimeUnit.MILLISECONDS) .submitConsumer(blockingFunction, (a, i, t) -> { log.tracef("Consumer invoked with %s, %s, %s", a, i, t); }); Exceptions.expectExecutionException(org.infinispan.util.concurrent.TimeoutException.class, futureLocal); checkPoint.get().awaitStrict("block_execution", 10, TimeUnit.SECONDS); checkPoint.get().trigger("resume_execution"); checkPoint.get().awaitStrict("complete", 10, TimeUnit.SECONDS); } }); } public void testExecutorTriConsumerExceptionFromConsumer() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).submitConsumer(m -> null, (a, i, t) -> { throw new NullPointerException(); }); Exceptions.expectExecutionException(NullPointerException.class, future); } }); } public void testExecutorTriConsumerExceptionWhenComplete() { withCacheManagers(new MultiCacheManagerCallable( TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false), TestCacheManagerFactory.createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cm1 = cms[0]; CompletableFuture<Void> future = executor(cm1).filterTargets(cm1.getAddress()::equals).submitConsumer(m -> null, (a, i, t) -> { throw new NullPointerException(); }); Exchanger<Throwable> exchanger = new Exchanger<>(); future.whenCompleteAsync((v, t) -> { try { TestBlocking.exchange(exchanger, t, 10, TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } }, TestingUtil.extractGlobalComponent(cm1, ExecutorService.class, KnownComponentNames.BLOCKING_EXECUTOR)); Throwable t = exchanger.exchange(null, 10, TimeUnit.SECONDS); assertNotNull(t); assertEquals(NullPointerException.class, t.getClass()); } }); } }
21,605
44.486316
121
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerAdminImmutableTest.java
package org.infinispan.manager; 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.globalstate.ConfigurationStorage; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; @Test(testName = "manager.CacheManagerAdminImmutableTest", groups = "functional") @CleanupAfterMethod public class CacheManagerAdminImmutableTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { for (int i = 0; i < 2; i++) { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().configurationStorage(ConfigurationStorage.IMMUTABLE); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); addClusterEnabledCacheManager(global, builder); } } public void testClusterCacheTest() { waitForClusterToForm(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration configuration = builder.build(); Exceptions.expectException(UnsupportedOperationException.class, "ISPN000515: The configuration is immutable", () -> manager(0).administration().createCache("a", configuration)); // attempt to delete a cache Exceptions.expectException(UnsupportedOperationException .class, "ISPN000515: The configuration is immutable", () -> manager(0).administration().removeCache("a")); } }
1,891
42
98
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/SingleClusterExecutorExecutionPolicyTest.java
package org.infinispan.manager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.fail; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import org.infinispan.commons.lambda.NamedLambdas; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.global.TransportConfiguration; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.remoting.transport.Address; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.util.function.TriConsumer; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests to verify that execution policy is applied properly when using a cluster executor * @author wburns * @since 9.1 */ @Test(groups = {"functional", "smoke"}, testName = "manager.SingleClusterExecutorExecutionPolicyTest") public class SingleClusterExecutorExecutionPolicyTest extends MultipleCacheManagersTest { @Override public String toString() { return super.toString(); } private static final int siteCount = 3; private static final int rackCount = 4; private static final int machineCount = 2; @DataProvider(name = "params") public Object[][] dataProvider() { return new Object[][] { { ClusterExecutionPolicy.ALL, 0, 0, 0, NamedLambdas.of("all_0", (Predicate<String>) v -> true) }, { ClusterExecutionPolicy.ALL, 2, 1, 1, NamedLambdas.of("all_2", (Predicate<String>) v -> true) }, { ClusterExecutionPolicy.DIFFERENT_MACHINE, 1, 0, 1, NamedLambdas.of("diff_machine_1", (Predicate<String>) v -> !v.equals("101")) }, { ClusterExecutionPolicy.DIFFERENT_MACHINE, 0, 1, 0, NamedLambdas.of("diff_machine_0", (Predicate<String>) v -> !v.equals("010")) }, { ClusterExecutionPolicy.SAME_MACHINE, 2, 1, 1, NamedLambdas.of("same_machine_2", (Predicate<String>) v -> v.equals("211")) }, { ClusterExecutionPolicy.SAME_MACHINE, 0, 0, 1, NamedLambdas.of("same_machine_0", (Predicate<String>) v -> v.equals("001")) }, { ClusterExecutionPolicy.DIFFERENT_RACK, 2, 2, 0, NamedLambdas.of("diff_rack_2", (Predicate<String>) v -> !v.startsWith("22")) }, { ClusterExecutionPolicy.DIFFERENT_RACK, 1, 0, 1, NamedLambdas.of("diff_rack_1", (Predicate<String>) v -> !v.startsWith("10")) }, { ClusterExecutionPolicy.DIFFERENT_RACK, 0, 1, 0, NamedLambdas.of("diff_rack_0", (Predicate<String>) v -> !v.startsWith("01")) }, { ClusterExecutionPolicy.SAME_RACK, 2, 1, 1, NamedLambdas.of("same_rack_2", (Predicate<String>) v -> v.startsWith("21")) }, { ClusterExecutionPolicy.SAME_RACK, 1, 0, 1, NamedLambdas.of("same_rack_1", (Predicate<String>) v -> v.startsWith("10")) }, { ClusterExecutionPolicy.SAME_RACK, 0, 2, 0, NamedLambdas.of("same_rack_0", (Predicate<String>) v -> v.startsWith("02")) }, { ClusterExecutionPolicy.DIFFERENT_SITE, 2, 0, 0, NamedLambdas.of("diff_site_2", (Predicate<String>) v -> !v.startsWith("2")) }, { ClusterExecutionPolicy.DIFFERENT_SITE, 1, 0, 1, NamedLambdas.of("diff_site_1", (Predicate<String>) v -> !v.startsWith("1")) }, { ClusterExecutionPolicy.DIFFERENT_SITE, 0, 1, 0, NamedLambdas.of("diff_site_0", (Predicate<String>) v -> !v.startsWith("0")) }, { ClusterExecutionPolicy.SAME_SITE, 2, 0, 1, NamedLambdas.of("same_site_2", (Predicate<String>) v -> v.startsWith("2")) }, { ClusterExecutionPolicy.SAME_SITE, 1, 0, 0, NamedLambdas.of("same_site_1", (Predicate<String>) v -> v.startsWith("1")) }, { ClusterExecutionPolicy.SAME_SITE, 0, 1, 0, NamedLambdas.of("same_site_0", (Predicate<String>) v -> v.startsWith("0")) }, }; } @Override protected void createCacheManagers() throws Throwable { for (int siteNumber = 0; siteNumber < siteCount; ++siteNumber) { for (int rackNumber = 0; rackNumber < rackCount; ++rackNumber) { for (int machineNumber = 0; machineNumber < machineCount; ++machineNumber) { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); GlobalConfigurationBuilder globalConfigurationBuilder = holder.getGlobalConfigurationBuilder().clusteredDefault(); globalConfigurationBuilder.transport() .machineId(String.valueOf(machineNumber)) .rackId(String.valueOf(rackNumber)) .siteId(String.valueOf(siteNumber)); addClusterEnabledCacheManager(holder); } } } TestingUtil.blockUntilViewsReceived(10_000, cacheManagers); } @Test(dataProvider = "params") public void runTest(ClusterExecutionPolicy policy, int site, int rack, int machine, Predicate<String> passFilter) throws InterruptedException, ExecutionException, TimeoutException { EmbeddedCacheManager cacheManager = cacheManagers.stream().filter(cm -> { TransportConfiguration tc = cm.getCacheManagerConfiguration().transport(); return Integer.valueOf(tc.siteId()) == site && Integer.valueOf(tc.rackId()) == rack && Integer.valueOf(tc.machineId()) == machine; }).findFirst().orElseThrow(() -> new AssertionError("No cache manager matches site: " + site + " rack: " + rack + " machine: " + machine)); AtomicInteger invocationCount = new AtomicInteger(); Queue<String> nonMatched = new ConcurrentLinkedQueue<>(); TriConsumer<Address, String, Throwable> triConsumer = (a, v, t) -> { invocationCount.incrementAndGet(); if (!passFilter.test(v)) { nonMatched.add(v); } }; int invocations = 5; ClusterExecutor executor = cacheManager.executor().singleNodeSubmission().filterTargets(policy); for (int i = 0; i < invocations; ++i) { executor.submitConsumer((cm) -> { TransportConfiguration tc = cm.getCacheManagerConfiguration().transport(); return tc.siteId() + tc.rackId() + tc.machineId(); }, triConsumer).get(10, TimeUnit.SECONDS); } assertEquals(invocations, invocationCount.get()); if (!nonMatched.isEmpty()) { fail("Invocations that didn't match [" + nonMatched + "]"); } } }
6,584
54.336134
184
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/ConcurrentCacheManagerTest.java
package org.infinispan.manager; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.infinispan.Cache; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test that verifies that CacheContainer.getCache() can be called concurrently. * * @author Galder Zamarreño * @since 4.2 */ @Test(groups = "functional", testName = "manager.ConcurrentCacheManagerTest") public class ConcurrentCacheManagerTest extends AbstractCacheTest { private static final int NUM_CACHES = 4; private static final int NUM_THREADS = 25; private EmbeddedCacheManager cacheManager; @BeforeMethod protected void setup() throws Exception { EmbeddedCacheManager manager = TestCacheManagerFactory.createCacheManager(); for (int i = 0; i < NUM_CACHES; i++) { manager.defineConfiguration("cache" + i, TestCacheManagerFactory.getDefaultCacheConfiguration(false).build()); } cacheManager = manager; } @AfterMethod protected void teardown() { TestingUtil.killCacheManagers(cacheManager); } public void testConcurrentGetCacheCalls() throws Exception { final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1); List<Future<Void>> futures = new ArrayList<>(NUM_THREADS); ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS, getTestThreadFactory("Worker")); for (int i = 0; i < NUM_THREADS; i++) { log.debug("Schedule execution"); final String name = "cache" + (i % NUM_CACHES); Future<Void> future = executorService.submit(() -> { try { barrier.await(); log.tracef("Creating cache %s", name); Cache<Object,Object> cache = cacheManager.getCache(name); cache.put("a", "b"); return null; } catch (Throwable t) { log.error("Got", t); throw new RuntimeException(t); } finally { log.debug("Wait for all execution paths to finish"); barrier.await(); } }); futures.add(future); } barrier.await(); // wait for all threads to be ready barrier.await(); // wait for all threads to finish log.debug("All threads finished, let's shutdown the executor and check whether any exceptions were reported"); for (Future<Void> future : futures) future.get(); executorService.shutdownNow(); } }
2,826
35.24359
119
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerComponentRegistryTest.java
package org.infinispan.manager; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.eviction.EvictionManager; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.impl.BatchingInterceptor; import org.infinispan.remoting.transport.Transport; import org.infinispan.test.AbstractCacheTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * @author Manik Surtani * @since 4.0 */ @Test(groups = "functional", testName = "manager.CacheManagerComponentRegistryTest") public class CacheManagerComponentRegistryTest extends AbstractCacheTest { private EmbeddedCacheManager cm; @AfterMethod public void tearDown() { TestingUtil.killCacheManagers(cm); cm = null; } public void testForceSharedComponents() { ConfigurationBuilder defaultCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC); defaultCfg .clustering() .stateTransfer() .fetchInMemoryState(false) .transaction() .transactionMode(TransactionMode.NON_TRANSACTIONAL); // cache manager with default configuration cm = TestCacheManagerFactory.createClusteredCacheManager(defaultCfg); // default cache with no overrides Cache c = cm.getCache(); ConfigurationBuilder overrides = TestCacheManagerFactory.getDefaultCacheConfiguration(true); overrides.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); cm.defineConfiguration("transactional", overrides.build()); Cache transactional = cm.getCache("transactional"); // assert components. assert TestingUtil.extractComponent(c, TransactionManager.class) == null; assert TestingUtil.extractComponent(transactional, TransactionManager.class) instanceof EmbeddedTransactionManager; // assert force-shared components assert TestingUtil.extractComponent(c, Transport.class) != null; assert TestingUtil.extractComponent(transactional, Transport.class) != null; assert TestingUtil.extractComponent(c, Transport.class) == TestingUtil.extractComponent(transactional, Transport.class); } public void testForceUnsharedComponents() { ConfigurationBuilder defaultCfg = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC); defaultCfg .clustering() .stateTransfer() .fetchInMemoryState(false); // cache manager with default configuration cm = TestCacheManagerFactory.createClusteredCacheManager(defaultCfg); // default cache with no overrides Cache c = cm.getCache(); ConfigurationBuilder overrides = TestCacheManagerFactory.getDefaultCacheConfiguration(true); overrides.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); cm.defineConfiguration("transactional", overrides.build()); Cache transactional = cm.getCache("transactional"); // assert components. assert TestingUtil.extractComponent(c, EvictionManager.class) != null; assert TestingUtil.extractComponent(transactional, EvictionManager.class) != null; assert TestingUtil.extractComponent(c, EvictionManager.class) != TestingUtil.extractComponent(transactional, EvictionManager.class); } public void testOverridingComponents() { cm = TestCacheManagerFactory.createClusteredCacheManager(new ConfigurationBuilder()); // default cache with no overrides Cache c = cm.getCache(); ConfigurationBuilder overrides = new ConfigurationBuilder(); overrides.invocationBatching().enable(); cm.defineConfiguration("overridden", overrides.build()); Cache overridden = cm.getCache("overridden"); // assert components. AsyncInterceptorChain initialChain = c.getAdvancedCache().getAsyncInterceptorChain(); assert !initialChain.containsInterceptorType(BatchingInterceptor.class); AsyncInterceptorChain overriddenChain = overridden.getAdvancedCache().getAsyncInterceptorChain(); assert overriddenChain.containsInterceptorType(BatchingInterceptor.class); } }
4,570
42.122642
138
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerTest.java
package org.infinispan.manager; import static java.util.concurrent.TimeUnit.SECONDS; import static org.infinispan.commons.test.Exceptions.expectException; import static org.infinispan.test.TestingUtil.extractComponent; import static org.infinispan.test.TestingUtil.extractGlobalComponentRegistry; import static org.infinispan.test.TestingUtil.getDefaultCacheName; import static org.infinispan.test.TestingUtil.getFirstStore; import static org.infinispan.test.TestingUtil.k; import static org.infinispan.test.TestingUtil.killCacheManagers; import static org.infinispan.test.TestingUtil.replaceComponent; import static org.infinispan.test.TestingUtil.v; import static org.infinispan.test.TestingUtil.waitForNoRebalance; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.infinispan.test.TestingUtil.withCacheManagers; import static org.infinispan.test.fwk.TestCacheManagerFactory.createCacheManager; import static org.infinispan.test.fwk.TestCacheManagerFactory.createClusteredCacheManager; 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.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.commands.module.TestGlobalConfigurationBuilder; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.CacheException; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.configuration.BuiltBy; import org.infinispan.commons.configuration.Combine; import org.infinispan.commons.configuration.ConfigurationFor; import org.infinispan.commons.configuration.attributes.AttributeSet; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.AbstractStoreConfiguration; import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder; import org.infinispan.configuration.cache.AsyncStoreConfiguration; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.InterceptorConfiguration; import org.infinispan.configuration.cache.PersistenceConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.container.DataContainer; import org.infinispan.container.impl.InternalDataContainer; import org.infinispan.factories.ComponentRegistry; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.marshall.core.GlobalMarshaller; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStarted; import org.infinispan.notifications.cachemanagerlistener.annotation.CacheStopped; import org.infinispan.notifications.cachemanagerlistener.event.CacheStartedEvent; import org.infinispan.notifications.cachemanagerlistener.event.CacheStoppedEvent; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.persistence.dummy.Element; import org.infinispan.persistence.spi.ExternalStore; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.MultiCacheManagerCallable; import org.infinispan.test.TestException; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * @author Manik Surtani * @since 4.0 */ @Test(groups = {"functional", "smoke"}, testName = "manager.CacheManagerTest") public class CacheManagerTest extends AbstractInfinispanTest { private static final java.lang.String CACHE_NAME = "name"; public void testDefaultCache() { EmbeddedCacheManager cm = createCacheManager(false); try { assertEquals(ComponentStatus.RUNNING, cm.getCache().getStatus()); assertEquals(getDefaultCacheName(cm), cm.getCache().getName()); expectException(CacheConfigurationException.class, () -> cm.defineConfiguration(getDefaultCacheName(cm), new ConfigurationBuilder().build())); expectException(CacheConfigurationException.class, () -> cm.getCache("non-existent-cache")); } finally { killCacheManagers(cm); } } public void testDefaultCacheStartedAutomatically() { EmbeddedCacheManager cm = createCacheManager(new ConfigurationBuilder()); try { assertEquals(new HashSet<>(Arrays.asList(getDefaultCacheName(cm))), cm.getCacheNames()); ComponentRegistry cr = extractGlobalComponentRegistry(cm).getNamedComponentRegistry(getDefaultCacheName(cm)); assertEquals(ComponentStatus.RUNNING, cr.getStatus()); assertEquals(getDefaultCacheName(cm), cr.getCacheName()); } finally { killCacheManagers(cm); } } public void testUnstartedCachemanager() { withCacheManager(new CacheManagerCallable(createCacheManager(false)) { @Override public void call() { assertEquals(ComponentStatus.INSTANTIATED, cm.getStatus()); assertFalse(cm.getStatus().allowInvocations()); Cache<Object, Object> cache = cm.getCache(); cache.put("k", "v"); assertEquals(cache.get("k"), "v"); } }); } @Test(expectedExceptions = CacheConfigurationException.class) public void testClashingNames() { EmbeddedCacheManager cm = createCacheManager(false); try { ConfigurationBuilder c = new ConfigurationBuilder(); cm.defineConfiguration("aCache", c.build()); cm.defineConfiguration("aCache", c.build()); } finally { killCacheManagers(cm); } } public void testWildcardTemplateNameMatchingInternalCache() { ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.newConfigurationBuilder("*") .template(true) .clustering().cacheMode(CacheMode.LOCAL) .memory().maxCount(1); EmbeddedCacheManager cm = createClusteredCacheManager(holder); try { Cache<Object, Object> aCache = cm.getCache("a"); assertEquals(1L, aCache.getCacheConfiguration().memory().maxCount()); } finally { killCacheManagers(cm); } } public void testStartAndStop() { EmbeddedCacheManager cm = createCacheManager(false); try { cm.defineConfiguration("cache1", new ConfigurationBuilder().build()); cm.defineConfiguration("cache2", new ConfigurationBuilder().build()); cm.defineConfiguration("cache3", new ConfigurationBuilder().build()); Cache<?, ?> c1 = cm.getCache("cache1"); Cache<?, ?> c2 = cm.getCache("cache2"); Cache<?, ?> c3 = cm.getCache("cache3"); assertEquals(ComponentStatus.RUNNING, c1.getStatus()); assertEquals(ComponentStatus.RUNNING, c2.getStatus()); assertEquals(ComponentStatus.RUNNING, c3.getStatus()); cm.stop(); assertEquals(ComponentStatus.TERMINATED, c1.getStatus()); assertEquals(ComponentStatus.TERMINATED, c2.getStatus()); assertEquals(ComponentStatus.TERMINATED, c3.getStatus()); } finally { killCacheManagers(cm); } } public void testDefiningConfigurationValidation() { EmbeddedCacheManager cm = createCacheManager(false); expectException(NullPointerException.class, () -> cm.defineConfiguration("cache1", null)); expectException(NullPointerException.class, () -> cm.defineConfiguration(null, null)); expectException(NullPointerException.class, () -> cm.defineConfiguration(null, new ConfigurationBuilder().build())); } public void testDefineConfigurationTwice() { EmbeddedCacheManager cm = createCacheManager(false); try { Configuration override = new ConfigurationBuilder().invocationBatching().enable().build(); assertTrue(override.invocationBatching().enabled()); assertTrue(cm.defineConfiguration("test1", override).invocationBatching().enabled()); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.read(override, Combine.DEFAULT); Configuration config = cb.build(); assertTrue(config.invocationBatching().enabled()); assertTrue(cm.defineConfiguration("test2", config).invocationBatching().enabled()); } finally { cm.stop(); } } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000436:.*") public void testMissingDefaultConfiguration() { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.jmx().enabled(false); EmbeddedCacheManager cm = new DefaultCacheManager(gcb.build()); try { cm.getCache("someCache"); } finally { cm.stop(); } } public void testGetCacheNames() { EmbeddedCacheManager cm = createCacheManager(false); try { cm.defineConfiguration("one", new ConfigurationBuilder().build()); cm.defineConfiguration("two", new ConfigurationBuilder().build()); cm.defineConfiguration("three", new ConfigurationBuilder().build()); cm.getCache("three"); Set<String> cacheNames = cm.getCacheNames(); assertEquals(4, cacheNames.size()); assertTrue(cacheNames.contains("one")); assertTrue(cacheNames.contains("two")); assertTrue(cacheNames.contains("three")); } finally { cm.stop(); } } public void testCacheStopTwice() { EmbeddedCacheManager localCacheManager = createCacheManager(false); try { Cache<String, String> cache = localCacheManager.getCache(); cache.put("k", "v"); cache.stop(); cache.stop(); } finally { killCacheManagers(localCacheManager); } } public void testCacheManagerStopTwice() { EmbeddedCacheManager localCacheManager = createCacheManager(false); try { Cache<String, String> cache = localCacheManager.getCache(); cache.put("k", "v"); localCacheManager.stop(); localCacheManager.stop(); } finally { killCacheManagers(localCacheManager); } } @Test(expectedExceptions = IllegalLifecycleStateException.class) public void testCacheStopManagerStopFollowedByGetCache() { EmbeddedCacheManager localCacheManager = createCacheManager(false); try { Cache<String, String> cache = localCacheManager.getCache(); cache.put("k", "v"); cache.stop(); localCacheManager.stop(); localCacheManager.getCache(); } finally { killCacheManagers(localCacheManager); } } @Test(expectedExceptions = IllegalLifecycleStateException.class) public void testCacheStopManagerStopFollowedByCacheOp() { EmbeddedCacheManager localCacheManager = createCacheManager(false); try { Cache<String, String> cache = localCacheManager.getCache(); cache.put("k", "v"); cache.stop(); localCacheManager.stop(); cache.put("k", "v2"); } finally { killCacheManagers(localCacheManager); } } public void testConcurrentCacheManagerStopAndGetCache() throws Exception { EmbeddedCacheManager manager = createCacheManager(false); CompletableFuture<Void> cacheStartBlocked = new CompletableFuture<>(); CompletableFuture<Void> cacheStartResumed = new CompletableFuture<>(); CompletableFuture<Void> managerStopBlocked = new CompletableFuture<>(); CompletableFuture<Void> managerStopResumed = new CompletableFuture<>(); try { manager.addListener(new MyListener(CACHE_NAME, cacheStartBlocked, cacheStartResumed)); replaceComponent(manager, GlobalMarshaller.class, new LatchGlobalMarshaller(managerStopBlocked, managerStopResumed), true); // Need to start after replacing the global marshaller because we can't delegate to the old GlobalMarshaller manager.start(); Future<?> cacheStartFuture = fork(() -> manager.createCache(CACHE_NAME, new ConfigurationBuilder().build())); cacheStartBlocked.get(10, SECONDS); Future<?> managerStopFuture = fork(() -> manager.stop()); Exceptions.expectException(TimeoutException.class, () -> managerStopBlocked.get(1, SECONDS)); Future<?> cacheStartFuture2 = fork(() -> manager.getCache(CACHE_NAME)); Exceptions.expectExecutionException(IllegalLifecycleStateException.class, cacheStartFuture2); cacheStartResumed.complete(null); cacheStartFuture.get(10, SECONDS); managerStopBlocked.get(10, SECONDS); managerStopResumed.complete(null); managerStopFuture.get(10, SECONDS); } finally { cacheStartBlocked.complete(null); cacheStartResumed.complete(null); managerStopBlocked.complete(null); managerStopResumed.complete(null); killCacheManagers(manager); } } public void testRemoveNonExistentCache(Method m) { EmbeddedCacheManager manager = getManagerWithStore(m, false, false); try { manager.getCache("cache"); // An attempt to remove a non-existing cache should be a no-op manager.administration().removeCache("does-not-exist"); } finally { manager.stop(); } } public void testRemoveCacheLocal(Method m) { EmbeddedCacheManager manager = getManagerWithStore(m, false, false); try { Cache<String, String> cache = manager.getCache("cache"); cache.put(k(m, 1), v(m, 1)); cache.put(k(m, 2), v(m, 2)); cache.put(k(m, 3), v(m, 3)); DummyInMemoryStore store = getDummyStore(cache); DataContainer<?, ?> data = getDataContainer(cache); assertFalse(store.isEmpty()); assertTrue(0 != data.size()); manager.administration().removeCache("cache"); assertEquals(0, DummyInMemoryStore.getStoreDataSize(store.getStoreName())); assertEquals(0, data.size()); // Try removing the cache again, it should be a no-op manager.administration().removeCache("cache"); assertEquals(0, DummyInMemoryStore.getStoreDataSize(store.getStoreName())); assertEquals(0, data.size()); } finally { manager.stop(); } } @Test(expectedExceptions = CacheException.class) public void testStartCachesFailed() { EmbeddedCacheManager cacheManager = null; try { cacheManager = createCacheManager(); Configuration configuration = new ConfigurationBuilder().build(); cacheManager.defineConfiguration("correct-cache-1", configuration); cacheManager.defineConfiguration("correct-cache-2", configuration); cacheManager.defineConfiguration("correct-cache-3", configuration); ConfigurationBuilder incorrectBuilder = new ConfigurationBuilder(); incorrectBuilder.customInterceptors().addInterceptor().position(InterceptorConfiguration.Position.FIRST) .interceptor(new ExceptionInterceptor()); cacheManager.defineConfiguration("incorrect", incorrectBuilder.build()); cacheManager.startCaches("correct-cache-1", "correct-cache-2", "correct-cache-3", "incorrect"); } finally { if (cacheManager != null) { killCacheManagers(cacheManager); } } } public void testCacheManagerStartFailure() { FailingGlobalComponent failingGlobalComponent = new FailingGlobalComponent(); GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder(); globalBuilder.addModule(TestGlobalConfigurationBuilder.class) .testGlobalComponent(FailingGlobalComponent.class.getName(), failingGlobalComponent); ConfigurationBuilder builder = new ConfigurationBuilder(); Exceptions.expectException(EmbeddedCacheManagerStartupException.class, () -> createCacheManager(globalBuilder, builder)); assertTrue(failingGlobalComponent.started); assertTrue(failingGlobalComponent.stopped); } public void testCacheManagerRestartReusingConfigurations() { withCacheManagers(new MultiCacheManagerCallable( createCacheManager(CacheMode.REPL_SYNC, false), createCacheManager(CacheMode.REPL_SYNC, false)) { @Override public void call() { EmbeddedCacheManager cm1 = cms[0]; EmbeddedCacheManager cm2 = cms[1]; waitForNoRebalance(cm1.getCache(), cm2.getCache()); Cache<Object, Object> c1 = cm1.getCache(); GlobalConfiguration globalCfg = cm1.getCacheManagerConfiguration(); Configuration cfg = c1.getCacheConfiguration(); killCacheManagers(cm1); ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder(); holder.getGlobalConfigurationBuilder().read(globalCfg); holder.getNamedConfigurationBuilders().put(TestCacheManagerFactory.DEFAULT_CACHE_NAME, new ConfigurationBuilder().read(cfg, Combine.DEFAULT)); withCacheManager(new CacheManagerCallable(new DefaultCacheManager(holder, true)) { @Override public void call() { Cache<Object, Object> c = cm.getCache(); c.put(1, "v1"); assertEquals("v1", c.get(1)); } }); } }); } public void testRemoveCacheClusteredLocalStores(Method m) throws Exception { doTestRemoveCacheClustered(m, false); } public void testRemoveCacheClusteredSharedStores(Method m) throws Exception { doTestRemoveCacheClustered(m, true); } public void testExceptionOnCacheManagerStop() { ConfigurationBuilder c = new ConfigurationBuilder(); c.persistence().addStore(UnreliableCacheStoreConfigurationBuilder.class) .segmented(false); EmbeddedCacheManager cm = createCacheManager(c); try { assertEquals(ComponentStatus.RUNNING, cm.getStatus()); Cache<Integer, String> cache = cm.getCache(); cache.put(1, "v1"); } finally { killCacheManagers(cm); assertEquals(ComponentStatus.TERMINATED, cm.getStatus()); } } public void testDefineConfigurationWithOverrideAndTemplate() { withCacheManager(new CacheManagerCallable(createClusteredCacheManager()) { @Override public void call() { // DIST_ASYNC isn't default so it should stay applied CacheMode cacheMode = CacheMode.DIST_ASYNC; String templateName = "dist-cache-template"; cm.defineConfiguration(templateName, new ConfigurationBuilder().clustering().cacheMode(cacheMode).template(true).build()); CacheMode overrideCacheMode = CacheMode.REPL_ASYNC; Configuration overrideConfiguration = new ConfigurationBuilder().clustering().cacheMode(overrideCacheMode).build(); String ourCacheName = "my-cache"; cm.defineConfiguration(ourCacheName, templateName, overrideConfiguration); Cache<?, ?> cache = cm.getCache(ourCacheName); // We expect the override to take precedence assertEquals(overrideCacheMode, cache.getCacheConfiguration().clustering().cacheMode()); } }); } public void testCacheNameLength() { final String cacheName = new String(new char[256]); final String exceptionMessage = String.format("ISPN000663: Name must be less than 256 bytes, current name '%s' exceeds the size.", cacheName); final Configuration configuration = new ConfigurationBuilder().build(); withCacheManager(new CacheManagerCallable(createCacheManager()) { @Override public void call() { expectException(exceptionMessage, () -> cm.createCache(cacheName, configuration), CacheConfigurationException.class); expectException(exceptionMessage, () -> cm.defineConfiguration(cacheName, configuration), CacheConfigurationException.class); } }); } private EmbeddedCacheManager getManagerWithStore(Method m, boolean isClustered, boolean isStoreShared) { return getManagerWithStore(m, isClustered, isStoreShared, "store-"); } private EmbeddedCacheManager getManagerWithStore(Method m, boolean isClustered, boolean isStoreShared, String storePrefix) { String storeName = storePrefix + m.getName(); ConfigurationBuilder c = new ConfigurationBuilder(); c .persistence() .addStore(DummyInMemoryStoreConfigurationBuilder.class).storeName(storeName).shared(isStoreShared) .clustering() .cacheMode(isClustered ? CacheMode.REPL_SYNC : CacheMode.LOCAL); GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().clusteredDefault(); EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(gcb, c); cm.defineConfiguration("cache", c.build()); return cm; } private void doTestRemoveCacheClustered(final Method m, final boolean isStoreShared) { withCacheManagers(new MultiCacheManagerCallable( getManagerWithStore(m, true, isStoreShared, "store1-"), getManagerWithStore(m, true, isStoreShared, "store2-")) { @Override public void call() { EmbeddedCacheManager manager1 = cms[0]; EmbeddedCacheManager manager2 = cms[0]; Cache<String, String> cache1 = manager1.getCache("cache", true); Cache<String, String> cache2 = manager2.getCache("cache", true); assertNotNull(cache1); assertNotNull(cache2); assertTrue(manager1.cacheExists("cache")); assertTrue(manager2.cacheExists("cache")); cache1.put(k(m, 1), v(m, 1)); cache1.put(k(m, 2), v(m, 2)); cache1.put(k(m, 3), v(m, 3)); cache2.put(k(m, 4), v(m, 4)); cache2.put(k(m, 5), v(m, 5)); DummyInMemoryStore store1 = getDummyStore(cache1); DataContainer<?, ?> data1 = getDataContainer(cache1); DummyInMemoryStore store2 = getDummyStore(cache2); DataContainer<?, ?> data2 = getDataContainer(cache2); assertFalse(store1.isEmpty()); assertEquals(5, data1.size()); assertFalse(store2.isEmpty()); assertEquals(5, data2.size()); manager1.administration().removeCache("cache"); assertFalse(manager1.cacheExists("cache")); assertFalse(manager2.cacheExists("cache")); assertNull(manager1.getCache("cache", false)); assertNull(manager2.getCache("cache", false)); assertEquals(0, DummyInMemoryStore.getStoreDataSize(store1.getStoreName())); assertEquals(0, data1.size()); assertEquals(0, DummyInMemoryStore.getStoreDataSize(store2.getStoreName())); assertEquals(0, data2.size()); } }); } private DummyInMemoryStore getDummyStore(Cache<String, String> cache1) { return (DummyInMemoryStore) getFirstStore(cache1); } private DataContainer<?, ?> getDataContainer(Cache<String, String> cache) { return extractComponent(cache, InternalDataContainer.class); } public static class UnreliableCacheStore implements ExternalStore<Object, Object> { @Override public void init(InitializationContext ctx) {} @Override public void write(MarshallableEntry<?, ?> entry) {} @Override public boolean delete(Object key) { return false; } @Override public MarshallableEntry<Object, Object> loadEntry(Object key) { return null; } @Override public boolean contains(Object key) { return false; } @Override public void start() {} @Override public void stop() { throw new IllegalStateException("Test"); } } @ConfigurationFor(UnreliableCacheStore.class) @BuiltBy(UnreliableCacheStoreConfigurationBuilder.class) public static class UnreliableCacheStoreConfiguration extends AbstractStoreConfiguration<UnreliableCacheStoreConfiguration> { public UnreliableCacheStoreConfiguration(AttributeSet attributes, AsyncStoreConfiguration async) { super(Element.DUMMY_STORE, attributes, async); } } public static class UnreliableCacheStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<UnreliableCacheStoreConfiguration, UnreliableCacheStoreConfigurationBuilder> { public UnreliableCacheStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) { super(builder, UnreliableCacheStoreConfiguration.attributeDefinitionSet()); } @Override public UnreliableCacheStoreConfiguration create() { return new UnreliableCacheStoreConfiguration(attributes.protect(), async.create()); } @Override public UnreliableCacheStoreConfigurationBuilder self() { return this; } } static class ExceptionInterceptor extends BaseCustomAsyncInterceptor { @Override protected void start() { throw new IllegalStateException(); } } @Listener private class MyListener { private final String cacheName; private final CompletableFuture<Void> cacheStartBlocked; private final CompletableFuture<Void> cacheStartResumed; public MyListener(String cacheName, CompletableFuture<Void> cacheStartBlocked, CompletableFuture<Void> cacheStartResumed) { this.cacheName = cacheName; this.cacheStartBlocked = cacheStartBlocked; this.cacheStartResumed = cacheStartResumed; } @CacheStarted public void cacheStarted(CacheStartedEvent event) { log.tracef("Cache started: %s", event.getCacheName()); if (cacheName.equals(event.getCacheName())) { cacheStartBlocked.complete(null); cacheStartResumed.join(); } } @CacheStopped public void cacheStopped(CacheStoppedEvent event) { log.tracef("Cache stopped: %s", event.getCacheName()); } } @Scope(Scopes.GLOBAL) public static class FailingGlobalComponent { private boolean started; private boolean stopped; @Start public void start() { started = true; throw new TestException(); } @Stop public void stop() { stopped = true; } } class LatchGlobalMarshaller extends GlobalMarshaller { private final CompletableFuture<Void> managerStopBlocked; private final CompletableFuture<Void> managerStopResumed; public LatchGlobalMarshaller(CompletableFuture<Void> managerStopBlocked, CompletableFuture<Void> managerStopResumed) { this.managerStopBlocked = managerStopBlocked; this.managerStopResumed = managerStopResumed; } @Override public void stop() { log.tracef("Stopping global component registry"); managerStopBlocked.complete(null); managerStopResumed.join(); super.stop(); } } }
28,333
41.736048
174
java
null
infinispan-main/core/src/test/java/org/infinispan/manager/CacheManagerAdminTest.java
package org.infinispan.manager; 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 org.infinispan.Cache; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.commons.test.Exceptions; 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.globalstate.ConfigurationStorage; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.fwk.CleanupAfterMethod; import org.testng.annotations.Test; @Test(testName = "manager.CacheManagerAdminTest", groups = "functional") @CleanupAfterMethod public class CacheManagerAdminTest extends MultipleCacheManagersTest { @Override protected void createCacheManagers() throws Throwable { GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder(); global.globalState().configurationStorage(ConfigurationStorage.VOLATILE); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); addClusterEnabledCacheManager(builder); addClusterEnabledCacheManager(builder); } public void testClusterCacheTest() { waitForClusterToForm(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clustering().cacheMode(CacheMode.DIST_SYNC); Configuration configuration = builder.build(); Cache<Object, Object> cache = manager(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).createCache("a", configuration); waitForClusterToForm("a"); assertEquals(cacheManagers.size(), cache.getAdvancedCache().getRpcManager().getMembers().size()); checkConsistencyAcrossCluster("a", configuration); addClusterEnabledCacheManager(); checkConsistencyAcrossCluster("a", configuration); Exceptions.expectException(CacheConfigurationException.class, "ISPN000374: No such template 'nonExistingTemplate' when declaring 'b'", () -> manager(0).administration().createCache("b", "nonExistingTemplate")); // attempt to create an existing cache Exceptions.expectException(CacheConfigurationException.class, "ISPN000507: Cache a already exists", () -> manager(0).administration().createCache("a", configuration)); // getOrCreate should work manager(0).administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("a", configuration); manager(1).administration().removeCache("a"); checkCacheExistenceAcrossCluster("a", false); addClusterEnabledCacheManager(); checkCacheExistenceAcrossCluster("a", false); } protected void checkCacheExistenceAcrossCluster(String cacheName, boolean exists) { for (EmbeddedCacheManager m : cacheManagers) { if (exists) { assertTrue("Cache '" + cacheName + "' should be present on " + m, m.cacheExists(cacheName)); } else { assertFalse("Cache '" + cacheName + "' should NOT be present on " + m, m.cacheExists(cacheName)); } } } protected void checkConsistencyAcrossCluster(String cacheName, Configuration configuration) { for (EmbeddedCacheManager m : cacheManagers) { Configuration actualConfiguration = m.getCacheConfiguration(cacheName); assertNotNull("Cache " + cacheName + " missing from " + m, actualConfiguration); assertEquals(configuration, actualConfiguration); Cache<Object, Object> cache = m.getCache(cacheName); assertEquals(cacheManagers.size(), cache.getAdvancedCache().getRpcManager().getMembers().size()); } } }
4,021
44.191011
146
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/DistributedParallelNonRehashStreamTest.java
package org.infinispan.stream; import org.infinispan.CacheCollection; import org.infinispan.CacheStream; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; /** * Verifies stream tests work when rehash is disabled on a parallel stream with parallel distribution */ @Test(groups = "functional", testName = "streams.DistributedParallelNonRehashStreamTest") @InCacheMode({ CacheMode.DIST_SYNC }) public class DistributedParallelNonRehashStreamTest extends DistributedStreamTest { @Override protected <E> CacheStream<E> createStream(CacheCollection<E> entries) { return entries.parallelStream().disableRehashAware().parallelDistribution(); } }
741
34.333333
101
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/LocalStreamIteratorEvictionTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Eviction test for stream when using a LOCAL cache to verify it works properly * * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.LocalStreamIteratorEvictionTest") public class LocalStreamIteratorEvictionTest extends BaseStreamIteratorEvictionTest { public LocalStreamIteratorEvictionTest() { super(false, CacheMode.LOCAL); } }
504
27.055556
85
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/DistributedNonRehashStreamTest.java
package org.infinispan.stream; import org.infinispan.CacheCollection; import org.infinispan.CacheStream; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.test.fwk.InCacheMode; import org.testng.annotations.Test; /** * Verifies stream tests work when rehash is disabled */ @Test(groups = "functional", testName = "streams.DistributedNonRehashStreamTest") @InCacheMode({ CacheMode.DIST_SYNC }) public class DistributedNonRehashStreamTest extends DistributedStreamTest { @Override protected <E> CacheStream<E> createStream(CacheCollection<E> entries) { return entries.stream().disableRehashAware().parallelDistribution(); } }
669
30.904762
81
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/DistributedStreamIteratorWithLoaderTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Test to verify distributed stream behavior when a loader is present * * @author wburns, afield * @since 8.0 */ @Test(groups = "functional", testName = "stream.DistributedStreamIteratorWithLoaderTest") public class DistributedStreamIteratorWithLoaderTest extends BaseStreamIteratorWithLoaderTest { public DistributedStreamIteratorWithLoaderTest() { super(false, CacheMode.DIST_SYNC); } }
533
27.105263
95
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/InvalidationStreamIteratorWithLoaderTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Test to verify invalidation stream behavior when a loader is present * * @author afield * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.InvalidationStreamIteratorWithLoaderTest") public class InvalidationStreamIteratorWithLoaderTest extends BaseStreamIteratorWithLoaderTest { public InvalidationStreamIteratorWithLoaderTest() { super(false, CacheMode.INVALIDATION_SYNC); } }
555
26.8
96
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/BaseStreamIteratorWithLoaderTest.java
package org.infinispan.stream; import static org.testng.Assert.assertEquals; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.distribution.MagicKey; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * Base test to verify stream behavior when a loader is present * * @author afield * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.BaseStreamIteratorWithLoaderTest") public abstract class BaseStreamIteratorWithLoaderTest extends MultipleCacheManagersTest { protected ConfigurationBuilder builderUsed; protected SerializationContextInitializer sci; protected final boolean tx; protected final CacheMode cacheMode; public BaseStreamIteratorWithLoaderTest(boolean tx, CacheMode cacheMode) { this.tx = tx; this.cacheMode = cacheMode; } @Override protected void createCacheManagers() throws Throwable { sci = TestDataSCI.INSTANCE; builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(cacheMode); builderUsed.clustering().hash().numOwners(1); builderUsed.persistence().passivation(false).addStore(DummyInMemoryStoreConfigurationBuilder.class) .storeName(this.getClass().getSimpleName()); if (tx) { builderUsed.transaction().transactionMode(TransactionMode.TRANSACTIONAL); } createClusteredCaches(cacheMode.isClustered() ? 3 : 1, sci, builderUsed); } private Map<Object, String> insertDefaultValues(boolean includeLoaderEntry) { Cache<Object, String> cache0 = cache(0); Map<Object, String> originalValues = new HashMap<>(); Object loaderKey; if (cacheMode.needsStateTransfer()) { Cache<Object, String> cache1 = cache(1); Cache<Object, String> cache2 = cache(2); originalValues.put(new MagicKey(cache0), "cache0"); originalValues.put(new MagicKey(cache1), "cache1"); originalValues.put(new MagicKey(cache2), "cache2"); loaderKey = new MagicKey(cache2); } else { originalValues.put(1, "value0"); originalValues.put(2, "value1"); originalValues.put(3, "value2"); loaderKey = 4; } cache0.putAll(originalValues); DummyInMemoryStore store = TestingUtil.getFirstStore(cache0); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(sci); try { String loaderValue = "loader-value"; store.write(MarshalledEntryUtil.create(loaderKey, loaderValue, sm)); if (includeLoaderEntry) { originalValues.put(loaderKey, loaderValue); } } finally { sm.stop(); } return originalValues; } @Test public void testCacheLoader() { Map<Object, String> originalValues = insertDefaultValues(true); Cache<Object, String> cache = cache(0); Iterator<Map.Entry<Object, String>> iterator = cache.entrySet().stream().iterator(); // we need this count since the map will replace same key'd value int count = 0; Map<Object, String> results = new HashMap<Object, String>(); while (iterator.hasNext()) { Map.Entry<Object, String> entry = iterator.next(); results.put(entry.getKey(), entry.getValue()); count++; } assertEquals(count, 4); assertEquals(originalValues, results); } @Test public void testCacheLoaderIgnored() { Map<Object, String> originalValues = insertDefaultValues(false); Cache<Object, String> cache = cache(0); Iterator<Map.Entry<Object, String>> iterator = cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_LOAD). entrySet().stream().iterator(); // we need this count since the map will replace same key'd value int count = 0; Map<Object, String> results = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<Object, String> entry = iterator.next(); results.put(entry.getKey(), entry.getValue()); count++; } assertEquals(count, 3); assertEquals(originalValues, results); } }
4,820
35.522727
110
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/BaseStreamIteratorEvictionTest.java
package org.infinispan.stream; import static org.testng.AssertJUnit.assertEquals; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.infinispan.Cache; import org.infinispan.CacheStream; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.container.entries.CacheEntry; import org.testng.annotations.Test; /** * Base class to test if evicted entries are not returned via stream * * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.BaseStreamIteratorEvictionTest") public abstract class BaseStreamIteratorEvictionTest extends BaseSetupStreamIteratorTest { public BaseStreamIteratorEvictionTest(boolean tx, CacheMode mode) { super(tx, mode); } public void testExpiredEntryNotReturned() throws InterruptedException { Cache<Object, String> cache = cache(0, CACHE_NAME); // First put some values in there Map<Object, String> valuesInserted = new LinkedHashMap<Object, String>(); for (int i = 0; i < 5; ++i) { Object key = i; String value = key + " stay in cache"; cache.put(key, value); valuesInserted.put(key, value); } int expectedTime = 2; // Now we insert a value that will expire in 2 seconds cache.put("expired", "this shouldn't be returned", expectedTime, TimeUnit.SECONDS); // We have to wait the time limit to make sure it is evicted before proceeding Thread.sleep(TimeUnit.SECONDS.toMillis(expectedTime) + 50); Map<Object, String> results; try (CacheStream<CacheEntry<Object, String>> stream = cache.getAdvancedCache().cacheEntrySet().stream()) { results = mapFromStream(stream); } assertEquals(valuesInserted, results); } }
1,794
32.867925
112
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/DistributedStreamRehashTest.java
package org.infinispan.stream; import static org.infinispan.context.Flag.STATE_TRANSFER_PROGRESS; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.commons.util.EnumUtil; import org.infinispan.commons.util.IntSets; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.distribution.MagicKey; import org.infinispan.reactive.publisher.impl.LocalPublisherManager; import org.infinispan.reactive.publisher.impl.SegmentAwarePublisherSupplier; import org.infinispan.test.Mocks; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestDataSCI; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.test.fwk.InCacheMode; import org.infinispan.util.ControlledConsistentHashFactory; import org.mockito.stubbing.Answer; import org.testng.annotations.Test; /** * Some tests to verify that * @author wburns * @since 10.0 */ @Test(groups = "functional", testName = "streams.DistributedStreamRehashTest") @InCacheMode({ CacheMode.DIST_SYNC }) public class DistributedStreamRehashTest extends MultipleCacheManagersTest { protected final String CACHE_NAME = "rehashStreamCache"; private ControlledConsistentHashFactory consistentHashFactory; @Override protected void createCacheManagers() throws Throwable { consistentHashFactory = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}); ConfigurationBuilder builderUsed = new ConfigurationBuilder(); builderUsed.clustering().cacheMode(cacheMode); if (cacheMode == CacheMode.DIST_SYNC) { builderUsed.clustering().clustering().hash().numOwners(2).numSegments(4).consistentHashFactory(consistentHashFactory); } createClusteredCaches(4, CACHE_NAME, TestDataSCI.INSTANCE, builderUsed); } public void testNodeFailureDuringProcessingForCollect() throws InterruptedException, TimeoutException, ExecutionException { // Insert a key into each cache - so we always have values to find on each node for (Cache<MagicKey, Object> cache : this.<MagicKey, Object>caches(CACHE_NAME)) { MagicKey key = new MagicKey(cache); cache.put(key, key.toString()); } Cache<MagicKey, Object> originator = cache(0, CACHE_NAME); // We stop the #1 node which equates to entries store in segment 2 Cache<MagicKey, Object> nodeToBlockBeforeProcessing = cache(1, CACHE_NAME); Cache<MagicKey, Object> nodeToStop = cache(3, CACHE_NAME); CheckPoint checkPoint = new CheckPoint(); // Always let it process the publisher checkPoint.triggerForever(Mocks.BEFORE_RELEASE); // Block on the publisher LocalPublisherManager<?, ?> lpm = TestingUtil.extractComponent(nodeToBlockBeforeProcessing, LocalPublisherManager.class); LocalPublisherManager<?, ?> spy = spy(lpm); Answer<SegmentAwarePublisherSupplier<?>> blockingLpmAnswer = invocation -> { SegmentAwarePublisherSupplier<?> result = (SegmentAwarePublisherSupplier<?>) invocation.callRealMethod(); return Mocks.blockingPublisherAware(result, checkPoint); }; doAnswer(blockingLpmAnswer).when(spy) .entryPublisher(eq(IntSets.immutableSet(1)), any(), any(), eq(EnumUtil.bitSetOf(STATE_TRANSFER_PROGRESS)), any(), any()); TestingUtil.replaceComponent(nodeToBlockBeforeProcessing, LocalPublisherManager.class, spy, true); Future<List<Map.Entry<MagicKey, Object>>> future = fork(() -> originator.entrySet().stream().collect(() -> Collectors.toList())); // Note that segment 2 doesn't map to the node1 anymore consistentHashFactory.setOwnerIndexes(new int[][]{{0, 1}, {0, 2}, {2, 1}, {1, 0}}); // Have to remove the cache manager so the cluster formation can work properly cacheManagers.remove(cacheManagers.size() - 1); nodeToStop.getCacheManager().stop(); TestingUtil.blockUntilViewsReceived((int) TimeUnit.SECONDS.toMillis(10), false, caches(CACHE_NAME)); Future<?> rebalanceFuture = fork(() -> TestingUtil.waitForNoRebalance(caches(CACHE_NAME))); // Now let the stream be processed checkPoint.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS); checkPoint.triggerForever(Mocks.AFTER_RELEASE); rebalanceFuture.get(10, TimeUnit.SECONDS); List<Map.Entry<MagicKey, Object>> list = future.get(10, TimeUnit.SECONDS); assertEquals(cacheManagers.size() + 1, list.size()); } }
5,056
43.752212
127
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/DistributedIteratorEvictionTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Eviction test for stream when using a distributed cache to verify it works properly * * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.DistributedIteratorEvictionTest") public class DistributedIteratorEvictionTest extends BaseStreamIteratorEvictionTest { public DistributedIteratorEvictionTest() { super(false, CacheMode.DIST_SYNC); } }
514
27.611111
86
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/LocalStreamIteratorWithLoaderTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.CacheMode; import org.testng.annotations.Test; /** * Test to verify local stream behavior when a loader is present * * @author afield * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "iteration.LocalStreamIteratorWithLoaderTest") public class LocalStreamIteratorWithLoaderTest extends BaseStreamIteratorWithLoaderTest { public LocalStreamIteratorWithLoaderTest() { super(false, CacheMode.LOCAL); } }
518
24.95
89
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/LocalStreamOffHeapTest.java
package org.infinispan.stream; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.testng.annotations.Test; /** * Verifies stream tests work on a local stream with off heap enabled */ @Test(groups = "functional", testName = "streams.LocalStreamOffHeapTest") public class LocalStreamOffHeapTest extends LocalStreamTest { @Override protected void enhanceConfiguration(ConfigurationBuilder builder) { builder.expiration().disableReaper(); builder.memory().storageType(StorageType.OFF_HEAP); } // Test is disabled, it assumes specific keys tie to specific segments which aren't true with // off heap @Test(enabled = false) @Override public void testKeySegmentFilter() { super.testKeySegmentFilter(); } }
828
30.884615
96
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/NoOpFilterConverterWithDependencies.java
package org.infinispan.stream; import java.io.Serializable; import org.infinispan.Cache; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.filter.AbstractKeyValueFilterConverter; import org.infinispan.metadata.Metadata; /** * @author anistor@redhat.com * @author wburns * @since 8.0 */ @Scope(Scopes.NONE) public class NoOpFilterConverterWithDependencies<K, V> extends AbstractKeyValueFilterConverter<K, V, V> implements Serializable { private transient Cache cache; @Inject protected void injectDependencies(Cache cache) { this.cache = cache; } @Override public V filterAndConvert(K key, V value, Metadata metadata) { if (cache == null) { throw new IllegalStateException("Dependencies were not injected"); } return value; } }
916
24.472222
103
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/LocalStreamIteratorWithPassivationTest.java
package org.infinispan.stream; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNull; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.eviction.impl.PassivationManager; import org.infinispan.filter.CacheFilters; import org.infinispan.marshall.TestObjectStreamMarshaller; import org.infinispan.marshall.persistence.impl.MarshalledEntryUtil; import org.infinispan.persistence.dummy.DummyInMemoryStore; import org.infinispan.persistence.manager.PersistenceManager; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CheckPoint; import org.infinispan.util.concurrent.CompletionStages; import org.mockito.AdditionalAnswers; import org.mockito.stubbing.Answer; import org.testng.annotations.Test; /** * Test to verify distributed entry behavior when a loader with passivation is present in local mode * * @author wburns * @since 8.0 */ @Test(groups = "functional", testName = "stream.LocalStreamIteratorWithPassivationTest") public class LocalStreamIteratorWithPassivationTest extends DistributedStreamIteratorWithPassivationTest { protected ConfigurationBuilder builderUsed; public LocalStreamIteratorWithPassivationTest() { super(false, CacheMode.LOCAL); } @Test(enabled = false, description = "This requires supporting concurrent activation in cache loader interceptor") public void testConcurrentActivation() throws InterruptedException, ExecutionException, TimeoutException { final Cache<String, String> cache = cache(0, CACHE_NAME); Map<String, String> originalValues = new HashMap<>(); originalValues.put(cache.toString() + 1, "cache0"); originalValues.put(cache.toString() + 2, "cache1"); originalValues.put(cache.toString() + 3, "cache2"); final String loaderKey = cache.toString() + " in loader"; final String loaderValue = "loader0"; cache.putAll(originalValues); // Put this in after the cache has been updated originalValues.put(loaderKey, loaderValue); PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class); DummyInMemoryStore store = persistenceManager.getStores(DummyInMemoryStore.class).iterator().next(); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(); PersistenceManager pm = null; try { store.write(MarshalledEntryUtil.create(loaderKey, loaderValue, sm)); final CheckPoint checkPoint = new CheckPoint(); pm = waitUntilAboutToProcessStoreTask(cache, checkPoint); Future<Void> future = fork(() -> { // Wait until loader is invoked checkPoint.awaitStrict("pre_process_on_all_stores_invoked", 10, TimeUnit.SECONDS); // Now force the entry to be moved to the in memory assertEquals(loaderValue, cache.get(loaderKey)); checkPoint.triggerForever("pre_process_on_all_stores_released"); return null; }); Iterator<Map.Entry<String, String>> iterator = cache.entrySet().stream().iterator(); // we need this count since the map will replace same key'd value int count = 0; Map<String, String> results = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); results.put(entry.getKey(), entry.getValue()); count++; } assertEquals(4, count); assertEquals(originalValues, results); future.get(10, TimeUnit.SECONDS); } finally { if (pm != null) { TestingUtil.replaceComponent(cache, PersistenceManager.class, pm, true, true); } sm.stop(); } } @Test(enabled = false, description = "This requires supporting concurrent activation in cache loader interceptor") public void testConcurrentActivationWithFilter() throws InterruptedException, ExecutionException, TimeoutException { final Cache<String, String> cache = cache(0, CACHE_NAME); Map<String, String> originalValues = new HashMap<>(); originalValues.put(cache.toString() + 1, "cache0"); originalValues.put(cache.toString() + 2, "cache1"); originalValues.put(cache.toString() + 3, "cache2"); final String loaderKey = cache.toString() + " in loader"; final String loaderValue = "loader0"; final String filteredLoaderKey = cache.toString() + " in loader1"; final String filteredLoaderValue = "loader1"; cache.putAll(originalValues); // Put this in after the cache has been updated originalValues.put(loaderKey, loaderValue); PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class); DummyInMemoryStore store = persistenceManager.getStores(DummyInMemoryStore.class).iterator().next(); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(); PersistenceManager pm = null; try { store.write(MarshalledEntryUtil.create(loaderKey, loaderValue, sm)); store.write(MarshalledEntryUtil.create(filteredLoaderKey, filteredLoaderValue, sm)); final CheckPoint checkPoint = new CheckPoint(); pm = waitUntilAboutToProcessStoreTask(cache, checkPoint); Future<Void> future = fork(() -> { // Wait until loader is invoked checkPoint.awaitStrict("pre_process_on_all_stores_invoked", 10, TimeUnit.SECONDS); // Now force the entry to be moved to the in memory assertEquals(loaderValue, cache.get(loaderKey)); checkPoint.triggerForever("pre_process_on_all_stores_released"); return null; }); Iterator<CacheEntry<String, String>> iterator = cache.getAdvancedCache().cacheEntrySet().stream() .filter(CacheFilters.predicate((k, v, m) -> originalValues.containsKey(k))) .iterator(); // we need this count since the map will replace same key'd value int count = 0; Map<String, String> results = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); results.put(entry.getKey(), entry.getValue()); count++; } // We shouldn't have found the value in the loader assertEquals(4, count); assertEquals(originalValues, results); future.get(10, TimeUnit.SECONDS); } finally { if (pm != null) { TestingUtil.replaceComponent(cache, PersistenceManager.class, pm, true, true); } sm.stop(); } } @Test(enabled = false, description = "This requires supporting concurrent activation in cache loader interceptor") public void testConcurrentActivationWithConverter() throws InterruptedException, ExecutionException, TimeoutException { final Cache<String, String> cache = cache(0, CACHE_NAME); Map<String, String> originalValues = new HashMap<>(); originalValues.put(cache.toString() + 1, "cache0"); originalValues.put(cache.toString() + 2, "cache1"); originalValues.put(cache.toString() + 3, "cache2"); final String loaderKey = cache.toString() + " in loader"; final String loaderValue = "loader0"; cache.putAll(originalValues); // Put this in after the cache has been updated originalValues.put(loaderKey, loaderValue); PersistenceManager persistenceManager = TestingUtil.extractComponent(cache, PersistenceManager.class); DummyInMemoryStore store = persistenceManager.getStores(DummyInMemoryStore.class).iterator().next(); TestObjectStreamMarshaller sm = new TestObjectStreamMarshaller(); PersistenceManager pm = null; try { store.write(MarshalledEntryUtil.create(loaderKey, loaderValue, sm)); final CheckPoint checkPoint = new CheckPoint(); pm = waitUntilAboutToProcessStoreTask(cache, checkPoint); Future<Void> future = fork(() -> { // Wait until loader is invoked checkPoint.awaitStrict("pre_process_on_all_stores_invoked", 10, TimeUnit.SECONDS); // Now force the entry to be moved to the in memory assertEquals(loaderValue, cache.get(loaderKey)); checkPoint.triggerForever("pre_process_on_all_stores_released"); return null; }); Iterator<CacheEntry<String, String>> iterator = cache.getAdvancedCache().cacheEntrySet().stream().map( CacheFilters.function(new StringTruncator(1, 3))).iterator(); // we need this count since the map will replace same key'd value int count = 0; Map<String, String> results = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); results.put(entry.getKey(), entry.getValue()); count++; } // We shouldn't have found the value in the loader assertEquals(4, count); for (Map.Entry<String, String> entry : originalValues.entrySet()) { assertEquals(entry.getValue().substring(1, 4), results.get(entry.getKey())); } future.get(10, TimeUnit.SECONDS); } finally { if (pm != null) { TestingUtil.replaceComponent(cache, PersistenceManager.class, pm, true, true); } sm.stop(); } } protected PersistenceManager waitUntilAboutToProcessStoreTask(final Cache<?, ?> cache, final CheckPoint checkPoint) { PersistenceManager pm = TestingUtil.extractComponent(cache, PersistenceManager.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(pm); PersistenceManager mockManager = mock(PersistenceManager.class, withSettings().defaultAnswer(forwardedAnswer)); doAnswer(invocation -> { // Wait for main thread to sync up checkPoint.trigger("pre_process_on_all_stores_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("pre_process_on_all_stores_released", 10, TimeUnit.SECONDS); return forwardedAnswer.answer(invocation); }).when(mockManager).publishEntries(any(), any(), anyBoolean(), anyBoolean(), any()); TestingUtil.replaceComponent(cache, PersistenceManager.class, mockManager, true); return pm; } /** * This test is to verify that if a concurrent passivation occurs while switching between data container and loader(s) * that we don't return the same key/value twice */ public void testConcurrentPassivation() throws InterruptedException, ExecutionException, TimeoutException { final Cache<String, String> cache = cache(0, CACHE_NAME); Map<String, String> originalValues = new HashMap<>(); originalValues.put(cache.toString() + 1, "cache0"); originalValues.put(cache.toString() + 2, "cache1"); originalValues.put(cache.toString() + 3, "cache2"); final String loaderKey = cache.toString() + " loader-value"; final String loaderValue = "loader0"; // Make sure this is in the cache to begin with originalValues.put(loaderKey, loaderValue); cache.putAll(originalValues); PersistenceManager pm = null; try { final CheckPoint checkPoint = new CheckPoint(); pm = waitUntilAboutToProcessStoreTask(cache, checkPoint); Future<Void> future = fork(() -> { // Wait until loader is invoked checkPoint.awaitStrict("pre_process_on_all_stores_invoked", 10, TimeUnit.SECONDS); // Now force the entry to be moved to loader CompletionStages.join(TestingUtil.extractComponent(cache, PassivationManager.class).passivateAsync(new ImmortalCacheEntry(loaderKey, loaderValue))); checkPoint.triggerForever("pre_process_on_all_stores_released"); return null; }); Iterator<Map.Entry<String, String>> iterator = cache.entrySet().stream().iterator(); // we need this count since the map will replace same key'd value Map<String, String> results = new HashMap<>(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); String prev = results.put(entry.getKey(), entry.getValue()); assertNull("Entry " + entry + " replaced an existing value of " + prev, prev); } assertEquals(originalValues, results); future.get(10, TimeUnit.SECONDS); } finally { if (pm != null) { TestingUtil.replaceComponent(cache, PersistenceManager.class, pm, true, true); } } } }
13,416
41.191824
160
java
null
infinispan-main/core/src/test/java/org/infinispan/stream/LocalParallelStreamTest.java
package org.infinispan.stream; import org.infinispan.CacheCollection; import org.infinispan.CacheStream; import org.testng.annotations.Test; /** * Verifies stream tests work on a local parallel stream */ @Test(groups = "functional", testName = "streams.LocalParallelStreamTest") public class LocalParallelStreamTest extends LocalStreamTest { @Override protected <E> CacheStream<E> createStream(CacheCollection<E> entries) { return entries.parallelStream(); } }
480
27.294118
74
java