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/tx/DummyTxTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Tests DummyTransactionManager commit issues when prepare fails.
*
* @author anistor@redhat.com
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.DummyTxTest")
public class DummyTxTest extends SingleCacheManagerTest {
protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
protected EmbeddedCacheManager createCacheManager() throws Exception {
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(false); // also try this test with 'true' so you can tell the difference between DummyTransactionManager and JBoss TM
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.transaction().transactionMode(TransactionMode.TRANSACTIONAL) //default to write-skew
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
cm.defineConfiguration("test", cb.build());
cache = cm.getCache("test");
return cm;
}
public void testConcurrentRemove() throws Exception {
runConcurrentRemove(false);
}
public void testConcurrentConditionalRemove() throws Exception {
runConcurrentRemove(true);
}
private void runConcurrentRemove(final boolean useConditionalRemove) throws Exception {
cache.put("k1", "v1");
// multiple threads will try to remove "k1" and commit.
// we expect only one to succeed. others will either rollback due to write skew
// or do nothing (because the key is already gone)
final int numThreads = 5;
final AtomicInteger removed = new AtomicInteger();
final AtomicInteger rolledBack = new AtomicInteger();
final AtomicInteger didNothing = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread("DummyTxTest.Remover-" + i) {
public void run() {
try {
latch.await();
tm().begin();
try {
boolean success;
if (useConditionalRemove) {
success = cache.remove("k1", "v1");
} else {
success = cache.remove("k1") != null;
}
log.trace("Remove call success: " + success);
TestingUtil.sleepRandom(200);
tm().commit();
if (success) {
removed.incrementAndGet();
}
else {
didNothing.incrementAndGet();
}
} catch (Throwable e) {
if (e instanceof RollbackException) {
rolledBack.incrementAndGet();
} else if (tm().getTransaction() != null) {
// the TX is most likely rolled back already, but we attempt a rollback just in case it isn't
try {
tm().rollback();
rolledBack.incrementAndGet();
} catch (SystemException e1) {
log.error("Failed to rollback", e1);
}
}
throw e;
}
} catch (Throwable e) {
log.error(e);
}
}
};
threads[i].start();
}
latch.countDown();
for (Thread t : threads) {
t.join();
}
log.trace("removed= " + removed.get());
log.trace("rolledBack= " + rolledBack.get());
log.trace("didNothing= " + didNothing.get());
assertFalse(cache.containsKey("k1"));
assertEquals(1, removed.get());
assertEquals(numThreads - 1, rolledBack.get() + didNothing.get());
}
}
| 4,709
| 35.511628
| 193
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/DefaultEnlistmentModeTest.java
|
package org.infinispan.tx;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.AbstractCacheTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@Test (groups = "functional", testName = "tx.DefaultEnlistmentModeTest")
public class DefaultEnlistmentModeTest extends AbstractCacheTest {
private EmbeddedCacheManager ecm;
@AfterMethod
protected void destroyCacheManager() {
TestingUtil.killCacheManagers(ecm);
}
public void testDefaultEnlistment() {
ConfigurationBuilder builder = getLocalBuilder();
builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
ecm = TestCacheManagerFactory.createCacheManager(builder);
Cache<Object,Object> cache = ecm.getCache();
assertFalse(cache.getCacheConfiguration().transaction().useSynchronization());
assertFalse(cache.getCacheConfiguration().transaction().recovery().enabled());
cache.put("k", "v");
assertEquals("v", cache.get("k"));
}
public void testXAEnlistment() {
ConfigurationBuilder builder = getLocalBuilder();
builder.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.useSynchronization(false);
ecm = TestCacheManagerFactory.createCacheManager(builder);
Cache<Object,Object> cache = ecm.getCache();
assertFalse(cache.getCacheConfiguration().transaction().useSynchronization());
assertFalse(cache.getCacheConfiguration().transaction().recovery().enabled());
cache.put("k", "v");
assertEquals("v", cache.get("k"));
}
public void testXAEnlistmentNoRecovery() {
ConfigurationBuilder builder = getLocalBuilder();
builder.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.useSynchronization(false)
.recovery().disable();
ecm = TestCacheManagerFactory.createCacheManager(builder);
Cache<Object,Object> cache = ecm.getCache();
assertFalse(cache.getCacheConfiguration().transaction().useSynchronization());
assertFalse(cache.getCacheConfiguration().transaction().recovery().enabled());
}
private ConfigurationBuilder getLocalBuilder() {
ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
builder.clustering().cacheMode(CacheMode.LOCAL);
return builder;
}
}
| 2,790
| 38.871429
| 96
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/exception/CustomInterceptorExceptionTest.java
|
package org.infinispan.tx.exception;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertEquals;
import jakarta.transaction.Status;
import jakarta.transaction.TransactionManager;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.CustomInterceptorConfigTest;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.context.InvocationContext;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.exception.CustomInterceptorExceptionTest")
public class CustomInterceptorExceptionTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
EmbeddedCacheManager eCm =
TestCacheManagerFactory.createCacheManager(getDefaultClusteredCacheConfig(CacheMode.LOCAL, true));
// Custom interceptor must be after TxInterceptor
extractInterceptorChain(eCm.getCache()).addInterceptor(new CustomInterceptorConfigTest.DummyInterceptor() {
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
throw new IllegalStateException("Induce failure!");
}
}, 4);
return eCm;
}
public void testFailure() throws Exception {
TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager();
transactionManager.begin();
try {
cache.put("k", "v");
assert false;
} catch (Exception e) {
log.debug("Ignoring expected exception during put", e);
assertEquals(transactionManager.getTransaction().getStatus(), Status.STATUS_MARKED_ROLLBACK);
}
}
}
| 1,986
| 37.960784
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/exception/TxAndTimeoutExceptionTest.java
|
package org.infinispan.tx.exception;
import static org.infinispan.commons.test.Exceptions.expectException;
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.util.Collections;
import jakarta.transaction.Status;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
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.impl.TransactionTable;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.Test;
/**
* Tester for https://jira.jboss.org/browse/ISPN-629.
*
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(testName = "tx.exception.TxAndTimeoutExceptionTest", groups = "functional")
public class TxAndTimeoutExceptionTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder config = getDefaultStandaloneCacheConfig(true);
config
.transaction().lockingMode(LockingMode.PESSIMISTIC)
.locking().useLockStriping(false).lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(config);
cache = cm.getCache();
return cm;
}
public void testPutTimeoutsInTx() throws Exception {
assertExpectedBehavior(() -> cache.put("k1", "v2222"));
}
public void testRemoveTimeoutsInTx() throws Exception {
assertExpectedBehavior(() -> cache.remove("k1"));
}
public void testReplaceTimeoutsInTx() throws Exception {
assertExpectedBehavior(() -> cache.replace("k1", "newValue"));
}
public void testPutAllTimeoutsInTx() throws Exception {
assertExpectedBehavior(() -> cache.putAll(Collections.singletonMap("k1", "v22222")));
}
private void assertExpectedBehavior(CacheOperation op) throws Exception {
LockManager lm = TestingUtil.extractLockManager(cache);
TransactionTable txTable = TestingUtil.getTransactionTable(cache);
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
tm.begin();
cache.put("k1", "v1");
Transaction k1LockOwner = tm.suspend();
assertTrue(lm.isLocked("k1"));
assertEquals(1, txTable.getLocalTxCount());
tm.begin();
cache.put("k2", "v2");
assertTrue(lm.isLocked("k2"));
assertEquals(2, txTable.getLocalTxCount());
assertNotNull(tm.getTransaction());
expectException(TimeoutException.class, op::execute);
//make sure that locks acquired by that tx were released even before the transaction is rolled back, the tx object
//was marked for rollback
Transaction transaction = tm.getTransaction();
assertNotNull(transaction);
assertEquals(Status.STATUS_MARKED_ROLLBACK, transaction.getStatus());
assertTrue(lm.isLocked("k2"));
assertTrue(lm.isLocked("k1"));
expectException(CacheException.class, IllegalStateException.class, () -> cache.put("k3", "v3"));
assertEquals(2, txTable.getLocalTxCount());
//now the TM is expected to rollback the tx
tm.rollback();
assertEquals(1, txTable.getLocalTxCount());
tm.resume(k1LockOwner);
tm.commit();
//now test that the other tx works as expected
assertEquals(0, txTable.getLocalTxCount());
assertEquals("v1", cache.get("k1"));
assertFalse(lm.isLocked("k1"));
assertFalse(lm.isLocked("k2"));
assertEquals(0, txTable.getLocalTxCount());
}
public interface CacheOperation {
void execute();
}
}
| 4,078
| 36.081818
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/exception/ExceptionInCommandTest.java
|
package org.infinispan.tx.exception;
import jakarta.transaction.Status;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.exception.ExceptionInCommandTest")
public class ExceptionInCommandTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
createCluster(getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true), 2);
waitForClusterToForm();
}
public void testPutThrowsLocalException() throws Exception {
tm(0).begin();
try {
cache(0).computeIfAbsent("k", (k) -> {
throw new RuntimeException();
});
assert false;
} catch (RuntimeException e) {
assert tx(0).getStatus() == Status.STATUS_MARKED_ROLLBACK;
}
}
}
| 961
| 27.294118
| 82
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/exception/ReplicationTxExceptionTest.java
|
package org.infinispan.tx.exception;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.RollbackException;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.util.ControlledRpcManager;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.exception.ReplicationTxExceptionTest")
public class ReplicationTxExceptionTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
registerCacheManager(TestCacheManagerFactory.createClusteredCacheManager(config));
registerCacheManager(TestCacheManagerFactory.createClusteredCacheManager(config));
TestingUtil.blockUntilViewsReceived(10000, cache(0), cache(1));
}
public void testReplicationFailure() throws Exception {
Cache<?, ?> cache = cache(0);
ControlledRpcManager controlledRpcManager = ControlledRpcManager.replaceRpcManager(cache);
try {
Future<Void> future = fork(() -> {
controlledRpcManager.expectCommand(VersionedPrepareCommand.class).fail();
controlledRpcManager.expectCommand(RollbackCommand.class).send().receiveAll();
});
TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager();
tm.begin();
cache(0).put("k0", "v");
Exceptions.expectException(RollbackException.class, tm::commit);
future.get(30, TimeUnit.SECONDS);
} finally {
controlledRpcManager.revertRpcManager();
}
}
}
| 2,162
| 39.811321
| 96
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/exception/TxAndRemoteTimeoutExceptionTest.java
|
package org.infinispan.tx.exception;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.fail;
import java.util.Collections;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Tester for https://jira.jboss.org/browse/ISPN-629.
*
* @author Mircea.Markus@jboss.com
* @since 4.2
*/
@Test(groups = "functional", testName = "tx.exception.TxAndRemoteTimeoutExceptionTest")
public class TxAndRemoteTimeoutExceptionTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(TxAndRemoteTimeoutExceptionTest.class);
private LockManager lm1;
private LockManager lm0;
private TransactionTable txTable0;
private TransactionTable txTable1;
private TransactionManager tm;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder defaultConfig = getDefaultConfig();
defaultConfig.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis())
.useLockStriping(false);
addClusterEnabledCacheManager(defaultConfig);
addClusterEnabledCacheManager(defaultConfig);
lm0 = TestingUtil.extractLockManager(cache(0));
lm1 = TestingUtil.extractLockManager(cache(1));
txTable0 = TestingUtil.getTransactionTable(cache(0));
txTable1 = TestingUtil.getTransactionTable(cache(1));
tm = cache(0).getAdvancedCache().getTransactionManager();
TestingUtil.blockUntilViewReceived(cache(0), 2);
}
protected ConfigurationBuilder getDefaultConfig() {
return getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
}
public void testPutTimeoutsInTx() throws Exception {
runAssertion(() -> cache(0).put("k1", "v2222"));
}
public void testRemoveTimeoutsInTx() throws Exception {
runAssertion(() -> cache(0).remove("k1"));
}
public void testReplaceTimeoutsInTx() throws Exception {
cache(1).put("k1", "value");
runAssertion(() -> cache(0).replace("k1", "newValue"));
}
public void testPutAllTimeoutsInTx() throws Exception {
runAssertion(() -> cache(0).putAll(Collections.singletonMap("k1", "v22222")));
}
private void runAssertion(CacheOperation operation) throws NotSupportedException, SystemException, HeuristicMixedException, HeuristicRollbackException, InvalidTransactionException, RollbackException {
// Start tx1
tm.begin();
cache(1).put("k1", "v1");
EmbeddedTransaction k1LockOwner = (EmbeddedTransaction) tm.suspend();
assertFalse(lm1.isLocked("k1"));
assertEquals(1, txTable1.getLocalTxCount());
// Start tx2
tm.begin();
cache(0).put("k2", "v2");
assertFalse(lm0.isLocked("k2"));
assertFalse(lm1.isLocked("k2"));
operation.execute();
assertEquals(1, txTable1.getLocalTxCount());
assertEquals(1, txTable0.getLocalTxCount());
final Transaction tx2 = tm.suspend();
// Acquire k1 for tx1
tm.resume(k1LockOwner);
k1LockOwner.runPrepare();
tm.suspend();
// Try (and fail) to commit tx2
tm.resume(tx2);
try {
tm.commit();
fail("Rollback expected.");
} catch (RollbackException re) {
//expected
}
assertEquals(0, txTable0.getLocalTxCount());
assertEquals(1, txTable1.getLocalTxCount());
// Commit tx1
log.trace("Right before second commit");
tm.resume(k1LockOwner);
k1LockOwner.runCommit(false);
// Final checks
assertEquals("v1", cache(0).get("k1"));
assertEquals("v1", cache(1).get("k1"));
assertEquals(0, txTable1.getLocalTxCount());
assertEquals(0, txTable1.getLocalTxCount());
assertNotLocked("k1");
assertNotLocked("k2");
}
public interface CacheOperation {
void execute();
}
}
| 4,874
| 33.574468
| 203
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/synchronisation/TransactionsSpanningCachesSyncTest.java
|
package org.infinispan.tx.synchronisation;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.xa.XaTransactionTable;
import org.infinispan.tx.TransactionsSpanningCachesTest;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.synchronisation.TransactionsSpanningCachesSyncTest")
public class TransactionsSpanningCachesSyncTest extends TransactionsSpanningCachesTest {
public Object[] factory() {
return new Object[] {
new TransactionsSpanningCachesSyncTest().withStorage(StorageType.OBJECT, StorageType.OBJECT),
new TransactionsSpanningCachesSyncTest().withStorage(StorageType.OFF_HEAP, StorageType.OFF_HEAP),
new TransactionsSpanningCachesSyncTest().withStorage(StorageType.OBJECT, StorageType.OFF_HEAP)
};
}
@Override
protected void amendConfig(ConfigurationBuilder defaultCacheConfig) {
defaultCacheConfig.transaction().useSynchronization(true);
}
public void testSyncIsUsed() {
assert cacheManagers.get(0).getCache().getCacheConfiguration().transaction().useSynchronization();
TransactionTable transactionTable = TestingUtil.extractComponent(cacheManagers.get(0).getCache(), TransactionTable.class);
assert !(transactionTable instanceof XaTransactionTable);
}
}
| 1,547
| 42
| 128
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/synchronisation/NoXaConfigTest.java
|
package org.infinispan.tx.synchronisation;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.synchronisation.NoXaConfigTest")
public class NoXaConfigTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.fromXml("configs/no-xa-config.xml");
}
public void testConfig() {
assertTrue(cacheManager.getCache("syncEnabled").getCacheConfiguration().transaction().useSynchronization());
assertFalse(cacheManager.getCache("notSpecified").getCacheConfiguration().transaction().useSynchronization());
cacheManager.getCache("syncAndRecovery");
}
public void testConfigOverride() {
ConfigurationBuilder configuration = getDefaultStandaloneCacheConfig(true);
configuration.transaction().useSynchronization(true);
cacheManager.defineConfiguration("newCache", configuration.build());
assertTrue(cacheManager.getCache("newCache").getCacheConfiguration().transaction().useSynchronization());
}
}
| 1,459
| 37.421053
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/synchronisation/LocalModeWithSyncTxTest.java
|
package org.infinispan.tx.synchronisation;
import static org.testng.Assert.assertEquals;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.SystemException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.tx.LocalModeTxTest;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.synchronisation.LocalModeWithSyncTxTest")
public class LocalModeWithSyncTxTest extends LocalModeTxTest {
@Factory
public Object[] factory() {
return new Object[] {
new LocalModeWithSyncTxTest().withStorage(StorageType.BINARY),
new LocalModeWithSyncTxTest().withStorage(StorageType.OBJECT),
new LocalModeWithSyncTxTest().withStorage(StorageType.OFF_HEAP)
};
}
@Override
protected EmbeddedCacheManager createCacheManager() {
ConfigurationBuilder config = getDefaultStandaloneCacheConfig(true);
config.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()).useSynchronization(true);
return TestCacheManagerFactory.createCacheManager(config);
}
public void testSyncRegisteredWithCommit() throws Exception {
EmbeddedTransaction dt = startTx();
tm().commit();
assertEquals(0, dt.getEnlistedResources().size());
assertEquals(0, dt.getEnlistedSynchronization().size());
assertEquals("v", cache.get("k"));
}
public void testSyncRegisteredWithRollback() throws Exception {
EmbeddedTransaction dt = startTx();
tm().rollback();
assertEquals(null, cache.get("k"));
assertEquals(0, dt.getEnlistedResources().size());
assertEquals(0, dt.getEnlistedSynchronization().size());
}
private EmbeddedTransaction startTx() throws NotSupportedException, SystemException {
tm().begin();
cache.put("k","v");
EmbeddedTransaction dt = (EmbeddedTransaction) tm().getTransaction();
assertEquals(0, dt.getEnlistedResources().size());
assertEquals(1, dt.getEnlistedSynchronization().size());
cache.put("k2","v2");
assertEquals(0, dt.getEnlistedResources().size());
assertEquals(1, dt.getEnlistedSynchronization().size());
return dt;
}
}
| 2,615
| 36.913043
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/synchronisation/APIDistWithSyncTest.java
|
package org.infinispan.tx.synchronisation;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.lock.APIDistTest;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.synchronisation.APIDistWithSyncTest")
public class APIDistWithSyncTest extends APIDistTest {
@Override
protected ConfigurationBuilder createConfig() {
ConfigurationBuilder config = super.createConfig();
config.transaction().useSynchronization(true);
return config;
}
}
| 582
| 28.15
| 81
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/PessimisticReplTxTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.RemoteException;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.TimeoutException;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.locking.PessimisticReplTxTest")
public class PessimisticReplTxTest extends AbstractClusteredTxTest {
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder conf = buildConfiguration();
createCluster(TestDataSCI.INSTANCE, conf, 2);
waitForClusterToForm();
k = new MagicKey(cache(0));
}
protected ConfigurationBuilder buildConfiguration() {
final ConfigurationBuilder conf = getDefaultClusteredCacheConfig(CacheMode.REPL_SYNC, true);
conf.transaction()
.lockingMode(LockingMode.PESSIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
return conf;
}
public void testTxInProgress1() throws Exception {
log.info("test :: start");
try {
test(0, 0);
} finally {
log.info("test :: end");
}
}
public void testTxInProgress2() throws Exception {
test(0, 1);
}
public void testTxInProgress3() throws Exception {
test(1, 1);
}
public void testTxInProgress4() throws Exception {
test(1, 0);
}
public void testLockingInterfaceOnPrimaryOwner() throws Exception {
testLockingWithRollback(0);
}
public void testLockingInterfaceOnBackupOwner() throws Exception {
testLockingWithRollback(1);
}
private void testLockingWithRollback(int executeOn) throws Exception {
tm(executeOn).begin();
advancedCache(executeOn).lock(k);
assertLockingOnRollback();
assertNoTransactions();
assertNull(cache(0).get(k));
assertNull(cache(1).get(k));
tm(executeOn).begin();
advancedCache(executeOn).lock(k);
cache(executeOn).put(k, "v");
assertLockingOnRollback();
assertNoTransactions();
assertNull(cache(0).get(k));
assertNull(cache(1).get(k));
}
// check that two transactions can progress in parallel on the same node
private void test(int firstTxIndex, int secondTxIndex) throws Exception {
tm(firstTxIndex).begin();
cache(firstTxIndex).put(k, "v1");
final Transaction tx1 = tm(firstTxIndex).suspend();
//another tx working on the same keys
tm(secondTxIndex).begin();
try {
cache(secondTxIndex).put(k, "v2");
assert false : "Exception expected";
} catch (TimeoutException e) {
//expected
tm(secondTxIndex).suspend();
} catch (RemoteException e) {
assert e.getCause() instanceof TimeoutException;
//expected
tm(secondTxIndex).suspend();
}
tm(firstTxIndex).resume(tx1);
tm(firstTxIndex).commit();
assert cache(0).get(k).equals("v1");
log.info("Before get...");
assertNotLocked(k);
assert cache(1).get(k).equals("v1");
assertNotLocked(k);
}
public void simpleTest() throws Exception {
tm(0).begin();
cache(0).put(k,"v");
tm(0).commit();
assertEquals(cache(0).get(k), "v");
assertEquals(cache(1).get(k), "v");
}
@Override
protected void assertLocking() {
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
prepare();
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
commit();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
@Override
protected void assertLockingNoChanges() {
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
prepare();
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
commit();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
@Override
protected void assertLockingOnRollback() {
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
rollback();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
}
| 4,976
| 29.347561
| 98
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/SizeDistTxReadCommittedTest.java
|
package org.infinispan.tx.locking;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import jakarta.transaction.Transaction;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* @author Martin Gencur
*/
@Test(groups = "functional", testName = "tx.locking.SizeDistTxReadCommittedTest")
public class SizeDistTxReadCommittedTest extends SizeDistTxRepeatableReadTest {
public SizeDistTxReadCommittedTest() {
isolation = IsolationLevel.READ_COMMITTED;
}
/**
* Manifestation of inconsistent behaviour of READ_COMMITTED mode. More information
* in https://issues.jboss.org/browse/ISPN-4910 and in comments below.
*/
@Override
public void testSizeWithPreviousRead() throws Exception {
preloadCacheAndCheckSize();
tm(0).begin();
//make sure we read k1 in this transaction
assertEquals("v1", cache(0).get(k1));
final Transaction tx1 = tm(0).suspend();
//another tx working on the same keys
tm(0).begin();
//remove the key that was previously read in another tx
cache(0).remove(k1);
cache(0).put(k0, "v2");
tm(0).commit();
tm(0).resume(tx1);
//We read k1 earlier and in READ_COMMITTED mode, the size() method should return the most
//up-to-date size. However, the current transaction does not see the parallel changes
//and still returns incorrect size == 2. The expected size would be 1.
//assertEquals(1, cache(0).size()); //This assertion would fail
assertEquals(2, cache(0).size());
assertEquals("v2", cache(0).get(k0));
//The current transaction does not see changes made to k1 in the parallel transaction.
//As a result, the get() operation returns k1 instead of expected null.
//assertNull(cache(0).get(k1)); //This assertion would fail
assertEquals("v1", cache(0).get(k1));
tm(0).commit();
assertNull(cache(1).get(k1));
}
@Override
public void testSizeWithReadFromRemoteNode() throws Exception {
preloadCacheAndCheckSize();
tm(0).begin();
assertEquals("v1", cache(0).get(k1));
assertEquals(2, cache(0).size());
tm(0).rollback();
}
}
| 2,258
| 31.73913
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/RollbackDuringLockAcquisitionTest.java
|
package org.infinispan.tx.locking;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractLockManager;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.tx.lookup.TransactionManagerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.statetransfer.TransactionSynchronizerInterceptor;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.lookup.JBossStandaloneJTAManagerLookup;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.InvalidTransactionException;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Reproducer for ISPN-13024
* <p>
* Note: remote transactions are synchronized in {@link TransactionSynchronizerInterceptor}, so you cannot have a
* {@link RollbackCommand} executing while waiting for any lock.
*
* @author Pedro Ruivo
* @since 13.0
*/
@Test(groups = "functional", testName = "tx.locking.RollbackDuringLockAcquisitionTest")
public class RollbackDuringLockAcquisitionTest extends SingleCacheManagerTest {
private static String concat(Object... components) {
return Arrays.stream(components)
.map(String::valueOf)
.map(String::toLowerCase)
.collect(Collectors.joining("-"));
}
@DataProvider(name = "sync-tm")
public Object[][] transactionManagerLookup() {
//use sync & tm lookup instance
return new Object[][]{
{true, new EmbeddedTransactionManagerLookup()},
{true, new JBossStandaloneJTAManagerLookup()},
{false, new EmbeddedTransactionManagerLookup()},
{false, new JBossStandaloneJTAManagerLookup()}
};
}
/*
* The "real world" conditions are:
* - Narayana timeout <= lock timeout
*
* Cause/Steps:
* - Narayana aborts a transaction which is waiting for a lock "L"
* - The RollbackCommand is sent.
* - Lock "L" is not locked by the transaction, so unlockAll(context.getLockedKeys(), context.getLockOwner());
* never changes the state from WAITING => RELEASED
* - When the lock "L" is released, the state changes from WAITING => ACQUIRED
* - No RollbackCommand/CommitCommand is followed leaving the lock "L" in ACQUIRED state forever
*/
@Test(dataProvider = "sync-tm")
public void testRollbackWhileWaitingForLockDuringPut(boolean useSynchronization, TransactionManagerLookup lookup)
throws Exception {
final String cacheName = concat("local-put", lookup.getClass().getSimpleName(), useSynchronization);
final String key = concat("reaper-put", lookup.getClass().getSimpleName(), useSynchronization);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.transaction()
.transactionManagerLookup(lookup)
.transactionMode(TransactionMode.TRANSACTIONAL)
.lockingMode(LockingMode.PESSIMISTIC)
.useSynchronization(useSynchronization)
.recovery().disable();
builder.locking()
.lockAcquisitionTimeout(TimeUnit.MINUTES.toMillis(1));
cacheManager.defineConfiguration(cacheName, builder.build());
Cache<String, String> cache = cacheManager.getCache(cacheName);
LockManager lockManager = extractLockManager(cache);
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
// simulates lock acquired by other transaction
lockManager.lock(key, "_tx_", 1, TimeUnit.SECONDS).lock();
assertLocked(cache, key);
tm.begin();
CompletableFuture<?> put = cache.putAsync(key, "value1");
GlobalTransaction gtx = extractComponent(cache, TransactionTable.class).getGlobalTransaction(tm.getTransaction());
// wait until the tx is queued in the InfinispanLock
eventually(() -> lockManager.getLock(key).containsLockOwner(gtx));
//abort the transaction, simulates the TM's reaper aborting a long running transaction
tm.rollback();
// release the lock. the "put" must not acquire the lock
lockManager.unlock(key, "_tx_");
Exceptions.expectCompletionException(InvalidTransactionException.class, put);
assertNotLocked(cache, key);
assertNoTransactions(cache);
}
@Test(dataProvider = "sync-tm")
public void testRollbackWhileWaitingForLockDuringLock(boolean useSynchronization, TransactionManagerLookup lookup)
throws Exception {
final String cacheName = concat("local-lock", lookup.getClass().getSimpleName(), useSynchronization);
final String key = concat("reaper-lock", lookup.getClass().getSimpleName(), useSynchronization);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.transaction()
.transactionManagerLookup(lookup)
.transactionMode(TransactionMode.TRANSACTIONAL)
.lockingMode(LockingMode.PESSIMISTIC)
.useSynchronization(useSynchronization)
.recovery().disable();
builder.locking()
.lockAcquisitionTimeout(TimeUnit.MINUTES.toMillis(1));
cacheManager.defineConfiguration(cacheName, builder.build());
Cache<String, String> cache = cacheManager.getCache(cacheName);
LockManager lockManager = extractLockManager(cache);
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
// simulates lock acquired by other transaction
lockManager.lock(key, "_tx_", 1, TimeUnit.SECONDS).lock();
assertLocked(cache, key);
AtomicReference<Transaction> tx = new AtomicReference<>();
Future<Boolean> lock = fork(() -> {
tm.begin();
tx.set(tm.getTransaction());
try {
return cache.getAdvancedCache().lock(key);
} finally {
// ignore transaction from rollback.
// if the tests works as expected, the transaction is rolled back when it reaches this point and the rollback()
// method will throw an IllegalStateException (which we don't want for the test)
safeRollback(tm);
}
});
TransactionTable txTable = extractComponent(cache, TransactionTable.class);
eventually(() -> !txTable.getLocalGlobalTransaction().isEmpty());
assertEquals(1, txTable.getLocalGlobalTransaction().size());
GlobalTransaction gtx = txTable.getLocalGlobalTransaction().iterator().next();
eventually(() -> lockManager.getLock(key).containsLockOwner(gtx));
//abort the transaction, simulates the TM's reaper aborting a long running transaction
tx.get().rollback();
// release the lock. the "lock" must not acquire the lock
lockManager.unlock(key, "_tx_");
Exceptions.expectException(ExecutionException.class, InvalidTransactionException.class, lock::get);
assertNotLocked(cache, key);
assertNoTransactions(cache);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.createCacheManager();
}
}
| 8,061
| 41.209424
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/AbstractClusteredTxTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertNull;
import java.util.Collections;
import java.util.Map;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.SystemException;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional")
public abstract class AbstractClusteredTxTest extends MultipleCacheManagersTest {
Object k;
public void testPut() throws Exception {
tm(0).begin();
cache(0).put(k, "v");
assertLocking();
}
public void testRemove() throws Exception {
tm(0).begin();
cache(0).remove(k);
assertLocking();
}
public void testReplace() throws Exception {
tm(0).begin();
cache(0).replace(k, "v1");
assertLockingNoChanges();
// if the key doesn't exist, replace is a no-op, so it shouldn't acquire locks
cache(0).put(k, "v1");
tm(0).begin();
cache(0).replace(k, "v2");
assertLocking();
}
public void testPutAll() throws Exception {
Map m = Collections.singletonMap(k, "v");
tm(0).begin();
cache(0).putAll(m);
assertLocking();
}
public void testRollbackOnPrimaryOwner() throws Exception {
testRollback(0);
}
public void testRollbackOnBackupOwner() throws Exception {
testRollback(1);
}
private void testRollback(int executeOn) throws Exception {
tm(executeOn).begin();
cache(executeOn).put(k, "v");
assertLockingOnRollback();
assertNoTransactions();
assertNull(cache(0).get(k));
assertNull(cache(1).get(k));
}
protected void commit() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm(0);
try {
dtm.getTransaction().runCommit(false);
} catch (HeuristicMixedException | HeuristicRollbackException | RollbackException e) {
throw new RuntimeException(e);
}
}
protected void prepare() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm(0);
dtm.getTransaction().runPrepare();
}
protected void rollback() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm(0);
try {
dtm.getTransaction().rollback();
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
protected abstract void assertLocking();
protected abstract void assertLockingNoChanges();
protected abstract void assertLockingOnRollback();
}
| 2,728
| 25.240385
| 92
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/OptimisticDistTxTest.java
|
package org.infinispan.tx.locking;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.locking.OptimisticDistTxTest")
public class OptimisticDistTxTest extends OptimisticReplTxTest {
public OptimisticDistTxTest() {
this.cacheMode = CacheMode.DIST_SYNC;
}
}
| 400
| 24.0625
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/LocalPessimisticTxTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.locking.LocalPessimisticTxTest")
public class LocalPessimisticTxTest extends AbstractLocalTest {
public void testLockingWithRollback() throws Exception {
tm().begin();
cache().getAdvancedCache().lock("k");
assertLockingOnRollback();
assertNull(cache().get("k"));
tm().begin();
cache().getAdvancedCache().lock("k");
cache().put("k", "v");
assertLockingOnRollback();
assertNull(cache().get("k"));
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
final ConfigurationBuilder config = getDefaultStandaloneCacheConfig(true);
config.transaction().lockingMode(LockingMode.PESSIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().disable();
return TestCacheManagerFactory.createCacheManager(config);
}
@Override
protected void assertLockingOnRollback() {
assertTrue(lockManager().isLocked("k"));
rollback();
assertFalse(lockManager().isLocked("k"));
}
@Override
protected void assertLocking() {
assertTrue(lockManager().isLocked("k"));
commit();
assertFalse(lockManager().isLocked("k"));
}
}
| 1,852
| 30.948276
| 80
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/AbstractLocalTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Collections;
import java.util.Map;
import jakarta.transaction.SystemException;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.context.Flag;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional")
public abstract class AbstractLocalTest extends SingleCacheManagerTest {
public void testPut() throws Exception {
tm().begin();
cache.put("k", "v");
assertLocking();
}
public void testRemove() throws Exception {
tm().begin();
cache.remove("k");
assertLocking();
}
public void testReplace() throws Exception {
cache.put("k", "initial");
tm().begin();
cache.replace("k", "v");
assertLocking();
}
public void testPutAll() throws Exception {
Map<String, String> m = Collections.singletonMap("k", "v");
tm().begin();
cache.putAll(m);
assertLocking();
}
public void testRollback() throws Exception {
tm().begin();
cache().put("k", "v");
assertLockingOnRollback();
assertNull(cache().get("k"));
}
protected abstract void assertLockingOnRollback();
protected abstract void assertLocking();
protected void commit() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm();
try {
dtm.firstEnlistedResource().commit(getXid(), true);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
protected void prepare() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm();
try {
dtm.firstEnlistedResource().prepare(getXid());
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
protected void rollback() {
EmbeddedTransactionManager dtm = (EmbeddedTransactionManager) tm();
try {
dtm.getTransaction().rollback();
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
private XidImpl getXid() throws SystemException {
EmbeddedTransaction tx = (EmbeddedTransaction) tm().getTransaction();
return tx.getXid();
}
public void testSizeAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertEquals(0, cache.size());
} finally {
tm().commit();
}
}
public void testEntrySetIsEmptyAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertTrue(cache.entrySet().isEmpty());
} finally {
tm().commit();
}
}
public void testEntrySetSizeAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertEquals(0, cache.entrySet().size());
} finally {
tm().commit();
}
}
public void testKeySetIsEmptyAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertTrue(cache.keySet().isEmpty());
} finally {
tm().commit();
}
}
public void testKeySetSizeAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertEquals(0, cache.keySet().size());
} finally {
tm().commit();
}
}
public void testValuesIsEmptyAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertTrue(cache.values().isEmpty());
} finally {
tm().commit();
}
}
public void testValuesSizeAfterLocalClear() throws Exception {
cache.put(1, "v1");
tm().begin();
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).clear();
assertEquals(0, cache.values().size());
} finally {
tm().commit();
}
}
}
| 4,631
| 25.930233
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/SizeDistTxRepeatableReadTest.java
|
package org.infinispan.tx.locking;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* @author Martin Gencur
*/
@Test(groups = "functional", testName = "tx.locking.SizeDistTxRepeatableReadTest")
public class SizeDistTxRepeatableReadTest extends MultipleCacheManagersTest {
IsolationLevel isolation;
Object k0;
Object k1;
public SizeDistTxRepeatableReadTest() {
this.isolation = IsolationLevel.REPEATABLE_READ;
}
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder conf = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
conf.clustering().hash().numOwners(1)
.locking().isolationLevel(isolation)
.transaction()
.lockingMode(LockingMode.OPTIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup());
createCluster(TestDataSCI.INSTANCE, conf, 2);
waitForClusterToForm();
k0 = getKeyForCache(0);
k1 = getKeyForCache(1);
}
public void testSizeWithPreviousRead() throws Exception {
preloadCacheAndCheckSize();
tm(0).begin();
//make sure we read k1 in this transaction
assertEquals("v1", cache(0).get(k1));
final Transaction tx1 = tm(0).suspend();
//another tx working on the same keys
tm(0).begin();
//remove the key that was previously read in another tx
cache(0).remove(k1);
cache(0).put(k0, "v2");
tm(0).commit();
assertEquals(1, cache(0).size());
assertEquals("v2", cache(0).get(k0));
tm(0).resume(tx1);
//we read k1 earlier so size() should take the key into account even though it was removed in another tx
assertEquals(2, cache(0).size());
//we did not read k0 previosly - getting the changed value
assertEquals("v2", cache(0).get(k0));
//we've read it before - getting original value
assertEquals("v1", cache(0).get(k1));
tm(0).commit();
assertNull(cache(1).get(k1));
}
public void testSizeWithReadFromRemoteNode() throws Exception {
preloadCacheAndCheckSize();
tm(0).begin();
assertEquals("v1", cache(0).get(k1));
assertEquals(2, cache(0).size());
tm(0).rollback();
}
public void testSizeWithoutPreviousRead() throws Exception {
preloadCacheAndCheckSize();
tm(0).begin();
//no reading of k1 here
final Transaction tx1 = tm(0).suspend();
//another tx working on the same keys
tm(0).begin();
//remove the key that was previously read in another tx
cache(0).remove(k1);
cache(0).put(k0, "v2");
tm(0).commit();
assertEquals(1, cache(0).size());
assertEquals("v2", cache(0).get(k0));
tm(0).resume(tx1);
//we did not read k1 earlier so size() should reflect the other transaction's changes
assertEquals(1, cache(0).size());
//we did not read any keys previosly - getting original values
assertEquals("v2", cache(0).get(k0));
assertNull(cache(0).get(k1));
tm(0).commit();
assertNull(cache(1).get(k1));
}
protected void preloadCacheAndCheckSize() throws Exception {
tm(0).begin();
cache(0).put(k0, "v0");
cache(0).put(k1, "v1");
assertEquals(2, cache(0).size());
tm(0).commit();
}
}
| 3,837
| 30.719008
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/LocalOptimisticTxTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.locking.LocalOptimisticTxTest")
public class LocalOptimisticTxTest extends AbstractLocalTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
final ConfigurationBuilder config = getDefaultStandaloneCacheConfig(true);
config
.transaction()
.lockingMode(LockingMode.OPTIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery()
.disable();
return TestCacheManagerFactory.createCacheManager(config);
}
@Override
protected void assertLockingOnRollback() {
assertFalse(lockManager().isLocked("k"));
rollback();
assertFalse(lockManager().isLocked("k"));
}
@Override
protected void assertLocking() {
assertFalse(lockManager().isLocked("k"));
prepare();
assertTrue(lockManager().isLocked("k"));
commit();
assertFalse(lockManager().isLocked("k"));
}
}
| 1,549
| 30.632653
| 80
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/PessimisticDistTxTest.java
|
package org.infinispan.tx.locking;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional", testName = "tx.locking.PessimisticDistTxTest")
public class PessimisticDistTxTest extends PessimisticReplTxTest {
@Override
protected ConfigurationBuilder buildConfiguration() {
ConfigurationBuilder builder = super.buildConfiguration();
builder.clustering()
.cacheMode(CacheMode.DIST_SYNC)
.hash().numOwners(1);
return builder;
}
}
| 650
| 27.304348
| 75
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/PrimaryOwnerChangePessimistTxTest.java
|
package org.infinispan.tx.locking;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import jakarta.transaction.NotSupportedException;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.test.ExceptionRunnable;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.concurrent.TimeoutException;
import org.testng.annotations.Test;
/**
* Reproducer for ISPN-7140
* <p>
* Issue: with pessimistic cache, if the primary owner change, the new primary owner can start a transaction and acquire
* the lock of key (previously locked) without checking for existing transactions
*
* @author Pedro Ruivo
* @since 13.0
*/
@CleanupAfterMethod
@Test(groups = "functional", testName = "tx.locking.PrimaryOwnerChangePessimistTxTest")
public class PrimaryOwnerChangePessimistTxTest extends MultipleCacheManagersTest {
private ControlledConsistentHashFactory.Default factory;
@Override
protected void createCacheManagers() throws Throwable {
factory = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {0, 2}});
createClusteredCaches(3, TestDataSCI.INSTANCE, configuration(), new TransportFlags().withFD(true));
}
private ConfigurationBuilder configuration() {
ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cb.transaction().lockingMode(LockingMode.PESSIMISTIC);
cb.clustering().hash().numSegments(2).consistentHashFactory(factory);
return cb;
}
public void testNodeLeaving() throws Exception {
testPrimaryChange(this::nodeLeaves);
}
public void testNodeJoining() throws Exception {
testPrimaryChange(this::nodeJoins);
}
/*
ISPN-7140 test case
1. TX1 originating on A acquires lock for key X, A is primary owner and either B or C is backup owner
2. C is killed and B becomes primary owner of key X
(the order of owners for a segment can change even if the set of owners stays the same)
3. TX2 originating on B acquires lock for key X, B is now primary owner
4. TX1 commits the tx, Prepare is sent with the new topology id so it commits fine
5. TX2 also commits the transaction
*/
private void testPrimaryChange(ExceptionRunnable topologyChange) throws Exception {
MagicKey backupKey = new MagicKey(cache(0), cache(1));
MagicKey nonOwnerKey = new MagicKey(cache(0), cache(2));
// node0 is the primary owner
assertPrimaryOwner(backupKey, 0);
tm(0).begin();
cache(0).put(backupKey, "value-0");
Transaction tx0 = tm(0).suspend();
tm(0).begin();
advancedCache(0).lock(nonOwnerKey);
Transaction tx1 = tm(0).suspend();
// expect keys to be locked on primary owner
assertLocked(0, backupKey);
assertLocked(0, nonOwnerKey);
// switch primary owner: node1
factory.setOwnerIndexes(new int[][]{{1, 0}, {1, 0}});
topologyChange.run();
assertPrimaryOwner(backupKey, 1);
assertPrimaryOwner(nonOwnerKey, 1);
AdvancedCache<Object, Object> zeroTimeoutCache1 = advancedCache(1).withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT);
assertPutTimeout(backupKey, zeroTimeoutCache1);
assertLockTimeout(backupKey, zeroTimeoutCache1);
assertPutTimeout(nonOwnerKey, zeroTimeoutCache1);
assertLockTimeout(nonOwnerKey, zeroTimeoutCache1);
tm(0).resume(tx0);
tm(0).commit();
tm(0).resume(tx1);
tm(0).commit();
assertEquals("value-0", cache(0).get(backupKey));
assertEquals("value-0", cache(1).get(backupKey));
assertNull(cache(0).get(nonOwnerKey));
assertNull(cache(1).get(nonOwnerKey));
}
private void nodeLeaves() {
killMember(2);
}
private void nodeJoins() {
addClusterEnabledCacheManager(configuration(), new TransportFlags().withFD(true));
waitForClusterToForm();
}
private void assertPutTimeout(MagicKey lockedKey1, AdvancedCache<Object, Object> zeroTimeoutCache)
throws NotSupportedException, SystemException {
tm(1).begin();
expectException(TimeoutException.class, () -> zeroTimeoutCache.put(lockedKey1, "value-1"));
tm(1).rollback();
}
private void assertLockTimeout(MagicKey lockedKey1, AdvancedCache<Object, Object> zeroTimeoutCache)
throws NotSupportedException, SystemException {
tm(1).begin();
expectException(TimeoutException.class, () -> zeroTimeoutCache.lock(lockedKey1));
tm(1).rollback();
}
private void assertPrimaryOwner(MagicKey key, int index) {
DistributionManager dm = cache(index).getAdvancedCache().getDistributionManager();
assertTrue(dm.getCacheTopology().getDistribution(key).isPrimary());
}
}
| 5,468
| 36.979167
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/locking/OptimisticReplTxTest.java
|
package org.infinispan.tx.locking;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.locking.OptimisticReplTxTest")
public class OptimisticReplTxTest extends AbstractClusteredTxTest {
CacheMode cacheMode;
public OptimisticReplTxTest() {
this.cacheMode = CacheMode.REPL_SYNC;
}
// check that two transactions can progress in parallel on the same node
public void testTxProgress() throws Exception {
tm(0).begin();
cache(0).put(k, "v1");
final Transaction tx1 = tm(0).suspend();
//another tx working on the same keys
tm(0).begin();
cache(0).put(k, "v2");
tm(0).commit();
assert cache(0).get(k).equals("v2");
assert cache(1).get(k).equals("v2");
tm(0).resume(tx1);
tm(0).commit();
assert cache(0).get(k).equals("v1");
assert cache(1).get(k).equals("v1");
}
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder conf = getDefaultClusteredCacheConfig(cacheMode, true);
conf.transaction()
.lockingMode(LockingMode.OPTIMISTIC)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup());
conf.locking().isolationLevel(IsolationLevel.READ_COMMITTED);
createCluster(TestDataSCI.INSTANCE, conf, 2);
waitForClusterToForm();
k = getKeyForCache(0);
}
@Override
protected void assertLocking() {
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
prepare();
assertTrue(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
commit();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
@Override
protected void assertLockingNoChanges() {
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
prepare();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
commit();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
@Override
protected void assertLockingOnRollback() {
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
rollback();
assertFalse(lockManager(0).isLocked(k));
assertFalse(lockManager(1).isLocked(k));
}
}
| 2,925
| 30.12766
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryWithDefaultCacheReplTest.java
|
package org.infinispan.tx.recovery;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
*/
@Test(groups = "functional", testName = "tx.recovery.RecoveryWithDefaultCacheReplTest")
@CleanupAfterMethod
public class RecoveryWithDefaultCacheReplTest extends RecoveryWithDefaultCacheDistTest {
@Override
protected ConfigurationBuilder configure() {
ConfigurationBuilder config = super.configure();
config.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.clustering().cacheMode(CacheMode.REPL_SYNC);
return config;
}
}
| 852
| 34.541667
| 91
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryHandlerTest.java
|
package org.infinispan.tx.recovery;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "tx.recovery.RecoveryHandlerTest")
public class RecoveryHandlerTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder config = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
config.transaction().useSynchronization(false).recovery().enable();
createCluster(config, 2);
waitForClusterToForm();
}
public void testRecoveryHandler() throws Exception {
final XAResource xaResource = cache(0).getAdvancedCache().getXAResource();
final Xid[] recover = xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
assert recover != null && recover.length == 0;
}
}
| 1,121
| 34.0625
| 100
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/LocalRecoveryTest.java
|
package org.infinispan.tx.recovery;
import static org.infinispan.test.TestingUtil.getCacheObjectName;
import static org.infinispan.tx.recovery.RecoveryTestUtil.assertPrepared;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import javax.management.ObjectName;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
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.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.transaction.xa.TransactionXaAdapter;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
*/
@Test(groups = "functional", testName = "tx.recovery.LocalRecoveryTest")
public class LocalRecoveryTest extends SingleCacheManagerTest {
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder().nonClusteredDefault();
gcb.jmx().enabled(true).mBeanServerLookup(mBeanServerLookup);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.transaction()
.transactionMode(TransactionMode.TRANSACTIONAL)
.useSynchronization(false)
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.recovery().enable();
return TestCacheManagerFactory.createCacheManager(gcb, cb);
}
public void testRecoveryManagerInJmx() {
assertTrue(cache.getCacheConfiguration().transaction().transactionMode().isTransactional());
String jmxDomain = cacheManager.getCacheManagerConfiguration().jmx().domain();
ObjectName recoveryManager = getCacheObjectName(jmxDomain, cache.getName() + "(local)", "RecoveryManager");
assertFalse(mBeanServerLookup.getMBeanServer().isRegistered(recoveryManager));
}
public void testOneTx() throws Exception {
embeddedTm().begin();
cache.put("k", "v");
TransactionXaAdapter xaRes = (TransactionXaAdapter) embeddedTm().firstEnlistedResource();
assertPrepared(0, embeddedTm().getTransaction());
xaRes.prepare(xaRes.getLocalTransaction().getXid());
assertPrepared(1, embeddedTm().getTransaction());
final EmbeddedTransaction suspend = (EmbeddedTransaction) embeddedTm().suspend();
xaRes.commit(xaRes.getLocalTransaction().getXid(), false);
assertPrepared(0, suspend);
assertEquals(0, TestingUtil.getTransactionTable(cache).getLocalTxCount());
}
public void testMultipleTransactions() throws Exception {
EmbeddedTransaction suspend1 = beginTx();
EmbeddedTransaction suspend2 = beginTx();
EmbeddedTransaction suspend3 = beginTx();
EmbeddedTransaction suspend4 = beginTx();
assertPrepared(0, suspend1, suspend2, suspend3, suspend4);
prepareTransaction(suspend1);
assertPrepared(1, suspend1, suspend2, suspend3, suspend4);
prepareTransaction(suspend2);
assertPrepared(2, suspend1, suspend2, suspend3, suspend4);
prepareTransaction(suspend3);
assertPrepared(3, suspend1, suspend2, suspend3, suspend4);
prepareTransaction(suspend4);
assertPrepared(4, suspend1, suspend2, suspend3, suspend4);
commitTransaction(suspend1);
assertPrepared(3, suspend1, suspend2, suspend3, suspend4);
commitTransaction(suspend2);
assertPrepared(2, suspend1, suspend2, suspend3, suspend4);
commitTransaction(suspend3);
assertPrepared(1, suspend1, suspend2, suspend3, suspend4);
commitTransaction(suspend4);
assertPrepared(0, suspend1, suspend2, suspend3, suspend4);
assertEquals(0, TestingUtil.getTransactionTable(cache).getLocalTxCount());
}
private EmbeddedTransaction beginTx() {
return beginAndSuspendTx(cache);
}
private EmbeddedTransactionManager embeddedTm() {
return (EmbeddedTransactionManager) tm();
}
}
| 4,757
| 40.736842
| 113
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryWithDefaultCacheDistTest.java
|
package org.infinispan.tx.recovery;
import static org.infinispan.tx.recovery.RecoveryTestUtil.assertPrepared;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.rm;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.util.List;
import java.util.Set;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.RecoveryConfiguration;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.xa.recovery.InDoubtTxInfo;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
*/
@Test (groups = "functional", testName = "tx.recovery.RecoveryWithDefaultCacheDistTest")
@CleanupAfterMethod
public class RecoveryWithDefaultCacheDistTest extends MultipleCacheManagersTest {
protected ConfigurationBuilder configuration;
@Override
protected void createCacheManagers() throws Throwable {
configuration = configure();
createCluster(configuration, 2);
waitForClusterToForm();
//check that a default cache has been created
assertNotNull(manager(0).getCache(getRecoveryCacheName(), false));
assertNotNull(manager(1).getCache(getRecoveryCacheName(), false));
}
protected ConfigurationBuilder configure() {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration.locking().useLockStriping(false)
.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().enable()
.clustering().stateTransfer().fetchInMemoryState(false);
return configuration;
}
public void testSimpleTx() throws Exception{
tm(0).begin();
cache(0).put("k","v");
tm(0).commit();
assert cache(1).get("k").equals("v");
}
public void testLocalAndRemoteTransaction() throws Exception {
EmbeddedTransaction t0 = beginAndSuspendTx(cache(0));
EmbeddedTransaction t1 = beginAndSuspendTx(cache(1));
assertPrepared(0, t0, t1);
prepareTransaction(t0);
assertPrepared(1, t0);
assertPrepared(0, t1);
prepareTransaction(t1);
assertPrepared(1, t0);
assertPrepared(1, t1);
commitTransaction(t0);
assertPrepared(0, t0);
assertPrepared(1, t1);
commitTransaction(t1);
assertPrepared(0, t0);
assertPrepared(0, t1);
eventually(() -> {
boolean noPrepTxOnFirstNode = cache(0, getRecoveryCacheName()).size() == 0;
boolean noPrepTxOnSecondNode = cache(1, getRecoveryCacheName()).size() == 0;
return noPrepTxOnFirstNode & noPrepTxOnSecondNode;
});
eventually(() -> {
final Set<InDoubtTxInfo> inDoubt = rm(cache(0)).getInDoubtTransactionInfo();
return inDoubt.size() == 0;
});
}
public void testNodeCrashesAfterPrepare() throws Exception {
EmbeddedTransaction t1_1 = beginAndSuspendTx(cache(1));
prepareTransaction(t1_1);
EmbeddedTransaction t1_2 = beginAndSuspendTx(cache(1));
prepareTransaction(t1_2);
EmbeddedTransaction t1_3 = beginAndSuspendTx(cache(1));
prepareTransaction(t1_3);
manager(1).stop();
super.cacheManagers.remove(1);
TestingUtil.blockUntilViewReceived(cache(0), 1, 60000, false);
eventually(() -> {
int size = rm(cache(0)).getInDoubtTransactionInfo().size();
return size == 3;
});
List<XidImpl> inDoubtTransactions = rm(cache(0)).getInDoubtTransactions();
assertEquals(3, inDoubtTransactions.size());
assert inDoubtTransactions.contains(t1_1.getXid());
assert inDoubtTransactions.contains(t1_2.getXid());
assert inDoubtTransactions.contains(t1_3.getXid());
configuration.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
startCacheManager();
TestingUtil.blockUntilViewsReceived(60000, cache(0), cache(1));
EmbeddedTransaction t1_4 = beginAndSuspendTx(cache(1));
prepareTransaction(t1_4);
log.trace("Before main recovery call.");
assertPrepared(4, t1_4);
//now second call would only return 1 prepared tx as we only go over the network once
assertPrepared(1, t1_4);
commitTransaction(t1_4);
assertPrepared(0, t1_4);
inDoubtTransactions = rm(cache(0)).getInDoubtTransactions();
assertEquals(3, inDoubtTransactions.size());
assert inDoubtTransactions.contains(t1_1.getXid());
assert inDoubtTransactions.contains(t1_2.getXid());
assert inDoubtTransactions.contains(t1_3.getXid());
//now let's start to forget transactions
t1_4.firstEnlistedResource().forget(t1_1.getXid());
log.info("returned");
eventually(() -> rm(cache(0)).getInDoubtTransactionInfo().size() == 2);
inDoubtTransactions = rm(cache(0)).getInDoubtTransactions();
assertEquals(2, inDoubtTransactions.size());
assert inDoubtTransactions.contains(t1_2.getXid());
assert inDoubtTransactions.contains(t1_3.getXid());
t1_4.firstEnlistedResource().forget(t1_2.getXid());
t1_4.firstEnlistedResource().forget(t1_3.getXid());
eventually(() -> rm(cache(0)).getInDoubtTransactionInfo().size() == 0);
assertEquals(0, rm(cache(0)).getInDoubtTransactionInfo().size());
}
protected void startCacheManager() {
addClusterEnabledCacheManager(configuration);
}
protected String getRecoveryCacheName() {
return RecoveryConfiguration.DEFAULT_RECOVERY_INFO_CACHE;
}
}
| 6,189
| 36.97546
| 101
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryWithCustomCacheDistTest.java
|
package org.infinispan.tx.recovery;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
*/
@Test(groups = "functional", testName = "tx.recovery.RecoveryWithCustomCacheDistTest")
public class RecoveryWithCustomCacheDistTest extends RecoveryWithDefaultCacheDistTest {
private static final String CUSTOM_CACHE = "customCache";
private ConfigurationBuilder recoveryCacheConfig;
@Override
protected void createCacheManagers() throws Throwable {
configuration = super.configure();
configuration.transaction().recovery().recoveryInfoCacheName(CUSTOM_CACHE);
recoveryCacheConfig = getDefaultClusteredCacheConfig(CacheMode.LOCAL, false);
recoveryCacheConfig.transaction().transactionManagerLookup(null);
// Explicitly disable recovery in recovery cache per se.
recoveryCacheConfig.transaction().recovery().disable();
startCacheManager();
startCacheManager();
manager(0).startCaches(getDefaultCacheName(), CUSTOM_CACHE);
manager(1).startCaches(getDefaultCacheName(), CUSTOM_CACHE);
waitForClusterToForm(CUSTOM_CACHE);
assert manager(0).getCacheNames().contains(CUSTOM_CACHE);
assert manager(1).getCacheNames().contains(CUSTOM_CACHE);
}
@Override
protected String getRecoveryCacheName() {
return CUSTOM_CACHE;
}
@Override
protected void startCacheManager() {
ConfigurationBuilderHolder holder = new ConfigurationBuilderHolder();
holder.getGlobalConfigurationBuilder().clusteredDefault().defaultCacheName(getDefaultCacheName());
holder.getNamedConfigurationBuilders().put(getDefaultCacheName(), configuration);
holder.getNamedConfigurationBuilders().put(CUSTOM_CACHE, recoveryCacheConfig);
registerCacheManager(TestCacheManagerFactory.createClusteredCacheManager(holder));
}
}
| 2,093
| 37.072727
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/PostCommitRecoveryStateTest.java
|
package org.infinispan.tx.recovery;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.XaTransactionTable;
import org.infinispan.transaction.xa.recovery.InDoubtTxInfo;
import org.infinispan.transaction.xa.recovery.RecoveryAwareRemoteTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryAwareTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.transaction.xa.recovery.RecoveryManagerImpl;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.PostCommitRecoveryStateTest")
public class PostCommitRecoveryStateTest extends MultipleCacheManagersTest {
private static Log log = LogFactory.getLog(PostCommitRecoveryStateTest.class);
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration
.locking().useLockStriping(false)
.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().enable()
.clustering().stateTransfer().fetchInMemoryState(false);
createCluster(configuration, 2);
waitForClusterToForm();
ComponentRegistry componentRegistry = this.cache(0).getAdvancedCache().getComponentRegistry();
XaTransactionTable txTable =
(XaTransactionTable) componentRegistry.getComponent(TransactionTable.class);
TestingUtil.replaceField(
new RecoveryManagerDelegate(TestingUtil.extractComponent(cache(0), RecoveryManager.class)),
"recoveryManager", txTable, XaTransactionTable.class);
}
public void testState() throws Exception {
RecoveryManagerImpl rm1 = (RecoveryManagerImpl) advancedCache(1).getComponentRegistry().getComponent(RecoveryManager.class);
TransactionTable tt1 = advancedCache(1).getComponentRegistry().getComponent(TransactionTable.class);
assertEquals(rm1.getInDoubtTransactionsMap().size(), 0);
assertEquals(tt1.getRemoteTxCount(), 0);
EmbeddedTransaction t0 = beginAndSuspendTx(cache(0));
assertEquals(rm1.getInDoubtTransactionsMap().size(),0);
assertEquals(tt1.getRemoteTxCount(), 0);
prepareTransaction(t0);
assertEquals(rm1.getInDoubtTransactionsMap().size(),0);
assertEquals(tt1.getRemoteTxCount(), 1);
commitTransaction(t0);
assertEquals(tt1.getRemoteTxCount(), 1);
assertEquals(rm1.getInDoubtTransactionsMap().size(), 0);
}
public static class RecoveryManagerDelegate implements RecoveryManager {
volatile RecoveryManager rm;
public boolean swallowRemoveRecoveryInfoCalls = true;
public RecoveryManagerDelegate(RecoveryManager recoveryManager) {
this.rm = recoveryManager;
}
@Override
public RecoveryIterator getPreparedTransactionsFromCluster() {
return rm.getPreparedTransactionsFromCluster();
}
@Override
public CompletionStage<Void> removeRecoveryInformation(Collection<Address> where, XidImpl xid, GlobalTransaction gtx, boolean fromCluster) {
if (swallowRemoveRecoveryInfoCalls){
log.trace("PostCommitRecoveryStateTest$RecoveryManagerDelegate.removeRecoveryInformation");
return CompletableFutures.completedNull();
} else {
return this.rm.removeRecoveryInformation(where, xid, null, false);
}
}
@Override
public CompletionStage<Void> removeRecoveryInformationFromCluster(Collection<Address> where, long internalId) {
return rm.removeRecoveryInformationFromCluster(where, internalId);
}
@Override
public RecoveryAwareTransaction removeRecoveryInformation(XidImpl xid) {
rm.removeRecoveryInformation(xid);
return null;
}
@Override
public void registerInDoubtTransaction(RecoveryAwareRemoteTransaction tx) {
rm.registerInDoubtTransaction(tx);
}
@Override
public Set<InDoubtTxInfo> getInDoubtTransactionInfoFromCluster() {
return rm.getInDoubtTransactionInfoFromCluster();
}
@Override
public Set<InDoubtTxInfo> getInDoubtTransactionInfo() {
return rm.getInDoubtTransactionInfo();
}
@Override
public List<XidImpl> getInDoubtTransactions() {
return rm.getInDoubtTransactions();
}
@Override
public RecoveryAwareTransaction getPreparedTransaction(XidImpl xid) {
return rm.getPreparedTransaction(xid);
}
@Override
public CompletionStage<String> forceTransactionCompletion(XidImpl xid, boolean commit) {
return rm.forceTransactionCompletion(xid, commit);
}
@Override
public String forceTransactionCompletionFromCluster(XidImpl xid, Address where, boolean commit) {
return rm.forceTransactionCompletionFromCluster(xid, where, commit);
}
@Override
public boolean isTransactionPrepared(GlobalTransaction globalTx) {
return rm.isTransactionPrepared(globalTx);
}
@Override
public RecoveryAwareTransaction removeRecoveryInformation(Long internalId) {
rm.removeRecoveryInformation(internalId);
return null;
}
}
}
| 6,508
| 37.976048
| 146
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/InDoubtXidReturnedOnceTest.java
|
package org.infinispan.tx.recovery;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.AssertJUnit.assertEquals;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.recovery.InDoubtXidReturnedOnceTest")
public class InDoubtXidReturnedOnceTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration
.locking()
.useLockStriping(false)
.transaction()
.transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery()
.enable()
.clustering()
.stateTransfer()
.fetchInMemoryState(false)
.hash()
.numOwners(3);
createCluster(configuration, 4);
waitForClusterToForm();
}
public void testXidReturnedOnlyOnce() throws Throwable {
EmbeddedTransaction tx = beginAndSuspendTx(this.cache(3));
prepareTransaction(tx);
manager(3).stop();
TestingUtil.blockUntilViewsReceived(60000, false, cache(0), cache(1), cache(2));
TestingUtil.waitForNoRebalance(cache(0), cache(1), cache(2));
EmbeddedTransaction tx2 = beginAndSuspendTx(this.cache(0));
Xid[] recover = tx2.firstEnlistedResource().recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
assertEquals(recover.length,1);
assertEquals(tx.getXid(), recover[0]);
}
}
| 2,167
| 34.540984
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryConfigTest.java
|
package org.infinispan.tx.recovery;
import static org.infinispan.configuration.cache.RecoveryConfiguration.DEFAULT_RECOVERY_INFO_CACHE;
import static org.infinispan.tx.recovery.RecoveryTestUtil.rm;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import org.infinispan.Cache;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.xa.recovery.RecoveryAwareRemoteTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryInfoKey;
import org.infinispan.transaction.xa.recovery.RecoveryManagerImpl;
import org.testng.annotations.Test;
/**
* @author Mircea.Markus@jboss.com
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.RecoveryConfigTest")
public class RecoveryConfigTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
return TestCacheManagerFactory.fromXml("configs/recovery-enabled-config.xml");
}
@Test(expectedExceptions = CacheConfigurationException.class)
public void testRecoveryAndAsyncCaches() {
//Note: this configuration uses Xa Enlistment (see configs/recovery-enabled-config.xml).
Configuration defaultConfig = cacheManager.getDefaultCacheConfiguration();
ConfigurationBuilder builder = new ConfigurationBuilder().read(defaultConfig, Combine.DEFAULT);
builder.clustering().cacheMode(CacheMode.REPL_ASYNC);
builder.transaction().recovery().enable();
//it should throw an exception when try to build this configuration.
builder.build();
}
public void testRecoveryWithCacheConfigured() {
Configuration withRecoveryAndCache = cacheManager.getCache("withRecoveryAndCache").getCacheConfiguration();
assertTrue(withRecoveryAndCache.transaction().recovery().enabled(), "Recovery is supposed to be enabled.");
assertEquals(withRecoveryAndCache.transaction().recovery().recoveryInfoCacheName(), "noRecovery", "Wrong recovery cache name.");
RecoveryManagerImpl recoveryManager = rm(cacheManager.getCache("withRecoveryAndCache"));
assertNotNull(recoveryManager, "RecoveryManager should be *not* null when recovery is enabled.");
Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction> preparedTransactions = (Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction>) recoveryManager.getInDoubtTransactionsMap();
assertEquals(preparedTransactions.getName(), "noRecovery", "Wrong recovery cache name.");
}
public void testRecoveryWithDefaultCache() {
Configuration recoveryDefaultCache = cacheManager.getCache("withRecoveryDefaultCache").getCacheConfiguration();
assertTrue(recoveryDefaultCache.transaction().recovery().enabled(), "Recovery is supposed to be enabled.");
assertEquals(recoveryDefaultCache.transaction().recovery().recoveryInfoCacheName(), DEFAULT_RECOVERY_INFO_CACHE, "Wrong recovery cache name.");
RecoveryManagerImpl recoveryManager = rm(cacheManager.getCache("withRecoveryDefaultCache"));
assertNotNull(recoveryManager, "RecoveryManager should be *not* null when recovery is enabled.");
Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction> preparedTransactions = (Cache<RecoveryInfoKey, RecoveryAwareRemoteTransaction>) recoveryManager.getInDoubtTransactionsMap();
assertEquals(preparedTransactions.getName(), DEFAULT_RECOVERY_INFO_CACHE, "Wrong recovery cache name.");
}
public void testNoRecovery() {
Configuration noRecovery = cacheManager.getCache("noRecovery").getCacheConfiguration();
assertFalse(noRecovery.transaction().recovery().enabled(), "Recovery is supposed to be disabled");
assertNull(rm(cacheManager.getCache("noRecovery")), "RecoveryManager should be null when recovery is disabled");
assertEquals(noRecovery.transaction().recovery().recoveryInfoCacheName(), "someName", "Wrong recovery cache name.");
}
}
| 4,442
| 58.24
| 185
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/RecoveryTestUtil.java
|
package org.infinispan.tx.recovery;
import static org.testng.Assert.assertEquals;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import org.infinispan.Cache;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.transaction.xa.TransactionXaAdapter;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.transaction.xa.recovery.RecoveryManagerImpl;
public class RecoveryTestUtil {
public static int count = 0;
public static void commitTransaction(EmbeddedTransaction dtx) throws XAException {
TransactionXaAdapter xaResource = (TransactionXaAdapter) dtx.firstEnlistedResource();
xaResource.commit(xaResource.getLocalTransaction().getXid(), false);
}
public static void rollbackTransaction(EmbeddedTransaction dtx) throws XAException {
TransactionXaAdapter xaResource = (TransactionXaAdapter) dtx.firstEnlistedResource();
xaResource.commit(xaResource.getLocalTransaction().getXid(), false);
}
public static void prepareTransaction(EmbeddedTransaction suspend1) {
TransactionXaAdapter xaResource = (TransactionXaAdapter) suspend1.firstEnlistedResource();
try {
xaResource.prepare(xaResource.getLocalTransaction().getXid());
} catch (XAException e) {
throw new RuntimeException(e);
}
}
static void assertPrepared(int count, EmbeddedTransaction... tx) throws XAException {
for (EmbeddedTransaction dt : tx) {
TransactionXaAdapter xaRes = (TransactionXaAdapter) dt.firstEnlistedResource();
assertEquals(count, xaRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN).length);
}
}
public static RecoveryManagerImpl rm(Cache cache) {
return (RecoveryManagerImpl) TestingUtil.extractComponentRegistry(cache).getComponent(RecoveryManager.class);
}
public static EmbeddedTransaction beginAndSuspendTx(Cache cache) {
return beginAndSuspendTx(cache, "k" + count++);
}
public static EmbeddedTransaction beginAndSuspendTx(Cache cache, Object key) {
EmbeddedTransactionManager dummyTm = (EmbeddedTransactionManager) TestingUtil.getTransactionManager(cache);
try {
dummyTm.begin();
cache.put(key, "v");
return (EmbeddedTransaction) dummyTm.suspend();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 2,522
| 37.815385
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/InDoubtWithCommitFailsTest.java
|
package org.infinispan.tx.recovery.admin;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.rollbackTransaction;
import static org.testng.Assert.assertEquals;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.interceptors.impl.InvocationContextInterceptor;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* This test makes sure that when a transaction fails during commit it is reported as in-doubt transaction.
*
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.recovery.admin.InDoubtWithCommitFailsTest")
@CleanupAfterMethod
public class InDoubtWithCommitFailsTest extends AbstractRecoveryTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().enable()
.locking().useLockStriping(false)
.clustering().hash().numOwners(2)
.clustering().l1().disable().stateTransfer().fetchInMemoryState(false);
createCluster(configuration, 2);
waitForClusterToForm();
advancedCache(1).getAsyncInterceptorChain().addInterceptorBefore(new ForceFailureInterceptor(), InvocationContextInterceptor.class);
}
public void testRecoveryInfoListCommit() throws Exception {
test(true);
}
public void testRecoveryInfoListRollback() throws Exception {
test(false);
}
private void test(boolean commit) {
assert recoveryOps(0).showInDoubtTransactions().isEmpty();
TransactionTable tt0 = cache(0).getAdvancedCache().getComponentRegistry().getComponent(TransactionTable.class);
EmbeddedTransaction dummyTransaction = beginAndSuspendTx(cache(0));
prepareTransaction(dummyTransaction);
assert tt0.getLocalTxCount() == 1;
try {
if (commit) {
commitTransaction(dummyTransaction);
} else {
rollbackTransaction(dummyTransaction);
}
assert false : "exception expected";
} catch (Exception e) {
//expected
}
assertEquals(tt0.getLocalTxCount(), 1);
assertEquals(countInDoubtTx(recoveryOps(0).showInDoubtTransactions()), 1);
assertEquals(countInDoubtTx(recoveryOps(1).showInDoubtTransactions()), 1);
}
public static class ForceFailureInterceptor extends DDAsyncInterceptor {
public boolean fail = true;
@Override
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable {
fail();
return super.visitCommitCommand(ctx, command);
}
private void fail() {
if (fail) throw new CacheException("Induced failure");
}
@Override
public Object visitRollbackCommand(TxInvocationContext ctx, RollbackCommand command) throws Throwable {
fail();
return super.visitRollbackCommand(ctx, command);
}
}
}
| 3,874
| 36.990196
| 138
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/OriginatorAndOwnerFailureReplicationTest.java
|
package org.infinispan.tx.recovery.admin;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.admin.OriginatorAndOwnerFailureReplicationTest")
@CleanupAfterMethod
public class OriginatorAndOwnerFailureReplicationTest extends OriginatorAndOwnerFailureTest {
@Override
protected ConfigurationBuilder defaultRecoveryConfig() {
ConfigurationBuilder configuration = super.defaultRecoveryConfig();
configuration.clustering().cacheMode(CacheMode.REPL_SYNC);
return configuration;
}
@Override
protected Object getKey() {
return "aKey";
}
@Test
public void recoveryInvokedOnNonTxParticipantTest() {
//all nodes are tx participants in replicated caches so this test makes no sense
}
@Override
public void recoveryInvokedOnTxParticipantTest() {
runTest(0);
}
}
| 1,081
| 27.473684
| 102
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/SimpleCacheRecoveryAdminTest.java
|
package org.infinispan.tx.recovery.admin;
import static org.infinispan.test.TestingUtil.checkMBeanOperationParameterNaming;
import static org.infinispan.test.TestingUtil.getCacheObjectName;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import javax.management.ObjectName;
import org.infinispan.commons.jmx.MBeanServerLookup;
import org.infinispan.commons.jmx.TestMBeanServerLookup;
import org.infinispan.commons.tx.XidImpl;
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.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.recovery.admin.SimpleCacheRecoveryAdminTest")
@CleanupAfterMethod
public class SimpleCacheRecoveryAdminTest extends AbstractRecoveryTest {
private static final String JMX_DOMAIN = SimpleCacheRecoveryAdminTest.class.getSimpleName();
private final MBeanServerLookup mBeanServerLookup = TestMBeanServerLookup.create();
private EmbeddedTransaction tx1;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
configuration.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().enable()
.locking().useLockStriping(false)
.clustering().hash().numOwners(3)
.l1().disable();
EmbeddedCacheManager cm1 = TestCacheManagerFactory.createClusteredCacheManager(createGlobalConfigurationBuilder(0), configuration, new TransportFlags());
EmbeddedCacheManager cm2 = TestCacheManagerFactory.createClusteredCacheManager(createGlobalConfigurationBuilder(1), configuration, new TransportFlags());
EmbeddedCacheManager cm3 = TestCacheManagerFactory.createClusteredCacheManager(createGlobalConfigurationBuilder(2), configuration, new TransportFlags());
registerCacheManager(cm1, cm2, cm3);
defineConfigurationOnAllManagers("test", configuration);
cache(0, "test");
cache(1, "test");
cache(2, "test");
TestingUtil.waitForNoRebalance(caches("test"));
assertTrue(showInDoubtTransactions(0).isEmpty());
assertTrue(showInDoubtTransactions(1).isEmpty());
assertTrue(showInDoubtTransactions(2).isEmpty());
tx1 = beginAndSuspendTx(cache(2, "test"));
prepareTransaction(tx1);
log.trace("Shutting down a cache " + address(cache(2, "test")));
TestingUtil.killCacheManagers(manager(2));
TestingUtil.blockUntilViewsReceived(90000, false, cache(0, "test"), cache(1, "test"));
}
private GlobalConfigurationBuilder createGlobalConfigurationBuilder(int index) {
GlobalConfigurationBuilder globalConfiguration = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalConfiguration.jmx().enabled(true).mBeanServerLookup(mBeanServerLookup).domain(JMX_DOMAIN + index);
return globalConfiguration;
}
public void testJmxOperationMetadata() throws Exception {
checkMBeanOperationParameterNaming(mBeanServerLookup.getMBeanServer(), getRecoveryAdminObjectName(0));
}
public void testForceCommitOnOtherNode() {
String inDoubt = showInDoubtTransactions(0);
assertInDoubtTxCount(inDoubt, 1);
assertInDoubtTxCount(showInDoubtTransactions(1), 1);
List<Long> ids = getInternalIds(inDoubt);
assertEquals(1, ids.size());
assertEquals(0, cache(0, "test").keySet().size());
assertEquals(0, cache(1, "test").keySet().size());
if (log.isTraceEnabled()) log.trace("Before forcing commit!");
String result = invokeForceWithId("forceCommit", 0, ids.get(0));
checkResponse(result, 1);
}
public void testForceCommitXid() {
String s = invokeForceWithXid("forceCommit", 0, tx1.getXid());
log.tracef("s = %s", s);
checkResponse(s, 1);
//try again
s = invokeForceWithXid("forceCommit", 0, tx1.getXid());
assertTrue(s.contains("Transaction not found"));
}
public void testForceRollbackInternalId() {
List<Long> ids = getInternalIds(showInDoubtTransactions(0));
log.tracef("test:: invoke rollback for %s", ids);
String result = invokeForceWithId("forceRollback", 0, ids.get(0));
checkResponse(result, 0);
assertTrue(invokeForceWithId("forceRollback", 0, ids.get(0)).contains("Transaction not found"));
}
public void testForceRollbackXid() {
String s = invokeForceWithXid("forceRollback", 0, tx1.getXid());
checkResponse(s, 0);
//try again
s = invokeForceWithXid("forceRollback", 0, tx1.getXid());
assertTrue(s.contains("Transaction not found"));
}
private void checkResponse(String result, int entryCount) {
assertTrue("Received: " + result, isSuccess(result));
assertEquals(cache(0, "test").keySet().size(), entryCount);
assertEquals(cache(1, "test").keySet().size(), entryCount);
eventually(() -> showInDoubtTransactions(0).isEmpty() && showInDoubtTransactions(1).isEmpty());
//just make sure everything is cleaned up properly now
checkProperlyCleanup(0);
checkProperlyCleanup(1);
}
@Override
protected void checkProperlyCleanup(final int managerIndex) {
eventually(() -> TestingUtil.extractLockManager(cache(managerIndex, "test")).getNumberOfLocksHeld() == 0);
final TransactionTable tt = TestingUtil.extractComponent(cache(managerIndex, "test"), TransactionTable.class);
eventuallyEquals(0, tt::getRemoteTxCount);
eventuallyEquals(0, tt::getLocalTxCount);
final RecoveryManager rm = TestingUtil.extractComponent(cache(managerIndex, "test"), RecoveryManager.class);
eventually(() -> rm.getInDoubtTransactions().size() == 0);
eventually(() -> rm.getPreparedTransactionsFromCluster().all().length == 0);
}
private String invokeForceWithId(String methodName, int cacheIndex, Long aLong) {
try {
ObjectName recoveryAdmin = getRecoveryAdminObjectName(cacheIndex);
return mBeanServerLookup.getMBeanServer().invoke(recoveryAdmin, methodName, new Object[]{aLong}, new String[]{long.class.getName()}).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private String invokeForceWithXid(String methodName, int cacheIndex, XidImpl xid) {
try {
ObjectName recoveryAdmin = getRecoveryAdminObjectName(cacheIndex);
Object[] params = {xid.getFormatId(), xid.getGlobalTransactionId(), xid.getBranchQualifier()};
String[] signature = {int.class.getName(), byte[].class.getName(), byte[].class.getName()};
return mBeanServerLookup.getMBeanServer().invoke(recoveryAdmin, methodName, params, signature).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void assertInDoubtTxCount(String inDoubt, int expectedCount) {
int count = countInDoubtTx(inDoubt);
assertEquals(expectedCount, count);
}
private String showInDoubtTransactions(int cacheIndex) {
try {
ObjectName recoveryAdmin = getRecoveryAdminObjectName(cacheIndex);
return (String) mBeanServerLookup.getMBeanServer().invoke(recoveryAdmin, "showInDoubtTransactions", new Object[0], new String[0]);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private ObjectName getRecoveryAdminObjectName(int cacheIndex) {
return getCacheObjectName(JMX_DOMAIN + cacheIndex, "test(dist_sync)", "RecoveryAdmin");
}
}
| 8,411
| 41.918367
| 159
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/CommitFailsReplicatedTest.java
|
package org.infinispan.tx.recovery.admin;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional", testName = "tx.recovery.admin.CommitFailsReplicatedTest")
public class CommitFailsReplicatedTest extends CommitFailsTest {
@Override
protected Object getKey() {
return "aKey";
}
@Override
protected ConfigurationBuilder defaultRecoveryConfig() {
ConfigurationBuilder configuration = super.defaultRecoveryConfig();
configuration.clustering().cacheMode(CacheMode.REPL_SYNC);
return configuration;
}
public void testForceCommitNonTxParticipant() throws Exception {
runTest(1);
}
public void testForceCommitTxParticipant() throws Exception {
runTest(0);
}
}
| 896
| 25.382353
| 86
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/AbstractRecoveryTest.java
|
package org.infinispan.tx.recovery.admin;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.xa.recovery.RecoveryAdminOperations;
import org.infinispan.transaction.xa.recovery.RecoveryAwareTransactionTable;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test(groups = "functional")
public abstract class AbstractRecoveryTest extends MultipleCacheManagersTest {
protected ConfigurationBuilder defaultRecoveryConfig() {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup())
.useSynchronization(false)
.recovery().enable()
.locking().useLockStriping(false)
.clustering().hash().numOwners(2)
.l1().disable()
.stateTransfer().fetchInMemoryState(false);
return builder;
}
protected int countInDoubtTx(String inDoubt) {
log.tracef("Retrieved in-doubt transactions: %s", inDoubt);
int lastIndex = 0;
int count = 0;
while ((lastIndex = inDoubt.indexOf("internalId", lastIndex + 1)) >= 0) {
count ++;
}
return count;
}
protected RecoveryAdminOperations recoveryOps(int cacheIndex) {
return advancedCache(cacheIndex).getComponentRegistry().getComponent(RecoveryAdminOperations.class);
}
protected List<Long> getInternalIds(String inDoubt) {
Pattern p = Pattern.compile("internalId = [0-9]*");
Matcher matcher = p.matcher(inDoubt);
List<Long> result = new ArrayList<>();
while (matcher.find()) {
String group = matcher.group();
Long id = Long.parseLong(group.substring("internalId = ".length()));
result.add(id);
}
return result;
}
protected boolean isSuccess(String result) {
return result.contains("successful");
}
public RecoveryAwareTransactionTable tt(int index) {
return (RecoveryAwareTransactionTable) advancedCache(index).getComponentRegistry().getComponent(TransactionTable.class);
}
protected void checkProperlyCleanup(final int managerIndex) {
eventually(new Condition() {
@Override
public boolean isSatisfied() {
return TestingUtil.extractLockManager(cache(managerIndex)).getNumberOfLocksHeld() == 0;
}
});
final TransactionTable tt = TestingUtil.extractComponent(cache(managerIndex), TransactionTable.class);
eventually(new Condition() {
@Override
public boolean isSatisfied() {
log.tracef("For cache %s have remoteTx=%s and localTx=%s", managerIndex, tt.getRemoteTxCount(), tt.getLocalTxCount());
return (tt.getRemoteTxCount() == 0) && (tt.getLocalTxCount() == 0);
}
});
final RecoveryManager rm = TestingUtil.extractComponent(cache(managerIndex), RecoveryManager.class);
eventually(new Condition() {
@Override
public boolean isSatisfied() {
return rm.getInDoubtTransactions().isEmpty() && rm.getPreparedTransactionsFromCluster().all().length == 0;
}
});
}
protected void assertCleanup(int... caches) {
for (int i : caches) {
checkProperlyCleanup(i);
}
}
protected RecoveryManager recoveryManager(int cacheIndex) {
return TestingUtil.extractComponent(cache(cacheIndex), RecoveryManager.class);
}
protected int getTxParticipant(boolean txParticipant) {
int expectedNumber = txParticipant ? 1 : 0;
int index = -1;
for (int i = 0; i < 2; i++) {
if (recoveryManager(i).getInDoubtTransactions().size() == expectedNumber) {
index = i;
break;
}
}
return index;
}
}
| 4,291
| 34.766667
| 130
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/CommitFailsTest.java
|
package org.infinispan.tx.recovery.admin;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.Assert.assertEquals;
import java.util.List;
import javax.transaction.xa.XAException;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.impl.InvocationContextInterceptor;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* This test makes sure that when a tx fails during commit it can still be completed.
*
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.admin.CommitFailsTest")
public class CommitFailsTest extends AbstractRecoveryTest {
private Object key;
private InDoubtWithCommitFailsTest.ForceFailureInterceptor failureInterceptor0;
private InDoubtWithCommitFailsTest.ForceFailureInterceptor failureInterceptor1;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = defaultRecoveryConfig();
configuration.transaction().autoCommit(false);
configuration.locking().isolationLevel(IsolationLevel.READ_COMMITTED); //skip WSC exceptions
createCluster(TestDataSCI.INSTANCE, configuration, 3);
waitForClusterToForm();
key = getKey();
failureInterceptor0 = new InDoubtWithCommitFailsTest.ForceFailureInterceptor();
failureInterceptor1 = new InDoubtWithCommitFailsTest.ForceFailureInterceptor();
advancedCache(0).getAsyncInterceptorChain().addInterceptorAfter(failureInterceptor0, InvocationContextInterceptor.class);
advancedCache(1).getAsyncInterceptorChain().addInterceptorAfter(failureInterceptor1, InvocationContextInterceptor.class);
}
@BeforeMethod
protected void setUpTx() throws Exception {
failureInterceptor0.fail = true;
failureInterceptor1.fail = true;
tm(2).begin();
cache(2).put(this.key, "newValue");
EmbeddedTransaction tx = (EmbeddedTransaction) tm(2).suspend();
prepareTransaction(tx);
try {
commitTransaction(tx);
assert false;
} catch (XAException e) {
//expected
}
assertEquals(countInDoubtTx(recoveryOps(2).showInDoubtTransactions()), 1);
log.trace("here is the remote get...");
assertEquals(countInDoubtTx(recoveryOps(0).showInDoubtTransactions()), 1);
assertEquals(countInDoubtTx(recoveryOps(1).showInDoubtTransactions()), 1);
failureInterceptor0.fail = false;
failureInterceptor1.fail = false;
}
protected Object getKey() {
return new MagicKey(cache(2));
}
public void testForceCommitOnOriginator() throws Exception {
runTest(2);
}
public void testForceCommitNonTxParticipant() throws Exception {
int where = getTxParticipant(false);
runTest(where);
}
public void testForceCommitTxParticipant() throws Exception {
int where = getTxParticipant(true);
runTest(where);
}
private void assertAllHaveNewValue(Object key) throws Exception {
for (Cache c : caches()) {
Object actual;
TestingUtil.getTransactionManager(c).begin();
actual = c.get(key);
TestingUtil.getTransactionManager(c).commit();
assertEquals(actual, "newValue");
}
}
protected void runTest(int where) throws Exception {
List<Long> internalIds = getInternalIds(recoveryOps(where).showInDoubtTransactions());
log.debugf("About to force commit on node %s", address(where));
recoveryOps(where).forceCommit(internalIds.get(0));
assertCleanup(0);
assertCleanup(1);
assertCleanup(2);
assertAllHaveNewValue(key);
assertCleanup(0, 1, 2);
}
@Override
protected int getTxParticipant(boolean txParticipant) {
int expectedNumber = txParticipant ? 1 : 0;
int index = -1;
for (int i = 0; i < 2; i++) {
if (tt(i).getRemoteTxCount() == expectedNumber) {
index = i;
break;
}
}
return index;
}
}
| 4,417
| 32.725191
| 127
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/ForgetTest.java
|
package org.infinispan.tx.recovery.admin;
import static org.infinispan.tx.recovery.RecoveryTestUtil.beginAndSuspendTx;
import static org.infinispan.tx.recovery.RecoveryTestUtil.commitTransaction;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.AssertJUnit.assertEquals;
import javax.transaction.xa.XAException;
import org.infinispan.commons.tx.XidImpl;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.impl.RemoteTransaction;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.XaTransactionTable;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.tx.recovery.PostCommitRecoveryStateTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.admin.ForgetTest")
public class ForgetTest extends AbstractRecoveryTest {
private EmbeddedTransaction tx;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = defaultRecoveryConfig();
createCluster(configuration, 2);
waitForClusterToForm();
XaTransactionTable txTable = tt(0);
PostCommitRecoveryStateTest.RecoveryManagerDelegate recoveryManager = new PostCommitRecoveryStateTest.RecoveryManagerDelegate(
TestingUtil.extractComponent(cache(0), RecoveryManager.class));
TestingUtil.replaceField(recoveryManager, "recoveryManager", txTable, XaTransactionTable.class);
}
@BeforeMethod
public void runTx() throws XAException {
tx = beginAndSuspendTx(cache(0));
prepareTransaction(tx);
assertEquals(recoveryManager(0).getPreparedTransactionsFromCluster().all().length, 1);
assertEquals(tt(0).getLocalPreparedXids().size(), 1);
assertEquals(tt(1).getRemoteTxCount(), 1);
commitTransaction(tx);
assertEquals(tt(1).getRemoteTxCount(), 1);
}
public void testInternalIdOnSameNode() {
XidImpl xid = tx.getXid();
recoveryOps(0).forget(xid.getFormatId(), xid.getGlobalTransactionId(), xid.getBranchQualifier());
assertEquals(tt(1).getRemoteTxCount(), 0);//make sure tx has been removed
}
public void testForgetXidOnSameNode() {
forgetWithXid(0);
}
public void testForgetXidOnOtherNode() {
forgetWithXid(1);
}
public void testForgetInternalIdOnSameNode() {
forgetWithInternalId(0);
}
public void testForgetInternalIdOnOtherNode() {
forgetWithInternalId(1);
}
protected void forgetWithInternalId(int cacheIndex) {
long internalId = -1;
for (RemoteTransaction rt : tt(1).getRemoteTransactions()) {
GlobalTransaction a = rt.getGlobalTransaction();
if (a.getXid().equals(tx.getXid())) {
internalId = a.getInternalId();
}
}
if (internalId == -1) throw new IllegalStateException();
log.tracef("About to forget... %s", internalId);
recoveryOps(cacheIndex).forget(internalId);
assertEquals(tt(0).getRemoteTxCount(), 0);
assertEquals(tt(1).getRemoteTxCount(), 0);
}
private void forgetWithXid(int nodeIndex) {
XidImpl xid = tx.getXid();
recoveryOps(nodeIndex).forget(xid.getFormatId(), xid.getGlobalTransactionId(), xid.getBranchQualifier());
assertEquals(tt(1).getRemoteTxCount(), 0);//make sure tx has been removed
}
}
| 3,614
| 34.792079
| 132
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/ForgetReplicationTest.java
|
package org.infinispan.tx.recovery.admin;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.admin.ForgetReplicationTest")
public class ForgetReplicationTest extends ForgetTest {
@Override
protected ConfigurationBuilder defaultRecoveryConfig() {
ConfigurationBuilder configuration = super.defaultRecoveryConfig();
configuration.clustering().cacheMode(CacheMode.REPL_SYNC);
return configuration;
}
}
| 632
| 29.142857
| 83
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/tx/recovery/admin/OriginatorAndOwnerFailureTest.java
|
package org.infinispan.tx.recovery.admin;
import static org.infinispan.tx.recovery.RecoveryTestUtil.prepareTransaction;
import static org.testng.Assert.assertEquals;
import java.util.List;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.testng.annotations.Test;
/**
* Tests the following scenario: the transaction originator fails and it also part of the transactions.
*
* @author Mircea Markus
* @since 5.0
*/
@Test (groups = "functional", testName = "tx.recovery.admin.OriginatorAndOwnerFailureTest")
@CleanupAfterMethod
public class OriginatorAndOwnerFailureTest extends AbstractRecoveryTest {
private Object key;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configuration = defaultRecoveryConfig();
assert configuration.build().transaction().transactionMode().isTransactional();
createCluster(TestDataSCI.INSTANCE, configuration, 3);
waitForClusterToForm();
key = getKey();
tm(2).begin();
cache(2).put(this.key, "newValue");
EmbeddedTransaction tx = (EmbeddedTransaction) tm(2).suspend();
prepareTransaction(tx);
killMember(2);
assert !recoveryOps(0).showInDoubtTransactions().isEmpty();
assert !recoveryOps(1).showInDoubtTransactions().isEmpty();
}
protected Object getKey() {
return new MagicKey(cache(2));
}
public void recoveryInvokedOnNonTxParticipantTest() {
runTest(false);
}
public void recoveryInvokedOnTxParticipantTest() {
runTest(true);
}
private void runTest(boolean txParticipant) {
int index = getTxParticipant(txParticipant);
runTest(index);
}
protected void runTest(int index) {
assert cache(0).getCacheConfiguration().transaction().transactionMode().isTransactional();
List<Long> internalIds = getInternalIds(recoveryOps(index).showInDoubtTransactions());
assertEquals(internalIds.size(), 1);
assertEquals(cache(0).get(key), null);
assertEquals(cache(1).get(key), null);
log.trace("About to force commit!");
isSuccess(recoveryOps(index).forceCommit(internalIds.get(0)));
assertEquals(cache(0).get(key), "newValue");
assertEquals(cache(1).get(key), "newValue");
assertCleanup(0);
assertCleanup(1);
}
}
| 2,522
| 29.035714
| 103
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/context/MarshalledValueContextTest.java
|
package org.infinispan.context;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.context.impl.LocalTxInvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.interceptors.impl.InvocationContextInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.data.Key;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.Test;
/**
* This is to test that contexts are properly constructed and cleaned up wven when using marshalled values and the
* explicit lock() API.
*
* @author Manik Surtani
* @version 4.1
*/
@Test (testName = "context.MarshalledValueContextTest", groups = "functional")
public class MarshalledValueContextTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder c = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
c.memory().storageType(StorageType.BINARY)
.transaction().lockingMode(LockingMode.PESSIMISTIC);
return TestCacheManagerFactory.createCacheManager(TestDataSCI.INSTANCE, c);
}
public void testContentsOfContext() throws Exception {
Cache<Key, String> c = cacheManager.getCache();
ContextExtractingInterceptor cex = new ContextExtractingInterceptor();
assertTrue(c.getAdvancedCache().getAsyncInterceptorChain().addInterceptorAfter(cex, InvocationContextInterceptor.class));
c.put(new Key("k"), "v");
assertEquals("v", c.get(new Key("k")));
TransactionManager tm = c.getAdvancedCache().getTransactionManager();
tm.begin();
c.getAdvancedCache().lock(new Key("k"));
LockManager lockManager = TestingUtil.extractComponent(c, LockManager.class);
assertTrue(cex.ctx instanceof LocalTxInvocationContext);
assertEquals("Looked up key should not be in transactional invocation context " +
"as we don't perform any changes", 0, cex.ctx.lookedUpEntriesCount());
assertEquals("Only one lock should be held", 1, lockManager.getNumberOfLocksHeld());
c.put(new Key("k"), "v2");
assertEquals("Still should only be one entry in the context", 1, cex.ctx.lookedUpEntriesCount());
assertEquals("Only one lock should be held", 1, lockManager.getNumberOfLocksHeld());
tm.commit();
assertEquals("No locks should be held anymore", 0, lockManager.getNumberOfLocksHeld());
assertEquals("v2", c.get(new Key("k")));
}
static class ContextExtractingInterceptor extends BaseAsyncInterceptor {
InvocationContext ctx;
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
this.ctx = ctx;
return invokeNext(ctx, command);
}
}
}
| 3,359
| 38.529412
| 127
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/context/InvocationContextTest.java
|
package org.infinispan.context;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestBlocking;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
@Test(groups = {"functional"}, testName = "context.InvocationContextTest")
public class InvocationContextTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(InvocationContextTest.class);
public InvocationContextTest() {
cleanup = CleanupPhase.AFTER_METHOD;
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
builder.transaction()
.lockingMode(LockingMode.PESSIMISTIC)
// TODO: Default values have for synchronization and recovery have changed
// These two calls are requires to make test behave as before
// (more info: https://issues.jboss.org/browse/ISPN-2651)
.useSynchronization(false)
.recovery().enabled(false);
createClusteredCaches(1, "timestamps", builder);
// Keep old configuration commented as reference for ISPN-2651
//
// Configuration cfg = TestCacheManagerFactory.getDefaultConfiguration(true);
// cfg.setSyncCommitPhase(true);
// cfg.setSyncRollbackPhase(true);
// cfg.fluent().transaction().lockingMode(LockingMode.PESSIMISTIC);
// createClusteredCaches(1, "timestamps", cfg);
}
public void testMishavingListenerResumesContext() {
Cache<String, String> cache = cache(0, "timestamps");
cache.addListener(new CacheListener());
try {
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).put("k", "v");
fail("Should have failed with an exception");
} catch (CacheException ce) {
Throwable cause = ce.getCause();
assertTrue("Unexpected exception cause " + cause,
cause instanceof RollbackException || cause instanceof HeuristicRollbackException);
}
}
public void testThreadInterruptedDuringLocking() throws Throwable {
final Cache<String, String> cache = cache(0, "timestamps");
cache.put("k", "v");
// now acquire a lock on k so that subsequent threads will block
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
tm.begin();
cache.put("k", "v2");
Transaction tx = tm.suspend();
final List<Throwable> throwables = new LinkedList<>();
Thread th = new Thread(() -> {
try {
cache.put("k", "v3");
} catch (Throwable th1) {
throwables.add(th1);
}
});
th.start();
// th will now block trying to acquire the lock.
th.interrupt();
th.join();
tm.resume(tx);
tm.rollback();
assertEquals(1, throwables.size());
assertTrue(throwables.get(0) instanceof CacheException);
assertTrue(throwables.get(0).getCause() instanceof InterruptedException);
}
public void testThreadInterruptedAfterLocking() throws Throwable {
final Cache<String, String> cache = cache(0, "timestamps");
cache.put("k", "v");
CountDownLatch willTimeoutLatch = new CountDownLatch(1);
CountDownLatch lockAquiredSignal = new CountDownLatch(1);
DelayingListener dl = new DelayingListener(lockAquiredSignal, willTimeoutLatch);
cache.addListener(dl);
final List<Throwable> throwables = new LinkedList<>();
Future<?> future = fork(() -> {
try {
cache.put("k", "v3");
} catch (Throwable th) {
throwables.add(th);
}
});
// wait for th to acquire the lock
lockAquiredSignal.await();
// and now throw the exception
dl.waitLatch.countDown();
future.get(10, SECONDS);
assert throwables.size() == 1;
assert throwables.get(0) instanceof CacheException;
}
@Listener
public static class DelayingListener {
CountDownLatch lockAcquiredLatch, waitLatch;
public DelayingListener(CountDownLatch lockAcquiredLatch, CountDownLatch waitLatch) {
this.lockAcquiredLatch = lockAcquiredLatch;
this.waitLatch = waitLatch;
}
@CacheEntryModified
@SuppressWarnings("unused")
public void entryModified(CacheEntryModifiedEvent event) {
if (!event.isPre()) {
lockAcquiredLatch.countDown();
try {
TestBlocking.await(waitLatch, 10, SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Induced exception");
}
}
}
@Listener
public static class CacheListener {
@CacheEntryCreated
@CacheEntryModified
@SuppressWarnings("unused")
public void entryModified(CacheEntryEvent event) {
if (!event.isPre()) {
log.debugf("Entry modified: %s, let's throw an exception!!", event);
throw new RuntimeException("Testing exception handling");
}
}
}
}
| 6,310
| 35.479769
| 98
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/context/FlagBitsetTest.java
|
package org.infinispan.context;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.Test;
/**
* @since 14.0
*/
@Test(groups = "unit", testName = "context.FlagBitsetTest")
public class FlagBitsetTest extends AbstractInfinispanTest {
private static final Flag[] FLAGS_CACHED = Flag.values();
public void testUniqueness() {
Map<Long, Flag> bits = new HashMap<>(FLAGS_CACHED.length);
for (Flag flag : FLAGS_CACHED) {
Flag existing = bits.putIfAbsent(EnumUtil.bitSetOf(flag), flag);
assertNull("Conflict flags: " + existing + " and " + flag, existing);
}
}
public void testBitSetOf() {
int startIdx = ThreadLocalRandom.current().nextInt(FLAGS_CACHED.length - 4);
Flag f1 = FLAGS_CACHED[startIdx];
Flag f2 = FLAGS_CACHED[startIdx + 1];
Flag f3 = FLAGS_CACHED[startIdx + 2];
Flag f4 = FLAGS_CACHED[startIdx + 3];
log.debugf("Flags: %s, %s, %s, %s", f1, f2, f3, f4);
assertBitSet(EnumUtil.bitSetOf(f1), startIdx, 1);
assertBitSet(EnumUtil.bitSetOf(f1, f2), startIdx, 2);
assertBitSet(EnumUtil.bitSetOf(f1, f2, f3), startIdx, 3);
assertBitSet(EnumUtil.bitSetOf(f1, f2, f3, f4), startIdx, 4);
}
public void testEnumFromBitSet() {
int startIdx = ThreadLocalRandom.current().nextInt(FLAGS_CACHED.length - 4);
Flag f1 = FLAGS_CACHED[startIdx];
Flag f2 = FLAGS_CACHED[startIdx + 1];
Flag f3 = FLAGS_CACHED[startIdx + 2];
Flag f4 = FLAGS_CACHED[startIdx + 3];
log.debugf("Flags: %s, %s, %s, %s", f1, f2, f3, f4);
assertEquals(EnumSet.of(f1), EnumUtil.enumSetOf(EnumUtil.bitSetOf(f1), Flag.class));
assertEquals(EnumSet.of(f1, f2), EnumUtil.enumSetOf(EnumUtil.bitSetOf(f1, f2), Flag.class));
assertEquals(EnumSet.of(f1, f2, f3), EnumUtil.enumSetOf(EnumUtil.bitSetOf(f1, f2, f3), Flag.class));
assertEquals(EnumSet.of(f1, f2, f3, f4), EnumUtil.enumSetOf(EnumUtil.bitSetOf(f1, f2, f3, f4), Flag.class));
}
public void testEnumSet() {
int startIdx = ThreadLocalRandom.current().nextInt(FLAGS_CACHED.length - 4);
Flag f1 = FLAGS_CACHED[startIdx];
Flag f2 = FLAGS_CACHED[startIdx + 1];
Flag f3 = FLAGS_CACHED[startIdx + 2];
Flag f4 = FLAGS_CACHED[startIdx + 3];
log.debugf("Flags: %s, %s, %s, %s", f1, f2, f3, f4);
assertBitSet(EnumUtil.setEnum(EnumUtil.bitSetOf(f1), f2), startIdx, 2);
assertBitSet(EnumUtil.setEnums(EnumUtil.bitSetOf(f1), Arrays.asList(f2, f3, f4)), startIdx, 4);
}
public void testEnumUnset() {
int startIdx = ThreadLocalRandom.current().nextInt(FLAGS_CACHED.length - 4);
Flag f1 = FLAGS_CACHED[startIdx];
Flag f2 = FLAGS_CACHED[startIdx + 1];
Flag f3 = FLAGS_CACHED[startIdx + 2];
log.debugf("Flags: %s, %s, %s", f1, f2, f3);
assertBitSet(EnumUtil.unsetEnum(EnumUtil.bitSetOf(f1, f2, f3), f3), startIdx, 2);
}
public void testBitSetOperations() {
int startIdx = ThreadLocalRandom.current().nextInt(FLAGS_CACHED.length - 4);
Flag f1 = FLAGS_CACHED[startIdx];
Flag f2 = FLAGS_CACHED[startIdx + 1];
Flag f3 = FLAGS_CACHED[startIdx + 2];
Flag f4 = FLAGS_CACHED[startIdx + 3];
log.debugf("Flags: %s, %s, %s, %s", f1, f2, f3, f4);
assertBitSet(EnumUtil.mergeBitSets(EnumUtil.bitSetOf(f1), EnumUtil.bitSetOf(f2, f3)), startIdx, 3);
assertBitSet(EnumUtil.diffBitSets(EnumUtil.bitSetOf(f1, f2, f3, f4), EnumUtil.bitSetOf(f4)), startIdx, 3);
assertTrue(EnumUtil.containsAll(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1, f2)));
assertTrue(EnumUtil.containsAll(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1)));
assertFalse(EnumUtil.containsAll(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1, f3)));
assertFalse(EnumUtil.containsAll(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f4)));
assertTrue(EnumUtil.containsAny(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1, f2)));
assertTrue(EnumUtil.containsAny(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1)));
assertTrue(EnumUtil.containsAny(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f1, f3)));
assertFalse(EnumUtil.containsAny(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f3, f4)));
assertFalse(EnumUtil.containsAny(EnumUtil.bitSetOf(f1, f2), EnumUtil.bitSetOf(f3)));
}
private static void assertBitSet(long bitSet, int startIdx, int range) {
IntStream.range(0, startIdx).forEach(idx -> assertNotFlag(bitSet, FLAGS_CACHED[idx]));
IntStream.range(startIdx, startIdx + range).forEach(idx -> assertFlag(bitSet, FLAGS_CACHED[idx]));
IntStream.range(startIdx + range, FLAGS_CACHED.length).forEach(idx -> assertNotFlag(bitSet, FLAGS_CACHED[idx]));
}
private static void assertFlag(long bitset, Flag flag) {
assertTrue("Flag " + flag + " should be in bitset!", EnumUtil.hasEnum(bitset, flag));
}
private static void assertNotFlag(long bitset, Flag flag) {
assertFalse("Flag " + flag + " should not be in bitset!", EnumUtil.hasEnum(bitset, flag));
}
}
| 5,502
| 41.330769
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/context/impl/SingleKeyNonTxInvocationContextTest.java
|
package org.infinispan.context.impl;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.testng.annotations.Test;
/**
* SingleKeyNonTxInvocationContextTest
*
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "context.SingleKeyNonTxInvocationContextTest")
public class SingleKeyNonTxInvocationContextTest extends MultipleCacheManagersTest {
private CheckInterceptor ci0;
private CheckInterceptor ci1;
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder c = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
c.clustering().hash().numOwners(1);
createCluster(c, 2);
waitForClusterToForm();
ci0 = new CheckInterceptor();
advancedCache(0).getAsyncInterceptorChain().addInterceptor(ci0, 1);
ci1 = new CheckInterceptor();
advancedCache(1).getAsyncInterceptorChain().addInterceptor(ci1, 1);
}
public void testPut() {
assert !ci0.putOkay && !ci1.putOkay;
cache(0).put(getKeyForCache(0), "v");
assert ci0.putOkay && !ci1.putOkay;
cache(1).put(getKeyForCache(1), "v");
assert ci0.putOkay && ci1.putOkay;
}
public void testRemove() {
assert !ci0.removeOkay && !ci1.removeOkay;
cache(0).remove(getKeyForCache(0));
assert ci0.removeOkay && !ci1.removeOkay;
cache(1).remove(getKeyForCache(1));
assert ci0.removeOkay && ci1.removeOkay;
}
public void testGet() {
assert !ci0.getOkay && !ci1.getOkay;
cache(0).get(getKeyForCache(0));
assert ci0.getOkay && !ci1.getOkay;
cache(1).get(getKeyForCache(1));
assert ci0.getOkay && ci1.getOkay;
}
public void testReplace() {
assert !ci0.replaceOkay && !ci1.replaceOkay;
cache(0).replace(getKeyForCache(0), "v");
assert ci0.replaceOkay && !ci1.replaceOkay;
cache(1).replace(getKeyForCache(1), "v");
assert ci0.replaceOkay && ci1.replaceOkay;
}
static class CheckInterceptor extends BaseCustomAsyncInterceptor {
private boolean putOkay;
private boolean removeOkay;
private boolean getOkay;
private boolean replaceOkay;
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (isRightType(ctx)) putOkay = true;
return super.visitPutKeyValueCommand(ctx, command);
}
@Override
public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
if (isRightType(ctx)) removeOkay = true;
return super.visitRemoveCommand(ctx, command);
}
@Override
public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
if (isRightType(ctx)) getOkay = true;
return super.visitGetKeyValueCommand(ctx, command);
}
@Override
public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
if (isRightType(ctx)) replaceOkay = true;
return super.visitReplaceCommand(ctx, command);
}
private boolean isRightType(InvocationContext ctx) {
return ctx instanceof SingleKeyNonTxInvocationContext;
}
}
}
| 3,751
| 31.068376
| 113
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/PutMapCommandStressTest.java
|
package org.infinispan.commands;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory;
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.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.transaction.TransactionMode;
import org.testng.annotations.Test;
/**
* Stress test designed to test to verify that get many works properly under constant
* topology changes
*
* @author wburns
* @since 7.2
*/
@Test(groups = "stress", testName = "commands.PutMapCommandStressTest", timeOut = 15*60*1000)
public class PutMapCommandStressTest extends StressTest {
protected final static int NUM_OWNERS = 3;
protected final static int CACHE_COUNT = 6;
protected final static int THREAD_MULTIPLIER = 1;
protected final static int THREAD_WORKER_COUNT = (CACHE_COUNT - 1) * THREAD_MULTIPLIER;
protected final static int CACHE_ENTRY_COUNT = 50000;
protected boolean enableStore;
@Override
public Object[] factory() {
return new Object[]{
new PutMapCommandStressTest().enableStore(false).cacheMode(CacheMode.DIST_SYNC).transactional(false),
new PutMapCommandStressTest().enableStore(false).cacheMode(CacheMode.DIST_SYNC).transactional(true),
new PutMapCommandStressTest().enableStore(true).cacheMode(CacheMode.DIST_SYNC).transactional(false),
new PutMapCommandStressTest().enableStore(true).cacheMode(CacheMode.DIST_SYNC).transactional(true),
};
}
PutMapCommandStressTest enableStore(boolean enableStore) {
this.enableStore = enableStore;
return this;
}
@Override
protected void createCacheManagers() throws Throwable {
builderUsed = new ConfigurationBuilder();
builderUsed.clustering().cacheMode(cacheMode);
builderUsed.clustering().hash().numOwners(NUM_OWNERS);
builderUsed.clustering().stateTransfer().chunkSize(25000);
// This is increased just for the put all command when doing full tracing
builderUsed.clustering().remoteTimeout(12000);
if (transactional) {
builderUsed.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
}
if (enableStore) {
builderUsed.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class)
.shared(true)
.storeName(PutMapCommandStressTest.class.toString());
}
createClusteredCaches(CACHE_COUNT, CACHE_NAME, builderUsed);
}
protected EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags) {
GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder();
// Amend first so we can increase the transport thread pool
TestCacheManagerFactory.amendGlobalConfiguration(gcb, flags);
// we need to increase the transport and remote thread pools to default values
BlockingThreadPoolExecutorFactory executorFactory = new BlockingThreadPoolExecutorFactory(
25, 25, 10000, 30000);
gcb.transport().transportThreadPool().threadPoolFactory(executorFactory);
gcb.transport().remoteCommandThreadPool().threadPoolFactory(executorFactory);
EmbeddedCacheManager cm = TestCacheManagerFactory.newDefaultCacheManager(true, gcb,
new ConfigurationBuilder());
cacheManagers.add(cm);
return cm;
}
public void testStressNodesLeavingWhileMultiplePutMap() throws Throwable {
final Map<Integer, Integer> masterValues = new HashMap<Integer, Integer>();
final Map<Integer, Integer>[] keys = new Map[THREAD_WORKER_COUNT];
for (int i = 0; i < keys.length; ++i) {
keys[i] = new HashMap<>();
}
// First populate our caches
for (int i = 0; i < CACHE_ENTRY_COUNT; ++i) {
masterValues.put(i, i);
keys[i % THREAD_WORKER_COUNT].put(i, i);
}
cache(0, CACHE_NAME).putAll(masterValues);
for (int i = 0; i < keys.length; ++i) {
keys[i] = Collections.unmodifiableMap(keys[i]);
}
List<Future<Void>> futures = forkWorkerThreads(CACHE_NAME, THREAD_MULTIPLIER, CACHE_COUNT, keys, (cache, keysToUse, iteration) -> {
// UNCOMMENT following to test insertions by themselves
// for (Entry<Integer, Integer> entry : keysToUse.entrySet()) {
// cache.put(entry.getKey(), entry.getValue());
// }
cache.getAdvancedCache().putAll(keysToUse);
// UNCOMMENT following to make sure puts are propagated properly
// List<Cache<Integer, Integer>> caches = caches(CACHE_NAME);
// for (int key : keysToUse.keySet()) {
// int hasValue = 0;
// for (Cache<Integer, Integer> cacheCheck : caches) {
// Integer value = cacheCheck.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).get(key);
// if (value != null && value.intValue() == key) {
// hasValue++;
// }
// }
// if (hasValue != NUM_OWNERS) {
// assertEquals("Key was " + key, NUM_OWNERS, hasValue);
// }
// }
});
// TODO: need to figure out code to properly test having a node dying constantly
// Then spawn a thread that just constantly kills the last cache and recreates over and over again
futures.add(forkRestartingThread(CACHE_COUNT));
waitAndFinish(futures, 1, TimeUnit.MINUTES);
}
}
| 5,997
| 42.781022
| 137
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/GetAllCacheNotFoundResponseTest.java
|
package org.infinispan.commands;
import static org.testng.AssertJUnit.assertEquals;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
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.commands.remote.ClusteredGetAllCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.ImmortalCacheValue;
import org.infinispan.container.entries.InternalCacheValue;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.responses.CacheNotFoundResponse;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.responses.UnsureResponse;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.statetransfer.StateTransferLock;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.topology.CacheTopology;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.ControlledRpcManager;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "commands.GetAllCacheNotFoundResponseTest")
public class GetAllCacheNotFoundResponseTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cb = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC);
ControlledConsistentHashFactory.Default chf = new ControlledConsistentHashFactory.Default(
new int[][]{{0, 1}, {0, 2}, {2, 3}});
cb.clustering().hash().numOwners(2).numSegments(3).consistentHashFactory(chf);
createClusteredCaches(5, cb);
}
public void test() throws InterruptedException, ExecutionException, TimeoutException {
ControlledRpcManager crm4 = ControlledRpcManager.replaceRpcManager(cache(4));
crm4.excludeCommands(StateResponseCommand.class);
MagicKey key1 = new MagicKey(cache(0), cache(1));
MagicKey key2 = new MagicKey(cache(0), cache(2));
MagicKey key3 = new MagicKey(cache(2), cache(3));
// We expect the targets of ClusteredGetAllCommands to be selected in a specific way and for that we need
// to iterate through the keys in certain order.
Set<Object> keys = new LinkedHashSet<>(Arrays.asList(key1, key2, key3));
Future<Map<Object, Object>> future = fork(() -> cache(4).getAdvancedCache().getAll(keys));
// Wait until the first two ClusteredGetAllCommands are sent
log.debugf("Expect first get all");
ControlledRpcManager.BlockedRequests round1 =
crm4.expectCommands(ClusteredGetAllCommand.class, address(0), address(2));
// Provide fake responses for the 1st round
round1.skipSendAndReceive(address(0), CacheNotFoundResponse.INSTANCE);
round1.skipSendAndReceiveAsync(address(2), UnsureResponse.INSTANCE);
// Key retries are independent: will retry key1 on cache1, key2 on cache2, and key3 on cache3
log.debugf("Expect 1st retry");
ControlledRpcManager.BlockedRequests round2 =
crm4.expectCommands(ClusteredGetAllCommand.class, address(1), address(2), address(3));
// Provide a response for the retry commands.
// We simulate that key1 is completely lost due to crashing nodes.
round2.skipSendAndReceive(address(1), CacheNotFoundResponse.INSTANCE);
round2.skipSendAndReceive(address(2), SuccessfulResponse.create(new InternalCacheValue[]{new ImmortalCacheValue("value2")}));
round2.skipSendAndReceiveAsync(address(3), SuccessfulResponse.create(new InternalCacheValue[]{new ImmortalCacheValue("value3")}));
// After all the owners are lost, we must wait for a new topology in case the key is still available
crm4.expectNoCommand(10, TimeUnit.MILLISECONDS);
log.debugf("Increment topology and expect 2nd retry");
Future<Void> topologyUpdateFuture = simulateTopologyUpdate(cache(4));
ControlledRpcManager.BlockedRequests round3 =
crm4.expectCommands(ClusteredGetAllCommand.class, address(0));
// Provide a response for the 2nd retry
// Because we only simulated the loss of cache0, the primary owner is the same
round3.skipSendAndReceive(address(0), SuccessfulResponse.create(new InternalCacheValue[]{null}));
log.debugf("Expect final result");
topologyUpdateFuture.get(10, TimeUnit.SECONDS);
Map<Object, Object> values = future.get(10, TimeUnit.SECONDS);
// assertEquals is more verbose than assertNull in case of failure
assertEquals(null, values.get(key1));
assertEquals("value2", values.get(key2));
assertEquals("value3", values.get(key3));
}
private Future<Void> simulateTopologyUpdate(Cache<Object, Object> cache) {
StateTransferLock stl4 = TestingUtil.extractComponent(cache, StateTransferLock.class);
DistributionManager dm4 = cache.getAdvancedCache().getDistributionManager();
LocalizedCacheTopology cacheTopology = dm4.getCacheTopology();
int newTopologyId = cacheTopology.getTopologyId() + 1;
CacheTopology newTopology = new CacheTopology(newTopologyId, cacheTopology.getRebalanceId(),
cacheTopology.getCurrentCH(), cacheTopology.getPendingCH(),
cacheTopology.getUnionCH(),
cacheTopology.getPhase(), cacheTopology.getActualMembers(),
cacheTopology.getMembersPersistentUUIDs());
dm4.setCacheTopology(newTopology);
return fork(() -> stl4.notifyTransactionDataReceived(newTopologyId));
}
}
| 6,033
| 51.929825
| 136
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/GetAllCommandStressTest.java
|
package org.infinispan.commands;
import static org.testng.AssertJUnit.assertEquals;
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.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commons.executors.BlockingThreadPoolExecutorFactory;
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.fwk.InCacheMode;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TransportFlags;
import org.testng.annotations.Test;
/**
* Stress test designed to test to verify that get many works properly under constant
* topology changes
*
* @author wburns
* @since 7.2
*/
@Test(groups = "stress", testName = "commands.GetAllCommandStressTest", timeOut = 15*60*1000)
@InCacheMode({ CacheMode.DIST_SYNC })
public class GetAllCommandStressTest extends StressTest {
protected final String CACHE_NAME = "testCache";
protected final static int CACHE_COUNT = 6;
protected final static int THREAD_MULTIPLIER = 4;
protected final static int CACHE_ENTRY_COUNT = 50000;
@Override
protected void createCacheManagers() throws Throwable {
builderUsed = new ConfigurationBuilder();
builderUsed.clustering().cacheMode(cacheMode);
builderUsed.clustering().stateTransfer().chunkSize(25000);
// Uncomment this line to make it transactional
// builderUsed.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
// This is increased just for the put all command when doing full tracing
builderUsed.clustering().remoteTimeout(30000);
createClusteredCaches(CACHE_COUNT, CACHE_NAME, builderUsed);
}
protected EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags) {
GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder();
// Amend first so we can increase the transport thread pool
TestCacheManagerFactory.amendGlobalConfiguration(gcb, flags);
// we need to increase the transport and remote thread pools to default values
BlockingThreadPoolExecutorFactory executorFactory = new BlockingThreadPoolExecutorFactory(
25, 25, 10000, 30000);
gcb.transport().transportThreadPool().threadPoolFactory(executorFactory);
gcb.transport().remoteCommandThreadPool().threadPoolFactory(executorFactory);
EmbeddedCacheManager cm = TestCacheManagerFactory.newDefaultCacheManager(true, gcb,
new ConfigurationBuilder());
cacheManagers.add(cm);
return cm;
}
public void testStressNodesLeavingWhileMultipleIterators() throws Throwable {
final Map<Integer, Integer> masterValues = new HashMap<Integer, Integer>();
int threadWorkerCount = THREAD_MULTIPLIER * (CACHE_COUNT - 1);
final Set<Integer>[] keys = new Set[threadWorkerCount];
for (int i = 0; i < keys.length; ++i) {
keys[i] = new HashSet<>();
}
// First populate our caches
for (int i = 0; i < CACHE_ENTRY_COUNT; ++i) {
masterValues.put(i, i);
keys[i % threadWorkerCount].add(i);
}
cache(0, CACHE_NAME).putAll(masterValues);
for (int i = 0; i < keys.length; ++i) {
keys[i] = Collections.unmodifiableSet(keys[i]);
}
List<Future<Void>> futures = forkWorkerThreads(CACHE_NAME, THREAD_MULTIPLIER, CACHE_COUNT, keys, this::workerLogic);
// Then spawn a thread that just constantly kills the last cache and recreates over and over again
futures.add(forkRestartingThread(CACHE_COUNT));
waitAndFinish(futures, 1, TimeUnit.MINUTES);
}
protected void workerLogic(Cache<Integer, Integer> cache, Set<Integer> threadKeys, int iteration) {
Map<Integer, Integer> results = cache.getAdvancedCache().getAll(threadKeys);
assertEquals("Missing: " + diff(threadKeys, results.keySet()), threadKeys.size(), results.size());
for (Integer key : threadKeys) {
assertEquals(key, results.get(key));
}
}
private Set<Integer> diff(Set<Integer> superset, Set<Integer> subset) {
Set<Integer> diff = new HashSet<>(superset);
diff.removeAll(subset);
return diff;
}
}
| 4,481
| 39.745455
| 122
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/CommandIdUniquenessTest.java
|
package org.infinispan.commands;
import static org.testng.AssertJUnit.assertNotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.infinispan.commons.util.ClassFinder;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "commands.CommandIdUniquenessTest")
public class CommandIdUniquenessTest extends AbstractInfinispanTest {
public void testCommandIdUniqueness() throws Exception {
List<Class<?>> commands = ClassFinder.isAssignableFrom(ReplicableCommand.class);
SortedMap<Byte, String> cmdIds = new TreeMap<Byte, String>();
for (Class<?> c : commands) {
if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers()) && !LocalCommand.class.isAssignableFrom(c)) {
log.infof("Testing %s", c.getSimpleName());
Constructor<?>[] declaredCtors = c.getDeclaredConstructors();
Constructor<?> constructor = null;
for (Constructor<?> declaredCtor : declaredCtors) {
if (declaredCtor.getParameterCount() == 0) {
constructor = declaredCtor;
constructor.setAccessible(true);
break;
}
}
assertNotNull("Empty constructor not found for " + c.getSimpleName(), constructor);
ReplicableCommand cmd = (ReplicableCommand) constructor.newInstance();
byte b = cmd.getCommandId();
assert b > 0 : "Command " + c.getSimpleName() + " has a command id of " + b + " and does not implement LocalCommand!";
assert !cmdIds.containsKey(b) : "Command ID [" + b + "] is duplicated in " + c.getSimpleName() + " and " + cmdIds.get(b);
cmdIds.put(b, c.getSimpleName());
}
}
}
}
| 1,896
| 42.113636
| 133
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/PutMapCommandTest.java
|
package org.infinispan.commands;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashMap;
import java.util.Map;
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.transaction.TransactionMode;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "commands.PutMapCommandTest")
public class PutMapCommandTest extends MultipleCacheManagersTest {
protected int numberOfKeys = 10;
protected boolean includePersistence;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
dcc.clustering().hash().numOwners(1).l1().disable();
dcc.locking().transaction().transactionMode(TransactionMode.TRANSACTIONAL);
dcc.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class);
createCluster(TestDataSCI.INSTANCE, dcc, 4);
waitForClusterToForm();
}
PutMapCommandTest includePersistence(boolean includePersistence) {
this.includePersistence = includePersistence;
return this;
}
@Override
protected Object[] parameterValues() {
return new Object[] { includePersistence };
}
@Override
protected String[] parameterNames() {
return new String[] {"persistance" };
}
@Override
public Object[] factory() {
return new Object[]{
new PutMapCommandTest().includePersistence(false),
new PutMapCommandTest().includePersistence(true),
};
}
public void testPutOnNonOwner() { //todo [anistor] this does not test putAll !
MagicKey mk = new MagicKey("key", cache(0));
cache(3).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).put(mk, "value");
assert cache(0).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(mk) != null;
assert cache(1).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(mk) == null;
assert cache(2).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(mk) == null;
assert cache(3).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(mk) == null;
}
public void testPutMapCommand() {
for (int i = 0; i < numberOfKeys; ++i) {
assert cache(0).get("key" + i) == null;
assert cache(1).get("key" + i) == null;
assert cache(2).get("key" + i) == null;
assert cache(3).get("key" + i) == null;
}
Map<String, String> map = new HashMap<>();
for (int i = 0; i < numberOfKeys; ++i) {
map.put("key" + i, "value" + i);
}
cache(0).putAll(map);
for (int i = 0; i < numberOfKeys; ++i) {
assertEquals("value" + i, cache(0).get("key" + i));
final int finalI = i;
eventuallyEquals("value" + i, () -> cache(1).get("key" + finalI));
eventuallyEquals("value" + i, () -> cache(2).get("key" + finalI));
eventuallyEquals("value" + i, () -> cache(3).get("key" + finalI));
}
}
}
| 3,315
| 35.43956
| 92
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/PutMapCommandNonTxTest.java
|
package org.infinispan.commands;
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.Collections;
import java.util.concurrent.Future;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.internal.PrivateGlobalConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "commands.PutMapCommandNonTxTest")
@CleanupAfterMethod
public class PutMapCommandNonTxTest extends MultipleCacheManagersTest {
@Override
public Object[] factory() {
return new Object[] {
new PutMapCommandNonTxTest().cacheMode(CacheMode.DIST_SYNC),
new PutMapCommandNonTxTest().cacheMode(CacheMode.DIST_SYNC).useTriangle(false),
};
}
@Override
protected void createCacheManagers() {
GlobalConfigurationBuilder gcb = GlobalConfigurationBuilder.defaultClusteredBuilder();
gcb.serialization().addContextInitializer(TestDataSCI.INSTANCE);
if (useTriangle == Boolean.FALSE) {
gcb.addModule(PrivateGlobalConfigurationBuilder.class).serverMode(true);
}
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(cacheMode, false);
dcc.clustering().hash().numOwners(3).l1().disable();
createCluster(gcb, dcc, 3);
waitForClusterToForm();
}
public void testPutMapCommandSyncOnPrimaryOwner() throws Exception {
testPutMapCommand(true, true);
}
public void testPutMapCommandAsyncOnPrimaryOwner() throws Exception {
testPutMapCommand(false, true);
}
public void testPutMapCommandSyncOnBackupOwner() throws Exception {
testPutMapCommand(true, false);
}
public void testPutMapCommandAsyncOnBackupOwner() throws Exception {
testPutMapCommand(false, false);
}
private void testPutMapCommand(boolean sync, boolean putOnPrimary) throws Exception {
MagicKey key = new MagicKey("key", cache(0));
if (sync) {
cache(putOnPrimary ? 0 : 1).putAll(Collections.singletonMap(key, "value"));
} else {
Future<Void> f = cache(putOnPrimary ? 0 : 1).putAllAsync(Collections.singletonMap(key, "value"));
assertNotNull(f);
assertNull(f.get());
assertTrue(f.isDone());
assertFalse(f.isCancelled());
}
assertEquals("value", cache(0).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(key));
assertEquals("value", cache(1).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(key));
assertEquals("value", cache(2).getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).get(key));
}
}
| 3,149
| 37.414634
| 106
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/GetAllCommandNodeCrashTest.java
|
package org.infinispan.commands;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.replaceComponent;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.commands.remote.ClusteredGetAllCommand;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.commands.statetransfer.StateTransferCancelCommand;
import org.infinispan.commands.statetransfer.StateTransferStartCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.statetransfer.StateConsumer;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CheckPoint;
import org.infinispan.util.ControlledRpcManager;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "commands.GetAllCommandNodeCrashTest")
public class GetAllCommandNodeCrashTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
createClusteredCaches(3, TestDataSCI.INSTANCE, getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC));
}
public void test() throws Exception {
MagicKey key = new MagicKey(cache(0), cache(1));
cache(2).put(key, "value");
CheckPoint checkPoint = new CheckPoint();
ControlledRpcManager rpcManager = ControlledRpcManager.replaceRpcManager(cache(2));
rpcManager.excludeCommands(StateResponseCommand.class, StateTransferStartCommand.class,
StateTransferCancelCommand.class);
StateConsumer stateConsumerSpy = spy(extractComponent(cache(2), StateConsumer.class));
doAnswer(invocation -> {
checkPoint.trigger("topology_update_blocked");
checkPoint.awaitStrict("topology_update_resumed", 10, TimeUnit.SECONDS);
return invocation.callRealMethod();
}).when(stateConsumerSpy).onTopologyUpdate(any(), anyBoolean());
replaceComponent(cache(2), StateConsumer.class, stateConsumerSpy, true);
Future<Map<Object, Object>> f = fork(() -> cache(2).getAdvancedCache().getAll(Collections.singleton(key)));
// Block the request before being sent
ControlledRpcManager.BlockedRequest<?> blockedGetAll = rpcManager.expectCommand(ClusteredGetAllCommand.class);
// it's necessary to stop whole cache manager, not just cache, because otherwise the exception would have
// suspect node defined
cacheManagers.get(0).stop();
checkPoint.awaitStrict("topology_update_blocked", 10, TimeUnit.SECONDS);
// Send the blocked request and wait for the CacheNotFoundResponse
blockedGetAll.send().receiveAll();
// The retry can't be sent at this point
rpcManager.expectNoCommand();
// Resume the topology update
checkPoint.trigger("topology_update_resumed");
// Now the command can be retried, and the operation can finish
rpcManager.expectCommand(ClusteredGetAllCommand.class).send().receiveAll();
try {
Map<Object, Object> map = f.get(10, TimeUnit.SECONDS);
assertNotNull(map);
assertFalse(map.isEmpty());
assertEquals("value", map.get(key));
} finally {
checkPoint.triggerForever("topology_update_resumed");
rpcManager.stopBlocking();
}
}
}
| 3,802
| 42.215909
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/GetAllCommandTest.java
|
package org.infinispan.commands;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
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 org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
/**
* @author Radim Vansa <rvansa@redhat.com>
* @author William Burns
*/
@Test(groups = "functional", testName = "commands.GetAllCommandTest")
public class GetAllCommandTest extends MultipleCacheManagersTest {
private final int numNodes = 4;
private final int numEntries = 100;
@Override
public Object[] factory() {
return new Object[] {
new GetAllCommandTest().transactional(false).cacheMode(CacheMode.DIST_SYNC),
new GetAllCommandTest().transactional(false).cacheMode(CacheMode.REPL_SYNC),
new GetAllCommandTest().transactional(true).cacheMode(CacheMode.DIST_SYNC),
new GetAllCommandTest().transactional(true).cacheMode(CacheMode.REPL_SYNC),
};
}
@Override
protected String parameters() {
return new StringBuilder().append('[')
.append(cacheMode)
.append(", tx=").append(transactional)
.append("]").toString();
}
public void testGetAllKeyNotPresent() {
for (int i = 0; i < numEntries; ++i)
advancedCache(i % numNodes).put("key" + i, "value" + i);
List<Cache<String, String>> caches = caches();
String notPresentString = "not-present";
for (Cache<String, String> cache : caches) {
Map<String, String> result = cache.getAdvancedCache().getAll(Collections.singleton(notPresentString));
assertFalse(result.containsKey(notPresentString));
assertNull(result.get(notPresentString));
}
}
public void testGetAllCacheEntriesKeyNotPresent() {
for (int i = 0; i < numEntries; ++i)
advancedCache(i % numNodes).put("key" + i, "value" + i);
List<Cache<String, String>> caches = caches();
String notPresentString = "not-present";
for (Cache<String, String> cache : caches) {
Map<String, CacheEntry<String, String>> result = cache.getAdvancedCache().getAllCacheEntries(
Collections.singleton(notPresentString));
assertFalse(result.containsKey(notPresentString));
assertNull(result.get(notPresentString));
}
}
public void testGetAllCacheEntriesWithBytes() {
Set<String> keys = new HashSet<>();
for (int i = 0; i < numEntries; ++i) {
String key = "key" + i;
advancedCache(i % numNodes).put(key, new byte[]{(byte) i});
keys.add(key);
}
List<Cache<String, byte[]>> caches = caches();
for (Cache<String, byte[]> cache : caches) {
Map<String, CacheEntry<String, byte[]>> map = cache.getAdvancedCache().getAllCacheEntries(keys);
assertEquals(map.size(), keys.size());
for (int i = 0; i < numEntries; ++i) {
CacheEntry<String, byte[]> entry = map.get("key" + i);
assertEquals(entry.getValue().length, 1);
assertEquals(entry.getValue()[0], i);
}
}
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = getDefaultClusteredCacheConfig(cacheMode, transactional);
if (transactional) {
dcc.transaction().locking().isolationLevel(IsolationLevel.READ_COMMITTED);
}
createCluster(dcc, numNodes);
waitForClusterToForm();
}
public void testGetAll() {
for (int i = 0; i < numEntries; ++i)
advancedCache(i % numNodes).put("key" + i, "value" + i);
for (int i = 0; i < numEntries; ++i)
for (Cache<Object, Object> cache : caches())
assertEquals(cache.get("key" + i), "value" + i);
for (int j = 0; j < 10; ++j) {
Set<Object> mutableKeys = new HashSet<>();
Map<Object, Object> expected = new HashMap<>();
for (int i = j; i < numEntries; i += 10) {
mutableKeys.add("key" + i);
expected.put("key" + i, "value" + i);
}
Set<Object> immutableKeys = Collections.unmodifiableSet(mutableKeys);
for (Cache<Object, Object> cache : caches()) {
Map<Object, Object> result = cache.getAdvancedCache().getAll(immutableKeys);
assertEquals(result, expected);
}
}
}
public void testGetAllCacheEntries() {
for (int i = 0; i < numEntries; ++i)
advancedCache(i % numNodes).put("key" + i, "value" + i);
for (int i = 0; i < numEntries; ++i)
for (Cache<Object, Object> cache : caches())
assertEquals(cache.get("key" + i), "value" + i);
for (int j = 0; j < 10; ++j) {
Set<Object> mutableKeys = new HashSet<>();
Map<Object, Object> expected = new HashMap<>();
for (int i = j; i < numEntries; i += 10) {
mutableKeys.add("key" + i);
expected.put("key" + i, "value" + i);
}
Set<Object> immutableKeys = Collections.unmodifiableSet(mutableKeys);
for (Cache<Object, Object> cache : caches()) {
Map<Object, CacheEntry<Object, Object>> result = cache.getAdvancedCache().getAllCacheEntries(immutableKeys);
expected.forEach((k, v) -> {
CacheEntry<Object, Object> value = result.get(k);
assertNotNull(value);
assertEquals(k, value.getKey());
assertEquals(v, value.getValue());
});
}
}
}
}
| 5,972
| 37.288462
| 120
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/StressTest.java
|
package org.infinispan.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.test.fwk.TransportFlags;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
public abstract class StressTest extends MultipleCacheManagersTest {
protected final String CACHE_NAME = "testCache";
final AtomicBoolean complete = new AtomicBoolean(false);
final BlockingQueue<Throwable> exceptions = new LinkedBlockingDeque<>();
protected ConfigurationBuilder builderUsed;
protected Future<Void> forkRestartingThread(int cacheCount) {
return fork(() -> {
TestResourceTracker.testThreadStarted(StressTest.this.getTestName());
try {
Cache<?, ?> cacheToKill = cache(cacheCount - 1);
while (!complete.get()) {
Thread.sleep(1000);
if (cacheManagers.remove(cacheToKill.getCacheManager())) {
log.trace("Killing cache to force rehash");
cacheToKill.getCacheManager().stop();
List<Cache<Object, Object>> caches = caches(CACHE_NAME);
if (caches.size() > 0) {
TestingUtil.blockUntilViewsReceived(60000, false, caches);
TestingUtil.waitForNoRebalance(caches);
}
} else {
throw new IllegalStateException("Cache Manager " + cacheToKill.getCacheManager() +
" wasn't found for some reason!");
}
log.trace("Adding new cache again to force rehash");
// We should only create one so just make it the next cache manager to kill
EmbeddedCacheManager cm = addClusterEnabledCacheManager(new TransportFlags());
cacheToKill = cm.createCache(CACHE_NAME, builderUsed.build());
log.trace("Added new cache again to force rehash");
}
return null;
} catch (Exception e) {
// Stop all the others as well
complete.set(true);
exceptions.add(e);
throw e;
}
});
}
public void waitAndFinish(List<Future<Void>> futures, int timeout, TimeUnit timeUnit) throws Throwable {
// If this returns means we had an issue
Throwable e = exceptions.poll(timeout, timeUnit);
if (e != null) {
Throwable e2 = e;
do {
log.error("Exception in another thread", e2);
e2 = exceptions.poll();
} while (e2 != null);
throw e;
}
complete.set(true);
// Make sure they all finish properly
for (Future future : futures) {
future.get(1, TimeUnit.MINUTES);
}
}
public <T> List<Future<Void>> forkWorkerThreads(String cacheName, int threadMultiplier, int cacheCount, T[] args, WorkerLogic<T> logic) {
// Now we spawn off CACHE_COUNT of threads. All but one will constantly call getAll() while another
// will constantly be killing and adding new caches
List<Future<Void>> futures = new ArrayList<>(threadMultiplier * (cacheCount - 1) + 1);
for (int j = 0; j < threadMultiplier; ++j) {
// We iterate over all but the last cache since we kill it constantly
for (int i = 0; i < cacheCount - 1; ++i) {
final int offset = j * (cacheCount - 1) + i;
final Cache<Integer, Integer> cache = cache(i, cacheName);
futures.add(fork(() -> {
try {
int iteration = 0;
while (!complete.get()) {
log.tracef("Starting operation %d", iteration);
logic.run(cache, args[offset], iteration);
iteration++;
}
System.out.println(Thread.currentThread() + " finished " + iteration + " iterations!");
} catch (Throwable e) {
log.trace("Failed", e);
// Stop all the others as well
complete.set(true);
exceptions.add(e);
throw e;
}
return null;
}));
}
}
return futures;
}
protected interface WorkerLogic<T> {
void run(Cache<Integer, Integer> cache, T argument, int iteration) throws Exception;
}
}
| 4,868
| 39.239669
| 140
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/module/TestModuleLifecycle.java
|
package org.infinispan.commands.module;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.factories.ComponentFactory;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.InfinispanModule;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentAccessor;
import org.infinispan.factories.impl.DynamicModuleMetadataProvider;
import org.infinispan.factories.impl.ModuleMetadataBuilder;
import org.infinispan.factories.impl.WireContext;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.lifecycle.ModuleLifecycle;
/**
* Allow tests to register global or cache components replacing the default ones.
*
* @author Dan Berindei
* @since 9.4
*/
@InfinispanModule(name = "core-tests", requiredModules = "core", optionalModules = {"cloudevents"})
public final class TestModuleLifecycle implements ModuleLifecycle, DynamicModuleMetadataProvider {
private TestGlobalConfiguration testGlobalConfiguration;
@Override
public void registerDynamicMetadata(ModuleMetadataBuilder.ModuleBuilder moduleBuilder, GlobalConfiguration globalConfiguration) {
testGlobalConfiguration = globalConfiguration.module(TestGlobalConfiguration.class);
if (testGlobalConfiguration != null) {
HashMap<String, String> defaultFactoryNames = new HashMap<>();
List<String> componentNames = new ArrayList<>(testGlobalConfiguration.globalTestComponents().keySet());
List<String> cacheComponentNames = new ArrayList<>(testGlobalConfiguration.cacheTestComponentNames());
for (String componentName : cacheComponentNames) {
defaultFactoryNames.put(componentName, moduleBuilder.getFactoryName(componentName));
}
moduleBuilder.registerComponentAccessor(TestGlobalComponentFactory.class.getName(), componentNames,
new GlobalFactoryComponentAccessor(testGlobalConfiguration));
moduleBuilder.registerComponentAccessor(TestCacheComponentFactory.class.getName(), cacheComponentNames,
new CacheFactoryComponentAccessor(testGlobalConfiguration,
defaultFactoryNames));
}
}
@Override
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) {
if (testGlobalConfiguration == null)
return;
Set<String> componentNames = testGlobalConfiguration.globalTestComponents().keySet();
for (String componentName : componentNames) {
assert testGlobalConfiguration.globalTestComponents().get(componentName) == gcr.getComponent(componentName);
}
}
@Override
public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) {
if (testGlobalConfiguration == null)
return;
if (testGlobalConfiguration.cacheStartCallback() != null) {
testGlobalConfiguration.cacheStartCallback().accept(cr);
}
Map<String, Object> testCacheComponents = testGlobalConfiguration.cacheTestComponents(cacheName);
if (testCacheComponents == null)
return;
Set<String> componentNames = testCacheComponents.keySet();
for (String componentName : componentNames) {
assert testCacheComponents.get(componentName) == cr.getComponent(componentName);
}
}
private static final class TestGlobalComponentFactory implements ComponentFactory {
private final TestGlobalConfiguration testGlobalConfiguration;
TestGlobalComponentFactory(TestGlobalConfiguration testGlobalConfiguration) {
this.testGlobalConfiguration = testGlobalConfiguration;
}
@Override
public Object construct(String componentName) {
return testGlobalConfiguration.globalTestComponents().get(componentName);
}
}
private static final class TestCacheComponentFactory implements ComponentFactory {
private final TestGlobalConfiguration testCacheConfiguration;
private final HashMap<String, String> defaultFactoryNames;
private String cacheName;
private BasicComponentRegistry cacheComponentRegistry;
TestCacheComponentFactory(TestGlobalConfiguration testCacheConfiguration,
HashMap<String, String> defaultFactoryNames) {
this.testCacheConfiguration = testCacheConfiguration;
this.defaultFactoryNames = defaultFactoryNames;
}
@Override
public Object construct(String componentName) {
Map<String, Object> testCacheComponents = testCacheConfiguration.cacheTestComponents(cacheName);
if (testCacheComponents != null) {
Object testComponent = testCacheComponents.get(componentName);
if (testComponent != null)
return testComponent;
}
String defaultFactoryName = defaultFactoryNames.get(componentName);
ComponentFactory defaultFactory =
cacheComponentRegistry.getComponent(defaultFactoryName, ComponentFactory.class).running();
return defaultFactory.construct(componentName);
}
}
private static final class GlobalFactoryComponentAccessor extends ComponentAccessor<TestGlobalComponentFactory> {
private final TestGlobalConfiguration testGlobalConfiguration;
GlobalFactoryComponentAccessor(TestGlobalConfiguration testGlobalConfiguration) {
super(TestGlobalComponentFactory.class.getName(), Scopes.GLOBAL.ordinal(), true, null,
Collections.emptyList());
this.testGlobalConfiguration = testGlobalConfiguration;
}
@Override
protected TestGlobalComponentFactory newInstance() {
return new TestGlobalComponentFactory(testGlobalConfiguration);
}
}
private static final class CacheFactoryComponentAccessor extends ComponentAccessor<TestCacheComponentFactory> {
private final TestGlobalConfiguration testGlobalConfiguration;
private final HashMap<String, String> defaultFactoryNames;
CacheFactoryComponentAccessor(TestGlobalConfiguration testGlobalConfiguration,
HashMap<String, String> defaultFactoryNames) {
super(TestCacheComponentFactory.class.getName(), Scopes.NAMED_CACHE.ordinal(), true, null,
Collections.emptyList());
this.testGlobalConfiguration = testGlobalConfiguration;
this.defaultFactoryNames = defaultFactoryNames;
}
@Override
protected void wire(TestCacheComponentFactory instance, WireContext context, boolean start) {
instance.cacheComponentRegistry = context.get(BasicComponentRegistry.class.getName(),
BasicComponentRegistry.class, false);
instance.cacheName = context.get(KnownComponentNames.CACHE_NAME, String.class, false);
}
@Override
protected TestCacheComponentFactory newInstance() {
return new TestCacheComponentFactory(testGlobalConfiguration, defaultFactoryNames);
}
}
}
| 7,524
| 44.331325
| 132
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/module/TestGlobalConfigurationSerializer.java
|
package org.infinispan.commands.module;
import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.configuration.serializing.ConfigurationSerializer;
/**
* A {@link ConfigurationSerializer} implementation for {@link TestGlobalConfiguration}.
* <p>
* The {@link TestGlobalConfiguration} is only to be used internally so this implementation is a no-op.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class TestGlobalConfigurationSerializer implements ConfigurationSerializer<TestGlobalConfiguration> {
@Override
public void serialize(ConfigurationWriter writer, TestGlobalConfiguration configuration) {
//nothing to do! test configuration is not serialized.
}
}
| 715
| 34.8
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/module/TestModuleCommandExtensions.java
|
package org.infinispan.commands.module;
import java.util.HashMap;
import java.util.Map;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.remoting.rpc.CustomCacheRpcCommand;
import org.infinispan.remoting.rpc.CustomReplicableCommand;
import org.infinispan.remoting.rpc.SleepingCacheRpcCommand;
import org.infinispan.util.ByteString;
import org.kohsuke.MetaInfServices;
/**
* @author anistor@redhat.com
* @since 5.3
*/
@MetaInfServices(ModuleCommandExtensions.class)
public final class TestModuleCommandExtensions implements ModuleCommandExtensions {
@Override
public ModuleCommandFactory getModuleCommandFactory() {
return new ModuleCommandFactory() {
@Override
public Map<Byte, Class<? extends ReplicableCommand>> getModuleCommands() {
Map<Byte, Class<? extends ReplicableCommand>> map = new HashMap<>(2);
map.put(CustomReplicableCommand.COMMAND_ID, CustomReplicableCommand.class);
map.put(CustomCacheRpcCommand.COMMAND_ID, CustomCacheRpcCommand.class);
map.put(SleepingCacheRpcCommand.COMMAND_ID, SleepingCacheRpcCommand.class);
return map;
}
@Override
public ReplicableCommand fromStream(byte commandId) {
ReplicableCommand c;
switch (commandId) {
case CustomReplicableCommand.COMMAND_ID:
c = new CustomReplicableCommand();
break;
default:
throw new IllegalArgumentException("Not registered to handle command id " + commandId);
}
return c;
}
@Override
public CacheRpcCommand fromStream(byte commandId, ByteString cacheName) {
CacheRpcCommand c;
switch (commandId) {
case CustomCacheRpcCommand.COMMAND_ID:
c = new CustomCacheRpcCommand(cacheName);
break;
case SleepingCacheRpcCommand.COMMAND_ID:
c = new SleepingCacheRpcCommand(cacheName);
break;
default:
throw new IllegalArgumentException("Not registered to handle command id " + commandId);
}
return c;
}
};
}
}
| 2,330
| 35.421875
| 105
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/module/TestGlobalConfiguration.java
|
package org.infinispan.commands.module;
import static org.infinispan.commons.configuration.attributes.IdentityAttributeCopier.identityCopier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.infinispan.commons.configuration.BuiltBy;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.serializing.SerializedWith;
import org.infinispan.factories.ComponentRegistry;
/**
* An configuration for tests that want to register global components before the manager is created.
*
* @author Dan Berindei
* @since 9.4
*/
@SerializedWith(TestGlobalConfigurationSerializer.class)
@BuiltBy(TestGlobalConfigurationBuilder.class)
public class TestGlobalConfiguration {
static final AttributeDefinition<Map<String, Object>> GLOBAL_TEST_COMPONENTS =
AttributeDefinition.<Map<String, Object>>builder("globalTestComponents", new HashMap<>())
.initializer(HashMap::new)
.copier(identityCopier()).build();
static final AttributeDefinition<Map<String, Map<String, Object>>> CACHE_TEST_COMPONENTS =
AttributeDefinition.<Map<String, Map<String, Object>>>builder("cacheTestComponents", new HashMap<>())
.initializer(HashMap::new)
.copier(identityCopier()).build();
static final AttributeDefinition<Consumer<ComponentRegistry>> CACHE_STARTING_CALLBACK =
AttributeDefinition.<Consumer<ComponentRegistry>>builder("cacheStartingCallback", cr -> {})
.copier(identityCopier()).build();
private final AttributeSet attributes;
TestGlobalConfiguration(AttributeSet attributeSet) {
this.attributes = attributeSet.checkProtection();
}
static AttributeSet attributeSet() {
return new AttributeSet(TestGlobalConfiguration.class, GLOBAL_TEST_COMPONENTS, CACHE_TEST_COMPONENTS,
CACHE_STARTING_CALLBACK);
}
public AttributeSet attributes() {
return attributes;
}
public Map<String, Object> globalTestComponents() {
return attributes.attribute(GLOBAL_TEST_COMPONENTS).get();
}
public Map<String, Object> cacheTestComponents(String cacheName) {
return attributes.attribute(CACHE_TEST_COMPONENTS).get().get(cacheName);
}
public Set<String> cacheTestComponentNames() {
return attributes.attribute(CACHE_TEST_COMPONENTS).get().values().stream()
.flatMap(m -> m.keySet().stream())
.collect(Collectors.toSet());
}
@Override
public String toString() {
return "TestGlobalConfiguration [attributes=" + attributes + ']';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestGlobalConfiguration that = (TestGlobalConfiguration) o;
return attributes.equals(that.attributes);
}
@Override
public int hashCode() {
return attributes.hashCode();
}
public Consumer<ComponentRegistry> cacheStartCallback() {
return attributes.attribute(CACHE_STARTING_CALLBACK).get();
}
}
| 3,286
| 34.728261
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/commands/module/TestGlobalConfigurationBuilder.java
|
package org.infinispan.commands.module;
import java.util.HashMap;
import java.util.function.Consumer;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.Combine;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.factories.ComponentRegistry;
/**
* A {@link Builder} implementation of {@link TestGlobalConfiguration}.
*
* @author Dan Berindei
* @see TestGlobalConfiguration
* @since 9.4
*/
public class TestGlobalConfigurationBuilder implements Builder<TestGlobalConfiguration> {
private final AttributeSet attributes;
public TestGlobalConfigurationBuilder(GlobalConfigurationBuilder builder) {
this.attributes = TestGlobalConfiguration.attributeSet();
}
@Override
public AttributeSet attributes() {
return attributes;
}
public TestGlobalConfigurationBuilder testGlobalComponent(String componentName, Object instance) {
this.attributes.attribute(TestGlobalConfiguration.GLOBAL_TEST_COMPONENTS).get()
.put(componentName, instance);
return this;
}
public TestGlobalConfigurationBuilder testGlobalComponent(Class<?> componentClass, Object instance) {
return testGlobalComponent(componentClass.getName(), instance);
}
public TestGlobalConfigurationBuilder testCacheComponent(String cacheName, String componentName, Object instance) {
this.attributes.attribute(TestGlobalConfiguration.CACHE_TEST_COMPONENTS).get()
.computeIfAbsent(cacheName, name -> new HashMap<>())
.put(componentName, instance);
return this;
}
public TestGlobalConfigurationBuilder cacheStartingCallback(Consumer<ComponentRegistry> callback) {
this.attributes.attribute(TestGlobalConfiguration.CACHE_STARTING_CALLBACK).set(callback);
return this;
}
@Override
public void validate() {
//nothing
}
@Override
public TestGlobalConfiguration create() {
return new TestGlobalConfiguration(attributes.protect());
}
@Override
public Builder<?> read(TestGlobalConfiguration template, Combine combine) {
this.attributes.read(template.attributes(), combine);
return this;
}
@Override
public String toString() {
return "TestGlobalConfigurationBuilder [attributes=" + attributes + ']';
}
}
| 2,442
| 31.573333
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/OptimisticTxPartitionAndMergeDuringPrepareTest.java
|
package org.infinispan.partitionhandling;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "functional", testName = "partitionhandling.OptimisticTxPartitionAndMergeDuringPrepareTest")
public class OptimisticTxPartitionAndMergeDuringPrepareTest extends BaseOptimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(OptimisticTxPartitionAndMergeDuringPrepareTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, false);
}
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, true);
}
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, false);
}
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, true);
}
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, false);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
switch (splitMode) {
case ORIGINATOR_ISOLATED:
//they assume that the originator has crashed, so the prepare is never processed.
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
break;
case PRIMARY_OWNER_ISOLATED:
//the originator can recover and will retry the prepare command until it succeeds.
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
break;
case BOTH_DEGRADED:
//with the new changes, the rollback succeeds on the originator partition. Cache1 releases the lock.
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
break;
}
//or the prepare is never received, so key never locked, or it is received and it decides to rollback the transaction.
assertEventuallyNotLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
@Override
protected boolean forceRollback() {
return false;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return PrepareCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 2,918
| 35.949367
| 124
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/StreamDistPartitionHandlingTest.java
|
package org.infinispan.partitionhandling;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.infinispan.Cache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.Closeables;
import org.infinispan.context.Flag;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.notifications.cachelistener.cluster.ClusterCacheNotifier;
import org.infinispan.reactive.publisher.impl.ClusterPublisherManager;
import org.infinispan.reactive.publisher.impl.SegmentPublisherSupplier;
import org.infinispan.reactive.publisher.impl.commands.batch.InitialPublisherCommand;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.Mocks;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CheckPoint;
import org.testng.annotations.Test;
/**
* Tests to make sure that distributed stream pays attention to partition status
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "partitionhandling.StreamDistPartitionHandlingTest")
public class StreamDistPartitionHandlingTest extends BasePartitionHandlingTest {
@Test( expectedExceptions = AvailabilityException.class)
public void testRetrievalWhenPartitionIsDegraded() {
Cache<MagicKey, String> cache0 = cache(0);
cache0.put(new MagicKey(cache(1), cache(2)), "not-local");
cache0.put(new MagicKey(cache(0), cache(1)), "local");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
try (CloseableIterator iterator = Closeables.iterator(cache(0).entrySet().stream())) {
iterator.next();
}
}
public void testRetrievalWhenPartitionIsDegradedButLocal() {
Cache<MagicKey, String> cache0 = cache(0);
cache0.put(new MagicKey(cache(1), cache(2)), "not-local");
cache0.put(new MagicKey(cache(0), cache(1)), "local");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
try (CloseableIterator<Map.Entry<MagicKey, String>> iterator = Closeables.iterator(cache0.getAdvancedCache()
.withFlags(Flag.CACHE_MODE_LOCAL).entrySet().stream())) {
assertEquals("local", iterator.next().getValue());
assertFalse(iterator.hasNext());
}
}
@Test(enabled = false)
public void testUsingIterableButPartitionOccursBeforeGettingIterator() throws InterruptedException {
// Repl only checks for partition when first retrieving the entrySet, keySet or values
}
public void testUsingIteratorButPartitionOccursBeforeRetrievingRemoteValues() throws Exception {
Cache<MagicKey, String> cache0 = cache(0);
// Make sure we have 1 entry in each - since onEach will then be invoked once on each node
cache0.put(new MagicKey(cache(1), cache(2)), "not-local");
cache0.put(new MagicKey(cache(0), cache(1)), "local");
CheckPoint iteratorCP = new CheckPoint();
// We let the completeable future be returned - but don't let it process the values yet
iteratorCP.triggerForever(Mocks.BEFORE_RELEASE);
// This must be before the stream is generated or else it won't see the update
registerBlockingRpcManagerOnInitialPublisherCommand(iteratorCP, cache0, testExecutor());
try (CloseableIterator<?> iterator = Closeables.iterator(cache0.entrySet().stream())) {
CheckPoint partitionCP = new CheckPoint();
// Now we replace the notifier so we know when the notifier was told of the partition change so we know
// our iterator should have been notified
registerBlockingCacheNotifierOnDegradedMode(partitionCP, cache0);
// We don't want to block the notifier
partitionCP.triggerForever(Mocks.BEFORE_RELEASE);
partitionCP.triggerForever(Mocks.AFTER_RELEASE);
// Now split the cluster
splitCluster(new int[]{0, 1}, new int[]{2, 3});
// Wait until we have been notified before letting remote responses to arrive
partitionCP.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS);
// Afterwards let all the responses come in
iteratorCP.triggerForever(Mocks.AFTER_RELEASE);
try {
while (iterator.hasNext()) {
iterator.next();
}
fail("Expected AvailabilityException");
} catch (AvailabilityException e) {
// Should go here
}
}
}
public void testUsingIteratorButPartitionOccursAfterRetrievingRemoteValues() throws InterruptedException, TimeoutException, ExecutionException {
Cache<MagicKey, String> cache0 = cache(0);
// Make sure we have 1 entry in each - since onEach will then be invoked once on each node
cache0.put(new MagicKey(cache(1), cache(2)), "not-local");
cache0.put(new MagicKey(cache(0), cache(1)), "local");
CheckPoint iteratorCP = new CheckPoint();
registerBlockingPublisher(iteratorCP, cache0);
// Let the iterator continue without blocking below
iteratorCP.triggerForever(Mocks.BEFORE_RELEASE);
iteratorCP.triggerForever(Mocks.AFTER_RELEASE);
// Just retrieving the iterator will spawn the remote command
try (CloseableIterator<?> iterator = Closeables.iterator(cache0.entrySet().stream())) {
// Make sure we got one value
assertTrue(iterator.hasNext());
iteratorCP.awaitStrict(Mocks.AFTER_INVOCATION, 10, TimeUnit.SECONDS);
CheckPoint partitionCP = new CheckPoint();
// Now we replace the notifier so we know when the notifier was told of the partition change so we know
// our iterator should have been notified
registerBlockingCacheNotifierOnDegradedMode(partitionCP, cache0);
// Now split the cluster
splitCluster(new int[]{0, 1}, new int[]{2, 3});
// Now let the notification occur after all the responses are done
partitionCP.triggerForever(Mocks.BEFORE_RELEASE);
partitionCP.triggerForever(Mocks.AFTER_RELEASE);
// This should complete without issue now
while (iterator.hasNext()) {
iterator.next();
}
}
}
private static <K, V> void registerBlockingCacheNotifierOnDegradedMode(final CheckPoint checkPoint,
Cache<K, V> cache) {
Mocks.blockingMock(checkPoint, CacheNotifier.class, cache,
(stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false)),
ClusterCacheNotifier.class);
}
private static void registerBlockingPublisher(final CheckPoint checkPoint, Cache<?, ?> cache) {
ClusterPublisherManager<Object, String> spy = Mocks.replaceComponentWithSpy(cache, ClusterPublisherManager.class);
doAnswer(invocation -> {
SegmentPublisherSupplier<?> result = (SegmentPublisherSupplier<?>) invocation.callRealMethod();
return Mocks.blockingPublisher(result, checkPoint);
}).when(spy).entryPublisher(any(), any(), any(), anyLong(), any(), anyInt(), any());
}
private static void registerBlockingRpcManagerOnInitialPublisherCommand(final CheckPoint checkPoint, Cache<?, ?> cache, Executor completionExecutor) {
RpcManager realManager = TestingUtil.extractComponent(cache, RpcManager.class);
RpcManager spy = spy(realManager);
doAnswer(invocation -> Mocks.blockingCompletableFuture(() -> {
try {
return (CompletableFuture) invocation.callRealMethod();
} catch (Throwable throwable) {
throw new AssertionError(throwable);
}
}, checkPoint, completionExecutor).call()
).when(spy).invokeCommand(any(Address.class), any(InitialPublisherCommand.class), any(), any());
TestingUtil.replaceComponent(cache, RpcManager.class, spy, true);
}
}
| 8,702
| 43.860825
| 153
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/ThreeWaySplitAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.ThreeWaySplitAndMergeTest")
public class ThreeWaySplitAndMergeTest extends BasePartitionHandlingTest {
private static Log log = LogFactory.getLog(ThreeWaySplitAndMergeTest.class);
@Override
public Object[] factory() {
return new Object[] {
new ThreeWaySplitAndMergeTest().partitionHandling(PartitionHandling.DENY_READ_WRITES),
new ThreeWaySplitAndMergeTest().partitionHandling(PartitionHandling.ALLOW_READS)
};
}
public void testSplitAndMerge1() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 1), new PartitionDescriptor(2), new PartitionDescriptor(3));
}
public void testSplitAndMerge2() throws Exception {
testSplitAndMerge(new PartitionDescriptor(1, 2), new PartitionDescriptor(0), new PartitionDescriptor(3));
}
public void testSplitAndMerge3() throws Exception {
testSplitAndMerge(new PartitionDescriptor(2, 3), new PartitionDescriptor(0), new PartitionDescriptor(1));
}
public void testSplitAndMerge4() throws Exception {
testSplitAndMerge(new PartitionDescriptor(2, 3), new PartitionDescriptor(1), new PartitionDescriptor(0));
}
private void testSplitAndMerge(PartitionDescriptor p0, PartitionDescriptor p1, PartitionDescriptor p2) throws Exception {
Object k0 = new MagicKey("k0", cache(p0.node(0)), cache(p0.node(1)));
cache(0).put(k0, 0);
Object k1 = new MagicKey("k1", cache(p0.node(1)), cache(p1.node(0)));
cache(1).put(k1, 1);
Object k2 = new MagicKey("k2", cache(p1.node(0)), cache(p2.node(0)));
cache(2).put(k2, 2);
Object k3 = new MagicKey(cache(p2.node(0)), cache(p0.node(0)));
cache(3).put(k3, 3);
log.trace("Before split.");
splitCluster(p0.getNodes(), p1.getNodes(), p2.getNodes());
partition(0).assertDegradedMode();
partition(1).assertDegradedMode();
partition(2).assertDegradedMode();
//1. check key visibility in partition 0
partition(0).assertKeyAvailableForRead(k0, 0);
if (partitionHandling == PartitionHandling.DENY_READ_WRITES) {
partition(0).assertKeysNotAvailableForRead(k1, k2, k3);
partition(1).assertKeysNotAvailableForRead(k0, k1, k2, k3);
partition(2).assertKeysNotAvailableForRead(k0, k1, k2, k3);
} else {
partition(0).assertKeyAvailableForRead(k1, 1);
partition(0).assertKeyAvailableForRead(k3, 3);
partition(0).assertKeyNotAvailableForRead(k2);
partition(1).assertKeyAvailableForRead(k1, 1);
partition(1).assertKeyAvailableForRead(k2, 2);
partition(1).assertKeyNotAvailableForRead(k3);
partition(2).assertKeyAvailableForRead(k2, 2);
partition(2).assertKeyAvailableForRead(k3, 3);
partition(2).assertKeyNotAvailableForRead(k1);
}
//4. check key ownership
assertTrue(dataContainer(p0.node(0)).containsKey(k0));
assertFalse(dataContainer(p0.node(0)).containsKey(k1));
assertFalse(dataContainer(p0.node(0)).containsKey(k2));
assertTrue(dataContainer(p0.node(0)).containsKey(k3));
assertTrue(dataContainer(p0.node(1)).containsKey(k0));
assertTrue(dataContainer(p0.node(1)).containsKey(k1));
assertFalse(dataContainer(p0.node(1)).containsKey(k2));
assertFalse(dataContainer(p0.node(1)).containsKey(k3));
assertFalse(dataContainer(p1.node(0)).containsKey(k0));
assertTrue(dataContainer(p1.node(0)).containsKey(k1));
assertTrue(dataContainer(p1.node(0)).containsKey(k2));
assertFalse(dataContainer(p1.node(0)).containsKey(k3));
assertFalse(dataContainer(p2.node(0)).containsKey(k0));
assertFalse(dataContainer(p2.node(0)).containsKey(k1));
assertTrue(dataContainer(p2.node(0)).containsKey(k2));
assertTrue(dataContainer(p2.node(0)).containsKey(k3));
//5. check writes on partition 0
partition(0).assertKeyAvailableForWrite(k0, -1);
partition(1).assertKeysNotAvailableForWrite(k1, k2, k3);
//5. check writes on partition 1
partition(1).assertKeysNotAvailableForWrite(k0, k1, k2, k3);
//6. check writes on partition 2
partition(2).assertKeysNotAvailableForWrite(k0, k1, k2, k3);
log.tracef("Before the 1st merge P0 = %s, P1 = %s, P2 = %s", partition(0), partition(1), partition(2));
assertEquals(partitions.length, 3);
partition(0).merge(partition(1));
assertEquals(partitions.length, 2);
log.tracef("After the 1st merge P0 = %s, P1 = %s", partition(0), partition(1));
partition(0).assertAvailabilityMode(AvailabilityMode.AVAILABLE);
partition(1).assertAvailabilityMode(AvailabilityMode.DEGRADED_MODE);
partition(0).assertKeyAvailableForRead(k0, -1);
partition(0).assertKeyAvailableForRead(k1, 1);
partition(0).assertKeyAvailableForRead(k2, 2);
partition(0).assertKeyAvailableForRead(k3, 3);
partition(0).assertKeyAvailableForWrite(k0, 10);
partition(0).assertKeyAvailableForWrite(k1, 11);
partition(0).assertKeyAvailableForWrite(k2, 12);
partition(0).assertKeyAvailableForWrite(k3, 13);
Set<Address> members = new HashSet<>(Arrays.asList(new Address[]{address(p0.node(0)), address(p0.node(1)), address(p1.node(0))}));
assertEquals(new HashSet<>(advancedCache(p0.node(0)).getDistributionManager().getWriteConsistentHash().getMembers()), members);
assertEquals(new HashSet<>(advancedCache(p0.node(1)).getDistributionManager().getWriteConsistentHash().getMembers()), members);
assertEquals(new HashSet<>(advancedCache(p1.node(0)).getDistributionManager().getWriteConsistentHash().getMembers()), members);
if (partitionHandling == PartitionHandling.DENY_READ_WRITES)
partition(1).assertKeysNotAvailableForRead(k0, k1, k2, k3);
members = new HashSet<>(Arrays.asList(new Address[]{address(0), address(1), address(2), address(3)}));
assertEquals(new HashSet<>(advancedCache(p2.node(0)).getDistributionManager().getWriteConsistentHash().getMembers()), members);
for (int i = 0; i < 100; i++) {
dataContainer(p2.node(0)).put(i, i, null);
}
log.tracef("Before the 2nd merge P0 = %s, P1 = %s", partition(0), partition(1));
partition(0).merge(partition(1));
log.tracef("After 2nd merge P0=%s", partition(0));
assertEquals(partitions.length, 1);
partition(0).assertAvailabilityMode(AvailabilityMode.AVAILABLE);
partition(0).assertKeyAvailableForRead(k0, 10);
partition(0).assertKeyAvailableForRead(k1, 11);
partition(0).assertKeyAvailableForRead(k2, 12);
partition(0).assertKeyAvailableForRead(k3, 13);
for (int i = 0; i < 100; i++) {
partition(0).assertKeyAvailableForRead(i, null);
}
cache(0).put(k0, 10);
cache(1).put(k1, 100);
cache(2).put(k2, 1000);
cache(3).put(k3, 10000);
assertExpectedValue(10, k0);
assertExpectedValue(100, k1);
assertExpectedValue(1000, k2);
assertExpectedValue(10000, k3);
}
}
| 7,557
| 40.988889
| 136
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/NumOwnersNodeStopInSequenceTest.java
|
package org.infinispan.partitionhandling;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
/**
* With a cluster made out of nodes {A,B,C,D}, tests that D stops gracefully and before the state transfer finishes,
* another node C also stops. {A,B} should enter degraded mode.
* The only way in which it could recover is explicitly, through JMX operations.
*/
@Test(groups = "functional", testName = "partitionhandling.NumOwnersNodeStopInSequenceTest")
public class NumOwnersNodeStopInSequenceTest extends NumOwnersNodeCrashInSequenceTest {
@Override
protected void crashCacheManagers(EmbeddedCacheManager... cacheManagers) {
TestingUtil.killCacheManagers(cacheManagers);
}
}
| 774
| 37.75
| 116
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/ForceWriteLockDegradedPartitionTest.java
|
package org.infinispan.partitionhandling;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.ForceWriteLockDegradedPartitionTest")
public class ForceWriteLockDegradedPartitionTest extends BasePartitionHandlingTest {
@Override
public Object[] factory() {
return new Object[] {
new ForceWriteLockDegradedPartitionTest().partitionHandling(PartitionHandling.ALLOW_READS),
new ForceWriteLockDegradedPartitionTest().partitionHandling(PartitionHandling.DENY_READ_WRITES)
};
}
public ForceWriteLockDegradedPartitionTest() {
numberOfOwners = 2;
numMembersInCluster = 2;
}
public void testGetWithForceWriteLock() {
PartitionDescriptor p0 = new PartitionDescriptor(0);
PartitionDescriptor p1 = new PartitionDescriptor(1);
String key = "key";
cache(0).put(key, 0);
splitCluster(p0, p1);
partition(0).assertDegradedMode();
partition(0).assertExceptionWithForceLock(key);
partition(1).assertDegradedMode();
partition(1).assertExceptionWithForceLock(key);
}
}
| 1,116
| 33.90625
| 107
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PreferConsistencyStrategyTest.java
|
package org.infinispan.partitionhandling;
import static org.mockito.Mockito.mock;
import java.util.Collections;
import java.util.Optional;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.partitionhandling.impl.PreferConsistencyStrategy;
import org.infinispan.statetransfer.RebalanceType;
import org.infinispan.topology.ClusterCacheStatus;
import org.infinispan.topology.ClusterTopologyManagerImpl;
import org.infinispan.topology.PersistentUUIDManager;
import org.infinispan.topology.PersistentUUIDManagerImpl;
import org.infinispan.topology.RebalancingStatus;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.util.logging.events.TestingEventLogManager;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "partitionhandling.PreferConsistencyStrategyTest")
public class PreferConsistencyStrategyTest {
private PreferConsistencyStrategy preferConsistencyStrategy;
private ClusterCacheStatus status;
@BeforeMethod
public void beforeMethod() {
EventLogManager eventLogManager = new TestingEventLogManager();
PersistentUUIDManager persistentUUIDManager = new PersistentUUIDManagerImpl();
ClusterTopologyManagerImpl topologyManager = new ClusterTopologyManagerImpl();
EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class);
preferConsistencyStrategy = new PreferConsistencyStrategy(eventLogManager, persistentUUIDManager, null);
status = new ClusterCacheStatus(cacheManager, null, "does-not-matter", preferConsistencyStrategy, RebalanceType.FOUR_PHASE, topologyManager,
null, persistentUUIDManager, eventLogManager, Optional.empty(), false);
}
public void testAvoidingNullPointerExceptionWhenUpdatingPartitionWithNullTopology() {
//when
preferConsistencyStrategy.onPartitionMerge(status, Collections.emptyMap());
//then
Assert.assertNull(status.getCurrentTopology());
Assert.assertNull(status.getStableTopology());
Assert.assertEquals(AvailabilityMode.AVAILABLE, status.getAvailabilityMode());
Assert.assertEquals(RebalancingStatus.COMPLETE, status.getRebalancingStatus());
}
}
| 2,280
| 42.037736
| 146
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/BaseOptimisticTxPartitionAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertEquals;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import javax.transaction.xa.XAException;
import org.infinispan.Cache;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
public abstract class BaseOptimisticTxPartitionAndMergeTest extends BaseTxPartitionAndMergeTest {
static final String OPTIMISTIC_TX_CACHE_NAME = "opt-cache";
@Override
protected void createCacheManagers() throws Throwable {
super.createCacheManagers();
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC);
builder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES);
builder.transaction().lockingMode(LockingMode.OPTIMISTIC).transactionMode(TransactionMode.TRANSACTIONAL).transactionManagerLookup(new EmbeddedTransactionManagerLookup());
defineConfigurationOnAllManagers(OPTIMISTIC_TX_CACHE_NAME, builder);
}
protected abstract void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard);
protected abstract boolean forceRollback();
protected abstract Class<? extends TransactionBoundaryCommand> getCommandClass();
protected void doTest(final SplitMode splitMode, boolean txFail, boolean discard) throws Exception {
waitForClusterToForm(OPTIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(OPTIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, OPTIMISTIC_TX_CACHE_NAME);
final FilterCollection filterCollection = createFilters(OPTIMISTIC_TX_CACHE_NAME, discard, getCommandClass(), splitMode);
Future<Integer> put = fork(() -> {
final EmbeddedTransactionManager transactionManager = (EmbeddedTransactionManager) originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
keyInfo.putFinalValue(originator);
final EmbeddedTransaction transaction = transactionManager.getTransaction();
transaction.runPrepare();
transaction.runCommit(forceRollback());
return transaction.getStatus();
});
filterCollection.await(30, TimeUnit.SECONDS);
splitMode.split(this);
filterCollection.unblock();
try {
Integer txStatus = put.get(10, TimeUnit.SECONDS);
assertEquals(txFail ? Status.STATUS_ROLLEDBACK : Status.STATUS_COMMITTED, (int) txStatus);
} catch (ExecutionException e) {
if (txFail) {
Exceptions.assertException(ExecutionException.class, RollbackException.class, XAException.class, AvailabilityException.class, e);
} else {
throw e;
}
}
checkLocksDuringPartition(splitMode, keyInfo, discard);
filterCollection.stopDiscard();
mergeCluster(OPTIMISTIC_TX_CACHE_NAME);
finalAsserts(OPTIMISTIC_TX_CACHE_NAME, keyInfo, txFail ? INITIAL_VALUE : FINAL_VALUE);
}
}
| 3,701
| 41.551724
| 176
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PartitionHappeningTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.test.fwk.InCacheMode;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.PartitionHappeningTest")
@InCacheMode({CacheMode.DIST_SYNC })
public class PartitionHappeningTest extends BasePartitionHandlingTest {
public PartitionHappeningTest() {
partitionHandling = PartitionHandling.ALLOW_READ_WRITES;
}
public void testPartitionHappening() throws Throwable {
final List<ViewChangedHandler> listeners = new ArrayList<>();
for (int i = 0; i < caches().size(); i++) {
ViewChangedHandler listener = new ViewChangedHandler();
cache(i).getCacheManager().addListener(listener);
listeners.add(listener);
}
splitCluster(new int[]{0, 1}, new int[]{2, 3});
eventually(() -> {
for (ViewChangedHandler l : listeners)
if (!l.isNotified()) return false;
return true;
});
eventuallyEquals(2, () -> advancedCache(0).getRpcManager().getTransport().getMembers().size());
eventually(() -> clusterAndChFormed(0, 2));
eventually(() -> clusterAndChFormed(1, 2));
eventually(() -> clusterAndChFormed(2, 2));
eventually(() -> clusterAndChFormed(3, 2));
cache(0).put("k", "v1");
cache(2).put("k", "v2");
assertEquals(cache(0).get("k"), "v1");
assertEquals(cache(1).get("k"), "v1");
assertEquals(cache(2).get("k"), "v2");
assertEquals(cache(3).get("k"), "v2");
partition(0).merge(partition(1));
assertTrue(clusterAndChFormed(0, 4));
assertTrue(clusterAndChFormed(1, 4));
assertTrue(clusterAndChFormed(2, 4));
assertTrue(clusterAndChFormed(3, 4));
}
public boolean clusterAndChFormed(int cacheIndex, int memberCount) {
return advancedCache(cacheIndex).getRpcManager().getTransport().getMembers().size() == memberCount &&
advancedCache(cacheIndex).getDistributionManager().getWriteConsistentHash().getMembers().size() == memberCount;
}
}
| 2,265
| 33.333333
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/OptimisticTxPartitionAndMergeDuringCommitTest.java
|
package org.infinispan.partitionhandling;
import org.infinispan.Cache;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = {"functional", "unstable"}, testName = "partitionhandling.OptimisticTxPartitionAndMergeDuringCommitTest", description = "ISPN-8232")
public class OptimisticTxPartitionAndMergeDuringCommitTest extends BaseOptimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(OptimisticTxPartitionAndMergeDuringCommitTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, false, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, false, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, false, true);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, false, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, true);
}
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, false);
}
public void testSplitBeforeCommit() throws Exception {
//the transaction is successfully prepare and then the split happens before the commit phase starts.
waitForClusterToForm(OPTIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(OPTIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, OPTIMISTIC_TX_CACHE_NAME);
final EmbeddedTransactionManager transactionManager = (EmbeddedTransactionManager) originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
final EmbeddedTransaction transaction = transactionManager.getTransaction();
keyInfo.putFinalValue(originator);
AssertJUnit.assertTrue(transaction.runPrepare());
transactionManager.suspend();
SplitMode.BOTH_DEGRADED.split(this);
transactionManager.resume(transaction);
transaction.runCommit(false);
assertLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
mergeCluster(OPTIMISTIC_TX_CACHE_NAME);
finalAsserts(OPTIMISTIC_TX_CACHE_NAME, keyInfo, FINAL_VALUE);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
if (splitMode == SplitMode.PRIMARY_OWNER_ISOLATED) {
//the majority partition, all the nodes involved commit the transaction
//the locks should be released (async) in all the nodes
assertEventuallyNotLocked(cache(0, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(0, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
assertEventuallyNotLocked(cache(3, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(3, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
} else {
//on both caches, the key is locked and it is unlocked after the merge
assertLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
}
@Override
protected boolean forceRollback() {
return false;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return CommitCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 4,591
| 41.12844
| 147
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/TwoWaySplitAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.HashSet;
import java.util.List;
import java.util.stream.IntStream;
import org.infinispan.distribution.MagicKey;
import org.infinispan.remoting.transport.Address;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.TwoWaySplitAndMergeTest")
public class TwoWaySplitAndMergeTest extends BasePartitionHandlingTest {
@Override
public Object[] factory() {
return new Object[] {
new TwoWaySplitAndMergeTest().partitionHandling(PartitionHandling.DENY_READ_WRITES),
new TwoWaySplitAndMergeTest().partitionHandling(PartitionHandling.ALLOW_READS)
};
}
public void testSplitAndMerge0() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 1), new PartitionDescriptor(2, 3));
}
public void testSplitAndMerge1() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 2), new PartitionDescriptor(1, 3));
}
public void testSplitAndMerge2() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 3), new PartitionDescriptor(1, 2));
}
public void testSplitAndMerge3() throws Exception {
testSplitAndMerge(new PartitionDescriptor(1, 2), new PartitionDescriptor(0, 3));
}
public void testSplitAndMerge4() throws Exception {
testSplitAndMerge(new PartitionDescriptor(1, 3), new PartitionDescriptor(0, 2));
}
public void testSplitAndMerge5() throws Exception {
testSplitAndMerge(new PartitionDescriptor(2, 3), new PartitionDescriptor(0, 1));
}
private void testSplitAndMerge(PartitionDescriptor p0, PartitionDescriptor p1) throws Exception {
Object k0 = new MagicKey(cache(p0.node(0)), cache(p0.node(1)));
cache(0).put(k0, 0);
Object k1 = new MagicKey(cache(p0.node(1)), cache(p1.node(0)));
cache(1).put(k1, 1);
Object k2 = new MagicKey(cache(p1.node(0)), cache(p1.node(1)));
cache(2).put(k2, 2);
Object k3 = new MagicKey(cache(p1.node(1)), cache(p0.node(0)));
cache(3).put(k3, 3);
List<Address> allMembers = advancedCache(0).getRpcManager().getMembers();
//use set comparison as the merge view will reshuffle the order of nodes
assertEquals(new HashSet<>(partitionHandlingManager(0).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(1).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(2).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(3).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
eventually(() -> {
for (int i = 0; i < numMembersInCluster; i++) {
if (partitionHandlingManager(i).getAvailabilityMode() != AvailabilityMode.AVAILABLE) {
return false;
}
}
return true;
});
splitCluster(p0.getNodes(), p1.getNodes());
partition(0).assertDegradedMode();
partition(1).assertDegradedMode();
assertEquals(partitionHandlingManager(0).getLastStableTopology().getMembers(), allMembers);
assertEquals(partitionHandlingManager(1).getLastStableTopology().getMembers(), allMembers);
assertEquals(partitionHandlingManager(2).getLastStableTopology().getMembers(), allMembers);
assertEquals(partitionHandlingManager(3).getLastStableTopology().getMembers(), allMembers);
partition(0).assertKeyAvailableForRead(k0, 0);
partition(1).assertKeyAvailableForRead(k2, 2);
if (partitionHandling == PartitionHandling.DENY_READ_WRITES) {
partition(0).assertKeysNotAvailableForRead(k1, k2, k3);
partition(1).assertKeysNotAvailableForRead(k0, k1, k3);
} else {
IntStream.range(0, 2).forEach(i -> {
partition(i).assertKeyAvailableForRead(k1, 1);
partition(i).assertKeyAvailableForRead(k3, 3);
});
partition(0).assertKeyNotAvailableForRead(k2);
partition(1).assertKeyNotAvailableForRead(k0);
}
//3. check key ownership
assertTrue(dataContainer(p0.node(0)).containsKey(k0));
assertFalse(dataContainer(p0.node(0)).containsKey(k1));
assertFalse(dataContainer(p0.node(0)).containsKey(k2));
assertTrue(dataContainer(p0.node(0)).containsKey(k3));
assertTrue(dataContainer(p0.node(1)).containsKey(k0));
assertTrue(dataContainer(p0.node(1)).containsKey(k1));
assertFalse(dataContainer(p0.node(1)).containsKey(k2));
assertFalse(dataContainer(p0.node(1)).containsKey(k3));
assertFalse(dataContainer(p1.node(0)).containsKey(k0));
assertTrue(dataContainer(p1.node(0)).containsKey(k1));
assertTrue(dataContainer(p1.node(0)).containsKey(k2));
assertFalse(dataContainer(p1.node(0)).containsKey(k3));
assertFalse(dataContainer(p1.node(1)).containsKey(k0));
assertFalse(dataContainer(p1.node(1)).containsKey(k1));
assertTrue(dataContainer(p1.node(1)).containsKey(k2));
assertTrue(dataContainer(p1.node(1)).containsKey(k3));
//4. check writes on partition one
partition(0).assertKeyAvailableForWrite(k0, -1);
partition(0).assertKeyNotAvailableForWrite(k1);
partition(0).assertKeyNotAvailableForWrite(k2);
partition(0).assertKeyNotAvailableForWrite(k3);
//5. check writes on partition two
partition(1).assertKeyAvailableForWrite(k2, -1);
partition(1).assertKeyNotAvailableForWrite(k0);
partition(1).assertKeyNotAvailableForWrite(k1);
partition(1).assertKeyNotAvailableForWrite(k3);
partition(0).merge(partition(1));
//use set comparison as the merge view will reshuffle the order of nodes
assertEquals(new HashSet<>(partitionHandlingManager(0).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(1).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(2).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
assertEquals(new HashSet<>(partitionHandlingManager(3).getLastStableTopology().getMembers()), new HashSet<>(allMembers));
partition(0).assertAvailabilityMode(AvailabilityMode.AVAILABLE);
// 4. check data seen correctly
assertExpectedValue(-1, k0);
assertExpectedValue(1, k1);
assertExpectedValue(-1, k2);
assertExpectedValue(3, k3);
//5. recheck key ownership
assertTrue(dataContainer(p0.node(0)).containsKey(k0));
assertFalse(dataContainer(p0.node(0)).containsKey(k1));
assertFalse(dataContainer(p0.node(0)).containsKey(k2));
assertTrue(dataContainer(p0.node(0)).containsKey(k3));
assertTrue(dataContainer(p0.node(1)).containsKey(k0));
assertTrue(dataContainer(p0.node(1)).containsKey(k1));
assertFalse(dataContainer(p0.node(1)).containsKey(k2));
assertFalse(dataContainer(p0.node(1)).containsKey(k3));
assertFalse(dataContainer(p1.node(0)).containsKey(k0));
assertTrue(dataContainer(p1.node(0)).containsKey(k1));
assertTrue(dataContainer(p1.node(0)).containsKey(k2));
assertFalse(dataContainer(p1.node(0)).containsKey(k3));
assertFalse(dataContainer(p1.node(1)).containsKey(k0));
assertFalse(dataContainer(p1.node(1)).containsKey(k1));
assertTrue(dataContainer(p1.node(1)).containsKey(k2));
assertTrue(dataContainer(p1.node(1)).containsKey(k3));
cache(0).put(k0, 10);
cache(1).put(k1, 100);
cache(2).put(k2, 1000);
cache(3).put(k3, 10000);
assertExpectedValue(10, k0);
assertExpectedValue(100, k1);
assertExpectedValue(1000, k2);
assertExpectedValue(10000, k3);
}
}
| 8,009
| 42.297297
| 127
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/StreamReplPartitionHandlingTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import java.util.Map;
import org.infinispan.Cache;
import org.infinispan.commons.util.CloseableIterator;
import org.infinispan.commons.util.Closeables;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.context.Flag;
import org.infinispan.distribution.MagicKey;
import org.testng.annotations.Test;
/**
* Tests to make sure that replicated stream pays attention to partition status
*
* @author wburns
* @since 7.0
*/
@Test(groups = "functional", testName = "partitionhandling.StreamReplPartitionHandlingTest")
public class StreamReplPartitionHandlingTest extends StreamDistPartitionHandlingTest {
public StreamReplPartitionHandlingTest() {
cacheMode = CacheMode.REPL_SYNC;
}
@Test(enabled = false)
@Override
public void testUsingIteratorButPartitionOccursBeforeRetrievingRemoteValues() throws InterruptedException {
// This test is disabled since we don't remotely retrieve values
}
@Test(enabled = false)
@Override
public void testUsingIteratorButPartitionOccursAfterRetrievingRemoteValues() throws InterruptedException {
// This test is disabled since we don't remotely retrieve values
}
@Override
public void testRetrievalWhenPartitionIsDegradedButLocal() {
Cache<MagicKey, String> cache0 = cache(0);
cache0.put(new MagicKey(cache(1), cache(2)), "not-local");
cache0.put(new MagicKey(cache(0), cache(1)), "local");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
try (CloseableIterator<Map.Entry<MagicKey, String>> iterator = Closeables.iterator(cache0.getAdvancedCache()
.withFlags(Flag.CACHE_MODE_LOCAL).entrySet().stream())) {
assertNotNull(iterator.next());
assertNotNull(iterator.next());
assertFalse(iterator.hasNext());
}
}
}
| 1,993
| 33.37931
| 114
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/LockPartitionHandlingTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.test.TestingUtil.waitForNoRebalance;
import static org.testng.AssertJUnit.assertTrue;
import java.util.stream.Stream;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.distribution.MagicKey;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.LockPartitionHandlingTest")
public class LockPartitionHandlingTest extends BasePartitionHandlingTest {
public LockPartitionHandlingTest() {
super();
transactional = true;
lockingMode = LockingMode.PESSIMISTIC;
}
public void testLockWhenDegraded() throws Exception {
Cache<MagicKey, String> c0 = cache(0);
MagicKey key = new MagicKey("key1", cache(1), cache(2));
c0.put(key, "value");
c0.put(new MagicKey("key2", cache(2), cache(0)), "value");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
TransactionManager tm = c0.getAdvancedCache().getTransactionManager();
tm.begin();
Exceptions.expectException(AvailabilityException.class, () -> c0.getAdvancedCache().lock(key));
tm.rollback();
}
public void testLockSucceedWhenLocal() throws Exception {
Cache<MagicKey, String> c0 = cache(0);
MagicKey key = new MagicKey("key1", c0, cache(1));
c0.put(key, "value");
c0.put(new MagicKey("key2", cache(2), cache(0)), "value");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
TransactionManager tm = c0.getAdvancedCache().getTransactionManager();
tm.begin();
assertTrue(c0.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).lock(key));
tm.rollback();
}
public void testLockSucceedWhenAllMembersInPartition() throws Exception {
Cache<MagicKey, String> c0 = cache(0);
Cache<MagicKey, String> c1 = cache(1);
MagicKey local = new MagicKey("key1", c0, c1);
MagicKey remote = new MagicKey("key2", cache(2), cache(3));
c0.put(local, "value");
c0.put(remote, "value");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
TransactionManager tm = c0.getAdvancedCache().getTransactionManager();
tm.begin();
assertTrue(c1.getAdvancedCache().lock(local));
// Can not reach remote key.
Exceptions.expectException(AvailabilityException.class, () -> c0.getAdvancedCache().lock(remote));
Exceptions.expectException(AvailabilityException.class, () -> c1.getAdvancedCache().lock(remote));
tm.rollback();
}
public void testLockWhenSplitThenMerge() throws Exception {
Cache<MagicKey, String> c0 = cache(0);
MagicKey key1 = new MagicKey("key1", cache(1), cache(2));
MagicKey key2 = new MagicKey("key2", cache(2), cache(0));
c0.put(key1, "value");
c0.put(key2, "value");
splitCluster(new int[]{0, 1}, new int[]{2, 3});
partition(0).assertDegradedMode();
TransactionManager tm = c0.getAdvancedCache().getTransactionManager();
tm.begin();
Exceptions.expectException(AvailabilityException.class, () -> c0.getAdvancedCache().lock(key1));
Exceptions.expectException(AvailabilityException.class, () -> c0.getAdvancedCache().lock(key2));
tm.rollback();
mergeCluster();
tm.begin();
assertTrue(c0.getAdvancedCache().lock(key1));
tm.rollback();
}
void mergeCluster() {
partition(0).merge(partition(1));
waitForNoRebalance(caches());
for (int i = 0; i < numMembersInCluster; i++) {
PartitionHandlingManager phmI = partitionHandlingManager(cache(i));
eventuallyEquals(AvailabilityMode.AVAILABLE, phmI::getAvailabilityMode);
}
}
@Override
protected void customizeCacheConfiguration(ConfigurationBuilder dcc) {
dcc.transaction().lockingMode(lockingMode)
.cacheStopTimeout(0)
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
}
@Override
protected ConfigurationBuilder cacheConfiguration() {
return getDefaultClusteredCacheConfig(cacheMode, transactional);
}
@Override
public Object[] factory() {
return Stream.of(PartitionHandling.values())
.filter(ph -> ph != PartitionHandling.ALLOW_READ_WRITES)
.map(ph -> new LockPartitionHandlingTest().partitionHandling(ph))
.toArray();
}
}
| 4,795
| 35.06015
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/BasePartitionHandlingTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.commons.test.Exceptions.expectException;
import static org.infinispan.test.TestingUtil.blockUntilViewsReceived;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractJChannel;
import static org.infinispan.test.TestingUtil.waitForNoRebalance;
import static org.testng.Assert.assertEquals;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.test.Exceptions;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.conflict.EntryMergePolicy;
import org.infinispan.context.Flag;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.MergeView;
import org.jgroups.View;
import org.jgroups.protocols.DISCARD;
import org.jgroups.protocols.Discovery;
import org.jgroups.protocols.TP;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.STABLE;
import org.jgroups.stack.Protocol;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.MutableDigest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.BasePartitionHandlingTest")
public class BasePartitionHandlingTest extends MultipleCacheManagersTest {
protected static Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final AtomicInteger viewId = new AtomicInteger(5);
protected int numMembersInCluster = 4;
protected int numberOfOwners = 2;
protected volatile Partition[] partitions;
protected PartitionHandling partitionHandling = PartitionHandling.DENY_READ_WRITES;
protected EntryMergePolicy<String, String> mergePolicy = null;
public BasePartitionHandlingTest() {
this.cacheMode = CacheMode.DIST_SYNC;
this.cleanup = CleanupPhase.AFTER_METHOD;
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = cacheConfiguration();
partitionHandlingBuilder(dcc);
customizeCacheConfiguration(dcc);
createClusteredCaches(numMembersInCluster, serializationContextInitializer(), dcc,
new TransportFlags().withFD(true).withMerge(true));
waitForClusterToForm();
}
protected String customCacheName() {
return null;
}
protected void customizeCacheConfiguration(ConfigurationBuilder dcc) {
}
protected void partitionHandlingBuilder(ConfigurationBuilder dcc) {
dcc.clustering().cacheMode(cacheMode).partitionHandling().whenSplit(partitionHandling).mergePolicy(mergePolicy);
if (cacheMode == CacheMode.DIST_SYNC) {
dcc.clustering().hash().numOwners(numberOfOwners);
}
if (lockingMode != null) {
dcc.transaction().lockingMode(lockingMode);
}
}
@AfterMethod(alwaysRun = true)
public void enableDiscovery() {
for (EmbeddedCacheManager manager : managers()) {
if (manager.getStatus().allowInvocations()) {
enableDiscoveryProtocol(channel(manager));
}
}
}
protected SerializationContextInitializer serializationContextInitializer() {
return TestDataSCI.INSTANCE;
}
protected BasePartitionHandlingTest partitionHandling(PartitionHandling partitionHandling) {
this.partitionHandling = partitionHandling;
return this;
}
protected String[] parameterNames() {
return new String[]{ null, "tx", "locking", "isolation", "triangle", null };
}
protected Object[] parameterValues() {
return new Object[]{ cacheMode, transactional, lockingMode, isolationLevel, useTriangle, partitionHandling};
}
protected ConfigurationBuilder cacheConfiguration() {
return new ConfigurationBuilder();
}
@Listener
public static class ViewChangedHandler {
private volatile boolean notified = false;
public boolean isNotified() {
return notified;
}
public void setNotified(boolean notified) {
this.notified = notified;
}
@ViewChanged
public void viewChanged(ViewChangedEvent vce) {
notified = true;
}
}
public static class PartitionDescriptor {
int[] nodes;
AvailabilityMode expectedMode;
public PartitionDescriptor(int... nodes) {
this(null, nodes);
}
public PartitionDescriptor(AvailabilityMode expectedMode, int... nodes) {
this.expectedMode = expectedMode;
this.nodes = nodes;
}
public int[] getNodes() {
return nodes;
}
public int node(int i) {
return nodes[i];
}
public void assertAvailabilityMode(Partition partition) {
partition.assertAvailabilityMode(expectedMode);
}
public AvailabilityMode getExpectedMode() {
return expectedMode;
}
@Override
public String toString() {
return Arrays.toString(nodes);
}
}
protected void disableDiscoveryProtocol(JChannel c) {
((Discovery)c.getProtocolStack().findProtocol(Discovery.class)).setClusterName(c.getAddressAsString());
}
protected void enableDiscoveryProtocol(JChannel c) {
try {
String defaultClusterName = TestResourceTracker.getCurrentTestName();
((Discovery) c.getProtocolStack().findProtocol(Discovery.class)).setClusterName(defaultClusterName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public class Partition {
private final List<Address> allMembers;
List<JChannel> channels = new ArrayList<>();
public Partition(List<Address> allMembers) {
this.allMembers = allMembers;
}
public void addNode(JChannel c) {
channels.add(c);
}
public void partition() {
log.trace("Partition forming");
disableDiscovery();
installNewView();
assertPartitionFormed();
log.trace("New views installed");
}
private void disableDiscovery() {
channels.forEach(BasePartitionHandlingTest.this::disableDiscoveryProtocol);
}
private void assertPartitionFormed() {
final List<Address> viewMembers = new ArrayList<>();
for (JChannel ac : channels) viewMembers.add(ac.getAddress());
for (JChannel c : channels) {
List<Address> members = c.getView().getMembers();
if (!members.equals(viewMembers)) throw new AssertionError();
}
}
private List<Address> installNewView() {
final List<Address> viewMembers = new ArrayList<>();
for (JChannel c : channels) viewMembers.add(c.getAddress());
View view = View.create(channels.get(0).getAddress(), viewId.incrementAndGet(),
viewMembers.toArray(new Address[0]));
log.trace("Before installing new view...");
for (JChannel c : channels) {
getGms(c).installView(view);
}
return viewMembers;
}
private List<Address> installMergeView(ArrayList<JChannel> view1, ArrayList<JChannel> view2) {
List<Address> allAddresses =
Stream.concat(view1.stream(), view2.stream()).map(JChannel::getAddress).distinct()
.collect(Collectors.toList());
View v1 = toView(view1);
View v2 = toView(view2);
List<View> allViews = new ArrayList<>();
allViews.add(v1);
allViews.add(v2);
// Remove all sent NAKACK2 messages to reproduce ISPN-9291
for (JChannel c : channels) {
STABLE stable = c.getProtocolStack().findProtocol(STABLE.class);
stable.gc();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
MergeView mv = new MergeView(view1.get(0).getAddress(), viewId.incrementAndGet(), allAddresses, allViews);
// Compute the merge digest, without it nodes would request the retransmission of all messages
// Including those that were removed by STABLE earlier
MutableDigest digest = new MutableDigest(allAddresses.toArray(new Address[0]));
for (JChannel c : channels) {
digest.merge(getGms(c).getDigest());
}
for (JChannel c : channels) {
getGms(c).installView(mv, digest);
}
return allMembers;
}
private View toView(ArrayList<JChannel> channels) {
final List<Address> viewMembers = new ArrayList<>();
for (JChannel c : channels) viewMembers.add(c.getAddress());
return View.create(channels.get(0).getAddress(), viewId.incrementAndGet(),
viewMembers.toArray(new Address[0]));
}
private void discardOtherMembers() {
List<Address> outsideMembers = new ArrayList<>();
for (Address a : allMembers) {
boolean inThisPartition = false;
for (JChannel c : channels) {
if (c.getAddress().equals(a)) inThisPartition = true;
}
if (!inThisPartition) outsideMembers.add(a);
}
for (JChannel c : channels) {
DISCARD discard = new DISCARD();
log.tracef("%s discarding messages from %s", c.getAddress(), outsideMembers);
for (Address a : outsideMembers) discard.addIgnoreMember(a);
try {
c.getProtocolStack().insertProtocol(discard, ProtocolStack.Position.ABOVE, TP.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public String toString() {
StringBuilder addresses = new StringBuilder();
for (JChannel c : channels) addresses.append(c.getAddress()).append(" ");
return "Partition{" + addresses + '}';
}
public void merge(Partition partition) {
merge(partition, true);
}
public void merge(Partition partition, boolean waitForNoRebalance) {
observeMembers(partition);
partition.observeMembers(this);
ArrayList<JChannel> view1 = new ArrayList<>(channels);
ArrayList<JChannel> view2 = new ArrayList<>(partition.channels);
partition.channels.stream().filter(c -> !channels.contains(c)).forEach(c -> channels.add(c));
installMergeView(view1, view2);
enableDiscovery();
waitForPartitionToForm(waitForNoRebalance);
List<Partition> tmp = new ArrayList<>(Arrays.asList(BasePartitionHandlingTest.this.partitions));
if (!tmp.remove(partition)) throw new AssertionError();
BasePartitionHandlingTest.this.partitions = tmp.toArray(new Partition[0]);
}
private String printView(ArrayList<JChannel> view1) {
StringBuilder sb = new StringBuilder();
for (JChannel c: view1) sb.append(c.getAddress()).append(" ");
return sb.insert(0, "[ ").append(" ]").toString();
}
private void waitForPartitionToForm(boolean waitForNoRebalance) {
List<Cache<Object, Object>> caches = new ArrayList<>(getCaches(customCacheName()));
caches.removeIf(objectObjectCache -> !channels.contains(channel(objectObjectCache)));
Cache<Object, Object> cache = caches.get(0);
blockUntilViewsReceived(10000, caches);
if (waitForNoRebalance) {
if (cache.getCacheConfiguration().clustering().cacheMode().isClustered()) {
waitForNoRebalance(caches);
}
}
}
public void enableDiscovery() {
channels.forEach(BasePartitionHandlingTest.this::enableDiscoveryProtocol);
log.trace("Discovery started.");
}
private void observeMembers(Partition partition) {
for (JChannel c : channels) {
List<Protocol> protocols = c.getProtocolStack().getProtocols();
for (Protocol p : protocols) {
if (p instanceof DISCARD) {
for (JChannel oc : partition.channels) {
((DISCARD) p).removeIgnoredMember(oc.getAddress());
}
}
}
}
}
public void assertDegradedMode() {
if (partitionHandling != PartitionHandling.ALLOW_READ_WRITES) {
assertAvailabilityMode(AvailabilityMode.DEGRADED_MODE);
}
// Keys do not become unavailable immediately after the partition becomes degraded
// but only after the cache topology is updated so that the key owners are not actual members
assertActualMembers();
}
public void assertKeyAvailableForRead(Object k, Object expectedValue) {
for (Cache<?, ?> c : cachesInThisPartition()) {
BasePartitionHandlingTest.this.assertKeyAvailableForRead(c, k, expectedValue);
}
}
public void assertKeyAvailableForWrite(Object k, Object newValue) {
for (Cache<Object, Object> c : cachesInThisPartition()) {
c.put(k, newValue);
assertEquals(c.get(k), newValue, "Cache " + c.getAdvancedCache().getRpcManager().getAddress() + " doesn't see the right value");
}
}
protected void assertKeysNotAvailableForRead(Object... keys) {
for (Object k : keys)
assertKeyNotAvailableForRead(k);
}
public void assertKeyNotAvailableForRead(Object key) {
for (Cache<Object, ?> c : cachesInThisPartition()) {
BasePartitionHandlingTest.this.assertKeyNotAvailableForRead(c, key);
}
}
private <K,V> List<Cache<K,V>> cachesInThisPartition() {
List<Cache<K,V>> caches = new ArrayList<>();
for (final Cache<K,V> c : BasePartitionHandlingTest.this.<K,V>caches(customCacheName())) {
JChannel ch = channel(c);
if (channels.contains(ch)) {
caches.add(c);
}
}
return caches;
}
public void assertExceptionWithForceLock(Object key) {
cachesInThisPartition().forEach(c -> Exceptions.expectException(AvailabilityException.class,
() -> c.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK).get(key)));
}
public void assertKeyNotAvailableForWrite(Object key) {
cachesInThisPartition().forEach(c -> Exceptions.expectException(AvailabilityException.class, () -> c.put(key, key)));
}
public void assertKeysNotAvailableForWrite(Object ... keys) {
for (Object k : keys) {
assertKeyNotAvailableForWrite(k);
}
}
public void assertAvailabilityMode(final AvailabilityMode state) {
for (final Cache<?, ?> c : cachesInThisPartition()) {
eventuallyEquals(state, () -> partitionHandlingManager(c).getAvailabilityMode());
}
}
public void assertConsistentHashMembers(List<org.infinispan.remoting.transport.Address> expectedMembers) {
for (Cache<?, ?> c : cachesInThisPartition()) {
assertEquals(new HashSet<>(c.getAdvancedCache().getDistributionManager().getCacheTopology().getMembers()), new HashSet<>(expectedMembers));
}
}
public void assertActualMembers() {
Set<org.infinispan.remoting.transport.Address> expected =
cachesInThisPartition().stream()
.map(c -> c.getAdvancedCache().getRpcManager().getAddress())
.collect(Collectors.toSet());
for (Cache<?, ?> c : cachesInThisPartition()) {
eventuallyEquals(expected, () -> new HashSet<>(c.getAdvancedCache().getDistributionManager().getCacheTopology().getActualMembers()));
}
}
public List<org.infinispan.remoting.transport.Address> getAddresses() {
return channels.stream().map(ch -> new JGroupsAddress(ch.getAddress())).collect(Collectors.toList());
}
}
private GMS getGms(JChannel c) {
return c.getProtocolStack().findProtocol(GMS.class);
}
protected void assertKeyAvailableForRead(Cache<?, ?> c, Object k, Object expectedValue) {
log.tracef("Checking key %s is available on %s", k, c);
assertEquals(c.get(k), expectedValue, "Cache " + c.getAdvancedCache().getRpcManager().getAddress() + " doesn't see the right value: ");
// While we keep the null values in the map inside interceptor stack, these are removed in CacheImpl.getAll
Map<Object, Object> expectedMap = expectedValue == null ? Collections.emptyMap() : Collections.singletonMap(k, expectedValue);
assertEquals(c.getAdvancedCache().getAll(Collections.singleton(k)), expectedMap, "Cache " + c.getAdvancedCache().getRpcManager().getAddress() + " doesn't see the right value: ");
}
protected void assertKeyNotAvailableForRead(Cache<Object, ?> c, Object key) {
log.tracef("Checking key %s is not available on %s", key, c);
expectException(AvailabilityException.class, () -> c.get(key));
expectException(AvailabilityException.class, () -> c.getAdvancedCache().getAll(Collections.singleton(key)));
}
protected void splitCluster(PartitionDescriptor... partitions) {
splitCluster(Arrays.stream(partitions).map(PartitionDescriptor::getNodes).toArray(int[][]::new));
}
protected void splitCluster(int[]... parts) {
List<Address> allMembers = channel(0).getView().getMembers();
partitions = new Partition[parts.length];
for (int i = 0; i < parts.length; i++) {
Partition p = new Partition(allMembers);
for (int j : parts[i]) {
p.addNode(channel(j));
}
partitions[i] = p;
p.discardOtherMembers();
}
// Only install the new views after installing DISCARD
// Otherwise broadcasts from the first partition would be visible in the other partitions
for (Partition p : partitions) {
p.partition();
}
}
protected AdvancedCache<?, ?>[] getPartitionCaches(PartitionDescriptor descriptor) {
int[] nodes = descriptor.getNodes();
AdvancedCache<?, ?>[] caches = new AdvancedCache[nodes.length];
for (int i = 0; i < nodes.length; i++)
caches[i] = advancedCache(nodes[i]);
return caches;
}
protected void isolatePartition(int[] isolatedPartition) {
List<Address> allMembers = channel(0).getView().getMembers();
Partition p0 = new Partition(allMembers);
IntStream.range(0, allMembers.size()).forEach(i -> p0.addNode(channel(i)));
Partition p1 = new Partition(allMembers);
Arrays.stream(isolatedPartition).forEach(i -> p1.addNode(channel(i)));
p1.partition();
partitions = new Partition[]{p0, p1};
}
private JChannel channel(int i) {
return channel(manager(i));
}
protected JChannel channel(Cache<?, ?> cache) {
return channel(cache.getCacheManager());
}
private JChannel channel(EmbeddedCacheManager manager) {
return extractJChannel(manager);
}
protected Partition partition(int i) {
if (partitions == null)
throw new IllegalStateException("splitCluster(..) must be invoked before this method!");
return partitions[i];
}
protected PartitionHandlingManager partitionHandlingManager(int index) {
return partitionHandlingManager(advancedCache(index));
}
protected PartitionHandlingManager partitionHandlingManager(Cache<?, ?> cache) {
return extractComponent(cache, PartitionHandlingManager.class);
}
protected void assertExpectedValue(Object expectedVal, Object key) {
for (int i = 0; i < numMembersInCluster; i++) {
assertEquals(cache(i).get(key), expectedVal);
}
}
}
| 20,935
| 36.927536
| 184
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/OptimisticTxPartitionAndMergeDuringRollbackTest.java
|
package org.infinispan.partitionhandling;
import org.infinispan.Cache;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.transaction.tm.EmbeddedTransaction;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "functional", testName = "partitionhandling.OptimisticTxPartitionAndMergeDuringRollbackTest")
public class OptimisticTxPartitionAndMergeDuringRollbackTest extends BaseOptimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(OptimisticTxPartitionAndMergeDuringRollbackTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, true);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, true, true);
}
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, true, false);
}
public void testSplitBeforeRollback() throws Exception {
//the transaction is successfully prepare and then the split happens before the commit phase starts.
waitForClusterToForm(OPTIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(OPTIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, OPTIMISTIC_TX_CACHE_NAME);
final EmbeddedTransactionManager transactionManager = (EmbeddedTransactionManager) originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
final EmbeddedTransaction transaction = transactionManager.getTransaction();
keyInfo.putFinalValue(originator);
AssertJUnit.assertTrue(transaction.runPrepare());
transactionManager.suspend();
SplitMode.BOTH_DEGRADED.split(this);
transactionManager.resume(transaction);
transaction.runCommit(true);
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
mergeCluster(OPTIMISTIC_TX_CACHE_NAME);
finalAsserts(OPTIMISTIC_TX_CACHE_NAME, keyInfo, INITIAL_VALUE);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
if (splitMode == SplitMode.ORIGINATOR_ISOLATED && discard) {
//rollback never received, so key is locked until the merge occurs.
assertLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
} else {
//key is unlocked because the rollback is always received in cache1
assertEventuallyNotLocked(cache(1, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
}
if (discard) {
//rollback never received, so key is locked until the merge occurs.
assertLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
} else {
//rollback received, so key is unlocked
assertEventuallyNotLocked(cache(2, OPTIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
}
@Override
protected boolean forceRollback() {
return true;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return RollbackCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 4,311
| 38.559633
| 143
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/ThreeNodesReplicatedSplitAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.HashSet;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.MagicKey;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.TestingUtil;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.ThreeNodesReplicatedSplitAndMergeTest")
public class ThreeNodesReplicatedSplitAndMergeTest extends BasePartitionHandlingTest {
public ThreeNodesReplicatedSplitAndMergeTest() {
numMembersInCluster = 3;
cacheMode = CacheMode.REPL_SYNC;
}
public void testSplitAndMerge0() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 1), new PartitionDescriptor(2));
}
public void testSplitAndMerge1() throws Exception {
testSplitAndMerge(new PartitionDescriptor(0, 2), new PartitionDescriptor(1));
}
public void testSplitAndMerge2() throws Exception {
testSplitAndMerge(new PartitionDescriptor(1, 2), new PartitionDescriptor(0));
}
private void testSplitAndMerge(PartitionDescriptor p0, PartitionDescriptor p1) throws Exception {
Object k0 = new MagicKey(cache(p0.node(0)), cache(p0.node(1)));
cache(0).put(k0, "v0");
Object k1 = new MagicKey(cache(p0.node(1)), cache(p1.node(0)));
cache(1).put(k1, "v1");
Object k2 = new MagicKey(cache(p1.node(0)), cache(p0.node(0)));
cache(2).put(k2, "v2");
HashSet<Address> allMembers = new HashSet<>(advancedCache(0).getRpcManager().getMembers());
//use set comparison as the merge view will reshuffle the order of nodes
assertStableTopologyMembers(allMembers, partitionHandlingManager(0));
assertStableTopologyMembers(allMembers, partitionHandlingManager(1));
assertStableTopologyMembers(allMembers, partitionHandlingManager(2));
for (int i = 0; i < numMembersInCluster; i++) {
assertEquals(AvailabilityMode.AVAILABLE, partitionHandlingManager(i).getAvailabilityMode());
}
splitCluster(p0.getNodes(), p1.getNodes());
TestingUtil.waitForNoRebalance(cache(p0.node(0)), cache(p0.node(1)));
partition(0).assertAvailabilityMode(AvailabilityMode.AVAILABLE);
partition(1).assertAvailabilityMode(AvailabilityMode.DEGRADED_MODE);
assertStableTopologyMembers(allMembers, partitionHandlingManager(p1.node(0)));
//1. check key visibility in partition 1
partition(0).assertKeyAvailableForRead(k0, "v0");
partition(0).assertKeyAvailableForRead(k1, "v1");
partition(0).assertKeyAvailableForRead(k2, "v2");
//2. check key visibility in partition 2
partition(1).assertKeysNotAvailableForRead(k0, k1, k2);
//3. check key ownership
assertTrue(dataContainer(p0.node(0)).containsKey(k0));
assertTrue(dataContainer(p0.node(0)).containsKey(k1));
assertTrue(dataContainer(p0.node(0)).containsKey(k2));
assertTrue(dataContainer(p0.node(1)).containsKey(k0));
assertTrue(dataContainer(p0.node(1)).containsKey(k1));
assertTrue(dataContainer(p0.node(1)).containsKey(k2));
assertTrue(dataContainer(p1.node(0)).containsKey(k0));
assertTrue(dataContainer(p1.node(0)).containsKey(k1));
assertTrue(dataContainer(p1.node(0)).containsKey(k2));
//4. check writes on partition one
partition(0).assertKeyAvailableForWrite(k0, "v00");
partition(0).assertKeyAvailableForWrite(k1, "v11");
partition(0).assertKeyAvailableForWrite(k2, "v22");
//5. check writes on partition two
partition(1).assertKeyNotAvailableForWrite(k0);
partition(1).assertKeyNotAvailableForWrite(k1);
partition(1).assertKeyNotAvailableForWrite(k2);
partition(0).merge(partition(1));
//use set comparison as the merge view will reshuffle the order of nodes
expectStableTopologyMembers(allMembers, partitionHandlingManager(0));
expectStableTopologyMembers(allMembers, partitionHandlingManager(1));
expectStableTopologyMembers(allMembers, partitionHandlingManager(2));
partition(0).assertAvailabilityMode(AvailabilityMode.AVAILABLE);
// 4. check data seen correctly
assertExpectedValue("v00", k0);
assertExpectedValue("v11", k1);
assertExpectedValue("v22", k2);
//5. recheck key ownership
assertTrue(dataContainer(p0.node(0)).containsKey(k0));
assertTrue(dataContainer(p0.node(0)).containsKey(k1));
assertTrue(dataContainer(p0.node(0)).containsKey(k2));
assertTrue(dataContainer(p0.node(1)).containsKey(k0));
assertTrue(dataContainer(p0.node(1)).containsKey(k1));
assertTrue(dataContainer(p0.node(1)).containsKey(k2));
assertTrue(dataContainer(p1.node(0)).containsKey(k0));
assertTrue(dataContainer(p1.node(0)).containsKey(k1));
assertTrue(dataContainer(p1.node(0)).containsKey(k2));
cache(0).put(k0, "v000");
cache(1).put(k1, "v111");
cache(2).put(k2, "v222");
assertExpectedValue("v000", k0);
assertExpectedValue("v111", k1);
assertExpectedValue("v222", k2);
assertNull(cache(0).get("nonExistentKey"));
}
private void assertStableTopologyMembers(HashSet<Address> allMembers, PartitionHandlingManager phm) {
assertEquals(allMembers, new HashSet<Address>(phm.getLastStableTopology().getMembers()));
}
private void expectStableTopologyMembers(HashSet<Address> expected, PartitionHandlingManager phm) {
eventuallyEquals(expected, () -> new HashSet<Address>(phm.getLastStableTopology().getMembers()));
}
}
| 5,780
| 40.292857
| 104
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/DegradedJoinTest.java
|
package org.infinispan.partitionhandling;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractGlobalComponent;
import static org.testng.AssertJUnit.assertEquals;
import java.util.HashSet;
import org.infinispan.AdvancedCache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.topology.LocalTopologyManager;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.DegradedJoinTest")
public class DegradedJoinTest extends BasePartitionHandlingTest {
@Override
public Object[] factory() {
return new Object[]{
new DegradedJoinTest().cacheMode(CacheMode.REPL_SYNC),
new DegradedJoinTest().cacheMode(CacheMode.DIST_SYNC)
};
}
public DegradedJoinTest() {
numMembersInCluster = 2;
}
public void testSplitAndJoin() throws Exception {
HashSet<Address> allMembers = new HashSet<>(asList(address(0), address(1)));
//use set comparison as the merge view will reshuffle the order of nodes
assertStableTopologyMembers(allMembers, partitionHandlingManager(0));
assertStableTopologyMembers(allMembers, partitionHandlingManager(1));
for (int i = 0; i < numMembersInCluster; i++) {
assertEquals(AvailabilityMode.AVAILABLE, partitionHandlingManager(i).getAvailabilityMode());
}
// Split cluster
PartitionDescriptor p0 = new PartitionDescriptor(0);
PartitionDescriptor p1 = new PartitionDescriptor(1);
splitCluster(p0.getNodes(), p1.getNodes());
// Both nodes are in degraded mode
partition(0).assertDegradedMode();
partition(1).assertDegradedMode();
assertStableTopologyMembers(allMembers, partitionHandlingManager(p1.node(0)));
// Kill node 1
manager(1).stop();
enableDiscovery();
// Start a new node
ConfigurationBuilder dcc = cacheConfiguration();
dcc.clustering().cacheMode(cacheMode).partitionHandling().whenSplit(partitionHandling).mergePolicy(mergePolicy);
if (cacheMode == CacheMode.DIST_SYNC) {
dcc.clustering().hash().numOwners(numberOfOwners);
}
GlobalConfigurationBuilder globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder();
globalBuilder.serialization().addContextInitializer(serializationContextInitializer());
addClusterEnabledCacheManager(globalBuilder, dcc, new TransportFlags().withFD(true).withMerge(true));
// Joiner can start, cache is still in degraded mode
for (EmbeddedCacheManager manager : asList(manager(0), manager(2))) {
AdvancedCache<Object, Object> cache = manager.getCache().getAdvancedCache();
LocalizedCacheTopology cacheTopology = cache.getDistributionManager().getCacheTopology();
assertEquals(singletonList(address(0)), cacheTopology.getActualMembers());
assertEquals(asList(address(0), address(1)), cacheTopology.getMembers());
PartitionHandlingManager partitionHandlingManager = extractComponent(cache, PartitionHandlingManager.class);
assertEquals(AvailabilityMode.DEGRADED_MODE, partitionHandlingManager.getAvailabilityMode());
assertStableTopologyMembers(allMembers, partitionHandlingManager);
}
// Make the cache available
LocalTopologyManager localTopologyManager = extractGlobalComponent(manager(0), LocalTopologyManager.class);
localTopologyManager.setCacheAvailability(getDefaultCacheName(), AvailabilityMode.AVAILABLE);
// Now the joiner can receive state
TestingUtil.waitForNoRebalance(cache(0), cache(2));
}
private void assertStableTopologyMembers(HashSet<Address> allMembers, PartitionHandlingManager phm) {
assertEquals(allMembers, new HashSet<>(phm.getLastStableTopology().getMembers()));
}
}
| 4,388
| 44.247423
| 118
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/DelayedAvailabilityUpdateTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.commons.test.Exceptions.expectExecutionException;
import static org.testng.Assert.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Future;
import org.infinispan.Cache;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.distribution.MagicKey;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.PartitionStatusChanged;
import org.infinispan.notifications.cachelistener.event.PartitionStatusChangedEvent;
import org.infinispan.test.concurrent.StateSequencer;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.DelayedAvailabilityUpdateTest")
public class DelayedAvailabilityUpdateTest extends BasePartitionHandlingTest {
public void testDelayedAvailabilityUpdate0() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(0, 1), new PartitionDescriptor(2, 3));
}
public void testDelayedAvailabilityUpdate1() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(0, 2), new PartitionDescriptor(1, 3));
}
public void testDelayedAvailabilityUpdate2() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(0, 3), new PartitionDescriptor(1, 2));
}
public void testDelayedAvailabilityUpdate3() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(1, 2), new PartitionDescriptor(0, 3));
}
public void testDelayedAvailabilityUpdate4() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(1, 3), new PartitionDescriptor(0, 2));
}
public void testDelayedAvailabilityUpdate5() throws Exception {
testDelayedAvailabilityUpdate(new PartitionDescriptor(2, 3), new PartitionDescriptor(0, 1));
}
protected void testDelayedAvailabilityUpdate(PartitionDescriptor p0, PartitionDescriptor p1) throws Exception {
Object k0Existing = new MagicKey("k0Existing", cache(p0.node(0)), cache(p0.node(1)));
Object k1Existing = new MagicKey("k1Existing", cache(p0.node(1)), cache(p1.node(0)));
Object k2Existing = new MagicKey("k2Existing", cache(p1.node(0)), cache(p1.node(1)));
Object k3Existing = new MagicKey("k3Existing", cache(p1.node(1)), cache(p0.node(0)));
Object k0Missing = new MagicKey("k0Missing", cache(p0.node(0)), cache(p0.node(1)));
Object k1Missing = new MagicKey("k1Missing", cache(p0.node(1)), cache(p1.node(0)));
Object k2Missing = new MagicKey("k2Missing", cache(p1.node(0)), cache(p1.node(1)));
Object k3Missing = new MagicKey("k3Missing", cache(p1.node(1)), cache(p0.node(0)));
Cache<Object, Object> cacheP0N0 = cache(p0.node(0));
cacheP0N0.put(k0Existing, "v0");
cacheP0N0.put(k1Existing, "v1");
cacheP0N0.put(k2Existing, "v2");
cacheP0N0.put(k3Existing, "v3");
StateSequencer ss = new StateSequencer();
ss.logicalThread("main", "main:block_availability_update_p0n0", "main:after_availability_update_p0n1",
"main:check_availability", "main:resume_availability_update_p0n0");
log.debugf("Delaying the availability mode update on node %s", address(p0.node(0)));
cache(p0.node(0)).addListener(new BlockAvailabilityChangeListener(true, ss,
"main:block_availability_update_p0n0", "main:resume_availability_update_p0n0"));
cache(p0.node(1)).addListener(new BlockAvailabilityChangeListener(false, ss,
"main:after_availability_update_p0n1"));
splitCluster(p0.getNodes(), p1.getNodes());
ss.enter("main:check_availability");
// Receive the topology update on p0.node1, block it on p1.node0
DistributionManager dmP0N1 = advancedCache(p0.node(1)).getDistributionManager();
eventuallyEquals(2, () -> dmP0N1.getCacheTopology().getActualMembers().size());
assertEquals(AvailabilityMode.AVAILABLE, partitionHandlingManager(p0.node(0)).getAvailabilityMode());
// Reads for k0* and k3* succeed because they're local and p0.node0 cache is available
assertKeyAvailableForRead(cacheP0N0, k0Existing, "v0");
assertKeyAvailableForRead(cacheP0N0, k3Existing, "v3");
partition(0).assertKeyAvailableForRead(k0Missing, null);
assertKeyAvailableForRead(cacheP0N0, k3Missing, null);
// Reads for k1* fail immediately because they are sent to p0.node1, which is already degraded
assertKeyNotAvailableForRead(cacheP0N0, k1Existing);
assertKeyNotAvailableForRead(cacheP0N0, k1Missing);
// Reads for k2 wait for the topology update before failing
// because all read owners are suspected, but the new topology could add read owners
Future<Object> getK2Existing = fork(() -> cacheP0N0.get(k2Existing));
Future<Map<Object, Object>> getAllK2Existing =
fork(() -> cacheP0N0.getAdvancedCache().getAll(Collections.singleton(k2Existing)));
Future<Object> getK2Missing = fork(() -> cacheP0N0.get(k2Missing));
Future<Map<Object, Object>> getAllK2Missing =
fork(() -> cacheP0N0.getAdvancedCache().getAll(Collections.singleton(k2Missing)));
Thread.sleep(50);
assertFalse(getK2Existing.isDone());
assertFalse(getAllK2Existing.isDone());
assertFalse(getK2Missing.isDone());
assertFalse(getAllK2Missing.isDone());
// Allow the partition handling manager on p0.node0 to update the availability mode
ss.exit("main:check_availability");
partition(0).assertDegradedMode();
partition(1).assertDegradedMode();
expectExecutionException(AvailabilityException.class, getK2Existing);
expectExecutionException(AvailabilityException.class, getAllK2Existing);
expectExecutionException(AvailabilityException.class, getK2Missing);
expectExecutionException(AvailabilityException.class, getAllK2Missing);
}
@Listener
public static class BlockAvailabilityChangeListener {
private boolean blockPre;
private StateSequencer ss;
private String[] states;
BlockAvailabilityChangeListener(boolean blockPre, StateSequencer ss, String... states) {
this.blockPre = blockPre;
this.ss = ss;
this.states = states;
}
@PartitionStatusChanged
public void onPartitionStatusChange(PartitionStatusChangedEvent e) throws Exception {
if (blockPre == e.isPre()) {
for (String state : states) {
ss.advance(state);
}
}
}
}
}
| 6,620
| 46.978261
| 114
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/IndependentClustersMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TransportFlags;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "partitionhandling.IndependentClustersMergeTest")
public class IndependentClustersMergeTest extends BasePartitionHandlingTest {
private static final String MERGE_RESULT = "merge-result";
@Override
public Object[] factory() {
return new Object[] {
new IndependentClustersMergeTest().partitionHandling(PartitionHandling.ALLOW_READS),
new IndependentClustersMergeTest().partitionHandling(PartitionHandling.DENY_READ_WRITES)
};
}
public IndependentClustersMergeTest() {
this.numMembersInCluster = 2;
this.mergePolicy = (preferredEntry, otherEntries) -> {
CacheEntry<String, String> entry = preferredEntry != null ? preferredEntry : otherEntries.get(0);
entry.setValue(MERGE_RESULT);
return entry;
};
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder dcc = cacheConfiguration();
dcc.clustering()
.cacheMode(cacheMode)
.partitionHandling().whenSplit(partitionHandling).mergePolicy(mergePolicy)
.hash().numOwners(numberOfOwners);
for (int i = 0; i < numMembersInCluster; i++) {
EmbeddedCacheManager cm = addClusterEnabledCacheManager(dcc, new TransportFlags().withFD(true).withMerge(true));
Cache cache = cm.getCache();
disableDiscoveryProtocol(channel(cache));
}
}
public void testConflictResolutionCalled() {
Cache c0 = cache(0);
Cache c1 = cache(1);
assertEquals(1, topologySize(c0));
assertEquals(1, topologySize(c1));
c0.put(1, 1);
c1.put(1, 2);
enableDiscoveryProtocol(channel(c0));
enableDiscoveryProtocol(channel(c1));
TestingUtil.waitForNoRebalance(c0, c1);
assertEquals(MERGE_RESULT, c0.get(1));
}
private int topologySize(Cache cache) {
return cache.getAdvancedCache().getDistributionManager().getCacheTopology().getMembers().size();
}
}
| 2,417
| 35.089552
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PessimisticTxPartitionHandlingReleaseLockTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractLockManager;
import static org.infinispan.test.TestingUtil.getDiscardForCache;
import static org.infinispan.test.TestingUtil.getTransactionTable;
import static org.infinispan.test.TestingUtil.wrapGlobalComponent;
import static org.infinispan.test.TestingUtil.wrapInboundInvocationHandler;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.TransactionManager;
import org.infinispan.AdvancedCache;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.conflict.MergePolicy;
import org.infinispan.distribution.MagicKey;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManagerImpl;
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.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.AbstractControlledLocalTopologyManager;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* Reproducer for ISPN-12757
* <p>
* It checks if the correct unlock method is invoked by the {@link PartitionHandlingManagerImpl} and no locks are
* leaked.
*
* @author Pedro Ruivo
* @since 12.1
*/
@Test(groups = "functional", testName = "partitionhandling.PessimisticTxPartitionHandlingReleaseLockTest")
public class PessimisticTxPartitionHandlingReleaseLockTest extends MultipleCacheManagersTest {
private static final Log log = LogFactory.getLog(PessimisticTxPartitionHandlingReleaseLockTest.class);
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.transaction().lockingMode(LockingMode.PESSIMISTIC).useSynchronization(true);
builder.clustering().partitionHandling().mergePolicy(MergePolicy.NONE).whenSplit(PartitionHandling.DENY_READ_WRITES);
builder.clustering().remoteTimeout(4, TimeUnit.MINUTES); // we don't want timeouts
createClusteredCaches(5, TestDataSCI.INSTANCE, builder, new TransportFlags().withFD(true).withMerge(true));
}
public void testLockReleased() throws Exception {
final AdvancedCache<MagicKey, String> cache0 = this.<MagicKey, String>cache(0).getAdvancedCache();
final TransactionManager tm = cache0.getTransactionManager();
final ControlledInboundHandler handler1 = wrapInboundInvocationHandler(cache(1), ControlledInboundHandler::new);
final ControlledLocalTopologyManager localTopologyManager0 = wrapGlobalComponent(cache0.getCacheManager(), LocalTopologyManager.class, ControlledLocalTopologyManager::new, true);
final MagicKey key = new MagicKey(cache0, cache(1));
Future<GlobalTransaction> f = fork(() -> {
tm.begin();
cache0.lock(key);
assertNull(cache0.get(key));
GlobalTransaction gtx = getTransactionTable(cache0).getGlobalTransaction(tm.getTransaction());
cache0.put(key, key.toString());
tm.commit();
return gtx;
});
//make sure the PrepareCommand was sent
assertTrue(handler1.receivedLatch.await(30, TimeUnit.SECONDS));
//block stable topology update on originator
localTopologyManager0.blockStableTopologyUpdate();
//isolate backup owner
getDiscardForCache(manager(1)).discardAll(true);
//wait for the transaction to finish
//after the view change, the transaction is handled by the PartitionHandlingManager which finishes the commit
final GlobalTransaction gtx = f.get();
//check lock & pending transaction list
Collection<GlobalTransaction> pendingTransactions = extractComponent(cache0, PartitionHandlingManager.class).getPartialTransactions();
assertEquals(1, pendingTransactions.size());
assertEquals(gtx, pendingTransactions.iterator().next());
final LockManager lockManager0 = extractLockManager(cache0);
assertTrue(lockManager0.isLocked(key));
assertEquals(gtx, lockManager0.getOwner(key));
//continue stable topology update
localTopologyManager0.unblockStableTopologyUpdate();
//eventually, the stable topology is installed which retries the prepare and releases the lock
eventuallyEquals(0, lockManager0::getNumberOfLocksHeld);
}
private static class ControlledInboundHandler extends AbstractDelegatingHandler {
private final CountDownLatch receivedLatch;
private ControlledInboundHandler(PerCacheInboundInvocationHandler delegate) {
super(delegate);
receivedLatch = new CountDownLatch(1);
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
if (command instanceof PrepareCommand) {
log.debugf("Ignoring command %s", command);
receivedLatch.countDown();
} else {
delegate.handle(command, reply, order);
}
}
}
public static class ControlledLocalTopologyManager extends AbstractControlledLocalTopologyManager {
private volatile CompletableFuture<Void> block = CompletableFutures.completedNull();
private ControlledLocalTopologyManager(LocalTopologyManager delegate) {
super(delegate);
}
@Override
protected CompletionStage<Void> beforeHandleTopologyUpdate(String cacheName, CacheTopology cacheTopology, int viewId) {
return block;
}
private void blockStableTopologyUpdate() {
block = new CompletableFuture<>();
}
private void unblockStableTopologyUpdate() {
block.complete(null);
}
}
}
| 6,924
| 42.28125
| 184
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PessimisticTxPartitionAndMergeDuringPrepareTest.java
|
package org.infinispan.partitionhandling;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "functional", testName = "partitionhandling.PessimisticTxPartitionAndMergeDuringPrepareTest")
public class PessimisticTxPartitionAndMergeDuringPrepareTest extends BasePessimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(PessimisticTxPartitionAndMergeDuringPrepareTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, false, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, false, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, false, true);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, false, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, true);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, false);
}
public void testSplitBeforePrepare() throws Exception {
//split happens before the commit() or rollback(). Locks are acquired
waitForClusterToForm(PESSIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(PESSIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, PESSIMISTIC_TX_CACHE_NAME);
final TransactionManager transactionManager = originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
keyInfo.putFinalValue(originator);
final Transaction transaction = transactionManager.suspend();
SplitMode.BOTH_DEGRADED.split(this);
transactionManager.resume(transaction);
transactionManager.commit();
assertLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
mergeCluster(PESSIMISTIC_TX_CACHE_NAME);
finalAsserts(PESSIMISTIC_TX_CACHE_NAME, keyInfo, FINAL_VALUE);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
if (splitMode == SplitMode.PRIMARY_OWNER_ISOLATED) {
//the majority partition, all the nodes involved prepare (i.e. one-phase-commit) the transaction
//the locks should be released (async) in all the nodes
assertEventuallyNotLocked(cache(0, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(0, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
assertEventuallyNotLocked(cache(3, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertEventuallyNotLocked(cache(3, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
} else {
//on both caches, the key is locked and it is unlocked after the merge
assertLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
}
@Override
protected boolean forceRollback() {
return false;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return PrepareCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 4,448
| 39.816514
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PartitionStressTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.transaction.xa.XAException;
import org.infinispan.Cache;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.CacheContainer;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.TransportFlags;
import org.infinispan.transaction.LockingMode;
import org.jgroups.protocols.DISCARD;
import org.testng.annotations.Test;
@Test(groups = "stress", testName = "partitionhandling.PartitionStressTest", timeOut = 15*60*1000)
public class PartitionStressTest extends MultipleCacheManagersTest {
public static final int NUM_NODES = 4;
@Override
public Object[] factory() {
return new Object[] {
new PartitionStressTest().cacheMode(CacheMode.DIST_SYNC).transactional(false),
new PartitionStressTest().cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.OPTIMISTIC),
new PartitionStressTest().cacheMode(CacheMode.DIST_SYNC).transactional(true).lockingMode(LockingMode.PESSIMISTIC),
};
}
public PartitionStressTest() {
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(cacheMode);
builder.transaction().transactionMode(transactionMode()).lockingMode(lockingMode);
builder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES);
for (int i = 0; i < NUM_NODES; i++) {
addClusterEnabledCacheManager(builder, new TransportFlags().withFD(true).withMerge(true));
}
waitForClusterToForm();
}
public void testWriteDuringPartition() throws Exception {
DISCARD[] discards = new DISCARD[NUM_NODES];
for (int i = 0; i < NUM_NODES; i++) {
discards[i] = TestingUtil.getDiscardForCache(manager(i));
}
final List<Future<Object>> futures = new ArrayList<>(NUM_NODES);
final ConcurrentMap<String, Integer> insertedKeys = new ConcurrentHashMap<>();
final AtomicBoolean stop = new AtomicBoolean(false);
for (int i = 0; i < NUM_NODES; i++) {
final int cacheIndex = i;
Future<Object> future = fork(new Callable<Object>() {
@Override
public Object call() throws Exception {
Cache<String, Integer> cache = cache(cacheIndex);
int count = 0;
while (!stop.get()) {
String key = "key" + cacheIndex + "_" + count;
try {
cache.put(key, count);
insertedKeys.put(key, count);
} catch (AvailabilityException e) {
// expected, ignore
} catch (CacheException e) {
if (e.getCause() instanceof XAException && e.getCause().getCause() instanceof AvailabilityException) {
// expected, ignore
}
}
count++;
Thread.sleep(0);
}
return count;
}
});
futures.add(future);
}
long startTime = TIME_SERVICE.time();
int splitIndex = 0;
while (splitIndex < NUM_NODES) {
List<Address> partitionOne = new ArrayList<Address>(NUM_NODES);
List<Address> partitionTwo = new ArrayList<Address>(NUM_NODES);
List<EmbeddedCacheManager> partitionOneManagers = new ArrayList<>();
List<EmbeddedCacheManager> partitionTwoManagers = new ArrayList<>();
for (int i = 0; i < NUM_NODES; i++) {
if ((i + splitIndex) % NUM_NODES < NUM_NODES / 2) {
partitionTwo.add(address(i));
partitionTwoManagers.add(manager(i));
} else {
partitionOne.add(address(i));
partitionOneManagers.add(manager(i));
}
}
assertEquals(NUM_NODES / 2, partitionTwo.size());
log.infof("Cache is available, splitting cluster at index %d. First partition is %s, second partition is %s",
splitIndex, partitionOne, partitionTwo);
for (int i = 0; i < NUM_NODES; i++) {
if (partitionOne.contains(address(i))) {
for (Address a : partitionTwo) {
discards[i].addIgnoreMember(((JGroupsAddress) a).getJGroupsAddress());
}
} else {
for (Address a : partitionOne) {
discards[i].addIgnoreMember(((JGroupsAddress) a).getJGroupsAddress());
}
}
}
TestingUtil.blockForMemberToFail(30000, partitionOneManagers.toArray(new CacheContainer[0]));
TestingUtil.blockForMemberToFail(30000, partitionTwoManagers.toArray(new CacheContainer[0]));
log.infof("Nodes split, waiting for the caches to become degraded");
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return TestingUtil.extractComponent(cache(0), PartitionHandlingManager.class).getAvailabilityMode() ==
AvailabilityMode.DEGRADED_MODE;
}
});
assertFuturesRunning(futures);
log.infof("Cache is degraded, merging partitions %s and %s", partitionOne, partitionTwo);
for (int i = 0; i < NUM_NODES; i++) {
discards[i].resetIgnoredMembers();
}
TestingUtil.blockUntilViewsReceived(60000, true, cacheManagers.toArray(new CacheContainer[0]));
log.infof("Partitions merged, waiting for the caches to become available");
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return TestingUtil.extractComponent(cache(0), PartitionHandlingManager.class).getAvailabilityMode() ==
AvailabilityMode.AVAILABLE;
}
});
TestingUtil.waitForNoRebalance(caches());
assertFuturesRunning(futures);
splitIndex++;
}
stop.set(true);
for (Future<Object> future : futures) {
future.get(10, TimeUnit.SECONDS);
}
for (String key : insertedKeys.keySet()) {
for (int i = 0; i < NUM_NODES; i++) {
assertEquals("Failure for key " + key + " on " + cache(i), insertedKeys.get(key), cache(i).get(key));
}
}
long duration = TIME_SERVICE.timeDuration(startTime, TimeUnit.SECONDS);
log.infof("Test finished in %d seconds", duration);
}
protected void assertFuturesRunning(List<Future<Object>> futures) {
for (Future<Object> future : futures) {
assertFalse(future.isDone());
}
}
}
| 7,561
| 39.875676
| 123
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/NumOwnersNodeCrashInSequenceTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.test.concurrent.StateSequencerUtil.advanceOnInboundRpc;
import static org.infinispan.test.concurrent.StateSequencerUtil.matchCommand;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.fail;
import java.util.Collection;
import java.util.List;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.distribution.MagicKey;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.commands.statetransfer.StateResponseCommand;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.concurrent.StateSequencer;
import org.infinispan.topology.LocalTopologyManager;
import org.infinispan.util.ControlledConsistentHashFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* With a cluster made out of nodes {A,B,C,D}, tests that D crashes and before the state transfer finishes, another node
* C crashes. {A,B} should enter in degraded mode. The only way in which it could recover is explicitly, through JMX
* operations.
*/
@Test(groups = "functional", testName = "partitionhandling.NumOwnersNodeCrashInSequenceTest")
public class NumOwnersNodeCrashInSequenceTest extends MultipleCacheManagersTest {
private static Log log = LogFactory.getLog(NumOwnersNodeCrashInSequenceTest.class);
ControlledConsistentHashFactory cchf;
private ConfigurationBuilder configBuilder;
protected AvailabilityMode expectedAvailabilityMode;
public NumOwnersNodeCrashInSequenceTest() {
cleanup = CleanupPhase.AFTER_METHOD;
expectedAvailabilityMode = AvailabilityMode.DEGRADED_MODE;
}
@Override
protected void createCacheManagers() throws Throwable {
cchf = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}});
configBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC);
configBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES);
configBuilder.clustering().hash().numSegments(4).stateTransfer().timeout(30000);
}
public void testNodeCrashedBeforeStFinished0() throws Exception {
testNodeCrashedBeforeStFinished(0, 1, 2, 3);
}
public void testNodeCrashedBeforeStFinished1() throws Exception {
testNodeCrashedBeforeStFinished(0, 2, 1, 3);
}
public void testNodeCrashedBeforeStFinished2() throws Exception {
testNodeCrashedBeforeStFinished(0, 3, 1, 2);
}
public void testNodeCrashedBeforeStFinished3() throws Exception {
testNodeCrashedBeforeStFinished(1, 2, 0, 3);
}
public void testNodeCrashedBeforeStFinished4() throws Exception {
testNodeCrashedBeforeStFinished(1, 3, 0, 2);
}
public void testNodeCrashedBeforeStFinished5() throws Exception {
testNodeCrashedBeforeStFinished(2, 3, 0, 1);
}
public void testNodeCrashedBeforeStFinished6() throws Exception {
testNodeCrashedBeforeStFinished(1, 2, 3, 0);
}
public void testNodeCrashedBeforeStFinished7() throws Exception {
testNodeCrashedBeforeStFinished(2, 3, 1, 0);
}
private void testNodeCrashedBeforeStFinished(final int a0, final int a1, final int c0, final int c1) throws Exception {
cchf.setOwnerIndexes(new int[][]{{a0, a1}, {a1, c0}, {c0, c1}, {c1, a0}});
configBuilder.clustering().hash().consistentHashFactory(cchf);
createCluster(TestDataSCI.INSTANCE, configBuilder, 4);
waitForClusterToForm();
Object k0 = new MagicKey("k1", cache(a0), cache(a1));
Object k1 = new MagicKey("k2", cache(a0), cache(a1));
Object k2 = new MagicKey("k3", cache(a1), cache(c0));
Object k3 = new MagicKey("k4", cache(a1), cache(c0));
Object k4 = new MagicKey("k5", cache(c0), cache(c1));
Object k5 = new MagicKey("k6", cache(c0), cache(c1));
Object k6 = new MagicKey("k7", cache(c1), cache(a0));
Object k7 = new MagicKey("k8", cache(c1), cache(a0));
final Object[] allKeys = new Object[] {k0, k1, k2, k3, k4, k5, k6, k7};
for (Object k : allKeys) cache(a0).put(k, k);
StateSequencer ss = new StateSequencer();
ss.logicalThread("main", "main:st_in_progress", "main:2nd_node_left", "main:cluster_degraded", "main:after_cluster_degraded");
advanceOnInboundRpc(ss, advancedCache(a1),
matchCommand(StateResponseCommand.class).matchCount(0).build())
.before("main:st_in_progress", "main:cluster_degraded");
// When the coordinator node stops gracefully there are two rebalance operations, one with the old coord
// and one with the new coord. The second
advanceOnInboundRpc(ss, advancedCache(a1),
matchCommand(StateResponseCommand.class).matchCount(1).build())
.before("main:after_cluster_degraded");
// Prepare for rebalance. Manager a1 will request state from c0 for segment 2
cchf.setMembersToUse(advancedCache(a0).getRpcManager().getTransport().getMembers());
cchf.setOwnerIndexes(new int[][]{{a0, a1}, {a1, c0}, {c0, a1}, {c0, a0}});
Address address1 = address(c1);
log.tracef("Before killing node %s", address1);
crashCacheManagers(manager(c1));
installNewView(advancedCache(a0).getRpcManager().getTransport().getMembers(), address1, manager(a0), manager(a1)
, manager(c0));
ss.enter("main:2nd_node_left");
Address address0 = address(c0);
log.tracef("Killing 2nd node %s", address0);
crashCacheManagers(manager(c0));
installNewView(advancedCache(a0).getRpcManager().getTransport().getMembers(), address0, manager(a0), manager(a1));
final PartitionHandlingManager phm0 = TestingUtil.extractComponent(cache(a0), PartitionHandlingManager.class);
final PartitionHandlingManager phm1 = TestingUtil.extractComponent(cache(a1), PartitionHandlingManager.class);
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return phm0.getAvailabilityMode() == expectedAvailabilityMode && phm1.getAvailabilityMode() == expectedAvailabilityMode;
}
});
ss.exit("main:2nd_node_left");
log.trace("Testing condition");
LocalizedCacheTopology topology = cache(a0).getAdvancedCache().getDistributionManager().getCacheTopology();
assertEquals(3, topology.getMembers().size());
for (Object k : allKeys) {
Collection<Address> owners = topology.getDistribution(k).readOwners();
try {
cache(a0).get(k);
if (owners.contains(address0) || owners.contains(address1)) {
fail("get(" + k + ") should have failed on cache " + address(a0));
}
} catch (AvailabilityException e) {
}
try {
cache(a1).put(k, k);
if (owners.contains(address0) || owners.contains(address1)) {
fail("put(" + k + ", v) should have failed on cache " + address(a0));
}
} catch (AvailabilityException e) {
}
}
log.debug("Changing partition availability mode back to AVAILABLE");
cchf.setOwnerIndexes(new int[][]{{a0, a1}, {a1, a0}, {a0, a1}, {a1, a0}});
LocalTopologyManager ltm = TestingUtil.extractGlobalComponent(manager(a0), LocalTopologyManager.class);
ltm.setCacheAvailability(TestingUtil.getDefaultCacheName(manager(a0)), AvailabilityMode.AVAILABLE);
TestingUtil.waitForNoRebalance(cache(a0), cache(a1));
eventuallyEquals(AvailabilityMode.AVAILABLE, phm0::getAvailabilityMode);
}
private void installNewView(List<Address> members, Address missing, EmbeddedCacheManager... where) {
TestingUtil.installNewView(members.stream().filter(a -> !a.equals(missing)), where);
}
protected void crashCacheManagers(EmbeddedCacheManager... cacheManagers) {
TestingUtil.crashCacheManagers(cacheManagers);
}
}
| 8,308
| 44.157609
| 132
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/BasePessimisticTxPartitionAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
public abstract class BasePessimisticTxPartitionAndMergeTest extends BaseTxPartitionAndMergeTest {
static final String PESSIMISTIC_TX_CACHE_NAME = "pes-cache";
@Override
protected void createCacheManagers() throws Throwable {
super.createCacheManagers();
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC);
builder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES);
builder.transaction().lockingMode(LockingMode.PESSIMISTIC).transactionMode(TransactionMode.TRANSACTIONAL).transactionManagerLookup(new EmbeddedTransactionManagerLookup());
defineConfigurationOnAllManagers(PESSIMISTIC_TX_CACHE_NAME, builder);
}
protected abstract void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard);
protected abstract boolean forceRollback();
protected abstract Class<? extends TransactionBoundaryCommand> getCommandClass();
protected void doTest(final SplitMode splitMode, boolean txFail, boolean discard) throws Exception {
waitForClusterToForm(PESSIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(PESSIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, PESSIMISTIC_TX_CACHE_NAME);
final FilterCollection filterCollection = createFilters(PESSIMISTIC_TX_CACHE_NAME, discard, getCommandClass(), splitMode);
Future<Void> put = fork(() -> {
final TransactionManager transactionManager = originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
final Transaction tx = transactionManager.getTransaction();
try {
keyInfo.putFinalValue(originator);
if (forceRollback()) {
tx.setRollbackOnly();
}
} finally {
transactionManager.commit();
}
return null;
});
filterCollection.await(30, TimeUnit.SECONDS);
splitMode.split(this);
filterCollection.unblock();
try {
put.get();
assertFalse(txFail);
} catch (ExecutionException e) {
assertTrue(txFail);
}
checkLocksDuringPartition(splitMode, keyInfo, discard);
filterCollection.stopDiscard();
mergeCluster(PESSIMISTIC_TX_CACHE_NAME);
finalAsserts(PESSIMISTIC_TX_CACHE_NAME, keyInfo, txFail ? INITIAL_VALUE : FINAL_VALUE);
}
}
| 3,277
| 37.116279
| 177
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PessimisticTxPartitionAndMergeDuringRuntimeTest.java
|
package org.infinispan.partitionhandling;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "functional", testName = "partitionhandling.PessimisticTxPartitionAndMergeDuringRuntimeTest")
public class PessimisticTxPartitionAndMergeDuringRuntimeTest extends BasePessimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(PessimisticTxPartitionAndMergeDuringRuntimeTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, false);
}
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, true);
}
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, false);
}
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, true);
}
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, false, false);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
switch (splitMode) {
case ORIGINATOR_ISOLATED:
//lock command never received or ignored because the originator is in another partition
//(safe because we will rollback anyway)
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
case BOTH_DEGRADED:
//originator rollbacks which is received by cache1
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
case PRIMARY_OWNER_ISOLATED:
//originator can commit the transaction, key is eventually unlocked
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
}
//lock command is discarded since the transaction originator is missing
assertEventuallyNotLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
@Override
protected boolean forceRollback() {
return false;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return LockControlCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 2,829
| 35.753247
| 109
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/BaseTxPartitionAndMergeTest.java
|
package org.infinispan.partitionhandling;
import static org.infinispan.test.TestingUtil.extractComponent;
import static org.infinispan.test.TestingUtil.extractLockManager;
import static org.infinispan.test.TestingUtil.waitForNoRebalance;
import static org.infinispan.test.TestingUtil.wrapInboundInvocationHandler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.infinispan.Cache;
import org.infinispan.commands.remote.CacheRpcCommand;
import org.infinispan.distribution.MagicKey;
import org.infinispan.partitionhandling.impl.PartitionHandlingManager;
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.test.TestingUtil;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.concurrent.ReclosableLatch;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.LockManager;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.AssertJUnit;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
public abstract class BaseTxPartitionAndMergeTest extends BasePartitionHandlingTest {
private static final Log log = LogFactory.getLog(BaseTxPartitionAndMergeTest.class);
static final String INITIAL_VALUE = "init-value";
static final String FINAL_VALUE = "final-value";
private static NotifierFilter notifyCommandOn(Cache<?, ?> cache, Class<? extends CacheRpcCommand> blockClass) {
NotifierFilter filter = new NotifierFilter(blockClass);
wrapAndApplyFilter(cache, filter);
return filter;
}
private static BlockingFilter blockCommandOn(Cache<?, ?> cache, Class<? extends CacheRpcCommand> blockClass) {
BlockingFilter filter = new BlockingFilter(blockClass);
wrapAndApplyFilter(cache, filter);
return filter;
}
private static DiscardFilter discardCommandOn(Cache<?, ?> cache, Class<? extends CacheRpcCommand> blockClass) {
DiscardFilter filter = new DiscardFilter(blockClass);
wrapAndApplyFilter(cache, filter);
return filter;
}
private static void wrapAndApplyFilter(Cache<?, ?> cache, Filter filter) {
ControlledInboundHandler controlledInboundHandler =
wrapInboundInvocationHandler(cache, delegate -> new ControlledInboundHandler(delegate, filter));
}
FilterCollection createFilters(String cacheName, boolean discard, Class<? extends CacheRpcCommand> commandClass,
SplitMode splitMode) {
Collection<AwaitAndUnblock> collection = new ArrayList<>(2);
if (splitMode == SplitMode.ORIGINATOR_ISOLATED) {
if (discard) {
collection.add(discardCommandOn(cache(1, cacheName), commandClass));
collection.add(discardCommandOn(cache(2, cacheName), commandClass));
} else {
collection.add(blockCommandOn(cache(1, cacheName), commandClass));
collection.add(blockCommandOn(cache(2, cacheName), commandClass));
}
} else {
collection.add(notifyCommandOn(cache(1, cacheName), commandClass));
if (discard) {
collection.add(discardCommandOn(cache(2, cacheName), commandClass));
} else {
collection.add(blockCommandOn(cache(2, cacheName), commandClass));
}
}
return new FilterCollection(collection);
}
protected abstract Log getLog();
void mergeCluster(String cacheName) {
getLog().debugf("Merging cluster");
partition(0).merge(partition(1));
waitForNoRebalance(caches(cacheName));
for (int i = 0; i < numMembersInCluster; i++) {
PartitionHandlingManager phmI = partitionHandlingManager(cache(i, cacheName));
eventuallyEquals(AvailabilityMode.AVAILABLE, phmI::getAvailabilityMode);
}
getLog().debugf("Cluster merged");
}
void finalAsserts(String cacheName, KeyInfo keyInfo, String value) {
assertNoTransactions(cacheName);
assertNoTransactionsInPartitionHandler(cacheName);
assertNoLocks(cacheName);
assertValue(keyInfo.getKey1(), value, this.caches(cacheName));
assertValue(keyInfo.getKey2(), value, this.caches(cacheName));
}
protected void assertNoLocks(String cacheName) {
eventually("Expected no locks acquired in all nodes", () -> {
for (Cache<?, ?> cache : caches(cacheName)) {
LockManager lockManager = extractLockManager(cache);
getLog().tracef("Locks info=%s", lockManager.printLockInfo());
if (lockManager.getNumberOfLocksHeld() != 0) {
getLog().warnf("Locks acquired on cache '%s'", cache);
return false;
}
}
return true;
}, 30000, TimeUnit.MILLISECONDS);
}
protected void assertValue(Object key, String value, Collection<Cache<Object, String>> caches) {
for (Cache<Object, String> cache : caches) {
AssertJUnit.assertEquals("Wrong value in cache " + address(cache), value, cache.get(key));
}
}
KeyInfo createKeys(String cacheName) {
final Object key1 = new MagicKey("k1", cache(1, cacheName), cache(2, cacheName));
final Object key2 = new MagicKey("k2", cache(2, cacheName), cache(1, cacheName));
cache(1, cacheName).put(key1, INITIAL_VALUE);
cache(2, cacheName).put(key2, INITIAL_VALUE);
return new KeyInfo(key1, key2);
}
private void assertNoTransactionsInPartitionHandler(final String cacheName) {
eventually("Transactions pending in PartitionHandlingManager", () -> {
for (Cache<?, ?> cache : caches(cacheName)) {
Collection<GlobalTransaction> partialTransactions = extractComponent(cache, PartitionHandlingManager.class).getPartialTransactions();
if (!partialTransactions.isEmpty()) {
getLog().debugf("transactions not finished in %s. %s", address(cache), partialTransactions);
return false;
}
}
return true;
});
}
protected enum SplitMode {
ORIGINATOR_ISOLATED {
@Override
public void split(BaseTxPartitionAndMergeTest test) {
test.getLog().debug("Splitting cluster isolating the originator.");
test.splitCluster(new int[]{0}, new int[]{1, 2, 3});
assertDegradedPartition(test, 0);
TestingUtil.waitForNoRebalance(test.cache(1), test.cache(2), test.cache(3));
test.getLog().debug("Cluster split.");
}
},
BOTH_DEGRADED {
@Override
public void split(BaseTxPartitionAndMergeTest test) {
test.getLog().debug("Splitting cluster in equal partition");
test.splitCluster(new int[]{0, 1}, new int[]{2, 3});
assertDegradedPartition(test, 0, 1);
test.getLog().debug("Cluster split.");
}
},
PRIMARY_OWNER_ISOLATED {
@Override
public void split(BaseTxPartitionAndMergeTest test) {
test.getLog().debug("Splitting cluster isolating a primary owner.");
test.splitCluster(new int[]{2}, new int[]{0, 1, 3});
assertDegradedPartition(test, 0);
TestingUtil.waitForNoRebalance(test.cache(0), test.cache(1), test.cache(3));
test.getLog().debug("Cluster split.");
}
};
public abstract void split(BaseTxPartitionAndMergeTest test);
private static void assertDegradedPartition(BaseTxPartitionAndMergeTest test, int... partitionIndexes) {
for (int i = 0; i < partitionIndexes.length; i++)
test.partition(i).assertDegradedMode();
}
}
private interface AwaitAndUnblock {
void await(long timeout, TimeUnit timeUnit) throws InterruptedException;
void unblock();
}
private interface Filter extends AwaitAndUnblock {
boolean before(CacheRpcCommand command, Reply reply, DeliverOrder order);
}
private static class ControlledInboundHandler extends AbstractDelegatingHandler {
private final Filter filter;
private ControlledInboundHandler(PerCacheInboundInvocationHandler delegate, Filter filter) {
super(delegate);
this.filter = filter;
}
@Override
public void handle(CacheRpcCommand command, Reply reply, DeliverOrder order) {
final Filter currentFilter = filter;
if (currentFilter != null && currentFilter.before(command, reply, order)) {
delegate.handle(command, reply, order);
} else {
log.debugf("Ignoring command %s", command);
}
}
}
private static class BlockingFilter implements Filter {
private final Class<? extends CacheRpcCommand> aClass;
private final ReclosableLatch notifier;
private final ReclosableLatch blocker;
private BlockingFilter(Class<? extends CacheRpcCommand> aClass) {
this.aClass = aClass;
blocker = new ReclosableLatch(false);
notifier = new ReclosableLatch(false);
}
@Override
public boolean before(CacheRpcCommand command, Reply reply, DeliverOrder order) {
log.tracef("[Blocking] Checking command %s.", command);
if (aClass.isAssignableFrom(command.getClass())) {
log.tracef("[Blocking] Blocking command %s", command);
notifier.open();
try {
blocker.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
log.tracef("[Blocking] Unblocking command %s", command);
}
return true;
}
public void await(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (!notifier.await(timeout, timeUnit)) {
throw new TimeoutException();
}
}
public void unblock() {
blocker.open();
}
}
private static class NotifierFilter implements Filter {
private final Class<? extends CacheRpcCommand> aClass;
private final CountDownLatch notifier;
private NotifierFilter(Class<? extends CacheRpcCommand> aClass) {
this.aClass = aClass;
notifier = new CountDownLatch(1);
}
@Override
public boolean before(CacheRpcCommand command, Reply reply, DeliverOrder order) {
log.tracef("[Notifier] Checking command %s.", command);
if (aClass.isAssignableFrom(command.getClass())) {
log.tracef("[Notifier] Notifying command %s.", command);
notifier.countDown();
}
return true;
}
public void await(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (!notifier.await(timeout, timeUnit)) {
throw new TimeoutException();
}
}
@Override
public void unblock() {
/*no-op*/
}
}
private static class DiscardFilter implements Filter {
private final Class<? extends CacheRpcCommand> aClass;
private final ReclosableLatch notifier;
private volatile boolean discard;
private DiscardFilter(Class<? extends CacheRpcCommand> aClass) {
this.aClass = aClass;
notifier = new ReclosableLatch(false);
discard = true; //discard everything by default. change if needed in the future.
}
@Override
public boolean before(CacheRpcCommand command, Reply reply, DeliverOrder order) {
log.tracef("[Discard] Checking command %s. (discard enabled=%s)", command, discard);
if (discard && aClass.isAssignableFrom(command.getClass())) {
log.tracef("[Discard] Discarding command %s.", command);
notifier.open();
return false;
}
return true;
}
public void await(long timeout, TimeUnit timeUnit) throws InterruptedException {
if (!notifier.await(timeout, timeUnit)) {
throw new TimeoutException();
}
}
@Override
public void unblock() {
/*no-op*/
}
private void stopDiscard() {
discard = false;
}
}
protected static class KeyInfo {
private final Object key1;
private final Object key2;
KeyInfo(Object key1, Object key2) {
this.key1 = key1;
this.key2 = key2;
}
void putFinalValue(Cache<Object, String> cache) {
cache.put(key1, FINAL_VALUE);
cache.put(key2, FINAL_VALUE);
}
public Object getKey1() {
return key1;
}
public Object getKey2() {
return key2;
}
}
protected static class FilterCollection implements AwaitAndUnblock {
private final Collection<AwaitAndUnblock> collection;
FilterCollection(Collection<AwaitAndUnblock> collection) {
this.collection = collection;
}
@Override
public void await(long timeout, TimeUnit timeUnit) throws InterruptedException {
for (AwaitAndUnblock await : collection) {
await.await(timeout, timeUnit);
}
}
public void unblock() {
collection.forEach(BaseTxPartitionAndMergeTest.AwaitAndUnblock::unblock);
}
public void stopDiscard() {
collection.stream()
.filter(DiscardFilter.class::isInstance)
.map(DiscardFilter.class::cast)
.forEach(DiscardFilter::stopDiscard);
}
}
}
| 13,742
| 35.453581
| 145
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/PessimisticTxPartitionAndMergeDuringRollbackTest.java
|
package org.infinispan.partitionhandling;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.tx.TransactionBoundaryCommand;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.Test;
/**
* It tests multiple scenarios where a split can happen during a transaction.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "functional", testName = "partitionhandling.PessimisticTxPartitionAndMergeDuringRollbackTest")
public class PessimisticTxPartitionAndMergeDuringRollbackTest extends BasePessimisticTxPartitionAndMergeTest {
private static final Log log = LogFactory.getLog(PessimisticTxPartitionAndMergeDuringRollbackTest.class);
public void testDegradedPartitionWithDiscard() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, true);
}
public void testDegradedPartition() throws Exception {
doTest(SplitMode.BOTH_DEGRADED, true, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testOriginatorIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, true);
}
public void testOriginatorIsolatedPartition() throws Exception {
doTest(SplitMode.ORIGINATOR_ISOLATED, true, false);
}
@Test(groups = "unstable", description = "https://issues.jboss.org/browse/ISPN-8232")
public void testPrimaryOwnerIsolatedPartitionWithDiscard() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, true, true);
}
public void testPrimaryOwnerIsolatedPartition() throws Exception {
doTest(SplitMode.PRIMARY_OWNER_ISOLATED, true, false);
}
public void testSplitBeforeRollback() throws Exception {
//split happens before the commit() or rollback(). Locks are acquired
waitForClusterToForm(PESSIMISTIC_TX_CACHE_NAME);
final KeyInfo keyInfo = createKeys(PESSIMISTIC_TX_CACHE_NAME);
final Cache<Object, String> originator = cache(0, PESSIMISTIC_TX_CACHE_NAME);
final TransactionManager transactionManager = originator.getAdvancedCache().getTransactionManager();
transactionManager.begin();
keyInfo.putFinalValue(originator);
final Transaction transaction = transactionManager.suspend();
SplitMode.BOTH_DEGRADED.split(this);
transactionManager.resume(transaction);
transactionManager.rollback();
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
assertLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
mergeCluster(PESSIMISTIC_TX_CACHE_NAME);
finalAsserts(PESSIMISTIC_TX_CACHE_NAME, keyInfo, INITIAL_VALUE);
}
@Override
protected void checkLocksDuringPartition(SplitMode splitMode, KeyInfo keyInfo, boolean discard) {
if (splitMode == SplitMode.ORIGINATOR_ISOLATED) {
if (discard) {
//rollback is never received.
assertLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
} else {
//rollback can be delivered
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
}
} else {
//key is unlocked because the rollback is always received in cache1
assertEventuallyNotLocked(cache(1, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey1());
}
if (discard) {
//rollback never received, so key is locked until the merge occurs.
assertLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
} else {
//rollback received, so key is unlocked
assertEventuallyNotLocked(cache(2, PESSIMISTIC_TX_CACHE_NAME), keyInfo.getKey2());
}
}
@Override
protected boolean forceRollback() {
return true;
}
@Override
protected Class<? extends TransactionBoundaryCommand> getCommandClass() {
return RollbackCommand.class;
}
@Override
protected Log getLog() {
return log;
}
}
| 4,144
| 36.008929
| 110
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/partitionhandling/impl/PreferAvailabilityStrategyTest.java
|
package org.infinispan.partitionhandling.impl;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.infinispan.partitionhandling.AvailabilityMode.AVAILABLE;
import static org.infinispan.partitionhandling.impl.PreferAvailabilityStrategyTest.ConflictResolution.IGNORE;
import static org.infinispan.partitionhandling.impl.PreferAvailabilityStrategyTest.ConflictResolution.RESOLVE;
import static org.infinispan.test.TestingUtil.mapOf;
import static org.infinispan.test.TestingUtil.setOf;
import static org.infinispan.topology.TestClusterCacheStatus.conflictResolutionConsistentHash;
import static org.infinispan.topology.TestClusterCacheStatus.persistentUUID;
import static org.infinispan.topology.TestClusterCacheStatus.start;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.testng.AssertJUnit.assertSame;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.distribution.TestAddress;
import org.infinispan.distribution.ch.impl.DefaultConsistentHashFactory;
import org.infinispan.remoting.transport.Address;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.topology.CacheJoinInfo;
import org.infinispan.topology.CacheStatusResponse;
import org.infinispan.topology.CacheTopology;
import org.infinispan.topology.ClusterTopologyManagerImpl;
import org.infinispan.topology.PersistentUUIDManagerImpl;
import org.infinispan.topology.TestClusterCacheStatus;
import org.infinispan.util.logging.events.EventLogManager;
import org.infinispan.util.logging.events.TestingEventLogManager;
import org.mockito.Mockito;
import org.mockito.MockitoSession;
import org.mockito.quality.Strictness;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
/**
* Test how PreferAvailabilityStrategy picks the post-merge topology in different scenarios.
*
* @author Dan Berindei
* @since 9.2
*/
@Test(groups = "unit", testName = "partitionhandling.impl.PreferAvailabilityStrategyTest")
public class PreferAvailabilityStrategyTest extends AbstractInfinispanTest {
private final ConflictResolution conflicts;
public enum ConflictResolution {
RESOLVE, IGNORE;
boolean resolve() {
return this == RESOLVE;
}
}
private static final CacheJoinInfo DIST_INFO =
new CacheJoinInfo(new DefaultConsistentHashFactory(), 8, 2, 1000, CacheMode.DIST_SYNC, 1.0f, null,
Optional.empty());
private static final CacheJoinInfo REPL_INFO =
new CacheJoinInfo(new DefaultConsistentHashFactory(), 8, 2, 1000, CacheMode.REPL_SYNC, 1.0f, null,
Optional.empty());
private static final Address A = new TestAddress(1, "A");
private static final Address B = new TestAddress(2, "B");
private static final Address C = new TestAddress(3, "C");
private static final Address D = new TestAddress(4, "D");
public static final String CACHE_NAME = "test";
private EventLogManager eventLogManager;
private PersistentUUIDManagerImpl persistentUUIDManager;
private AvailabilityStrategyContext context;
private PreferAvailabilityStrategy strategy;
private MockitoSession mockitoSession;
@DataProvider
public static Object[][] conflictResolutionProvider() {
return new Object[][]{{RESOLVE}, {IGNORE}};
}
@Factory(dataProvider = "conflictResolutionProvider")
public PreferAvailabilityStrategyTest(ConflictResolution conflicts) {
this.conflicts = conflicts;
}
@BeforeMethod(alwaysRun = true)
public void setup() {
mockitoSession = Mockito.mockitoSession()
.strictness(Strictness.STRICT_STUBS)
.startMocking();
persistentUUIDManager = new PersistentUUIDManagerImpl();
eventLogManager = new TestingEventLogManager();
context = mock(AvailabilityStrategyContext.class);
persistentUUIDManager.addPersistentAddressMapping(A, persistentUUID(A));
persistentUUIDManager.addPersistentAddressMapping(B, persistentUUID(B));
persistentUUIDManager.addPersistentAddressMapping(C, persistentUUID(C));
persistentUUIDManager.addPersistentAddressMapping(D, persistentUUID(D));
strategy = new PreferAvailabilityStrategy(eventLogManager, persistentUUIDManager,
ClusterTopologyManagerImpl::distLostDataCheck);
}
@AfterMethod(alwaysRun = true)
public void teardown() {
mockitoSession.finishMocking();
}
public void testSinglePartitionOnlyJoiners() {
// There's no cache topology, so the first cache topology is created with the joiners
List<Address> joiners = asList(A, B);
CacheStatusResponse response = new CacheStatusResponse(DIST_INFO, null, null, AVAILABLE, joiners);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, response, B, response);
when(context.getCacheName()).thenReturn(CACHE_NAME);
when(context.getExpectedMembers()).thenReturn(joiners);
strategy.onPartitionMerge(context, statusResponses);
verify(context).updateCurrentTopology(joiners);
verify(context).queueRebalance(joiners);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionJoinersAndMissingNode() {
// B and C both tried to join, but only B got a response from the old coordinator
List<Address> mergeMembers = asList(B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A);
CacheStatusResponse responseB = availableResponse(B, cacheA);
CacheStatusResponse responseC = new CacheStatusResponse(DIST_INFO, null, null, AVAILABLE, List.of(B));
Map<Address, CacheStatusResponse> statusResponses = mapOf(B, responseB, C, responseC);
when(context.getCacheName()).thenReturn(CACHE_NAME);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheA.copy();
expectedCache.incrementIds();
verify(context).updateCurrentTopology(mergeMembers);
verify(context).queueRebalance(mergeMembers);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionTopologyNotUpdatedAfterLeave() {
// A crashed and it's the next coordinator's job to remove it from the cache topology
List<Address> remainingMembers = asList(B, C);
TestClusterCacheStatus cacheABC = start(DIST_INFO, A, B, C);
CacheStatusResponse responseB = availableResponse(B, cacheABC);
CacheStatusResponse responseC = availableResponse(C, cacheABC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(remainingMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheABC.copy();
expectedCache.updateActualMembers(B, C);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).updateCurrentTopology(remainingMembers);
verify(context).queueRebalance(remainingMembers);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionTopologyPartiallyUpdatedAfterLeave() {
// A crashed, but only C has the updated cache topology
List<Address> remainingMembers = asList(B, C);
TestClusterCacheStatus cacheAB = start(DIST_INFO, A, B, C);
TestClusterCacheStatus cacheC = cacheAB.copy();
cacheC.removeMembers(A);
CacheStatusResponse responseB = availableResponse(B, cacheAB);
CacheStatusResponse responseC = availableResponse(C, cacheC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(remainingMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
expectedCache.incrementIds();
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(remainingMembers);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionLeaveDuringRebalancePhaseReadOld() {
// C joins and rebalance starts, but A crashes and B doesn't receive either rebalance start or leave topology
// Leave topology updates are fire-and-forget, so it's possible for A to miss both the leave topology
// and the phase change and still have a single partition
// However, PreferAvailabilityStrategy will not recognize it as a single partition
List<Address> remainingMembers = asList(B, C);
TestClusterCacheStatus cacheAB = start(DIST_INFO, A, B);
TestClusterCacheStatus cacheC = cacheAB.copy();
cacheC.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, A, B, C);
cacheC.removeMembers(A);
CacheStatusResponse responseB = availableResponse(B, cacheAB);
CacheStatusResponse responseC = availableResponse(C, cacheC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(remainingMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
expectedCache.cancelRebalance();
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(remainingMembers);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionRepl2LeaveDuringRebalancePhaseReadOld() {
// A and B are running, rebalancing is disabled, then C and D join
// Re-enable rebalance, but stop B and A before the rebalance is done
// C sees the finished rebalance, D sees the READ_OLD phase
// C becomes coordinator and should recover with C's topology
List<Address> remainingMembers = asList(C, D);
TestClusterCacheStatus cacheAB = start(REPL_INFO, A, B);
TestClusterCacheStatus cacheD = cacheAB.copy();
cacheD.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, A, B, C, D);
TestClusterCacheStatus cacheC = cacheD.copy();
cacheC.removeMembers(B);
cacheC.removeMembers(A);
cacheC.finishRebalance();
cacheC.updateStableTopology();
CacheStatusResponse responseC = availableResponse(C, cacheC);
CacheStatusResponse responseD = availableResponse(D, cacheD);
Map<Address, CacheStatusResponse> statusResponses = mapOf(C, responseC, D, responseD);
when(context.getExpectedMembers()).thenReturn(remainingMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
when(context.resolveConflictsOnMerge()).thenReturn(conflicts.resolve());
if (conflicts.resolve()) {
when(context.calculateConflictHash(cacheC.readConsistentHash(),
setOf(cacheC.readConsistentHash(), cacheD.readConsistentHash()),
remainingMembers))
.thenReturn(conflictResolutionConsistentHash(cacheC, cacheD));
}
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
if (conflicts.resolve()) {
expectedCache.startConflictResolution(conflictResolutionConsistentHash(cacheC, cacheD), C, D);
} else {
expectedCache.incrementIds();
}
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).updateCurrentTopology(remainingMembers);
if (conflicts.resolve()) {
verify(context).queueConflictResolution(expectedCache.topology(), setOf(C, D));
} else {
verify(context).queueRebalance(remainingMembers);
}
verifyNoMoreInteractions(context);
}
public void testSinglePartitionLeaveDuringRebalancePhaseReadNew() {
// C joins and rebalance starts, but A crashes and B doesn't receive 2 topology updates (rebalance phase + leave)
// Leave topology updates are fire-and-forget, so it's possible for B to miss both the leave topology
// and the phase change and still have a single partition
List<Address> mergeMembers = asList(B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A, B);
cacheA.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, A, B, C);
cacheA.advanceRebalance(CacheTopology.Phase.READ_ALL_WRITE_ALL);
TestClusterCacheStatus cacheC = cacheA.copy();
cacheC.removeMembers(A);
cacheC.advanceRebalance(CacheTopology.Phase.READ_NEW_WRITE_ALL);
CacheStatusResponse responseB = availableResponse(B, cacheA);
CacheStatusResponse responseC = availableResponse(C, cacheC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
expectedCache.cancelRebalance();
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(mergeMembers);
verifyNoMoreInteractions(context);
}
public void testSinglePartitionOneNodeSplits() {
// C starts a partition by itself
TestClusterCacheStatus cacheABC = start(DIST_INFO, A, B, C);
List<Address> remainingMembers = singletonList(C);
CacheStatusResponse responseC = availableResponse(C, cacheABC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(C, responseC);
when(context.getExpectedMembers()).thenReturn(remainingMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheABC.copy();
expectedCache.updateActualMembers(C);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).updateCurrentTopology(remainingMembers);
verify(context).queueRebalance(remainingMembers);
verifyNoMoreInteractions(context);
}
public void testMerge1Paused2Rebalancing() {
// A was paused and keeps the stable topology, B and C are rebalancing
List<Address> mergeMembers = asList(A, B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A, B, C);
TestClusterCacheStatus cacheB = cacheA.copy();
cacheB.removeMembers(A);
cacheB.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, B, C);
TestClusterCacheStatus cacheC = cacheB.copy();
cacheC.advanceRebalance(CacheTopology.Phase.READ_ALL_WRITE_ALL);
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseB = availableResponse(B, cacheB);
CacheStatusResponse responseC = availableResponse(C, cacheC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
expectedCache.cancelRebalance();
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(mergeMembers);
verifyNoMoreInteractions(context);
}
public void testMerge1Paused2StableAfterRebalance() {
// A was paused and keeps the stable topology, B and C finished rebalancing and have a new stable topology
List<Address> mergeMembers = asList(A, B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A, B, C);
TestClusterCacheStatus cacheBC = cacheA.copy();
cacheBC.removeMembers(A);
cacheBC.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, B, C);
cacheBC.advanceRebalance(CacheTopology.Phase.READ_ALL_WRITE_ALL);
cacheBC.finishRebalance();
cacheBC.updateStableTopology();
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseB = availableResponse(B, cacheBC);
CacheStatusResponse responseC = availableResponse(C, cacheBC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, B, responseB, C, responseC);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheBC.copy();
expectedCache.incrementIds();
expectedCache.incrementIdsIfNeeded(cacheA);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(mergeMembers);
verifyNoMoreInteractions(context);
}
public void testMerge1Paused2StableNoRebalance() {
// A was paused and keeps the stable topology, B has a new stable topology (no rebalance needed)
// No conflict resolution needed, because B has all the data
List<Address> mergeMembers = asList(A, B);
TestClusterCacheStatus cacheA = TestClusterCacheStatus.start(DIST_INFO, A, B);
TestClusterCacheStatus cacheB = cacheA.copy();
cacheB.removeMembers(A);
cacheB.updateStableTopology();
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseB = availableResponse(B, cacheB);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, B, responseB);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheB.copy();
expectedCache.incrementIds();
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).queueRebalance(mergeMembers);
verifyNoMoreInteractions(context);
}
public void testMerge1Paused2StableAfterLosingAnotherNode() {
// A was paused and keeps the stable topology
// B and C finished rebalancing, then B was paused
// Now A has resumed and merges with C
// Conflict resolution is needed because A might have changed some keys by talking only to B
List<Address> mergeMembers = asList(A, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A, B, C);
TestClusterCacheStatus cacheB = cacheA.copy();
cacheB.removeMembers(A);
cacheB.startRebalance(CacheTopology.Phase.READ_OLD_WRITE_ALL, B, C);
cacheB.advanceRebalance(CacheTopology.Phase.READ_ALL_WRITE_ALL);
cacheB.finishRebalance();
cacheB.updateStableTopology();
TestClusterCacheStatus cacheC = cacheB.copy();
cacheC.removeMembers(B);
cacheC.updateStableTopology();
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseC = availableResponse(C, cacheC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, C, responseC);
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.getCacheName()).thenReturn(CACHE_NAME);
when(context.resolveConflictsOnMerge()).thenReturn(conflicts.resolve());
if (conflicts.resolve()) {
when(context.calculateConflictHash(cacheC.readConsistentHash(),
setOf(cacheA.readConsistentHash(), cacheC.readConsistentHash()), mergeMembers))
.thenReturn(conflictResolutionConsistentHash(cacheC, cacheA));
}
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheC.copy();
if (conflicts.resolve()) {
expectedCache.startConflictResolution(conflictResolutionConsistentHash(cacheC, cacheA), A, C);
}
expectedCache.incrementIdsIfNeeded(cacheC);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
if (!conflicts.resolve()) {
verify(context).updateCurrentTopology(singletonList(C));
verify(context).queueRebalance(mergeMembers);
} else {
verify(context).updateCurrentTopology(mergeMembers);
verify(context).queueConflictResolution(expectedCache.topology(), setOf(C));
}
verifyNoMoreInteractions(context);
}
public void testMerge1HigherTopologyId2MoreNodesSameStableTopology() {
// Partition A has a higher topology id, but BCD should win because it is larger
List<Address> mergeMembers = asList(A, B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A, B, C);
TestClusterCacheStatus cacheBC = cacheA.copy();
cacheA.removeMembers(B);
cacheA.removeMembers(C);
cacheBC.removeMembers(A);
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseB = availableResponse(B, cacheBC);
CacheStatusResponse responseC = availableResponse(C, cacheBC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, B, responseB, C, responseC);
assertTrue(cacheA.topology().getTopologyId() > cacheBC.topology().getTopologyId());
assertSame(cacheA.stableTopology(), cacheBC.stableTopology());
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.resolveConflictsOnMerge()).thenReturn(conflicts.resolve());
when(context.getCacheName()).thenReturn(CACHE_NAME);
if (conflicts.resolve()) {
when(context.calculateConflictHash(cacheBC.readConsistentHash(),
setOf(cacheA.readConsistentHash(), cacheBC.readConsistentHash()), mergeMembers))
.thenReturn(conflictResolutionConsistentHash(cacheA, cacheBC));
}
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheBC.copy();
if (conflicts.resolve()) {
expectedCache.startConflictResolution(conflictResolutionConsistentHash(cacheA, cacheBC), A, B, C);
} else {
expectedCache.incrementIds();
}
expectedCache.incrementIdsIfNeeded(cacheA);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).updateCurrentTopology(expectedCache.topology().getMembers());
if (!conflicts.resolve()) {
verify(context).queueRebalance(mergeMembers);
} else {
verify(context).queueConflictResolution(expectedCache.topology(), setOf(B, C));
}
verifyNoMoreInteractions(context);
}
public void testMerge1HigherTopologyId2MoreNodesIndependentStableTopology() {
// Partition A has a higher topology id, but BC should win because it is larger
List<Address> mergeMembers = asList(A, B, C);
TestClusterCacheStatus cacheA = start(DIST_INFO, A);
cacheA.incrementIds();
TestClusterCacheStatus cacheBC = start(DIST_INFO, B, C);
CacheStatusResponse responseA = availableResponse(A, cacheA);
CacheStatusResponse responseB = availableResponse(B, cacheBC);
CacheStatusResponse responseC = availableResponse(C, cacheBC);
Map<Address, CacheStatusResponse> statusResponses = mapOf(A, responseA, B, responseB, C, responseC);
assertTrue(cacheA.topology().getTopologyId() > cacheBC.topology().getTopologyId());
when(context.getExpectedMembers()).thenReturn(mergeMembers);
when(context.resolveConflictsOnMerge()).thenReturn(conflicts.resolve());
when(context.getCacheName()).thenReturn(CACHE_NAME);
if (conflicts.resolve()) {
when(context.calculateConflictHash(cacheBC.readConsistentHash(),
setOf(cacheA.readConsistentHash(), cacheBC.readConsistentHash()), mergeMembers))
.thenReturn(conflictResolutionConsistentHash(cacheA, cacheBC));
}
strategy.onPartitionMerge(context, statusResponses);
TestClusterCacheStatus expectedCache = cacheBC.copy();
if (conflicts.resolve()) {
expectedCache.startConflictResolution(conflictResolutionConsistentHash(cacheA, cacheBC), A, B, C);
} else {
expectedCache.incrementIds();
}
expectedCache.incrementIdsIfNeeded(cacheA);
verify(context).updateTopologiesAfterMerge(expectedCache.topology(), expectedCache.stableTopology(), null);
verify(context).updateCurrentTopology(expectedCache.topology().getMembers());
if (!conflicts.resolve()) {
verify(context).queueRebalance(mergeMembers);
} else {
verify(context).queueConflictResolution(expectedCache.topology(), setOf(B, C));
}
verifyNoMoreInteractions(context);
}
private CacheStatusResponse availableResponse(Address a, TestClusterCacheStatus cacheStatus) {
return new CacheStatusResponse(cacheStatus.joinInfo(a), cacheStatus.topology(), cacheStatus.stableTopology(),
AVAILABLE, asList(A, B, C));
}
@Override
protected String parameters() {
return "[" + conflicts + "]";
}
}
| 26,149
| 48.154135
| 124
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/StripedHashFunctionTest.java
|
package org.infinispan.lock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.util.StripedHashFunction;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "lock.StripedHashFunctionTest")
public class StripedHashFunctionTest extends AbstractInfinispanTest {
private StripedHashFunction<String> stripedHashFunction;
@BeforeMethod
public void setUp() {
stripedHashFunction = new StripedHashFunction<>(500);
}
public void testHashingDistribution() {
// ensure even bucket distribution of lock stripes
List<String> keys = createRandomKeys(1000);
Map<Integer, Integer> distribution = new HashMap<>();
for (String s : keys) {
int segmentIndex = stripedHashFunction.hashToSegment(s);
log.tracef("Lock for %s is %s", s, segmentIndex);
if (distribution.containsKey(segmentIndex)) {
int count = distribution.get(segmentIndex) + 1;
distribution.put(segmentIndex, count);
} else {
distribution.put(segmentIndex, 1);
}
}
// cannot be larger than the number of locks
log.trace("dist size: " + distribution.size());
log.trace("num shared locks: " + stripedHashFunction.getNumSegments());
assert distribution.size() <= stripedHashFunction.getNumSegments();
// assume at least a 2/3rd spread
assert distribution.size() * 1.5 >= stripedHashFunction.getNumSegments();
}
private List<String> createRandomKeys(int number) {
List<String> f = new ArrayList<>(number);
int i = number;
while (f.size() < number) {
String s = i + "baseKey" + (10000 + i++);
f.add(s);
}
return f;
}
}
| 1,878
| 30.847458
| 79
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/CheckRemoteLockAcquiredOnlyOnceTest.java
|
package org.infinispan.lock;
import static org.infinispan.test.TestingUtil.extractInterceptorChain;
import static org.testng.Assert.assertEquals;
import java.util.Collections;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* This test makes sure that once a remote lock has been acquired, this acquisition attempt won't happen again during
* the same transaction.
*
* @author Mircea Markus
* @since 5.1
*/
@Test(groups = "functional", testName = "lock.CheckRemoteLockAcquiredOnlyOnceTest")
public class CheckRemoteLockAcquiredOnlyOnceTest extends MultipleCacheManagersTest {
protected ControlInterceptor controlInterceptor;
protected Object key;
protected CacheMode mode = CacheMode.REPL_SYNC;
@Override
protected void createCacheManagers() throws Throwable {
final ConfigurationBuilder c = getDefaultClusteredCacheConfig(mode, true);
c.transaction().lockingMode(LockingMode.PESSIMISTIC);
createCluster(TestDataSCI.INSTANCE, c, 2);
waitForClusterToForm();
controlInterceptor = new ControlInterceptor();
extractInterceptorChain(cache(0)).addInterceptor(controlInterceptor, 1);
key = new MagicKey("k", cache(0));
}
public void testLockThenLock() throws Exception {
testLockThenOperation(new CacheOperation() {
@Override
public void execute() {
advancedCache(1).lock(key);
}
});
}
public void testLockThenPut() throws Exception {
testLockThenOperation(new CacheOperation() {
@Override
public void execute() {
cache(1).put(key, "v");
}
});
}
public void testLockThenRemove() throws Exception {
testLockThenOperation(new CacheOperation() {
@Override
public void execute() {
cache(1).remove(key);
}
});
}
public void testLockThenReplace() throws Exception {
testLockThenOperation(new CacheOperation() {
@Override
public void execute() {
cache(1).replace(key, "", "v");
}
});
}
public void testLockThenPutAll() throws Exception {
testLockThenOperation(new CacheOperation() {
@Override
public void execute() {
cache(1).putAll(Collections.singletonMap(key, "value"));
}
});
}
public void testPutThenLock() throws Exception {
testOperationThenLock(new CacheOperation() {
@Override
public void execute() {
cache(1).put(key, "v");
}
});
}
public void testRemoveThenLock() throws Exception {
testOperationThenLock(new CacheOperation() {
@Override
public void execute() {
cache(1).remove(key);
}
});
}
public void testReplaceThenLock() throws Exception {
testOperationThenLock(new CacheOperation() {
@Override
public void execute() {
cache(1).replace(key, "", "v");
}
});
}
public void testPutAllThenLock() throws Exception {
testOperationThenLock(new CacheOperation() {
@Override
public void execute() {
cache(1).putAll(Collections.singletonMap(key, "value"));
}
});
}
private void testLockThenOperation(CacheOperation o) throws Exception {
assert controlInterceptor.remoteInvocations == 0;
tm(1).begin();
advancedCache(1).lock(key);
assert lockManager(0).isLocked(key);
assertEquals(controlInterceptor.remoteInvocations, 1);
for (int i = 0; i < 100; i++) {
o.execute();
}
assertEquals(controlInterceptor.remoteInvocations, 1);
tm(1).commit();
assertEquals(controlInterceptor.remoteInvocations, 1);
controlInterceptor.remoteInvocations = 0;
}
private void testOperationThenLock(CacheOperation o) throws Exception {
assert controlInterceptor.remoteInvocations == 0;
tm(1).begin();
for (int i = 0; i < 100; i++) {
o.execute();
}
assert lockManager(0).isLocked(key);
assertEquals(controlInterceptor.remoteInvocations, 1);
advancedCache(1).lock(key);
assertEquals(controlInterceptor.remoteInvocations, 1);
tm(1).commit();
assertEquals(controlInterceptor.remoteInvocations, 1);
controlInterceptor.remoteInvocations = 0;
}
public static class ControlInterceptor extends DDAsyncInterceptor {
volatile int remoteInvocations = 0;
@Override
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable {
if (!ctx.isOriginLocal()) remoteInvocations++;
return super.visitLockControlCommand(ctx, command);
}
}
public interface CacheOperation {
void execute();
}
}
| 5,281
| 28.674157
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/StaleLocksOnPrepareFailureTest.java
|
package org.infinispan.lock;
import org.infinispan.Cache;
import org.infinispan.commands.tx.VersionedPrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.distribution.VersionedDistributionInterceptor;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(testName = "lock.StaleLocksOnPrepareFailureTest", groups = "functional")
@CleanupAfterMethod
public class StaleLocksOnPrepareFailureTest extends MultipleCacheManagersTest {
private static final int NUM_CACHES = 10;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cfg.clustering().hash().numOwners(NUM_CACHES)
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
for (int i = 0; i < NUM_CACHES; i++) {
EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(cfg);
registerCacheManager(cm);
}
waitForClusterToForm();
}
public void testModsCommit() throws Exception {
Cache<Object, Object> c1 = cache(0);
Cache<Object, Object> c2 = cache(NUM_CACHES /2);
// force the prepare command to fail on c2
FailInterceptor interceptor = new FailInterceptor();
interceptor.failFor(VersionedPrepareCommand.class);
AsyncInterceptorChain ic = c2.getAdvancedCache().getAsyncInterceptorChain();
ic.addInterceptorBefore(interceptor, VersionedDistributionInterceptor.class);
MagicKey k1 = new MagicKey("k1", c1);
tm(c1).begin();
c1.put(k1, "v1");
try {
tm(c1).commit();
assert false : "Commit should have failed";
} catch (Exception e) {
// expected
}
for (int i = 0; i < NUM_CACHES; i++) {
assertEventuallyNotLocked(cache(i), k1);
}
}
}
| 2,283
| 35.83871
| 92
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/KeyLockTest.java
|
package org.infinispan.lock;
import java.util.concurrent.TimeUnit;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.commons.marshall.WrappedByteArray;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.impl.LockContainer;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* Tests if the same lock is used for the same key.
*
* @author Pedro Ruivo
* @since 7.0
*/
@Test(groups = "unit", testName = "lock.KeyLockTest")
@CleanupAfterTest
public class KeyLockTest extends SingleCacheManagerTest {
private static final int RETRIES = 100;
public void testByteArrayStrippedLockTx() throws Exception {
doTest(CacheName.STRIPPED_LOCK_TX);
}
public void testByteArrayStrippedLockNonTx() throws Exception {
doTest(CacheName.STRIPPED_LOCK_NON_TX);
}
public void testByteArrayPerEntryLockTx() throws Exception {
doTest(CacheName.PER_ENTRY_LOCK_TX);
}
public void testByteArrayPerEntryLockNonTx() throws Exception {
doTest(CacheName.PER_ENTRY_LOCK_NON_TX);
}
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.LOCAL);
builder.locking().lockAcquisitionTimeout(100, TimeUnit.MILLISECONDS);
EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(builder);
for (CacheName cacheName : CacheName.values()) {
cacheName.configure(builder);
cacheManager.defineConfiguration(cacheName.name(), builder.build());
}
return cacheManager;
}
private void doTest(CacheName cacheName) throws Exception {
final LockContainer lockContainer = TestingUtil.extractComponent(cache(cacheName.name()), LockContainer.class);
final Object lockOwner = new Object();
try {
lockContainer.acquire(byteArray(), lockOwner, 10, TimeUnit.MILLISECONDS).lock();
} catch (InterruptedException | TimeoutException e) {
AssertJUnit.fail();
}
AssertJUnit.assertTrue(lockContainer.isLocked(byteArray()));
fork(() -> {
for (int i = 0; i < RETRIES; ++i) {
AssertJUnit.assertTrue(lockContainer.isLocked(byteArray()));
try {
lockContainer.acquire(byteArray(), new Object(), 10, TimeUnit.MILLISECONDS).lock();
AssertJUnit.fail();
} catch (InterruptedException | TimeoutException e) {
//expected
}
}
return null;
}).get(10, TimeUnit.SECONDS);
}
private static WrappedByteArray byteArray() {
return new WrappedByteArray(new byte[]{1});
}
private enum CacheName {
STRIPPED_LOCK_TX {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(true);
builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
}
},
STRIPPED_LOCK_NON_TX {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(true);
builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
}
},
PER_ENTRY_LOCK_TX {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(false);
builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
}
},
PER_ENTRY_LOCK_NON_TX {
@Override
void configure(ConfigurationBuilder builder) {
builder.locking().useLockStriping(false);
builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
}
};
abstract void configure(ConfigurationBuilder builder);
}
}
| 4,231
| 34.266667
| 117
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/CheckNoRemoteCallForLocalKeyDistTest.java
|
package org.infinispan.lock;
import org.infinispan.configuration.cache.CacheMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "lock.CheckNoRemoteCallForLocalKeyDistTest")
public class CheckNoRemoteCallForLocalKeyDistTest extends CheckNoRemoteCallForLocalKeyTest {
public CheckNoRemoteCallForLocalKeyDistTest() {
mode = CacheMode.DIST_SYNC;
}
@Override
protected void createCacheManagers() throws Throwable {
super.createCacheManagers();
key = getKeyForCache(0);
}
}
| 583
| 24.391304
| 92
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/ExplicitLockingAndOptimisticCachesTest.java
|
package org.infinispan.lock;
import static org.infinispan.test.TestingUtil.withTx;
import java.util.concurrent.Callable;
import org.infinispan.commons.CacheException;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.SingleCacheManagerTest;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* @author Mircea Markus
* @since 5.1
*/
@Test (groups = "functional", testName = "lock.ExplicitLockingAndOptimisticCachesTest")
public class ExplicitLockingAndOptimisticCachesTest extends SingleCacheManagerTest {
@Override
protected EmbeddedCacheManager createCacheManager() throws Exception {
final ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true);
c.transaction().lockingMode(LockingMode.OPTIMISTIC);
return TestCacheManagerFactory.createCacheManager(c);
}
public void testExplicitLockingNotWorkingWithOptimisticCaches() throws Exception {
// Also provide guarantees that the transaction will come to an end
withTx(tm(), new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
cache.getAdvancedCache().lock("a");
assert false;
} catch (CacheException e) {
// expected
}
return null;
}
});
}
public void testExplicitLockingOptimisticCachesFailSilent() throws Exception {
// Also provide guarantees that the transaction will come to an end
withTx(tm(), new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
cache.getAdvancedCache().withFlags(Flag.FAIL_SILENTLY).lock("a");
assert false : "Should be throwing an exception in spite of fail silent";
} catch (CacheException e) {
// expected
}
return null;
}
});
}
}
| 2,118
| 32.634921
| 88
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/NonTxRemoteLockTest.java
|
package org.infinispan.lock;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.context.InvocationContext;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.DDAsyncInterceptor;
import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.Test;
/**
* Tests if the {@link org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor} releases
* locks if an exception occurs.
*
* @author Pedro Ruivo
* @author Dan Berindei
* @since 8.1
*/
@Test(groups = "functional", testName = "lock.NonTxRemoteLockTest")
public class NonTxRemoteLockTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false);
builder.clustering().hash().numOwners(1);
builder.clustering().stateTransfer().fetchInMemoryState(false);
createClusteredCaches(2, TestDataSCI.INSTANCE, builder);
}
public void testExceptionBeforeLockingInterceptor() {
final Object key = new MagicKey(cache(1));
final LockManager lockManager = TestingUtil.extractLockManager(cache(1));
TestingUtil.extractInterceptorChain(cache(1)).addInterceptorAfter(new ExceptionInRemotePutInterceptor(lockManager), NonTransactionalLockingInterceptor.class);
assertFalse(lockManager.isLocked(key));
try {
cache(0).put(key, "foo");
fail("Exception expected!");
} catch (Exception e) {
//expected
assertEquals("Induced Exception!", e.getCause().getMessage());
}
//it sends the reply before invoke the finally. So, we need to use eventually :)
eventually(() -> !lockManager.isLocked(key));
}
public static class ExceptionInRemotePutInterceptor extends DDAsyncInterceptor {
LockManager lockManager;
ExceptionInRemotePutInterceptor(LockManager lockManager) {
this.lockManager = lockManager;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (ctx.isOriginLocal()) {
return invokeNext(ctx, command);
}
assertTrue(lockManager.isLocked(command.getKey()));
throw new RuntimeException("Induced Exception!");
}
}
}
| 2,904
| 37.733333
| 164
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/PessimistTxFailureAfterLockingTest.java
|
package org.infinispan.lock;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Collection;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.infinispan.Cache;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
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.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.AbstractDelegatingRpcManager;
import org.infinispan.util.concurrent.IsolationLevel;
import org.infinispan.util.concurrent.TimeoutException;
import org.testng.annotations.Test;
/**
* Test the failures after lock acquired for Pessimistic transactional caches.
*
* @author Pedro Ruivo
* @since 6.0
*/
@Test(groups = "functional", testName = "lock.PessimistTxFailureAfterLockingTest")
@CleanupAfterMethod
public class PessimistTxFailureAfterLockingTest extends MultipleCacheManagersTest {
/**
* ISPN-3556
*/
public void testReplyLostWithImplicitLocking() throws Exception {
doTest(false);
}
/**
* ISPN-3556
*/
public void testReplyLostWithExplicitLocking() throws Exception {
doTest(true);
}
private void doTest(boolean explicitLocking) throws Exception {
final Object key = new MagicKey(cache(1), cache(2));
replaceRpcManagerInCache(cache(0));
boolean failed = false;
tm(0).begin();
try {
if (explicitLocking) {
cache(0).getAdvancedCache().lock(key);
} else {
cache(0).put(key, "value");
}
} catch (Exception e) {
failed = true;
//expected
}
tm(0).rollback();
assertTrue("Expected an exception", failed);
assertNoTransactions();
assertEventuallyNotLocked(cache(1), key);
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.locking()
.isolationLevel(IsolationLevel.READ_COMMITTED); //read committed is enough
builder.transaction()
.lockingMode(LockingMode.PESSIMISTIC);
builder.clustering().hash()
.numOwners(2);
createClusteredCaches(3, builder);
}
private void replaceRpcManagerInCache(Cache cache) {
RpcManager rpcManager = TestingUtil.extractComponent(cache, RpcManager.class);
TestControllerRpcManager testControllerRpcManager = new TestControllerRpcManager(rpcManager);
TestingUtil.replaceComponent(cache, RpcManager.class, testControllerRpcManager, true);
}
/**
* this RpcManager simulates a reply lost from LockControlCommand by throwing a TimeoutException. However, it is
* expected the command to acquire the remote lock.
*/
private class TestControllerRpcManager extends AbstractDelegatingRpcManager {
public TestControllerRpcManager(RpcManager realOne) {
super(realOne);
}
@Override
protected <T> CompletionStage<T> performRequest(Collection<Address> targets, ReplicableCommand command,
ResponseCollector<T> collector,
Function<ResponseCollector<T>, CompletionStage<T>> invoker,
RpcOptions rpcOptions) {
if (command instanceof LockControlCommand) {
throw new TimeoutException("Exception expected!");
}
return super.performRequest(targets, command, collector, invoker, rpcOptions);
}
}
}
| 4,086
| 34.53913
| 115
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/StaleEagerLocksOnPrepareFailureTest.java
|
package org.infinispan.lock;
import static org.testng.Assert.assertNull;
import org.infinispan.Cache;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.distribution.TxDistributionInterceptor;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
@Test(testName = "lock.StaleEagerLocksOnPrepareFailureTest", groups = "functional")
@CleanupAfterMethod
public class StaleEagerLocksOnPrepareFailureTest extends MultipleCacheManagersTest {
Cache<MagicKey, String> c1, c2;
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder cfg = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
cfg
.transaction()
.lockingMode(LockingMode.PESSIMISTIC)
.useSynchronization(false)
.recovery()
.disable()
.locking()
.lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis());
createCluster(TestDataSCI.INSTANCE, cfg, 2);
waitForClusterToForm();
c1 = cache(0);
c2 = cache(1);
}
public void testNoModsCommit() throws Exception {
doTest(false);
}
public void testModsCommit() throws Exception {
doTest(true);
}
private void doTest(boolean mods) throws Exception {
// force the prepare command to fail on c2
FailInterceptor interceptor = new FailInterceptor();
interceptor.failFor(PrepareCommand.class);
AsyncInterceptorChain ic = c2.getAdvancedCache().getAsyncInterceptorChain();
ic.addInterceptorBefore(interceptor, TxDistributionInterceptor.class);
MagicKey k1 = new MagicKey("k1", c1);
MagicKey k2 = new MagicKey("k2", c2);
tm(c1).begin();
if (mods) {
c1.put(k1, "v1");
c1.put(k2, "v2");
assertKeyLockedCorrectly(k1);
assertKeyLockedCorrectly(k2);
} else {
c1.getAdvancedCache().lock(k1);
c1.getAdvancedCache().lock(k2);
assertNull(c1.get(k1));
assertNull(c1.get(k2));
assertKeyLockedCorrectly(k1);
assertKeyLockedCorrectly(k2);
}
try {
tm(c1).commit();
assert false : "Commit should have failed";
} catch (Exception e) {
// expected
}
assertEventuallyNotLocked(c1, k1);
assertEventuallyNotLocked(c2, k1);
assertEventuallyNotLocked(c1, k2);
assertEventuallyNotLocked(c2, k2);
}
}
| 2,868
| 30.527473
| 91
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/InfinispanLockTest.java
|
package org.infinispan.lock;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.commons.util.ByRef;
import org.infinispan.test.AbstractCacheTest;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.DeadlockDetectedException;
import org.infinispan.util.concurrent.locks.ExtendedLockPromise;
import org.infinispan.util.concurrent.locks.LockPromise;
import org.infinispan.util.concurrent.locks.LockState;
import org.infinispan.util.concurrent.locks.impl.InfinispanLock;
import org.testng.annotations.Test;
/**
* Unit tests for the {@link InfinispanLock}.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "unit", testName = "lock.InfinispanLockTest")
public class InfinispanLockTest extends AbstractInfinispanTest {
public void testTimeout() throws InterruptedException {
final String lockOwner1 = "LO1";
final String lockOwner2 = "LO2";
final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE);
final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS);
assertTrue(lockPromise1.isAvailable());
assertTrue(lockPromise2.isAvailable());
lockPromise1.lock();
assertEquals(lockOwner1, lock.getLockOwner());
try {
lockPromise2.lock();
fail();
} catch (TimeoutException e) {
//expected!
}
lock.release(lockOwner1);
assertNull(lock.getLockOwner());
assertFalse(lock.isLocked());
//no side effects
lock.release(lockOwner2);
assertFalse(lock.isLocked());
assertNull(lock.getLockOwner());
}
public void testTimeout2() throws InterruptedException {
final String lockOwner1 = "LO1";
final String lockOwner2 = "LO2";
final String lockOwner3 = "LO3";
final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE);
final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise3 = lock.acquire(lockOwner3, 1, TimeUnit.DAYS);
assertTrue(lockPromise1.isAvailable());
assertTrue(lockPromise2.isAvailable());
assertFalse(lockPromise3.isAvailable());
lockPromise1.lock();
assertEquals(lockOwner1, lock.getLockOwner());
try {
lockPromise2.lock();
fail();
} catch (TimeoutException e) {
//expected!
}
lock.release(lockOwner1);
assertTrue(lock.isLocked());
assertTrue(lockPromise3.isAvailable());
lockPromise3.lock();
assertEquals(lockOwner3, lock.getLockOwner());
lock.release(lockOwner3);
assertFalse(lock.isLocked());
//no side effects
lock.release(lockOwner2);
assertFalse(lock.isLocked());
assertNull(lock.getLockOwner());
}
public void testTimeout3() throws InterruptedException {
final String lockOwner1 = "LO1";
final String lockOwner2 = "LO2";
final String lockOwner3 = "LO3";
final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE);
final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise2 = lock.acquire(lockOwner2, 1, TimeUnit.DAYS);
final LockPromise lockPromise3 = lock.acquire(lockOwner3, 1, TimeUnit.DAYS);
assertTrue(lockPromise1.isAvailable());
assertFalse(lockPromise2.isAvailable());
assertFalse(lockPromise3.isAvailable());
lockPromise1.lock();
assertEquals(lockOwner1, lock.getLockOwner());
//premature release. the lock is never acquired by owner 2
//when the owner 1 releases, owner 3 is able to acquire it
lock.release(lockOwner2);
assertTrue(lock.isLocked());
assertEquals(lockOwner1, lock.getLockOwner());
lock.release(lockOwner1);
assertTrue(lock.isLocked());
assertTrue(lockPromise3.isAvailable());
lockPromise3.lock();
assertEquals(lockOwner3, lock.getLockOwner());
lock.release(lockOwner3);
assertFalse(lock.isLocked());
//no side effects
lock.release(lockOwner2);
assertFalse(lock.isLocked());
assertNull(lock.getLockOwner());
}
public void testCancel() throws InterruptedException {
final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE);
final String lockOwner1 = "LO1";
final String lockOwner2 = "LO2";
final String lockOwner3 = "LO3";
ExtendedLockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS); //will be acquired
ExtendedLockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS); //will be timed-out
ExtendedLockPromise lockPromise3 = lock.acquire(lockOwner3, 1, TimeUnit.DAYS); //will be waiting
assertTrue(lockPromise1.isAvailable());
assertTrue(lockPromise2.isAvailable());
assertFalse(lockPromise3.isAvailable());
assertEquals(lockOwner1, lock.getLockOwner());
lockPromise1.cancel(LockState.TIMED_OUT); //no-op
lockPromise1.lock();
try {
lockPromise2.lock();
fail("TimeoutException expected");
} catch (TimeoutException e) {
//expected
}
assertEquals(lockOwner1, lock.getLockOwner());
assertTrue(lockPromise2.isAvailable());
assertFalse(lockPromise3.isAvailable());
lockPromise2.cancel(LockState.DEADLOCKED);
try {
//check state didn't change
lockPromise2.lock();
fail("TimeoutException expected");
} catch (TimeoutException e) {
//expected
}
assertEquals(lockOwner1, lock.getLockOwner());
assertFalse(lockPromise3.isAvailable());
lockPromise3.cancel(LockState.DEADLOCKED);
try {
lockPromise3.lock();
fail("DeadlockDetectedException expected");
} catch (DeadlockDetectedException e) {
//expected
}
lock.release(lockOwner1);
assertNull(lock.getLockOwner());
assertFalse(lock.isLocked());
lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS);
lockPromise2 = lock.acquire(lockOwner2, 1, TimeUnit.DAYS);
lockPromise1.lock();
lockPromise1.cancel(LockState.TIMED_OUT);
lockPromise1.lock(); //should not throw anything
//lock2 is in WAITING state
lockPromise2.cancel(LockState.TIMED_OUT);
assertTrue(lockPromise2.isAvailable());
lock.release(lockOwner1);
try {
lockPromise2.lock();
fail("TimeoutException expected");
} catch (TimeoutException e) {
//expected
}
assertNull(lock.getLockOwner());
assertFalse(lock.isLocked());
}
public void testSingleCounter() throws ExecutionException, InterruptedException {
final NotThreadSafeCounter counter = new NotThreadSafeCounter();
final InfinispanLock counterLock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE);
final int numThreads = 8;
final int maxCounterValue = 100;
final CyclicBarrier barrier = new CyclicBarrier(numThreads);
List<Future<Collection<Integer>>> callableResults = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; ++i) {
callableResults.add(fork(() -> {
final Thread lockOwner = Thread.currentThread();
assertEquals(0, counter.getCount());
List<Integer> seenValues = new LinkedList<>();
barrier.await();
while (true) {
counterLock.acquire(lockOwner, 1, TimeUnit.DAYS).lock();
assertEquals(lockOwner, counterLock.getLockOwner());
try {
int value = counter.getCount();
if (value == maxCounterValue) {
return seenValues;
}
seenValues.add(value);
counter.setCount(value + 1);
} finally {
counterLock.release(lockOwner);
}
}
}));
}
Set<Integer> seenResults = new HashSet<>();
for (Future<Collection<Integer>> future : callableResults) {
for (Integer integer : future.get()) {
assertTrue(seenResults.add(integer));
}
}
assertEquals(maxCounterValue, seenResults.size());
for (int i = 0; i < maxCounterValue; ++i) {
assertTrue(seenResults.contains(i));
}
assertFalse(counterLock.isLocked());
}
public void testLockAcquiredCreation() throws InterruptedException {
String lockOwner = "LO";
ByRef<ExtendedLockPromise> lockPromise = ByRef.create(null);
AtomicInteger releaseCount = new AtomicInteger();
InfinispanLock lock = new InfinispanLock(testExecutor(), TIME_SERVICE, releaseCount::incrementAndGet, lockOwner, lockPromise);
ExtendedLockPromise promise = lockPromise.get();
assertEquals(lockOwner, lock.getLockOwner());
assertEquals(lockOwner, promise.getOwner());
assertEquals(lockOwner, promise.getRequestor());
assertTrue(lock.containsLockOwner(lockOwner));
assertEquals(promise, lock.acquire(lockOwner, 0, TimeUnit.SECONDS));
assertTrue(lock.isLocked());
assertTrue(promise.isAvailable());
promise.lock();
assertTrue(promise.toInvocationStage(() -> {throw new IllegalStateException();}).isDone());
assertTrue(promise.toInvocationStage().isDone());
promise.addListener(state -> assertEquals(LockState.ACQUIRED, state));
assertEquals(0, releaseCount.get());
// unable to cancel acquired lock!
promise.cancel(LockState.TIMED_OUT);
promise.addListener(state -> assertEquals(LockState.ACQUIRED, state));
assertEquals(0, releaseCount.get());
lock.release(lockOwner);
assertFalse(lock.isLocked());
assertEquals(1, releaseCount.get());
// after release, a second owner should be able to acquire
lockOwner = "LO2";
promise = lock.acquire(lockOwner, 0, TimeUnit.SECONDS);
assertEquals(lockOwner, lock.getLockOwner());
assertEquals(lockOwner, promise.getOwner());
assertEquals(lockOwner, promise.getRequestor());
assertTrue(lock.containsLockOwner(lockOwner));
assertTrue(promise.isAvailable());
promise.lock();
lock.release(lockOwner);
assertEquals(2, releaseCount.get());
}
public void testLockAcquiredCreation2() throws InterruptedException {
// test if the next in queue is able to acquire the lock after the first owner releases it.
String lockOwner = "LO";
ByRef<ExtendedLockPromise> lockPromise = ByRef.create(null);
AtomicInteger releaseCount = new AtomicInteger();
InfinispanLock lock = new InfinispanLock(testExecutor(), TIME_SERVICE, releaseCount::incrementAndGet, lockOwner, lockPromise);
ExtendedLockPromise promise = lockPromise.get();
String lockOwner2 = "LO2";
ExtendedLockPromise promise2 = lock.acquire(lockOwner2, 1, TimeUnit.DAYS);
assertTrue(lock.isLocked());
assertTrue(promise.isAvailable());
assertFalse(promise2.isAvailable());
promise.lock();
lock.release(lockOwner);
assertEquals(1, releaseCount.get());
assertTrue(lock.isLocked());
assertTrue(promise2.isAvailable());
promise2.lock();
assertEquals(lockOwner2, lock.getLockOwner());
assertEquals(lockOwner2, promise2.getOwner());
assertEquals(lockOwner2, promise2.getRequestor());
lock.release(lockOwner2);
assertFalse(lock.isLocked());
assertEquals(2, releaseCount.get());
}
private static class NotThreadSafeCounter {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
}
| 12,737
| 33.89863
| 132
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/FailInterceptor.java
|
package org.infinispan.lock;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.infinispan.commands.ReplicableCommand;
import org.infinispan.commands.VisitableCommand;
import org.infinispan.commons.CacheException;
import org.infinispan.context.InvocationContext;
import org.infinispan.interceptors.BaseAsyncInterceptor;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Interceptor that can selectively fail or skip executing commands.
*
* The executor is controlled through a series of {@code Action}s.
* Each action represents a number of executions, skips or failures for a given command type.
* The interceptor will match the actions in order, so if the first action has a count of
* {@code Integer.MAX_VALUE} the rest of the actions will practically never match.
*
* @author Dan Berindei <dan@infinispan.org>
*/
class FailInterceptor extends BaseAsyncInterceptor {
private enum ActionType {
EXEC, SKIP, FAIL
}
private static class Action {
public Class<?> commandClass;
public ActionType type;
public Object returnValue;
public int count;
private Action(ActionType type, Class<?> commandClass, Object returnValue, int count) {
this.commandClass = commandClass;
this.type = type;
this.returnValue = returnValue;
this.count = count;
}
}
private static final Log log = LogFactory.getLog(FailInterceptor.class);
public Queue<Action> actions = new LinkedBlockingQueue<Action>();
@Override
public Object visitCommand(InvocationContext ctx, VisitableCommand command) throws Throwable {
Action action = actions.peek();
if (action == null || !command.getClass().equals(action.commandClass))
return invokeNext(ctx, command);
action.count--;
if (action.count <= 0)
actions.poll();
switch (action.type) {
case EXEC:
return invokeNext(ctx, command);
case SKIP:
log.debugf("Skipped executing command %s", command);
return action.returnValue;
case FAIL:
throw new CacheException("Forced failure executing command " + command);
default:
throw new CacheException("Unexpected FailInterceptor action type: " + action.type);
}
}
public void failFor(Class<? extends ReplicableCommand> commandClass) {
failFor(commandClass, Integer.MAX_VALUE);
}
public void failFor(Class<? extends ReplicableCommand> commandClass, int failCount) {
actions.add(new Action(ActionType.FAIL, commandClass, null, failCount));
}
public void skipFor(Class<? extends ReplicableCommand> commandClass, Object returnValue) {
skipFor(commandClass, returnValue, Integer.MAX_VALUE);
}
public void skipFor(Class<? extends ReplicableCommand> commandClass, Object returnValue, int skipCount) {
actions.add(new Action(ActionType.SKIP, commandClass, returnValue, skipCount));
}
public void execFor(Class<? extends ReplicableCommand> commandClass) {
execFor(commandClass, Integer.MAX_VALUE);
}
public void execFor(Class<? extends ReplicableCommand> commandClass, int execCount) {
actions.add(new Action(ActionType.EXEC, commandClass, null, execCount));
}
}
| 3,338
| 34.521277
| 108
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/InvalidationModePessimisticLockReleaseTest.java
|
package org.infinispan.lock;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.Callable;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* Test for stale remote locks on invalidation mode caches with pessimistic transactions.
* See https://issues.jboss.org/browse/ISPN-2549.
*
* @author anistor@redhat.com
* @since 5.3
*/
@Test(groups = "functional", testName = "lock.InvalidationModePessimisticLockReleaseTest")
public class InvalidationModePessimisticLockReleaseTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, true, true);
builder.transaction().useSynchronization(false)
.lockingMode(LockingMode.PESSIMISTIC)
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis())
.useLockStriping(false);
createCluster(builder, 2);
waitForClusterToForm();
}
public void testStaleRemoteLocks() throws Exception {
// put two keys on node 1
TestingUtil.withTx(tm(1), new Callable<Object>() {
@Override
public Object call() throws Exception {
cache(1).put(1, "val_1");
cache(1).put(2, "val_2");
return null;
}
});
assertValue(1, 1, "val_1");
assertValue(1, 2, "val_2");
// assert that no locks remain on node 1
assertFalse(checkLocked(1, 1));
assertFalse(checkLocked(1, 2));
// assert that no locks remain on node 0 (need to wait a bit for tx completion notifications to be processed async)
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return !checkLocked(0, 1) && !checkLocked(0, 2);
}
});
// try to modify a key. this should not fail due to residual locks.
cache(0).put(1, "new_val_1");
// assert expected values on each node
assertValue(0, 1, "new_val_1");
assertValue(1, 1, null);
assertValue(1, 2, "val_2");
}
private void assertValue(int nodeIndex, Object key, Object expectedValue) {
assertEquals(expectedValue, cache(nodeIndex).get(key));
}
}
| 2,577
| 32.921053
| 121
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/OptimisticTxFailureAfterLockingTest.java
|
package org.infinispan.lock;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Transaction;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.distribution.MagicKey;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestDataSCI;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.transaction.LockingMode;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* Test the failures after lock acquired for Optimistic transactional caches.
*
* @author Pedro Ruivo
* @since 6.0
*/
@Test(groups = "functional", testName = "lock.OptimisticTxFailureAfterLockingTest")
@CleanupAfterMethod
public class OptimisticTxFailureAfterLockingTest extends MultipleCacheManagersTest {
/**
* ISPN-3556
*/
public void testInOwner() throws Exception {
//primary owner is cache(0) and the failure is executed in cache(0)
doTest(0, 0);
}
/**
* ISPN-3556
*/
public void testInNonOwner() throws Exception {
//primary owner is cache(1) and the failure is executed in cache(0)
doTest(1, 0);
}
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true);
builder.locking().isolationLevel(IsolationLevel.REPEATABLE_READ);
builder.transaction().lockingMode(LockingMode.OPTIMISTIC);
builder.clustering().hash().numOwners(2);
createClusteredCaches(3, TestDataSCI.INSTANCE, builder);
}
private void doTest(int primaryOwnerIndex, int execIndex) throws Exception {
final Object key = new MagicKey(cache(primaryOwnerIndex), cache(2));
cache(primaryOwnerIndex).put(key, "v1");
tm(execIndex).begin();
AssertJUnit.assertEquals("v1", cache(execIndex).get(key));
final Transaction transaction = tm(execIndex).suspend();
cache(primaryOwnerIndex).put(key, "v2");
tm(execIndex).resume(transaction);
AssertJUnit.assertEquals("v1", cache(execIndex).put(key, "v3"));
try {
tm(execIndex).commit();
AssertJUnit.fail("Exception expected!");
} catch (RollbackException e) {
//expected
}
assertNoTransactions();
assertEventuallyNotLocked(cache(primaryOwnerIndex), key);
}
}
| 2,475
| 31.578947
| 95
|
java
|
null |
infinispan-main/core/src/test/java/org/infinispan/lock/LockContainerTest.java
|
package org.infinispan.lock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.infinispan.test.AbstractCacheTest;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.util.concurrent.TimeoutException;
import org.infinispan.util.concurrent.locks.LockPromise;
import org.infinispan.util.concurrent.locks.impl.LockContainer;
import org.infinispan.util.concurrent.locks.impl.PerKeyLockContainer;
import org.infinispan.util.concurrent.locks.impl.StripedLockContainer;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
/**
* Unit test for {@link LockContainer}.
*
* @author Pedro Ruivo
* @since 8.0
*/
@Test(groups = "unit", testName = "lock.LockContainerTest")
public class LockContainerTest extends AbstractInfinispanTest {
public void testSingleLockWithPerEntry() throws InterruptedException {
PerKeyLockContainer lockContainer = new PerKeyLockContainer();
TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE);
doSingleLockTest(lockContainer, -1);
}
public void testSingleCounterTestPerEntry() throws ExecutionException, InterruptedException {
PerKeyLockContainer lockContainer = new PerKeyLockContainer();
TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE);
doSingleCounterTest(lockContainer, -1);
}
public void testSingleLockWithStriped() throws InterruptedException {
StripedLockContainer lockContainer = new StripedLockContainer(16);
TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE);
doSingleLockTest(lockContainer, 16);
}
public void testSingleCounterWithStriped() throws ExecutionException, InterruptedException {
StripedLockContainer lockContainer = new StripedLockContainer(16);
TestingUtil.inject(lockContainer, AbstractCacheTest.TIME_SERVICE);
doSingleCounterTest(lockContainer, 16);
}
private void doSingleCounterTest(LockContainer lockContainer, int poolSize) throws InterruptedException, ExecutionException {
final NotThreadSafeCounter counter = new NotThreadSafeCounter();
final String key = "key";
final int numThreads = 8;
final int maxCounterValue = 100;
final CyclicBarrier barrier = new CyclicBarrier(numThreads);
List<Future<Collection<Integer>>> callableResults = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; ++i) {
callableResults.add(fork(() -> {
final Thread lockOwner = Thread.currentThread();
AssertJUnit.assertEquals(0, counter.getCount());
List<Integer> seenValues = new LinkedList<>();
barrier.await();
while (true) {
lockContainer.acquire(key, lockOwner, 1, TimeUnit.DAYS).lock();
AssertJUnit.assertEquals(lockOwner, lockContainer.getLock(key).getLockOwner());
try {
int value = counter.getCount();
if (value == maxCounterValue) {
return seenValues;
}
seenValues.add(value);
counter.setCount(value + 1);
} finally {
lockContainer.release(key, lockOwner);
}
}
}));
}
Set<Integer> seenResults = new HashSet<>();
for (Future<Collection<Integer>> future : callableResults) {
for (Integer integer : future.get()) {
AssertJUnit.assertTrue(seenResults.add(integer));
}
}
AssertJUnit.assertEquals(maxCounterValue, seenResults.size());
for (int i = 0; i < maxCounterValue; ++i) {
AssertJUnit.assertTrue(seenResults.contains(i));
}
AssertJUnit.assertEquals(0, lockContainer.getNumLocksHeld());
if (poolSize == -1) {
AssertJUnit.assertEquals(0, lockContainer.size());
} else {
AssertJUnit.assertEquals(poolSize, lockContainer.size());
}
}
private void doSingleLockTest(LockContainer container, int poolSize) throws InterruptedException {
final String lockOwner1 = "LO1";
final String lockOwner2 = "LO2";
final String lockOwner3 = "LO3";
final LockPromise lockPromise1 = container.acquire("key", lockOwner1, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise2 = container.acquire("key", lockOwner2, 0, TimeUnit.MILLISECONDS);
final LockPromise lockPromise3 = container.acquire("key", lockOwner3, 0, TimeUnit.MILLISECONDS);
AssertJUnit.assertEquals(1, container.getNumLocksHeld());
if (poolSize == -1) {
//dynamic
AssertJUnit.assertEquals(1, container.size());
} else {
AssertJUnit.assertEquals(poolSize, container.size());
}
acquireLock(lockPromise1, false);
acquireLock(lockPromise2, true);
acquireLock(lockPromise3, true);
AssertJUnit.assertEquals(1, container.getNumLocksHeld());
if (poolSize == -1) {
//dynamic
AssertJUnit.assertEquals(1, container.size());
} else {
AssertJUnit.assertEquals(poolSize, container.size());
}
container.release("key", lockOwner2);
container.release("key", lockOwner3);
AssertJUnit.assertEquals(1, container.getNumLocksHeld());
if (poolSize == -1) {
//dynamic
AssertJUnit.assertEquals(1, container.size());
} else {
AssertJUnit.assertEquals(poolSize, container.size());
}
container.release("key", lockOwner1);
AssertJUnit.assertEquals(0, container.getNumLocksHeld());
if (poolSize == -1) {
//dynamic
AssertJUnit.assertEquals(0, container.size());
} else {
AssertJUnit.assertEquals(poolSize, container.size());
}
}
private void acquireLock(LockPromise promise, boolean timeout) throws InterruptedException {
try {
promise.lock();
AssertJUnit.assertFalse(timeout);
} catch (TimeoutException e) {
AssertJUnit.assertTrue(timeout);
}
}
private static class NotThreadSafeCounter {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
}
| 6,547
| 35.176796
| 128
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.